From 557956fedd47dc1d8d446b96e8bd30cabda48edd Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Sat, 17 Oct 2026 11:10:34 +0200 Subject: [PATCH 1/3] feat(fiche): onglet Vie, la frise de vie d'une personne Naissance, unions et deces en grands reperes (direction A2 choisie par Patch le 16/10), evenements importes plus petits, famille proche tiree de l'arbre en retrait, sources repliees. Evenements charges a l'ouverture de l'onglet via GET /persons/:id/life, donnees propres a la demo pour Robert. Co-Authored-By: Claude Opus 5.5 --- frontend/src/api/treeApi.js | 8 + frontend/src/components/LifeTimeline.css | 44 +++++ frontend/src/components/LifeTimeline.jsx | 56 +++++++ frontend/src/components/PersonCard.jsx | 59 ++++++- frontend/src/data/mockData.js | 47 ++++-- frontend/src/i18n/en/fiche.js | 61 +++++++ frontend/src/utils/lifeTimeline.js | 197 +++++++++++++++++++++++ frontend/src/utils/lifeTimeline.test.js | 58 +++++++ 8 files changed, 518 insertions(+), 12 deletions(-) create mode 100644 frontend/src/components/LifeTimeline.css create mode 100644 frontend/src/components/LifeTimeline.jsx create mode 100644 frontend/src/utils/lifeTimeline.js create mode 100644 frontend/src/utils/lifeTimeline.test.js diff --git a/frontend/src/api/treeApi.js b/frontend/src/api/treeApi.js index e96f210..3d38e56 100644 --- a/frontend/src/api/treeApi.js +++ b/frontend/src/api/treeApi.js @@ -59,6 +59,14 @@ export async function fetchTreeGraph(treeId, token) { } } +// Frise de vie d'une personne : événements, précisions de date, lieux des unions +export async function fetchPersonLife(treeId, personId, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/life`, { + method: 'GET', + headers: { Authorization: `Bearer ${token}` }, + }) +} + export async function listTrees(token) { const data = await apiRequest('/trees', { method: 'GET', diff --git a/frontend/src/components/LifeTimeline.css b/frontend/src/components/LifeTimeline.css new file mode 100644 index 0000000..51994fb --- /dev/null +++ b/frontend/src/components/LifeTimeline.css @@ -0,0 +1,44 @@ +/* Onglet Vie de la fiche (direction A2 retenue le 16/10). Variables --pz-* : src/styles/pz.css */ + +.lt { padding: 2px 0 4px; } +.lt-rail { position: relative; list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } +.lt-rail::before { content: ""; position: absolute; left: 54px; top: 12px; bottom: 12px; width: 1px; background: var(--pz-line); } + +.lt-ev { position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 0 30px; padding: 8px 0; } +.lt-ev::after { + content: ""; position: absolute; left: 51px; top: 14px; width: 7px; height: 7px; border-radius: 50%; + background: var(--pz-surface); box-shadow: inset 0 0 0 1.5px var(--pz-a500); +} +.lt-year { font: 400 13.5px/1.35 var(--pz-sans); color: var(--pz-ink-2); font-variant-numeric: tabular-nums; text-align: right; padding-top: 1px; } +.lt-title { font: 400 14px/1.35 var(--pz-sans); color: var(--pz-ink); overflow-wrap: anywhere; } +.lt-meta { font: 400 13px/1.45 var(--pz-sans); color: var(--pz-muted); margin-top: 2px; } +.lt-note { font: 400 13px/1.5 var(--pz-sans); color: var(--pz-ink-2); margin: 4px 0 0; white-space: pre-line; } + +/* Grands repères : naissance, unions, décès */ +.lt-ev--mile { padding: 12px 0 10px; } +.lt-ev--mile::after { top: 19px; left: 50px; width: 9px; height: 9px; background: var(--pz-a500); } +.lt-ev--mile .lt-title { font: 400 21px/1.2 var(--pz-serif); letter-spacing: -.005em; } +.lt-ev--mile .lt-year { font-size: 14px; color: var(--pz-ink); padding-top: 6px; } + +/* Famille proche, en retrait */ +.lt-ev--fam::after { box-shadow: inset 0 0 0 1.5px var(--pz-line); } +.lt-ev--fam .lt-title { color: var(--pz-muted); } + +.lt-sources { margin-top: 3px; } +.lt-src { + appearance: none; border: 0; background: none; padding: 2px 0; cursor: pointer; + font: 500 12.5px var(--pz-sans); color: var(--pz-a700); text-underline-offset: 3px; +} +@media (hover: hover) and (pointer: fine) { .lt-src:hover { text-decoration: underline; } } +.lt-src:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; border-radius: 4px; } +.lt-src-list { + list-style: none; margin: 6px 0 0; padding: 8px 10px; display: grid; gap: 4px; + background: var(--pz-bg); border-radius: var(--pz-r-s); + font: 400 12.5px/1.5 var(--pz-sans); color: var(--pz-ink-2); + animation: lt-open 180ms var(--pz-ease) both; +} +@keyframes lt-open { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } } + +.lt-failed { margin-top: 10px; } + +@media (prefers-reduced-motion: reduce) { .lt-src-list { animation: none; } } diff --git a/frontend/src/components/LifeTimeline.jsx b/frontend/src/components/LifeTimeline.jsx new file mode 100644 index 0000000..67a2ca1 --- /dev/null +++ b/frontend/src/components/LifeTimeline.jsx @@ -0,0 +1,56 @@ +import { useState } from 'react' +import { t } from '../i18n/index.js' +import { buildLifeTimeline } from '../utils/lifeTimeline.js' +import './LifeTimeline.css' + +// Onglet Vie de la fiche : naissance, unions et décès en grands repères, les autres événements +// plus petits entre eux, la famille proche en retrait. Les sources restent repliées. +function Sources({ text }) { + const [open, setOpen] = useState(false) + const list = text.split('\n').map((s) => s.trim()).filter(Boolean) + if (list.length === 0) return null + return ( +
+ + {open && ( +
    + {list.map((source) =>
  • {source}
  • )} +
+ )} +
+ ) +} + +export default function LifeTimeline({ person, family, life, loading = false, failed = false }) { + const entries = buildLifeTimeline(person, family, life) + + if (entries.length === 0) { + return ( +
+

{t('Pas encore de date connue pour {name}.', { name: person.firstName })}

+

{t('Les dates de naissance, d’union et de décès, et celles de sa famille, apparaîtront ici.')}

+
+ ) + } + + return ( +
+
    + {entries.map((entry) => ( +
  1. + {entry.year ?? ''} +
    +
    {entry.title}
    + {entry.meta &&
    {entry.meta}
    } + {entry.note &&

    {entry.note}

    } + {entry.sources && } +
    +
  2. + ))} +
+ {failed &&

{t('Les autres événements n’ont pas pu être chargés.')}

} +
+ ) +} diff --git a/frontend/src/components/PersonCard.jsx b/frontend/src/components/PersonCard.jsx index 8b44272..8bb1aee 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -1,7 +1,9 @@ import { useState, useEffect, useRef, forwardRef } from 'react' import { createPortal } from 'react-dom' import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus, Sparkles, ChevronLeft, ChevronRight } from 'lucide-react' -import { getParents, getChildren, getPersonUnions, getPersonMedias, filiations, persons, unions } from '../data/mockData' +import { getParents, getChildren, getPersonUnions, getPersonMedias, getDemoLife, filiations, persons, unions } from '../data/mockData' +import { fetchPersonLife } from '../api/treeApi.js' +import LifeTimeline from './LifeTimeline.jsx' import { fetchImmichConfig } from '../api/immichApi.js' import GeoMediaThumbnail from './GeoMediaThumbnail' import ImmichFacePanel from './ImmichFacePanel.jsx' @@ -57,6 +59,28 @@ const PersonCard = ({ }) => { // Souvenirs d'abord quand il y en a, ou quand on peut en ajouter : c'est là qu'est le bouton const [tab, setTab] = useState(() => (getPersonMedias(person.id).length > 0 || canManageMedia ? 'medias' : 'infos')) + const [lifeState, setLifeState] = useState({ personId: null, data: null, loading: false, failed: false }) + + const lifeRequestedFor = useRef(null) + + useEffect(() => { + if (tab !== 'vie' || lifeRequestedFor.current === person.id) return undefined + lifeRequestedFor.current = person.id + if (!treeId || !immichToken) { + setLifeState({ personId: person.id, data: getDemoLife(person.id), loading: false, failed: false }) + return undefined + } + let cancelled = false + // Retour sur l'onglet : on garde la frise affichée pendant qu'elle se rafraîchit + setLifeState((prev) => (prev.personId === person.id && prev.data ? prev : { personId: person.id, data: null, loading: true, failed: false })) + fetchPersonLife(treeId, person.id, immichToken) + .then((data) => { if (!cancelled) setLifeState({ personId: person.id, data, loading: false, failed: false }) }) + .catch(() => { if (!cancelled) setLifeState({ personId: person.id, data: null, loading: false, failed: true }) }) + return () => { + cancelled = true + lifeRequestedFor.current = null + } + }, [tab, person.id, treeId, immichToken]) // État local pour les modifications en mode édition const [edits, setEdits] = useState({}) @@ -239,6 +263,25 @@ const PersonCard = ({ })() const personMedias = getPersonMedias(person.id) + // Frise de vie : la famille vient de l'arbre déjà chargé, les événements de la route /life, + // demandée seulement à l'ouverture de l'onglet (la démo a ses propres données) + const siblingsList = (() => { + const seen = new Map() + for (const parent of parentsList) { + for (const child of getChildren(parent.id)) if (child.id !== person.id) seen.set(child.id, child) + } + return [...seen.values()] + })() + const lifeFamily = { + parents: parentsList, + children: childrenList, + siblings: siblingsList, + unions: personUnions.map((union) => ({ + ...union, + partner: persons.find((p) => p.id === (union.partner1Id === person.id ? union.partner2Id : union.partner1Id)) || null, + })), + } + // Filter persons for relation search (exclude current person + already linked) const getFilteredPersonsForRelation = (relationType) => { const excludeIds = new Set([person.id]) @@ -498,6 +541,9 @@ const PersonCard = ({ + @@ -581,6 +627,17 @@ const PersonCard = ({ )} + {/* ── Vie ── */} + {tab === 'vie' && ( + + )} + {/* ── Infos ── */} {tab === 'infos' && (
diff --git a/frontend/src/data/mockData.js b/frontend/src/data/mockData.js index 6c3d1ba..3ccf6f9 100644 --- a/frontend/src/data/mockData.js +++ b/frontend/src/data/mockData.js @@ -8,17 +8,17 @@ import { buildMediaUrl } from '../utils/mediaToken.js' // Démo : noms et lieux restent français, les textes descriptifs sont traduits. export let persons = [ - { id: 1, firstName: 'Jean', lastName: 'Dupont', birthYear: 1890, deathYear: 1965, isAlive: false, photo: '/demo/jean.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Menuisier'), nationality: t('Française'), note: t('Patriarche de la famille') }, - { id: 2, firstName: 'Marie', lastName: 'Martin', birthYear: 1895, deathYear: 1970, isAlive: false, photo: '/demo/marie.webp', frameType: 'round', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Couturière'), note: t('Atelier de couture rue du Commerce') }, - { id: 3, firstName: 'Robert', lastName: 'Dupont', birthYear: 1920, deathYear: 1995, isAlive: false, photo: '/demo/robert.webp', frameType: 'rect', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Instituteur'), note: t("A enseigné 35 ans à l'école communale") }, - { id: 4, firstName: 'André', lastName: 'Dupont', birthYear: 1923, deathYear: 2000, isAlive: false, photo: '/demo/andre.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Charpentier') }, - { id: 5, firstName: 'Simone', lastName: 'Petit', birthYear: 1925, deathYear: 2010, isAlive: false, photo: '/demo/simone.webp', frameType: 'round', birthPlace: 'Guéret', region: 'Creuse', profession: t('Infirmière') }, - { id: 9, firstName: 'Isabelle', lastName: 'Bernard', birthYear: 1928, isAlive: true, photo: '/demo/isabelle.webp', frameType: 'rect', birthPlace: 'Fort-de-France', region: 'Martinique', profession: t('Sage-femme'), note: t('Doyenne de la famille, vit à Brive') }, - { id: 6, firstName: 'Jacques', lastName: 'Dupont', birthYear: 1945, deathYear: 2015, isAlive: false, photo: '/demo/jacques.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Journaliste'), note: t('Reporter au Populaire du Centre') }, - { id: 7, firstName: 'Philippe', lastName: 'Dupont', birthYear: 1948, isAlive: true, photo: '/demo/philippe.webp', frameType: 'round', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Pharmacien') }, - { id: 8, firstName: 'Sophie', lastName: 'Dupont', birthYear: 1960, isAlive: true, photo: '/demo/sophie.webp', frameType: 'rect', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Architecte'), note: t('Cabinet d’architecture à Bordeaux') }, - { id: 10, firstName: 'Thomas', lastName: 'Dupont', birthYear: 1962, isAlive: true, photo: '/demo/thomas.webp', frameType: 'polaroid', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Vétérinaire') }, - { id: 11, firstName: 'Claire', lastName: 'Dupont', birthYear: 1955, isAlive: true, photo: '/demo/claire.webp', birthPlace: 'Paris', region: 'Ile-de-France', profession: t('Enseignante') }, + { id: 1, firstName: 'Jean', sex: 'male', lastName: 'Dupont', birthYear: 1890, deathYear: 1965, isAlive: false, photo: '/demo/jean.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Menuisier'), nationality: t('Française'), note: t('Patriarche de la famille') }, + { id: 2, firstName: 'Marie', sex: 'female', lastName: 'Martin', birthYear: 1895, deathYear: 1970, isAlive: false, photo: '/demo/marie.webp', frameType: 'round', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Couturière'), note: t('Atelier de couture rue du Commerce') }, + { id: 3, firstName: 'Robert', sex: 'male', lastName: 'Dupont', birthYear: 1920, deathYear: 1995, isAlive: false, photo: '/demo/robert.webp', frameType: 'rect', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Instituteur'), note: t("A enseigné 35 ans à l'école communale") }, + { id: 4, firstName: 'André', sex: 'male', lastName: 'Dupont', birthYear: 1923, deathYear: 2000, isAlive: false, photo: '/demo/andre.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Charpentier') }, + { id: 5, firstName: 'Simone', sex: 'female', lastName: 'Petit', birthYear: 1925, deathYear: 2010, isAlive: false, photo: '/demo/simone.webp', frameType: 'round', birthPlace: 'Guéret', region: 'Creuse', profession: t('Infirmière') }, + { id: 9, firstName: 'Isabelle', sex: 'female', lastName: 'Bernard', birthYear: 1928, isAlive: true, photo: '/demo/isabelle.webp', frameType: 'rect', birthPlace: 'Fort-de-France', region: 'Martinique', profession: t('Sage-femme'), note: t('Doyenne de la famille, vit à Brive') }, + { id: 6, firstName: 'Jacques', sex: 'male', lastName: 'Dupont', birthYear: 1945, deathYear: 2015, isAlive: false, photo: '/demo/jacques.webp', frameType: 'polaroid', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Journaliste'), note: t('Reporter au Populaire du Centre') }, + { id: 7, firstName: 'Philippe', sex: 'male', lastName: 'Dupont', birthYear: 1948, isAlive: true, photo: '/demo/philippe.webp', frameType: 'round', birthPlace: 'Limoges', region: 'Haute-Vienne', profession: t('Pharmacien') }, + { id: 8, firstName: 'Sophie', sex: 'female', lastName: 'Dupont', birthYear: 1960, isAlive: true, photo: '/demo/sophie.webp', frameType: 'rect', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Architecte'), note: t('Cabinet d’architecture à Bordeaux') }, + { id: 10, firstName: 'Thomas', sex: 'male', lastName: 'Dupont', birthYear: 1962, isAlive: true, photo: '/demo/thomas.webp', frameType: 'polaroid', birthPlace: 'Brive-la-Gaillarde', region: 'Corrèze', profession: t('Vétérinaire') }, + { id: 11, firstName: 'Claire', sex: 'female', lastName: 'Dupont', birthYear: 1955, isAlive: true, photo: '/demo/claire.webp', birthPlace: 'Paris', region: 'Ile-de-France', profession: t('Enseignante') }, ] export let medias = [ @@ -114,11 +114,36 @@ function mapRemotePersonToLocal(person, current = null) { region: person?.region || null, profession: person?.profession || null, nationality: person?.nationality || null, + sex: person?.sex ?? current?.sex ?? null, photo: current?.photo || null, avatarFromImmich: person?.avatarFromImmich ?? false, } } +// Frise de vie de la démo (onglet Vie), au format de GET /trees/:id/persons/:personId/life. Personnes fictives. +const DEMO_LIFE = { + 3: { + person: { birthDatePrecision: null, deathPlace: 'Brive-la-Gaillarde', nickname: null }, + unions: [ + { id: 'u2', startDate: '1943-06-12', startPlace: 'Limoges', startDatePrecision: null }, + { id: 'u3', startDate: '1959-01-01', startPlace: 'Brive-la-Gaillarde', startDatePrecision: null }, + ], + events: [ + { id: 'd1', type: 'birth', sources: t('Registre des naissances de Limoges, acte n° 412') }, + { id: 'd2', type: 'baptism', date: '1920-03-21', place: 'Saint-Michel-des-Lions, Limoges' }, + { id: 'd3', type: 'education', date: '1938-01-01', dateEnd: '1940-01-01', datePrecision: 'from', description: t('École normale d’instituteurs'), place: 'Limoges' }, + { id: 'd4', type: 'military', date: '1940-01-01', dateEnd: '1942-01-01', datePrecision: 'between', notes: t('Affecté au 63e régiment d’infanterie.') }, + { id: 'd5', type: 'marriage', unionId: 'u2', sources: t('Registre des mariages de Limoges') }, + { id: 'd6', type: 'occupation', date: '1946-01-01', dateEnd: '1981-01-01', datePrecision: 'from', description: t('Instituteur à l’école communale'), place: 'Limoges' }, + { id: 'd7', type: 'retirement', date: '1981-01-01' }, + ], + }, +} + +export function getDemoLife(personId) { + return DEMO_LIFE[personId] || null +} + export function resetToDemoData() { persons = JSON.parse(JSON.stringify(INITIAL_PERSONS)) medias = JSON.parse(JSON.stringify(INITIAL_MEDIAS)) diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index d3777ea..84cb2fd 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -296,4 +296,65 @@ export default { 'A portrait is already in place. Linking this Immich person will replace the current portrait and delete its file.', 'Garder le portrait actuel': 'Keep the current portrait', 'Remplacer le portrait et associer': 'Replace the portrait and link', + // Onglet Vie (frise de vie) + '1 source': '1 source', + '{n} sources': '{n} sources', + 'Pas encore de date connue pour {name}.': 'No known dates for {name} yet.', + 'Les dates de naissance, d’union et de décès, et celles de sa famille, apparaîtront ici.': 'Dates of birth, marriage and death, and those of their family, will show up here.', + 'Les autres événements n’ont pas pu être chargés.': 'The other events could not be loaded.', + 'Vie': 'Life', + 'Registre des naissances de Limoges, acte n° 412': 'Limoges birth register, entry no. 412', + 'École normale d’instituteurs': 'Teacher training college', + 'Affecté au 63e régiment d’infanterie.': 'Assigned to the 63rd infantry regiment.', + 'Registre des mariages de Limoges': 'Limoges marriage register', + 'Instituteur à l’école communale': 'Teacher at the village school', + 'Baptême': 'Baptism', + 'Inhumation': 'Burial', + 'Crémation': 'Cremation', + 'Résidence': 'Residence', + 'Études': 'Education', + 'Religion': 'Religion', + 'Confirmation': 'Confirmation', + 'Première communion': 'First communion', + 'Bar-mitzvah': 'Bar mitzvah', + 'Bat-mitzvah': 'Bat mitzvah', + 'Ordination': 'Ordination', + 'Émigration': 'Emigration', + 'Immigration': 'Immigration', + 'Naturalisation': 'Naturalisation', + 'Recensement': 'Census', + 'Biens': 'Property', + 'Retraite': 'Retirement', + 'Testament': 'Will', + 'Succession': 'Probate', + 'Santé': 'Health', + 'Divorce': 'Divorce', + 'Demande de divorce': 'Divorce filed', + 'Annulation du mariage': 'Annulment', + 'Fiançailles': 'Engagement', + 'Bans du mariage': 'Marriage banns', + 'Contrat de mariage': 'Marriage contract', + 'Autorisation de mariage': 'Marriage licence', + 'Accord de mariage': 'Marriage settlement', + 'vers {year}': 'about {year}', + 'avant {year}': 'before {year}', + 'après {year}': 'after {year}', + 'entre {year} et {end}': 'between {year} and {end}', + 'jusqu’en {end}': 'until {end}', + 'jusqu’en {year}': 'until {year}', + 'Décès de son père {name}': 'Death of their father, {name}', + 'Décès de sa mère {name}': 'Death of their mother, {name}', + 'Décès de {name}, son parent': 'Death of {name}, a parent', + 'Naissance de son frère {name}': 'Birth of a brother, {name}', + 'Naissance de sa sœur {name}': 'Birth of a sister, {name}', + 'Naissance de {name}, sa fratrie': 'Birth of a sibling, {name}', + 'Naissance à {place}': 'Born in {place}', + 'Conjoint inconnu': 'Unknown partner', + 'Union avec {name}': 'Partnership with {name}', + 'Épouse {name}': 'Marries {name}', + 'Fin de l’union avec {name}': 'End of the relationship with {name}', + 'Décès de {name}': 'Death of {name}', + 'Événement': 'Event', + 'Naissance de {name}': 'Birth of {name}', + 'Décès à {place}': 'Died in {place}', } diff --git a/frontend/src/utils/lifeTimeline.js b/frontend/src/utils/lifeTimeline.js new file mode 100644 index 0000000..eaa924a --- /dev/null +++ b/frontend/src/utils/lifeTimeline.js @@ -0,0 +1,197 @@ +// Frise de vie d'une personne (onglet Vie de la fiche). +// +// Trois sources, rangées par date : la naissance, les unions et le décès, qui servent de grands repères ; +// les événements importés ou saisis (baptême, métiers, service militaire…) ; et la famille proche que +// l'arbre connaît déjà (naissance des enfants et des frères et sœurs, décès des parents, du conjoint, d'un +// enfant), limitée aux années où la personne a vécu. Une fiche sans aucun événement a donc déjà une frise. + +import { t, dateLocale } from '../i18n/index.js' +import { formatPlace } from './place.js' + +const EVENT_LABELS = { + baptism: t('Baptême'), + burial: t('Inhumation'), + cremation: t('Crémation'), + residence: t('Résidence'), + occupation: t('Métier'), + education: t('Études'), + graduation: t('Diplôme'), + degree: t('Diplôme'), + religion: t('Religion'), + confirmation: t('Confirmation'), + first_communion: t('Première communion'), + bar_mitzvah: t('Bar-mitzvah'), + bat_mitzvah: t('Bat-mitzvah'), + ordination: t('Ordination'), + adoption: t('Adoption'), + emigration: t('Émigration'), + immigration: t('Immigration'), + naturalization: t('Naturalisation'), + census: t('Recensement'), + title: t('Titre'), + property: t('Biens'), + retirement: t('Retraite'), + will: t('Testament'), + probate: t('Succession'), + military: t('Service militaire'), + medical: t('Santé'), + divorce: t('Divorce'), + divorce_filed: t('Demande de divorce'), + annulment: t('Annulation du mariage'), + engagement: t('Fiançailles'), + marriage_banns: t('Bans du mariage'), + marriage_contract: t('Contrat de mariage'), + marriage_license: t('Autorisation de mariage'), + marriage_settlement: t('Accord de mariage'), +} + +const yearOf = (value) => { + const match = String(value ?? '').match(/^(\d{4})/) + return match ? Number(match[1]) : null +} + +const fullName = (p) => [p?.firstName, p?.lastName].filter(Boolean).join(' ') + +// « 12 mars » pour une date complète, rien pour une année seule (stockée au 1er janvier) +function dayMonth(value) { + const match = String(value ?? '').match(/^(\d{4})-(\d{2})-(\d{2})/) + if (!match || (match[2] === '01' && match[3] === '01')) return '' + const date = new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))) + return date.toLocaleDateString(dateLocale, { day: 'numeric', month: 'long', timeZone: 'UTC' }) +} + +// La date telle qu'on la dit : « vers 1879 », « entre 1914 et 1918 », « jusqu'en 1981 » +export function describeDate(date, end, precision) { + const year = yearOf(date) + const endYear = yearOf(end) + if (!year) return '' + switch (precision) { + case 'about': + case 'estimated': + case 'calculated': + return t('vers {year}', { year }) + case 'before': return t('avant {year}', { year }) + case 'after': return t('après {year}', { year }) + case 'between': return endYear ? t('entre {year} et {end}', { year, end: endYear }) : t('après {year}', { year }) + case 'from': return endYear ? t('jusqu’en {end}', { end: endYear }) : t('depuis {year}', { year }) + case 'to': return t('jusqu’en {year}', { year }) + default: return dayMonth(date) + } +} + +const ageAt = (birthYear, year) => (birthYear && year && year > birthYear ? t('{age} ans', { age: year - birthYear }) : '') +const joinMeta = (...parts) => parts.filter(Boolean).join(' · ') + +const parentWord = (p) => { + if (p.sex === 'male' || p.sex === 'M') return t('Décès de son père {name}', { name: p.firstName }) + if (p.sex === 'female' || p.sex === 'F') return t('Décès de sa mère {name}', { name: p.firstName }) + return t('Décès de {name}, son parent', { name: p.firstName }) +} + +const siblingWord = (p) => { + if (p.sex === 'male' || p.sex === 'M') return t('Naissance de son frère {name}', { name: p.firstName }) + if (p.sex === 'female' || p.sex === 'F') return t('Naissance de sa sœur {name}', { name: p.firstName }) + return t('Naissance de {name}, sa fratrie', { name: p.firstName }) +} + +/** + * @param person personne de la fiche (birthDate, deathDate, birthPlace, birthYear, deathYear) + * @param family { parents, children, siblings, unions: [{ id, partner, startYear, endYear, unionType }] } + * @param life réponse de GET /trees/:id/persons/:personId/life, ou null tant qu'elle n'est pas là + * @returns entrées triées { key, year, kind: 'mile' | 'minor' | 'fam', title, meta, note, sources } + */ +export function buildLifeTimeline(person, family = {}, life = null) { + const details = life?.person || {} + const lifeUnions = new Map((life?.unions || []).map((u) => [String(u.id), u])) + const events = life?.events || [] + const birthYear = yearOf(person.birthDate) ?? person.birthYear ?? null + const deathYear = yearOf(person.deathDate) ?? person.deathYear ?? null + const lastYear = deathYear ?? new Date().getFullYear() + const within = (year) => year && (!birthYear || year >= birthYear) && year <= lastYear + const sourcesOf = (type, unionId = null) => events.find((e) => e.type === type && (unionId ? String(e.unionId) === String(unionId) : !e.unionId)) + const out = [] + + if (birthYear) { + const place = formatPlace(person.birthPlace || '') + const extra = sourcesOf('birth') + out.push({ + key: 'birth', year: birthYear, order: 0, kind: 'mile', + title: place ? t('Naissance à {place}', { place: place.split(',')[0] }) : t('Naissance'), + meta: describeDate(person.birthDate, details.birthDateEnd, details.birthDatePrecision), + note: extra?.notes || '', sources: extra?.sources || '', + }) + } + + for (const union of family.unions || []) { + const detail = lifeUnions.get(String(union.id)) || {} + const year = yearOf(detail.startDate) ?? union.startYear + const partnerName = union.partner ? fullName(union.partner) : t('Conjoint inconnu') + const place = formatPlace(detail.startPlace || '') + const extra = sourcesOf('marriage', union.id) + out.push({ + key: `union-${union.id}`, year, order: 2, kind: 'mile', + title: union.unionType === 'union' ? t('Union avec {name}', { name: partnerName }) : t('Épouse {name}', { name: partnerName }), + meta: joinMeta(place, detail.startDatePrecision ? describeDate(detail.startDate, null, detail.startDatePrecision) : '', ageAt(birthYear, year)), + note: extra?.notes || '', sources: extra?.sources || '', + }) + const hasEndEvent = events.some((e) => String(e.unionId) === String(union.id) && ['divorce', 'annulment'].includes(e.type)) + if (union.endYear && !hasEndEvent) { + out.push({ key: `union-end-${union.id}`, year: union.endYear, order: 3, kind: 'minor', title: t('Fin de l’union avec {name}', { name: union.partner?.firstName || partnerName }), meta: ageAt(birthYear, union.endYear) }) + } + if (union.partner && within(yearOf(union.partner.deathDate) ?? union.partner.deathYear)) { + const year2 = yearOf(union.partner.deathDate) ?? union.partner.deathYear + out.push({ key: `partner-death-${union.id}`, year: year2, order: 4, kind: 'fam', title: t('Décès de {name}', { name: union.partner.firstName }) }) + } + } + + for (const event of events) { + if (['birth', 'death', 'marriage'].includes(event.type)) continue + const year = yearOf(event.date) + let title = event.type === 'custom' ? (event.label || t('Événement')) : (EVENT_LABELS[event.type] || event.label || t('Événement')) + // Métier, études, diplôme, titre : la description dit déjà ce que c'est (« Instituteur », « École normale ») + if (['occupation', 'education', 'graduation', 'degree', 'title'].includes(event.type) && event.description) title = event.description + else if (event.description && event.type !== 'custom') title = `${title}, ${event.description}` + else if (event.type === 'custom' && event.description) title = `${title}, ${event.description}` + if (event.unionId) { + const union = (family.unions || []).find((u) => String(u.id) === String(event.unionId)) + if (union?.partner && ['divorce', 'annulment', 'engagement', 'marriage_contract'].includes(event.type)) title = `${title} (${union.partner.firstName})` + } + out.push({ + key: `event-${event.id}`, year, order: 1, kind: 'minor', title, + meta: joinMeta(formatPlace(event.place || ''), describeDate(event.date, event.dateEnd, event.datePrecision), ageAt(birthYear, year)), + note: event.notes || '', sources: event.sources || '', + }) + } + + for (const child of family.children || []) { + const year = yearOf(child.birthDate) ?? child.birthYear + if (within(year)) out.push({ key: `child-${child.id}`, year, order: 5, kind: 'fam', title: t('Naissance de {name}', { name: child.firstName }) }) + const death = yearOf(child.deathDate) ?? child.deathYear + if (within(death) && death !== deathYear) out.push({ key: `child-death-${child.id}`, year: death, order: 6, kind: 'fam', title: t('Décès de {name}', { name: child.firstName }) }) + } + for (const sibling of family.siblings || []) { + const year = yearOf(sibling.birthDate) ?? sibling.birthYear + if (within(year) && year !== birthYear) out.push({ key: `sibling-${sibling.id}`, year, order: 5, kind: 'fam', title: siblingWord(sibling) }) + } + for (const parent of family.parents || []) { + const year = yearOf(parent.deathDate) ?? parent.deathYear + if (within(year)) out.push({ key: `parent-death-${parent.id}`, year, order: 6, kind: 'fam', title: parentWord(parent) }) + } + + if (deathYear) { + const place = formatPlace(details.deathPlace || '') + const extra = sourcesOf('death') + out.push({ + key: 'death', year: deathYear, order: 9, kind: 'mile', + title: place ? t('Décès à {place}', { place: place.split(',')[0] }) : t('Décès'), + meta: joinMeta(describeDate(person.deathDate, details.deathDateEnd, details.deathDatePrecision), ageAt(birthYear, deathYear)), + note: extra?.notes || '', sources: extra?.sources || '', + }) + } + + // Les entrées sans date restent en bas, dans l'ordre où elles sont arrivées + return out + .map((entry, index) => ({ ...entry, index })) + .sort((a, b) => (a.year ?? Infinity) - (b.year ?? Infinity) || a.order - b.order || a.index - b.index) + .map(({ order, index, ...entry }) => entry) // eslint-disable-line no-unused-vars +} diff --git a/frontend/src/utils/lifeTimeline.test.js b/frontend/src/utils/lifeTimeline.test.js new file mode 100644 index 0000000..520217b --- /dev/null +++ b/frontend/src/utils/lifeTimeline.test.js @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { buildLifeTimeline, describeDate } from './lifeTimeline.js' + +const robert = { id: 3, firstName: 'Robert', birthYear: 1920, deathYear: 1995, birthDate: '1920-03-12', deathDate: '1995-05-01', birthPlace: 'Limoges,87085,Haute-Vienne,,France,' } +const simone = { id: 5, firstName: 'Simone', lastName: 'Petit', birthYear: 1925, deathYear: 2010 } +const family = { + parents: [{ id: 1, firstName: 'Jean', sex: 'male', deathYear: 1965 }, { id: 2, firstName: 'Marie', sex: 'female', deathYear: 2001 }], + children: [{ id: 6, firstName: 'Jacques', birthYear: 1945, deathYear: 2015 }], + siblings: [{ id: 4, firstName: 'André', sex: 'male', birthYear: 1923 }, { id: 9, firstName: 'Paul', sex: 'male', birthYear: 1915 }], + unions: [{ id: 'u2', partner: simone, startYear: 1943, endYear: 1958, unionType: 'mariage' }], +} +const life = { + person: { deathPlace: 'Brive-la-Gaillarde', birthDatePrecision: null }, + unions: [{ id: 'u2', startDate: '1943-06-12', startPlace: 'Limoges' }], + events: [ + { id: 'e1', type: 'birth', sources: 'Registre A\nRegistre B' }, + { id: 'e2', type: 'occupation', date: '1946-01-01', dateEnd: '1981-01-01', datePrecision: 'from', description: 'Instituteur' }, + { id: 'e3', type: 'custom', label: 'Militaire', date: '1940-01-01', dateEnd: '1942-01-01', datePrecision: 'between', notes: 'Verdun' }, + { id: 'e4', type: 'residence', place: 'Rue des Écoles' }, + ], +} + +describe('frise de vie', () => { + const entries = buildLifeTimeline(robert, family, life) + const titles = entries.map((e) => e.title) + + it('range tout par date, les entrées sans date en bas', () => { + expect(titles).toEqual([ + 'Naissance à Limoges', 'Naissance de son frère André', 'Militaire', 'Épouse Simone Petit', 'Naissance de Jacques', + 'Instituteur', 'Fin de l’union avec Simone', 'Décès de son père Jean', 'Décès à Brive-la-Gaillarde', 'Résidence', + ]) + }) + + it('grands repères, précisions, âge et sources', () => { + const birth = entries[0] + expect(birth).toMatchObject({ kind: 'mile', year: 1920, sources: 'Registre A\nRegistre B' }) + expect(entries.find((e) => e.title === 'Instituteur').meta).toBe('jusqu’en 1981 · 26 ans') + expect(entries.find((e) => e.title === 'Militaire')).toMatchObject({ kind: 'minor', meta: 'entre 1940 et 1942 · 20 ans', note: 'Verdun' }) + expect(entries.find((e) => e.title === 'Épouse Simone Petit')).toMatchObject({ kind: 'mile', meta: 'Limoges · 23 ans' }) + }) + + it('famille limitée à sa vie : frère aîné, mère morte après lui, enfant mort après lui écartés', () => { + expect(titles.join()).not.toMatch(/Paul|Marie|Décès de Jacques/) + }) + + it('sans données de la route, la famille et les repères suffisent', () => { + const bare = buildLifeTimeline({ id: 1, firstName: 'X', birthYear: 1900 }, { children: [{ id: 2, firstName: 'Y', birthYear: 1930 }] }, null) + expect(bare.map((e) => e.title)).toEqual(['Naissance', 'Naissance de Y']) + expect(buildLifeTimeline({ id: 1, firstName: 'X' }, {}, null)).toEqual([]) + }) + + it('dit les dates comme on les dit', () => { + expect(describeDate('1879-01-01', null, 'about')).toBe('vers 1879') + expect(describeDate('1879-01-01', null, 'before')).toBe('avant 1879') + expect(describeDate('1920-03-12', null, null)).toBe('12 mars') + expect(describeDate('1920-01-01', null, null)).toBe('') + }) +}) From cd147e93877949ed9f625e83b5732f0980d6f486 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Sat, 17 Oct 2026 11:23:35 +0200 Subject: [PATCH 2/3] fix(vie): le fil s'arrete au dernier evenement Co-Authored-By: Claude Opus 5.5 --- frontend/src/components/LifeTimeline.css | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/LifeTimeline.css b/frontend/src/components/LifeTimeline.css index 51994fb..6571d95 100644 --- a/frontend/src/components/LifeTimeline.css +++ b/frontend/src/components/LifeTimeline.css @@ -2,9 +2,13 @@ .lt { padding: 2px 0 4px; } .lt-rail { position: relative; list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } -.lt-rail::before { content: ""; position: absolute; left: 54px; top: 12px; bottom: 12px; width: 1px; background: var(--pz-line); } +/* Le fil : un segment par entrée, du premier point au dernier (il s'arrête au décès) */ -.lt-ev { position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 0 30px; padding: 8px 0; } +.lt-ev { --dot-y: 17.5px; position: relative; display: grid; grid-template-columns: 40px minmax(0, 1fr); gap: 0 30px; padding: 8px 0; } +.lt-ev::before { content: ""; position: absolute; left: 54px; top: 0; bottom: -2px; width: 1px; background: var(--pz-line); } +.lt-ev:first-child::before { top: var(--dot-y); } +.lt-ev:last-child::before { bottom: auto; height: var(--dot-y); } +.lt-ev:only-child::before { display: none; } .lt-ev::after { content: ""; position: absolute; left: 51px; top: 14px; width: 7px; height: 7px; border-radius: 50%; background: var(--pz-surface); box-shadow: inset 0 0 0 1.5px var(--pz-a500); @@ -15,7 +19,7 @@ .lt-note { font: 400 13px/1.5 var(--pz-sans); color: var(--pz-ink-2); margin: 4px 0 0; white-space: pre-line; } /* Grands repères : naissance, unions, décès */ -.lt-ev--mile { padding: 12px 0 10px; } +.lt-ev--mile { --dot-y: 23.5px; padding: 12px 0 10px; } .lt-ev--mile::after { top: 19px; left: 50px; width: 9px; height: 9px; background: var(--pz-a500); } .lt-ev--mile .lt-title { font: 400 21px/1.2 var(--pz-serif); letter-spacing: -.005em; } .lt-ev--mile .lt-year { font-size: 14px; color: var(--pz-ink); padding-top: 6px; } From 9d34796d11728586514e53bdbe69eacf63048804 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Sat, 17 Oct 2026 11:38:35 +0200 Subject: [PATCH 3/3] feat(vie): ajouter, modifier et supprimer un moment depuis l'onglet Vie MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Un bouton « Ajouter un moment » pour les administrateurs, une fiche courte (quoi, quand, environ, ou, une photo), date exacte, fin, source et note sous « Plus de details ». La photo devient un souvenir de la personne, rattache au moment (life_events.mediaId, migration additive). Toucher un moment l'ouvre pour le modifier ou le supprimer. Co-Authored-By: Claude Opus 5.5 --- .../20261017_001_moment_photo/migration.sql | 2 + backend/prisma/schema.prisma | 1 + backend/src/routes/graph.ts | 2 +- backend/src/routes/trees.ts | 121 ++++++++++ backend/test/api-routes.test.ts | 53 +++++ frontend/src/App.jsx | 1 + frontend/src/api/treeApi.js | 24 ++ frontend/src/components/LifeTimeline.css | 16 ++ frontend/src/components/LifeTimeline.jsx | 23 +- frontend/src/components/MomentSheet.css | 45 ++++ frontend/src/components/MomentSheet.jsx | 224 ++++++++++++++++++ frontend/src/components/PersonCard.jsx | 28 ++- frontend/src/hooks/useMediaManager.js | 29 +++ frontend/src/i18n/en/fiche.js | 25 ++ frontend/src/utils/lifeTimeline.js | 19 +- 15 files changed, 604 insertions(+), 9 deletions(-) create mode 100644 backend/prisma/migrations/20261017_001_moment_photo/migration.sql create mode 100644 frontend/src/components/MomentSheet.css create mode 100644 frontend/src/components/MomentSheet.jsx diff --git a/backend/prisma/migrations/20261017_001_moment_photo/migration.sql b/backend/prisma/migrations/20261017_001_moment_photo/migration.sql new file mode 100644 index 0000000..1557622 --- /dev/null +++ b/backend/prisma/migrations/20261017_001_moment_photo/migration.sql @@ -0,0 +1,2 @@ +-- Photo rattachée à un événement de vie (souvenir de la personne), facultative +ALTER TABLE "life_events" ADD COLUMN "mediaId" TEXT; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 43660a1..aaa17fc 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -424,6 +424,7 @@ model LifeEvent { description String? notes String? sources String? + mediaId String? displayOrder Int @default(1) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/backend/src/routes/graph.ts b/backend/src/routes/graph.ts index a4c9e2e..8b7364e 100644 --- a/backend/src/routes/graph.ts +++ b/backend/src/routes/graph.ts @@ -203,7 +203,7 @@ export const graphRoutes: FastifyPluginAsync = async (app) => { 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, + dateText: true, place: true, description: true, notes: true, sources: true, mediaId: true, displayOrder: true, }, orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }, { createdAt: 'asc' }], }) diff --git a/backend/src/routes/trees.ts b/backend/src/routes/trees.ts index 86c8eb2..31278aa 100644 --- a/backend/src/routes/trees.ts +++ b/backend/src/routes/trees.ts @@ -156,6 +156,49 @@ const patchParentChildLinkSchema = z message: 'at_least_one_field_required', }) +// Événements de vie saisis dans l'onglet Vie (« Ajouter un moment »). Naissance, décès et mariage gardent +// leur date sur la personne ou l'union et ne passent pas par ici. +const LIFE_EVENT_PRECISIONS = ['about', 'estimated', 'calculated', 'before', 'after', 'between', 'from', 'to', 'interpreted'] as const +const RESERVED_LIFE_EVENT_TYPES = new Set(['birth', 'death', 'marriage']) +const lifeEventDateRegex = /^\d{4}(-\d{2}-\d{2})?$/ +const lifeEventPayloadSchema = z.object({ + type: z.string().trim().min(1).max(40).regex(/^[a-z_]+$/).refine((type) => !RESERVED_LIFE_EVENT_TYPES.has(type)).default('custom'), + label: z.string().trim().max(120).nullable().optional(), + description: z.string().trim().max(1000).nullable().optional(), + date: z.string().regex(lifeEventDateRegex).nullable().optional(), + dateEnd: z.string().regex(lifeEventDateRegex).nullable().optional(), + datePrecision: z.enum(LIFE_EVENT_PRECISIONS).nullable().optional(), + place: z.string().trim().max(300).nullable().optional(), + notes: z.string().trim().max(4000).nullable().optional(), + sources: z.string().trim().max(4000).nullable().optional(), + mediaId: z.string().min(1).nullable().optional(), +}) +const lifeEventParamsSchema = z.object({ id: z.string().min(1), eventId: z.string().min(1) }) + +const lifeEventDate = (value: string | null | undefined) => { + if (value === undefined) return undefined + if (!value) return null + return new Date(`${value.length === 4 ? `${value}-01-01` : value}T00:00:00.000Z`) +} +const emptyToNull = (value: string | null | undefined) => (value === undefined ? undefined : value?.trim() ? value.trim() : null) + +function lifeEventData(payload: z.infer) { + return { + type: payload.type, + label: emptyToNull(payload.label), + description: emptyToNull(payload.description), + date: lifeEventDate(payload.date), + dateEnd: lifeEventDate(payload.dateEnd), + datePrecision: payload.datePrecision, + // Saisi dans l'app : pas de texte GEDCOM d'origine à garder + dateText: null, + place: emptyToNull(payload.place), + notes: emptyToNull(payload.notes), + sources: emptyToNull(payload.sources), + mediaId: payload.mediaId, + } +} + const personParamsSchema = z.object({ id: z.string().min(1), personId: z.string().min(1), @@ -2006,6 +2049,84 @@ export const treeRoutes: FastifyPluginAsync = async (app) => { }) // Réordonner une fratrie : displayOrder des liens parent-enfant réécrit en une transaction + // Photo rattachée : un souvenir de cette personne, dans cet arbre + const checkLifeEventMedia = async (treeId: string, personId: string, mediaId: string | null | undefined) => { + if (!mediaId) return true + const media = await app.prisma.mediaItem.findFirst({ where: { id: mediaId, treeId, personId, deletedAt: null }, select: { id: true } }) + return Boolean(media) + } + + app.post('/trees/:id/persons/:personId/life/events', async (request, reply) => { + const user = requireUser(request, reply) + if (!user) return + const params = personParamsSchema.safeParse(request.params) + if (!params.success) return reply.code(400).send({ error: 'invalid_params' }) + const payload = lifeEventPayloadSchema.safeParse(request.body ?? {}) + if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() }) + if (!payload.data.label?.trim() && !payload.data.description?.trim() && payload.data.type === 'custom') { + return reply.code(400).send({ error: 'invalid_payload' }) + } + + const membership = await getAdminMembership(app, user.userId, params.data.id) + if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' }) + + const person = await app.prisma.person.findFirst({ where: { id: params.data.personId, treeId: params.data.id, deletedAt: null }, select: { id: true } }) + if (!person) return reply.code(404).send({ error: 'person_not_found' }) + if (!(await checkLifeEventMedia(params.data.id, params.data.personId, payload.data.mediaId))) { + return reply.code(400).send({ error: 'invalid_media_reference' }) + } + + const event = await app.prisma.lifeEvent.create({ + data: { treeId: params.data.id, personId: params.data.personId, ...lifeEventData(payload.data) }, + }) + return reply.code(201).send({ event: { id: event.id } }) + }) + + app.patch('/trees/:id/life/events/:eventId', async (request, reply) => { + const user = requireUser(request, reply) + if (!user) return + const params = lifeEventParamsSchema.safeParse(request.params) + if (!params.success) return reply.code(400).send({ error: 'invalid_params' }) + const payload = lifeEventPayloadSchema.partial().safeParse(request.body ?? {}) + if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() }) + + const membership = await getAdminMembership(app, user.userId, params.data.id) + if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' }) + + const existing = await app.prisma.lifeEvent.findFirst({ + where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null }, + select: { personId: true, type: true }, + }) + if (!existing || !existing.personId || RESERVED_LIFE_EVENT_TYPES.has(existing.type)) { + return reply.code(404).send({ error: 'event_not_found' }) + } + if (!(await checkLifeEventMedia(params.data.id, existing.personId, payload.data.mediaId))) { + return reply.code(400).send({ error: 'invalid_media_reference' }) + } + + // Le type ne change pas après coup (le schéma partiel remettrait sa valeur par défaut) + const data = lifeEventData({ ...payload.data, type: existing.type } as z.infer) + await app.prisma.lifeEvent.update({ where: { id: params.data.eventId }, data }) + return reply.send({ ok: true }) + }) + + app.delete('/trees/:id/life/events/:eventId', async (request, reply) => { + const user = requireUser(request, reply) + if (!user) return + const params = lifeEventParamsSchema.safeParse(request.params) + if (!params.success) return reply.code(400).send({ error: 'invalid_params' }) + + const membership = await getAdminMembership(app, user.userId, params.data.id) + if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' }) + + const deleted = await app.prisma.lifeEvent.updateMany({ + where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null, personId: { not: null }, type: { notIn: [...RESERVED_LIFE_EVENT_TYPES] } }, + data: { deletedAt: new Date() }, + }) + if (deleted.count === 0) return reply.code(404).send({ error: 'event_not_found' }) + return reply.code(204).send() + }) + app.put('/trees/:id/links/order', async (request, reply) => { const user = requireUser(request, reply) if (!user) { diff --git a/backend/test/api-routes.test.ts b/backend/test/api-routes.test.ts index 23fbdfd..ad29829 100644 --- a/backend/test/api-routes.test.ts +++ b/backend/test/api-routes.test.ts @@ -71,6 +71,9 @@ const { prismaMock } = vi.hoisted(() => ({ updateMany: vi.fn(), }, lifeEvent: { + findFirst: vi.fn(), + create: vi.fn(), + update: vi.fn(), findMany: vi.fn().mockResolvedValue([]), createMany: vi.fn().mockResolvedValue({ count: 0 }), updateMany: vi.fn().mockResolvedValue({ count: 0 }), @@ -628,6 +631,56 @@ describe('Graph routes', () => { }) }) +describe('Événements de vie saisis dans l’onglet Vie', () => { + it('un admin ajoute un moment avec sa photo, le modifie sans changer son type, le supprime', async () => { + const app = createApp() + const token = await createUserToken(app) + const auth = { authorization: `Bearer ${token}` } + prismaMock.mediaItem.findFirst.mockResolvedValue({ id: 'm-1' }) + prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-1' }) + + const created = await app.inject({ + method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, + payload: { label: 'Service militaire', date: '1940', datePrecision: 'about', place: 'Limoges', mediaId: 'm-1' }, + }) + expect(created.statusCode).toBe(201) + expect(prismaMock.lifeEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ + treeId: 'tree-1', personId: 'person-1', type: 'custom', label: 'Service militaire', + date: new Date('1940-01-01T00:00:00.000Z'), datePrecision: 'about', place: 'Limoges', mediaId: 'm-1', + }) }) + + prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', type: 'occupation' }) + const patched = await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: '' } }) + expect(patched.statusCode).toBe(200) + expect(prismaMock.lifeEvent.update).toHaveBeenCalledWith({ where: { id: 'e-1' }, data: expect.objectContaining({ type: 'occupation', place: null }) }) + + prismaMock.lifeEvent.updateMany.mockResolvedValue({ count: 1 }) + const deleted = await app.inject({ method: 'DELETE', url: '/trees/tree-1/life/events/e-1', headers: auth }) + expect(deleted.statusCode).toBe(204) + await app.close() + }) + + it('refuse un membre non admin, une photo d’une autre personne, un moment sans titre, une naissance', async () => { + const app = createApp() + const token = await createUserToken(app) + const auth = { authorization: `Bearer ${token}` } + const post = (payload: object) => app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload }) + + prismaMock.mediaItem.findFirst.mockResolvedValue(null) + expect((await post({ label: 'Mariage', mediaId: 'autre' })).statusCode).toBe(400) + expect((await post({ label: ' ' })).statusCode).toBe(400) + expect((await post({ type: 'birth', label: 'Naissance' })).statusCode).toBe(400) + + prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', type: 'birth' }) + expect((await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: 'x' } })).statusCode).toBe(404) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ role: 'member', tree: { deletedAt: null } }) + expect((await post({ label: 'Service militaire' })).statusCode).toBe(403) + expect(prismaMock.lifeEvent.create).not.toHaveBeenCalled() + await app.close() + }) +}) + describe('Visit log', () => { it('refuses the visit log to a non-admin member', async () => { const app = createApp() diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 3158aff..e9a6323 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -2966,6 +2966,7 @@ function App() { relationActionError={relationFeedback.error} siblingPlace={siblingPlace} onMoveSibling={(delta) => galaxyZoomApiRef.current?.moveSibling?.(tree.selectedPerson.id, delta)} + onUploadMomentPhoto={tree.canEditCurrentTree ? media.uploadMomentPhoto : undefined} /> )} {tree.selectedMedia && ( diff --git a/frontend/src/api/treeApi.js b/frontend/src/api/treeApi.js index 3d38e56..8ad1ad0 100644 --- a/frontend/src/api/treeApi.js +++ b/frontend/src/api/treeApi.js @@ -67,6 +67,30 @@ export async function fetchPersonLife(treeId, personId, token) { }) } +// Moments saisis dans l'onglet Vie (administrateurs) +export async function createLifeEvent(treeId, personId, payload, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/life/events`, { + method: 'POST', + headers: { Authorization: `Bearer ${token}` }, + body: JSON.stringify(payload), + }) +} + +export async function updateLifeEvent(treeId, eventId, payload, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/life/events/${encodeURIComponent(eventId)}`, { + method: 'PATCH', + headers: { Authorization: `Bearer ${token}` }, + body: JSON.stringify(payload), + }) +} + +export async function deleteLifeEvent(treeId, eventId, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/life/events/${encodeURIComponent(eventId)}`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${token}` }, + }) +} + export async function listTrees(token) { const data = await apiRequest('/trees', { method: 'GET', diff --git a/frontend/src/components/LifeTimeline.css b/frontend/src/components/LifeTimeline.css index 6571d95..09b8212 100644 --- a/frontend/src/components/LifeTimeline.css +++ b/frontend/src/components/LifeTimeline.css @@ -46,3 +46,19 @@ .lt-failed { margin-top: 10px; } @media (prefers-reduced-motion: reduce) { .lt-src-list { animation: none; } } + +/* Moment modifiable (administrateurs) : le titre s'ouvre en fiche */ +.lt-title--edit { + appearance: none; border: 0; background: none; padding: 0; margin: 0; text-align: left; cursor: pointer; + font: inherit; color: inherit; border-radius: 4px; text-decoration: underline; text-decoration-color: transparent; + text-underline-offset: 3px; transition: text-decoration-color 160ms ease; +} +@media (hover: hover) and (pointer: fine) { .lt-title--edit:hover { text-decoration-color: var(--pz-a300); } } +.lt-title--edit:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; } + +.lt-photo { + display: block; width: 112px; height: 84px; object-fit: cover; margin-top: 8px; + border-radius: var(--pz-r-s); box-shadow: 0 0 0 1px rgba(42, 38, 34, .06); +} +.lt-add { margin-top: 14px; } +.pc-empty .lt-add { margin-top: 12px; } diff --git a/frontend/src/components/LifeTimeline.jsx b/frontend/src/components/LifeTimeline.jsx index 67a2ca1..a566834 100644 --- a/frontend/src/components/LifeTimeline.jsx +++ b/frontend/src/components/LifeTimeline.jsx @@ -1,4 +1,5 @@ import { useState } from 'react' +import { Plus } from 'lucide-react' import { t } from '../i18n/index.js' import { buildLifeTimeline } from '../utils/lifeTimeline.js' import './LifeTimeline.css' @@ -23,14 +24,22 @@ function Sources({ text }) { ) } -export default function LifeTimeline({ person, family, life, loading = false, failed = false }) { +export default function LifeTimeline({ person, family, life, loading = false, failed = false, medias = [], canEdit = false, onAdd, onEdit }) { const entries = buildLifeTimeline(person, family, life) + const mediaById = new Map(medias.map((m) => [String(m.id), m])) + const addButton = canEdit && ( + + ) if (entries.length === 0) { return (

{t('Pas encore de date connue pour {name}.', { name: person.firstName })}

{t('Les dates de naissance, d’union et de décès, et celles de sa famille, apparaîtront ici.')}

+ {addButton}
) } @@ -42,15 +51,25 @@ export default function LifeTimeline({ person, family, life, loading = false, fa
  • {entry.year ?? ''}
    -
    {entry.title}
    + {canEdit && entry.event ? ( + + ) : ( +
    {entry.title}
    + )} {entry.meta &&
    {entry.meta}
    } {entry.note &&

    {entry.note}

    } {entry.sources && } + {entry.mediaId && mediaById.get(String(entry.mediaId))?.url && ( + {entry.title} + )}
  • ))} {failed &&

    {t('Les autres événements n’ont pas pu être chargés.')}

    } + {addButton}
    ) } diff --git a/frontend/src/components/MomentSheet.css b/frontend/src/components/MomentSheet.css new file mode 100644 index 0000000..6b484d3 --- /dev/null +++ b/frontend/src/components/MomentSheet.css @@ -0,0 +1,45 @@ +/* Fiche « Ajouter un moment » de l'onglet Vie. Variables --pz-* : src/styles/pz.css */ + +.ms { width: min(100%, 460px); } +.ms-title { font-size: 26px; } +.ms-form { display: grid; gap: 16px; } +.ms-optional { font-weight: 400; color: var(--pz-faint); margin-left: 4px; } + +.ms-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.ms-chip { + appearance: none; border: 1px solid var(--pz-line); background: var(--pz-surface); border-radius: 999px; + padding: 5px 11px; font: 500 12.5px var(--pz-sans); color: var(--pz-ink-2); cursor: pointer; + transition: background-color 160ms ease, border-color 160ms ease, transform 140ms var(--pz-ease); +} +@media (hover: hover) and (pointer: fine) { .ms-chip:hover { border-color: var(--pz-a300); } } +.ms-chip:active { transform: scale(.97); } +.ms-chip.is-on { background: var(--pz-a50); border-color: var(--pz-a300); color: var(--pz-a700); } +.ms-chip:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; } + +.ms-row { display: flex; gap: 12px; align-items: flex-end; flex-wrap: wrap; } +.ms-row > .pz-field { flex: 1 1 150px; min-width: 0; } +.ms-row > .ms-year { flex: 0 1 120px; } +.ms-check { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; font: 400 14px var(--pz-sans); color: var(--pz-ink-2); cursor: pointer; } +.ms-check input { width: 16px; height: 16px; accent-color: var(--pz-a500); } + +.ms-photo-add { + display: inline-flex; align-items: center; gap: 8px; min-height: 40px; padding: 0 14px; + border: 1.5px dashed var(--pz-a300); border-radius: 999px; background: var(--pz-a50); + font: 500 13.5px var(--pz-sans); color: var(--pz-a700); cursor: pointer; + transition: background-color 160ms ease, transform 140ms var(--pz-ease); +} +@media (hover: hover) and (pointer: fine) { .ms-photo-add:hover { background: var(--pz-a100); } } +.ms-photo-add:active { transform: scale(.97); } +.ms-photo-current { display: flex; align-items: center; gap: 12px; } +.ms-photo-current img { width: 84px; height: 64px; object-fit: cover; border-radius: var(--pz-r-s); box-shadow: 0 0 0 1px rgba(42, 38, 34, .06); } + +.ms-more { border-top: 1px solid var(--pz-line-soft); padding-top: 12px; } +.ms-more summary { cursor: pointer; font: 500 13.5px var(--pz-sans); color: var(--pz-ink-2); list-style-position: inside; } +.ms-more summary:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 2px; border-radius: 4px; } +.ms-more-body { display: grid; gap: 14px; margin-top: 12px; } + +.ms-actions-end { display: flex; gap: 8px; margin-left: auto; } +.ms-confirm { display: flex; gap: 8px; } +.pz-btn.ms-delete { color: var(--pz-danger); padding-left: 0; } + +@media (prefers-reduced-motion: reduce) { .ms-chip, .ms-photo-add { transition: none; } } diff --git a/frontend/src/components/MomentSheet.jsx b/frontend/src/components/MomentSheet.jsx new file mode 100644 index 0000000..548955d --- /dev/null +++ b/frontend/src/components/MomentSheet.jsx @@ -0,0 +1,224 @@ +import { useEffect, useRef, useState } from 'react' +import { createPortal } from 'react-dom' +import { X, ImagePlus } from 'lucide-react' +import { t } from '../i18n/index.js' +import { createLifeEvent, updateLifeEvent, deleteLifeEvent } from '../api/treeApi.js' +import { DESCRIBED_TYPES, eventTitle } from '../utils/lifeTimeline.js' +import './MomentSheet.css' + +// Fiche « Ajouter un moment » de l'onglet Vie : quoi, quand, où, une photo. La date exacte, la fin, +// la source et la note restent dans « Plus de détails ». Sert aussi à modifier un moment existant. + +// Suggestions touchables : le texte exact devient le type correspondant (exporté en GEDCOM sous sa balise) +const SUGGESTIONS = [ + { label: t('Baptême'), type: 'baptism' }, + { label: t('Déménagement'), type: 'residence' }, + { label: t('Diplôme'), type: 'graduation' }, + { label: t('Service militaire'), type: 'military' }, + { label: t('Retraite'), type: 'retirement' }, +] + +const yearOf = (value) => String(value ?? '').match(/^(\d{4})/)?.[1] || '' +const exactDay = (value) => (/^\d{4}-\d{2}-\d{2}$/.test(String(value ?? '')) && !String(value).endsWith('-01-01') ? value : '') + +export default function MomentSheet({ person, event = null, treeId, token, medias = [], onUploadPhoto, onClose, onSaved }) { + const editing = Boolean(event) + const [what, setWhat] = useState(() => (event ? eventTitle(event) : '')) + const [year, setYear] = useState(() => yearOf(event?.date)) + const [approx, setApprox] = useState(() => ['about', 'estimated', 'calculated', 'between'].includes(event?.datePrecision)) + const [place, setPlace] = useState(event?.place || '') + const [day, setDay] = useState(() => exactDay(event?.date)) + const [endYear, setEndYear] = useState(() => yearOf(event?.dateEnd)) + const [sources, setSources] = useState(event?.sources || '') + const [notes, setNotes] = useState(event?.notes || '') + const [mediaId, setMediaId] = useState(event?.mediaId || null) + const [file, setFile] = useState(null) + const [preview, setPreview] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const [confirmDelete, setConfirmDelete] = useState(false) + const whatRef = useRef(null) + const fileRef = useRef(null) + const hasDetails = Boolean(day || endYear || sources || notes) + + useEffect(() => { whatRef.current?.focus() }, []) + useEffect(() => { + const onKey = (e) => { if (e.key === 'Escape' && !busy) onClose() } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [busy, onClose]) + useEffect(() => { + if (!file) { setPreview(''); return undefined } + const url = URL.createObjectURL(file) + setPreview(url) + return () => URL.revokeObjectURL(url) + }, [file]) + + const linkedMedia = mediaId ? medias.find((m) => String(m.id) === String(mediaId)) : null + const yearValid = !year || /^\d{4}$/.test(year) + const endValid = !endYear || (/^\d{4}$/.test(endYear) && (!year || Number(endYear) >= Number(year))) + const canSave = what.trim().length > 0 && yearValid && endValid && !busy + + const buildPayload = (photoId) => { + const text = what.trim() + const suggestion = SUGGESTIONS.find((s) => s.label.toLowerCase() === text.toLowerCase()) + const type = editing ? event.type : (suggestion?.type || 'custom') + const textField = DESCRIBED_TYPES.includes(type) ? 'description' : 'label' + // Une suggestion reprise telle quelle n'a pas besoin de libellé : le type suffit + const textValue = !editing && suggestion ? null : text + const start = day || year || null + let datePrecision = null + if (start && endYear) datePrecision = approx ? 'between' : 'from' + else if (start && approx && !day) datePrecision = 'about' + return { + ...(editing ? {} : { type }), + [textField]: textValue, + ...(textField === 'description' ? { label: null } : {}), + date: start, + dateEnd: start && endYear ? endYear : null, + datePrecision, + place: place.trim() || null, + sources: sources.trim() || null, + notes: notes.trim() || null, + mediaId: photoId, + } + } + + const save = async () => { + if (!canSave) return + setBusy(true) + setError('') + try { + let photoId = mediaId + if (file && onUploadPhoto) { + const created = await onUploadPhoto(person.id, file, [what.trim(), year].filter(Boolean).join(', ')) + photoId = created?.id || null + } + const payload = buildPayload(photoId) + if (editing) await updateLifeEvent(treeId, event.id, payload, token) + else await createLifeEvent(treeId, person.id, payload, token) + onSaved() + } catch (err) { + setError(err?.message && !/^request_failed|^invalid_/.test(err.message) ? err.message : t('L’enregistrement n’a pas abouti. Réessayez dans un instant.')) + setBusy(false) + } + } + + const remove = async () => { + setBusy(true) + setError('') + try { + await deleteLifeEvent(treeId, event.id, token) + onSaved() + } catch { + setError(t('La suppression n’a pas abouti. Réessayez dans un instant.')) + setBusy(false) + } + } + + return createPortal( +
    { if (e.target === e.currentTarget && !busy) onClose() }}> +
    + +
    +

    + {editing ? t('Modifier ce moment') : t('Ajouter à la vie de {name}', { name: person.firstName })} +

    +
    + +
    { e.preventDefault(); save() }}> +
    + + setWhat(e.target.value)} placeholder={t('Service militaire, premier emploi, départ pour Paris…')} /> + {!editing && ( +
    + {SUGGESTIONS.map((s) => ( + + ))} +
    + )} +
    + +
    +
    + + setYear(e.target.value.replace(/\D/g, ''))} placeholder={t('Année')} aria-invalid={!yearValid || undefined} disabled={Boolean(day)} /> +
    + +
    + +
    + + setPlace(e.target.value)} placeholder={t('Ville ou adresse')} /> +
    + +
    + {(preview || linkedMedia?.url) ? ( +
    + + +
    + ) : onUploadPhoto && ( + + )} + { setFile(e.target.files?.[0] || null); e.target.value = '' }} /> +
    + +
    + {t('Plus de détails')} +
    +
    +
    + + { setDay(e.target.value); if (e.target.value) setYear(e.target.value.slice(0, 4)) }} /> +
    +
    + + setEndYear(e.target.value.replace(/\D/g, ''))} placeholder={t('Année')} aria-invalid={!endValid || undefined} /> +
    +
    +
    + +