diff --git a/apps/app/src/animals/age.ts b/apps/app/src/animals/age.ts
new file mode 100644
index 00000000..6e0ca5c6
--- /dev/null
+++ b/apps/app/src/animals/age.ts
@@ -0,0 +1,29 @@
+/**
+ * The age shown on an animal's page, for display only (contract §5.2): from
+ * the full date when known, else « environ N ans » from the year. Nothing is
+ * stored or sent.
+ */
+export interface AnimalAge {
+ unit: 'year' | 'month'
+ count: number
+ /** From the year alone: the day is unknown. */
+ about: boolean
+}
+
+export function animalAge(
+ birthYear: number | null,
+ birthDate: string | null,
+ today: string,
+): AnimalAge | null {
+ const [ty, tm, td] = today.split('-').map(Number)
+ if (birthDate) {
+ const [by, bm, bd] = birthDate.split('-').map(Number)
+ const months = (ty - by) * 12 + (tm - bm) - (td < bd ? 1 : 0)
+ if (months < 0) return null
+ return months >= 12
+ ? { unit: 'year', count: Math.floor(months / 12), about: false }
+ : { unit: 'month', count: months, about: false }
+ }
+ if (birthYear === null || birthYear > ty) return null
+ return { unit: 'year', count: ty - birthYear, about: true }
+}
diff --git a/apps/app/src/animals/species.tsx b/apps/app/src/animals/species.tsx
new file mode 100644
index 00000000..0c445b4c
--- /dev/null
+++ b/apps/app/src/animals/species.tsx
@@ -0,0 +1,100 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from 'react'
+import {
+ classifyRecordError,
+ fetchSpeciesLabels,
+ type RecordFailureKind,
+ type SpeciesLabel,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
+import type { Locale } from '@/i18n/types'
+
+export type SpeciesState =
+ | { status: 'idle' }
+ | { status: 'loading' }
+ | { status: 'ready'; labels: SpeciesLabel[] }
+ | { status: 'error'; failure: RecordFailureKind }
+
+interface SpeciesContextValue {
+ state: SpeciesState
+ /** Starts the read once; later calls change nothing. */
+ request: () => void
+ retry: () => void
+}
+
+const SpeciesContext = createContext(null)
+
+/**
+ * The active species (reference rows of contract §5.4), read once per
+ * workspace and only when a page needs them: the list filter, the form and
+ * the record pages share one answer. Mounted under RequireWorkspace, it
+ * leaves with the workspace on a change of account.
+ */
+export function SpeciesProvider({ children }: { children: ReactNode }) {
+ const [state, setState] = useState({ status: 'idle' })
+ // 0 until a page asks; each retry bumps it.
+ const [attempt, setAttempt] = useState(0)
+
+ useEffect(() => {
+ if (attempt === 0) return
+ let live = true
+ const client = getSupabaseClient()
+ setState({ status: 'loading' })
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ fetchSpeciesLabels(client)
+ .then((labels) => {
+ if (live) setState({ status: 'ready', labels })
+ })
+ .catch((error: unknown) => {
+ if (live)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ return () => {
+ live = false
+ }
+ }, [attempt])
+
+ const request = useCallback(() => setAttempt((n) => (n === 0 ? 1 : n)), [])
+ const retry = useCallback(() => setAttempt((n) => n + 1), [])
+ const value = useMemo(
+ () => ({ state, request, retry }),
+ [state, request, retry],
+ )
+ return (
+ {children}
+ )
+}
+
+/** The species labels of the workspace; the first page that asks starts the read. */
+export function useSpecies(): Omit {
+ const context = useContext(SpeciesContext)
+ if (!context) throw new Error('useSpecies needs a SpeciesProvider')
+ const { request } = context
+ useEffect(() => request(), [request])
+ return { state: context.state, retry: context.retry }
+}
+
+/** The species name in the locale, followed by the « Autre » detail when there is one. */
+export function speciesName(
+ labels: readonly SpeciesLabel[],
+ speciesId: string,
+ detail: string | null,
+ locale: Locale,
+): string {
+ const label = labels.find((s) => s.id === speciesId)
+ const name = label
+ ? pickLocaleLabel(label.name_fr, label.name_en, locale, speciesId)
+ : speciesId
+ return detail ? `${name} (${detail})` : name
+}
diff --git a/apps/app/src/animals/useAnimalForm.ts b/apps/app/src/animals/useAnimalForm.ts
new file mode 100644
index 00000000..958a029c
--- /dev/null
+++ b/apps/app/src/animals/useAnimalForm.ts
@@ -0,0 +1,232 @@
+import { useRef, useState, type FormEvent } from 'react'
+import {
+ classifyRecordError,
+ createAnimalRecord,
+ fetchAnimalRecord,
+ updateAnimalRecord,
+ type AnimalRecord,
+ type AnimalRelationRole,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { generateUuid } from '@/lib/id'
+import { localDateIso } from '@/lib/dates'
+import {
+ EMPTY_ANIMAL_VALUES,
+ EMPTY_RELATION_VALUES,
+ animalFieldErrors,
+ animalFormValues,
+ animalSchema,
+ relationIssues,
+ withBirthDate,
+ type AnimalFieldErrors,
+ type AnimalFormValues,
+ type RelationFieldErrors,
+ type RelationFormValues,
+} from './validation'
+
+export interface PickedClient {
+ id: string
+ display_name: string
+}
+
+export type AnimalFormTarget =
+ | {
+ mode: 'create'
+ workspaceId: string
+ /** The client the form opened from, pre-associated; the practitioner may remove it. */
+ initialClient: PickedClient | null
+ }
+ | { mode: 'edit'; record: AnimalRecord }
+
+export type AnimalFormPhase =
+ | { kind: 'idle' }
+ | { kind: 'saving' }
+ | { kind: 'failed'; failure: RecordFailureKind }
+
+export interface AnimalSaved {
+ animalId: string
+ /** The client the new animal was linked to, if any. */
+ linkedClientId: string | null
+}
+
+const FIELDS = Object.keys(EMPTY_ANIMAL_VALUES) as (keyof AnimalFormValues)[]
+
+function sameValues(a: AnimalFormValues, b: AnimalFormValues): boolean {
+ return FIELDS.every((key) => a[key] === b[key])
+}
+
+function sameRelation(a: RelationFormValues, b: RelationFormValues): boolean {
+ return (
+ a.client?.id === b.client?.id &&
+ a.relation_role === b.relation_role &&
+ a.started_on === b.started_on
+ )
+}
+
+/**
+ * The animal form: typed values, the D-R7 schema, one save. A create keeps
+ * one request id for the life of the form, and sends the animal with its
+ * optional first client in one create_animal call, so a retry after a lost
+ * answer returns the animal (and relation) already made. An update sends the
+ * revision it was read at; on `conflict` the stored animal is shown beside
+ * the typed values, which stay.
+ */
+export function useAnimalForm(
+ target: AnimalFormTarget,
+ activeSpeciesIds: readonly string[],
+ onSaved: (saved: AnimalSaved) => void,
+) {
+ const initial =
+ target.mode === 'edit'
+ ? animalFormValues(target.record)
+ : EMPTY_ANIMAL_VALUES
+ const initialRelation: RelationFormValues =
+ target.mode === 'create'
+ ? { ...EMPTY_RELATION_VALUES, client: target.initialClient }
+ : EMPTY_RELATION_VALUES
+ const [values, setValues] = useState(initial)
+ const [baseline, setBaseline] = useState(initial)
+ const [relation, setRelation] = useState(initialRelation)
+ const [relationBaseline, setRelationBaseline] = useState(initialRelation)
+ const [errors, setErrors] = useState({})
+ const [relationErrors, setRelationErrors] = useState({})
+ const [errorRound, setErrorRound] = useState(0)
+ const [phase, setPhase] = useState({ kind: 'idle' })
+ const [stored, setStored] = useState(null)
+ const [requestId] = useState(generateUuid)
+ const revision = useRef(target.mode === 'edit' ? target.record.revision : 0)
+ const inFlight = useRef(false)
+
+ const setField = (key: keyof AnimalFormValues) => (value: string) =>
+ setValues((v) => ({ ...v, [key]: value }))
+ const setBirthDate = (value: string) =>
+ setValues((v) => withBirthDate(v, value))
+ const chooseClient = (client: PickedClient | null) =>
+ setRelation((r) => ({ ...r, client }))
+ const setRelationRole = (role: AnimalRelationRole) =>
+ setRelation((r) => ({ ...r, relation_role: role }))
+ const setStartedOn = (value: string) =>
+ setRelation((r) => ({ ...r, started_on: value }))
+
+ /** The species the form may send: on an edit, the stored one even if it left the active list. */
+ const speciesIds =
+ target.mode === 'edit' &&
+ !activeSpeciesIds.includes(target.record.species_id)
+ ? [...activeSpeciesIds, target.record.species_id]
+ : activeSpeciesIds
+
+ async function readStored(animalId: string) {
+ const client = getSupabaseClient()
+ const record = client
+ ? await fetchAnimalRecord(client, animalId).catch(() => null)
+ : null
+ if (record) {
+ revision.current = record.revision
+ setStored(record)
+ }
+ }
+
+ function validate() {
+ const today = localDateIso()
+ const parsed = animalSchema({ speciesIds, today }).safeParse(values)
+ const linkIssues =
+ target.mode === 'create' ? relationIssues(relation, today, false) : {}
+ const fieldIssues = parsed.success ? {} : animalFieldErrors(parsed.error)
+ setErrors(fieldIssues)
+ setRelationErrors(linkIssues)
+ if (!parsed.success || Object.keys(linkIssues).length > 0) {
+ setErrorRound((n) => n + 1)
+ return null
+ }
+ return parsed.data
+ }
+
+ async function save(fields: NonNullable>) {
+ const client = getSupabaseClient()
+ if (!client) throw new TypeError('no backend')
+ if (target.mode === 'edit') {
+ revision.current = (
+ await updateAnimalRecord(client, {
+ animalId: target.record.id,
+ expectedRevision: revision.current,
+ fields,
+ })
+ ).revision
+ return { animalId: target.record.id, linkedClientId: null }
+ }
+ const linked = relation.client
+ const created = await createAnimalRecord(client, {
+ workspaceId: target.workspaceId,
+ requestId,
+ fields,
+ relation: linked
+ ? {
+ clientId: linked.id,
+ relationRole: relation.relation_role as AnimalRelationRole,
+ startedOn: relation.started_on || null,
+ }
+ : null,
+ })
+ return { animalId: created.id, linkedClientId: linked?.id ?? null }
+ }
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ if (inFlight.current) return
+ const fields = validate()
+ if (!fields) return
+ inFlight.current = true
+ setPhase({ kind: 'saving' })
+ try {
+ const saved = await save(fields)
+ setBaseline(values)
+ setRelationBaseline(relation)
+ setPhase({ kind: 'idle' })
+ onSaved(saved)
+ } catch (error) {
+ const failure = classifyRecordError(error)
+ if (failure === 'conflict' && target.mode === 'edit')
+ await readStored(target.record.id)
+ setPhase({ kind: 'failed', failure })
+ } finally {
+ inFlight.current = false
+ }
+ }
+
+ /** Drops the typed values for the stored ones after a conflict. */
+ function takeStored() {
+ if (!stored) return
+ const next = animalFormValues(stored)
+ setValues(next)
+ setBaseline(next)
+ setStored(null)
+ setErrors({})
+ setPhase({ kind: 'idle' })
+ }
+
+ return {
+ mode: target.mode,
+ values,
+ setField,
+ setBirthDate,
+ relation,
+ chooseClient,
+ setRelationRole,
+ setStartedOn,
+ errors,
+ relationErrors,
+ /** Changes after each refused submit, so the form can focus the first error. */
+ errorRound,
+ phase,
+ /** The stored animal after a conflict, shown beside the typed values. */
+ stored,
+ takeStored,
+ dirty:
+ !sameValues(values, baseline) ||
+ !sameRelation(relation, relationBaseline),
+ submit,
+ }
+}
+
+export type AnimalForm = ReturnType
diff --git a/apps/app/src/animals/useAnimalList.ts b/apps/app/src/animals/useAnimalList.ts
new file mode 100644
index 00000000..bcefddab
--- /dev/null
+++ b/apps/app/src/animals/useAnimalList.ts
@@ -0,0 +1,110 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ searchAnimals,
+ type AnimalListItem,
+ type NameCursor,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { SEARCH_DELAY_MS } from '@/clients/useClientList'
+
+export type AnimalListState =
+ | { status: 'loading' }
+ | {
+ status: 'ready'
+ rows: AnimalListItem[]
+ next: NameCursor | null
+ moreFailure: RecordFailureKind | null
+ }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/**
+ * The animals of the workspace for a term, a species and the archived
+ * toggle: the server searches (search_animals, POST), pages of 25 in name
+ * order, « Afficher plus » appends the next page. An answer to an older
+ * search is dropped.
+ */
+export function useAnimalList(workspaceId: string) {
+ const [query, setQuery] = useState('')
+ const [term, setTerm] = useState('')
+ const [speciesId, setSpeciesId] = useState(null)
+ const [archived, setArchived] = useState(false)
+ const [state, setState] = useState({ status: 'loading' })
+ const [loadingMore, setLoadingMore] = useState(false)
+ const [reload, setReload] = useState(0)
+ const generation = useRef(0)
+
+ useEffect(() => {
+ const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS)
+ return () => clearTimeout(timer)
+ }, [query])
+
+ useEffect(() => {
+ const current = ++generation.current
+ const client = getSupabaseClient()
+ setState({ status: 'loading' })
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ searchAnimals(client, { workspaceId, query: term, speciesId, archived })
+ .then((page) => {
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: page.rows,
+ next: page.next,
+ moreFailure: null,
+ })
+ })
+ .catch((error: unknown) => {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ }, [workspaceId, term, speciesId, archived, reload])
+
+ const loadMore = useCallback(async () => {
+ const client = getSupabaseClient()
+ if (state.status !== 'ready' || !state.next || !client || loadingMore)
+ return
+ const current = generation.current
+ setLoadingMore(true)
+ try {
+ const page = await searchAnimals(client, {
+ workspaceId,
+ query: term,
+ speciesId,
+ archived,
+ after: state.next,
+ })
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: [...state.rows, ...page.rows],
+ next: page.next,
+ moreFailure: null,
+ })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ ...state, moreFailure: classifyRecordError(error) })
+ } finally {
+ setLoadingMore(false)
+ }
+ }, [state, loadingMore, workspaceId, term, speciesId, archived])
+
+ return {
+ query,
+ setQuery,
+ /** The term the shown rows answer (the typed one after the pause). */
+ term,
+ speciesId,
+ setSpeciesId,
+ archived,
+ setArchived,
+ state,
+ loadingMore,
+ loadMore,
+ retry: () => setReload((n) => n + 1),
+ }
+}
diff --git a/apps/app/src/animals/useAnimalRecord.ts b/apps/app/src/animals/useAnimalRecord.ts
new file mode 100644
index 00000000..fd920920
--- /dev/null
+++ b/apps/app/src/animals/useAnimalRecord.ts
@@ -0,0 +1,50 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ fetchAnimalRecord,
+ type AnimalRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+export type AnimalRecordState =
+ | { status: 'loading' }
+ | { status: 'ready'; record: AnimalRecord }
+ | { status: 'not_found' }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/** One animal by id; an unknown id and an id of another workspace are both not_found. */
+export function useAnimalRecord(animalId: string) {
+ const [state, setState] = useState({ status: 'loading' })
+ const [reload, setReload] = useState(0)
+ const shownId = useRef(null)
+
+ useEffect(() => {
+ let live = true
+ const client = getSupabaseClient()
+ // A refresh of the same animal keeps it on screen until the new answer.
+ if (shownId.current !== animalId) setState({ status: 'loading' })
+ shownId.current = animalId
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ fetchAnimalRecord(client, animalId)
+ .then((record) => {
+ if (live)
+ setState(
+ record ? { status: 'ready', record } : { status: 'not_found' },
+ )
+ })
+ .catch((error: unknown) => {
+ if (live)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ return () => {
+ live = false
+ }
+ }, [animalId, reload])
+
+ const refresh = useCallback(() => setReload((n) => n + 1), [])
+ return { state, refresh }
+}
diff --git a/apps/app/src/animals/validation.ts b/apps/app/src/animals/validation.ts
new file mode 100644
index 00000000..15b6be94
--- /dev/null
+++ b/apps/app/src/animals/validation.ts
@@ -0,0 +1,253 @@
+import { z } from 'zod'
+import {
+ ANIMAL_FIELD_LIMITS,
+ BIRTH_YEAR_MIN,
+ CONTROL_CHARACTERS,
+ RECORD_DATE_MIN,
+ codePointLength,
+ type AnimalFields,
+ type AnimalRecord,
+ type AnimalRelationRole,
+ type AnimalSex,
+} from '@faunosteo/supabase'
+
+/**
+ * The animal form (contract §5.2, §11.3; D-R7): bounds from field-limits,
+ * proven equal to the SQL CHECKs, so the form never sends what the database
+ * refuses. The birth keeps the precision given (D6b): a year alone stays a
+ * year, a full date carries its year again. « Not in the future » is the
+ * device's local date (`today`); the RPCs allow up to tomorrow UTC. Messages
+ * are i18n keys; `|n` carries the {max} placeholder.
+ */
+
+export const ANIMAL_SEXES: readonly AnimalSex[] = ['male', 'female', 'unknown']
+export const RELATION_ROLES: readonly AnimalRelationRole[] = [
+ 'owner',
+ 'keeper',
+ 'contact',
+]
+
+/** The species that asks for a detail (« Autre »). */
+export const OTHER_SPECIES = 'other'
+
+export interface AnimalFormValues {
+ name: string
+ species_id: string
+ species_detail: string
+ /** '' until the practitioner picks one: no default (N8). */
+ sex: AnimalSex | ''
+ breed: string
+ birth_year: string
+ birth_date: string
+}
+
+export const EMPTY_ANIMAL_VALUES: AnimalFormValues = {
+ name: '',
+ species_id: '',
+ species_detail: '',
+ sex: '',
+ breed: '',
+ birth_year: '',
+ birth_date: '',
+}
+
+/** The form's view of a stored animal: null fields become empty inputs. */
+export function animalFormValues(record: AnimalRecord): AnimalFormValues {
+ return {
+ name: record.name,
+ species_id: record.species_id,
+ species_detail: record.species_detail ?? '',
+ sex: record.sex,
+ breed: record.breed ?? '',
+ birth_year: record.birth_year === null ? '' : String(record.birth_year),
+ birth_date: record.birth_date ?? '',
+ }
+}
+
+/**
+ * U3: a complete date fills the year (which the form then locks); clearing
+ * the date leaves the year as it was, editable again.
+ */
+export function withBirthDate(
+ values: AnimalFormValues,
+ birthDate: string,
+): AnimalFormValues {
+ const year = /^\d{4}-\d{2}-\d{2}$/.test(birthDate)
+ ? birthDate.slice(0, 4)
+ : values.birth_year
+ return { ...values, birth_date: birthDate, birth_year: year }
+}
+
+function isCalendarDate(value: string): boolean {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
+ if (!match) return false
+ const [y, m, d] = match.slice(1).map(Number)
+ const date = new Date(Date.UTC(y, m - 1, d))
+ return (
+ date.getUTCFullYear() === y &&
+ date.getUTCMonth() === m - 1 &&
+ date.getUTCDate() === d
+ )
+}
+
+/**
+ * The issue of an optional record date (birth, relation start or end), or
+ * null when it is fine: a real calendar date from 1900 to `today` (ISO text
+ * compares in date order).
+ */
+export function recordDateIssue(value: string, today: string): string | null {
+ if (value === '') return null
+ if (!isCalendarDate(value)) return 'animals.error.date_format'
+ if (value < RECORD_DATE_MIN || value > today)
+ return 'animals.error.date_range'
+ return null
+}
+
+/** Trimmed text of at most `max` code points without control characters. */
+function textIssue(value: string, max: number): string | null {
+ if (codePointLength(value) > max) return `animals.error.too_long|${max}`
+ if (CONTROL_CHARACTERS.test(value)) return 'animals.error.characters'
+ return null
+}
+
+export interface AnimalSchemaContext {
+ /** The species the form may send: the active ones, plus the stored one on an edit. */
+ speciesIds: readonly string[]
+ /** The device's local date, YYYY-MM-DD. */
+ today: string
+}
+
+type Issue = { path: keyof AnimalFormValues; message: string }
+
+function identityIssues(v: AnimalFormValues, ctx: AnimalSchemaContext) {
+ const issues: Issue[] = []
+ const name = v.name.trim()
+ const nameIssue =
+ name === ''
+ ? 'animals.error.required'
+ : textIssue(name, ANIMAL_FIELD_LIMITS.name)
+ if (nameIssue) issues.push({ path: 'name', message: nameIssue })
+ if (!ctx.speciesIds.includes(v.species_id))
+ issues.push({ path: 'species_id', message: 'animals.error.species' })
+ if (v.species_id === OTHER_SPECIES) {
+ const detail = v.species_detail.trim()
+ const detailIssue =
+ detail === ''
+ ? 'animals.error.species_detail'
+ : textIssue(detail, ANIMAL_FIELD_LIMITS.speciesDetail)
+ if (detailIssue)
+ issues.push({ path: 'species_detail', message: detailIssue })
+ }
+ if (!ANIMAL_SEXES.includes(v.sex as AnimalSex))
+ issues.push({ path: 'sex', message: 'animals.error.sex' })
+ const breedIssue = textIssue(v.breed.trim(), ANIMAL_FIELD_LIMITS.breed)
+ if (breedIssue) issues.push({ path: 'breed', message: breedIssue })
+ return issues
+}
+
+function birthIssues(v: AnimalFormValues, today: string) {
+ const issues: Issue[] = []
+ if (v.birth_year !== '') {
+ if (!/^\d{4}$/.test(v.birth_year))
+ issues.push({ path: 'birth_year', message: 'animals.error.year_format' })
+ else if (
+ Number(v.birth_year) < BIRTH_YEAR_MIN ||
+ Number(v.birth_year) > Number(today.slice(0, 4))
+ )
+ issues.push({ path: 'birth_year', message: 'animals.error.year_range' })
+ }
+ const dateIssue = recordDateIssue(v.birth_date, today)
+ if (dateIssue) issues.push({ path: 'birth_date', message: dateIssue })
+ else if (v.birth_date !== '' && v.birth_date.slice(0, 4) !== v.birth_year)
+ issues.push({ path: 'birth_year', message: 'animals.error.date_year' })
+ return issues
+}
+
+const nullIfEmpty = (value: string) => (value === '' ? null : value)
+
+/** Parses the typed values into the seven fields the RPCs take. */
+export function animalSchema(ctx: AnimalSchemaContext) {
+ return z
+ .object({
+ name: z.string(),
+ species_id: z.string(),
+ species_detail: z.string(),
+ sex: z.string(),
+ breed: z.string(),
+ birth_year: z.string(),
+ birth_date: z.string(),
+ })
+ .superRefine((raw, zctx) => {
+ const v = raw as AnimalFormValues
+ for (const issue of [
+ ...identityIssues(v, ctx),
+ ...birthIssues(v, ctx.today),
+ ])
+ zctx.addIssue({
+ code: 'custom',
+ path: [issue.path],
+ message: issue.message,
+ })
+ })
+ .transform(
+ (v): AnimalFields => ({
+ name: v.name.trim(),
+ species_id: v.species_id,
+ // Any other species refuses a detail: a hidden leftover is dropped, never sent.
+ species_detail:
+ v.species_id === OTHER_SPECIES ? v.species_detail.trim() : null,
+ sex: v.sex as AnimalSex,
+ breed: nullIfEmpty(v.breed.trim()),
+ birth_year: v.birth_year === '' ? null : Number(v.birth_year),
+ birth_date: nullIfEmpty(v.birth_date),
+ }),
+ )
+}
+
+/** The optional client of a new animal, or of a relation added from a page. */
+export interface RelationFormValues {
+ client: { id: string; display_name: string } | null
+ /** '' until chosen: no role is preselected (owner decision 2026-10-26). */
+ relation_role: AnimalRelationRole | ''
+ started_on: string
+}
+
+export const EMPTY_RELATION_VALUES: RelationFormValues = {
+ client: null,
+ relation_role: '',
+ started_on: '',
+}
+
+export type RelationFieldErrors = Partial<
+ Record<'client' | 'relation_role' | 'started_on', string>
+>
+
+/** Errors of a relation choice; `requireClient` when the client is the point of the form. */
+export function relationIssues(
+ values: RelationFormValues,
+ today: string,
+ requireClient: boolean,
+): RelationFieldErrors {
+ const errors: RelationFieldErrors = {}
+ if (!values.client) {
+ if (requireClient) errors.client = 'animals.error.client'
+ return errors
+ }
+ if (!RELATION_ROLES.includes(values.relation_role as AnimalRelationRole))
+ errors.relation_role = 'animals.error.role'
+ const dateIssue = recordDateIssue(values.started_on, today)
+ if (dateIssue) errors.started_on = dateIssue
+ return errors
+}
+
+export type AnimalFieldErrors = Partial>
+
+/** The first message of each field, in form order. */
+export function animalFieldErrors(error: z.ZodError): AnimalFieldErrors {
+ const errors: AnimalFieldErrors = {}
+ for (const issue of error.issues) {
+ const key = issue.path[0] as keyof AnimalFormValues
+ errors[key] ??= issue.message
+ }
+ return errors
+}
diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx
index cc2bc844..b952bc8d 100644
--- a/apps/app/src/app/App.tsx
+++ b/apps/app/src/app/App.tsx
@@ -21,6 +21,10 @@ import ClientsListRoute from './routes/app/clients/ClientsListRoute'
import ClientCreateRoute from './routes/app/clients/ClientCreateRoute'
import ClientDetailRoute from './routes/app/clients/ClientDetailRoute'
import ClientEditRoute from './routes/app/clients/ClientEditRoute'
+import AnimalsListRoute from './routes/app/animals/AnimalsListRoute'
+import AnimalCreateRoute from './routes/app/animals/AnimalCreateRoute'
+import AnimalDetailRoute from './routes/app/animals/AnimalDetailRoute'
+import AnimalEditRoute from './routes/app/animals/AnimalEditRoute'
import { useUnsavedGuard } from './useUnsavedGuard'
/** The local tool: unchanged routes, no account needed, shared footer. */
@@ -55,11 +59,20 @@ export function AppRoutes() {
}>
} />
} />
- }>
- } />
- } />
- } />
- } />
+ {/* One workspace gate for the records: moving between clients and animals keeps it. */}
+ }>
+
+ } />
+ } />
+ } />
+ } />
+
+
+ } />
+ } />
+ } />
+ } />
+
} />
diff --git a/apps/app/src/app/guards/RequireWorkspace.tsx b/apps/app/src/app/guards/RequireWorkspace.tsx
index 309151e8..f320c770 100644
--- a/apps/app/src/app/guards/RequireWorkspace.tsx
+++ b/apps/app/src/app/guards/RequireWorkspace.tsx
@@ -2,6 +2,7 @@ import { Fragment } from 'react'
import { Outlet, useOutletContext } from 'react-router-dom'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
+import { SpeciesProvider } from '@/animals/species'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
@@ -15,9 +16,10 @@ export function useWorkspaceId(): string {
}
/**
- * Wraps the record routes: they render only once the personal workspace is
- * read, and remount when it changes, so no list or form of another account
- * survives a change of account. Every other state is said, never guessed.
+ * Wraps the record routes (clients and animals): they render only once the
+ * personal workspace is read, and remount when it changes, so no list, form
+ * or species answer of another account survives a change of account. Every
+ * other state is said, never guessed.
*/
export default function RequireWorkspace() {
const t = useT()
@@ -27,9 +29,11 @@ export default function RequireWorkspace() {
if (workspace.status === 'ready') {
return (
-
+
+
+
)
}
diff --git a/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx
new file mode 100644
index 00000000..aca11539
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx
@@ -0,0 +1,108 @@
+import { useLocation, useNavigate } from 'react-router-dom'
+import { UUID_PATTERN } from '@faunosteo/supabase'
+import AnimalForm from '@/components/animals/AnimalForm'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useSpecies } from '@/animals/species'
+import { useAnimalForm, type PickedClient } from '@/animals/useAnimalForm'
+import { useClientRecord } from '@/clients/useClientRecord'
+import { useT } from '@/i18n/useT'
+import type { ClientFlash } from '../clients/ClientDetailRoute'
+import type { AnimalFlash } from './AnimalDetailRoute'
+
+/**
+ * What a client page hands to this page: the client to pre-associate, in
+ * the navigation state, never in the URL (brief V1-1.6 §6).
+ */
+export interface AnimalCreateState {
+ clientId: string
+}
+
+type Origin =
+ | { status: 'none' }
+ | { status: 'loading' }
+ | { status: 'ready'; client: PickedClient }
+ | { status: 'unavailable' }
+
+/** The client the form opened from, read again: only an active client of this workspace is pre-associated. */
+function useOrigin(clientId: string | null): Origin {
+ const { state } = useClientRecord(clientId ?? '')
+ if (!clientId) return { status: 'none' }
+ if (state.status === 'loading') return { status: 'loading' }
+ if (state.status === 'ready' && state.record.archived_at === null)
+ return {
+ status: 'ready',
+ client: { id: state.record.id, display_name: state.record.display_name },
+ }
+ return { status: 'unavailable' }
+}
+
+function CreateForm({ origin }: { origin: PickedClient | null }) {
+ const t = useT()
+ const navigate = useNavigate()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const activeIds =
+ species.status === 'ready' ? species.labels.map((s) => s.id) : []
+ const form = useAnimalForm(
+ { mode: 'create', workspaceId, initialClient: origin },
+ activeIds,
+ (saved) => {
+ if (origin && saved.linkedClientId === origin.id)
+ navigate(`/app/clients/${origin.id}`, {
+ replace: true,
+ state: { flash: 'animal_added' satisfies ClientFlash },
+ })
+ else
+ navigate(`/app/animals/${saved.animalId}`, {
+ replace: true,
+ state: { flash: 'created' satisfies AnimalFlash },
+ })
+ },
+ )
+ useLeaveGuard(form.dirty)
+ return (
+
+ )
+}
+
+/** /app/animals/new: one creation intent, one request id kept for retries, an optional first client. */
+export default function AnimalCreateRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const location = useLocation()
+ const passed = (location.state as Partial | null)?.clientId
+ const origin = useOrigin(
+ typeof passed === 'string' && UUID_PATTERN.test(passed) ? passed : null,
+ )
+
+ return (
+
+
+ {t('animals.form.create_title')}
+
+ {origin.status === 'loading' && (
+
+ {t('animals.form.origin_loading')}
+
+ )}
+ {origin.status === 'unavailable' && (
+
{t('animals.form.origin_unavailable')}
+ )}
+ {origin.status !== 'loading' && (
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx
new file mode 100644
index 00000000..8d2874f3
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx
@@ -0,0 +1,248 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
+import {
+ classifyRecordError,
+ setAnimalArchived,
+ type AnimalRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import AnimalNotFound from '@/components/animals/AnimalNotFound'
+import ArchiveAnimalDialog from '@/components/animals/ArchiveAnimalDialog'
+import AnimalRelations from '@/components/relations/AnimalRelations'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { usePageHeading } from '@/app/usePageHeading'
+import { animalAge, type AnimalAge } from '@/animals/age'
+import { speciesName, useSpecies } from '@/animals/species'
+import { useAnimalRecord } from '@/animals/useAnimalRecord'
+import { formatDate, localDateIso } from '@/lib/dates'
+import { getSupabaseClient } from '@/lib/supabase'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+/** What a page that saved the animal asks this page to announce (no value in it). */
+export type AnimalFlash = 'created' | 'updated'
+
+type Translate = ReturnType
+
+const linkClass =
+ 'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
+
+function ageText(age: AnimalAge | null, t: Translate): string | null {
+ if (!age) return null
+ if (age.about && age.count === 0) return t('animals.age.under_one')
+ const unit = age.unit === 'year' ? 'years' : 'months'
+ const base = t(
+ `animals.age.${unit}_${age.count === 1 ? 'one' : 'other'}`,
+ ).replace('{count}', String(age.count))
+ return age.about ? t('animals.age.about').replace('{age}', base) : base
+}
+
+/** The birth with the precision known (D6b): a date, a year, or « inconnue »; never a made-up day. */
+function birthText(record: AnimalRecord, t: Translate, locale: 'fr' | 'en') {
+ const age = ageText(
+ animalAge(record.birth_year, record.birth_date, localDateIso()),
+ t,
+ )
+ const when = record.birth_date
+ ? t('animals.detail.birth_on').replace(
+ '{date}',
+ formatDate(record.birth_date, locale),
+ )
+ : record.birth_year !== null
+ ? t('animals.detail.birth_in').replace(
+ '{year}',
+ String(record.birth_year),
+ )
+ : null
+ if (!when) return t('animals.detail.birth_unknown')
+ return age ? `${when} (${age})` : when
+}
+
+function IdentityCard({ record }: { record: AnimalRecord }) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const rows: [string, ReactNode][] = [
+ [
+ t('animals.detail.species'),
+ speciesName(labels, record.species_id, record.species_detail, locale),
+ ],
+ [t('animals.detail.sex'), t(`animals.sex.${record.sex}`)],
+ [t('animals.detail.breed'), record.breed ?? t('animals.detail.breed_none')],
+ [t('animals.detail.birth'), birthText(record, t, locale)],
+ [
+ t('animals.detail.status'),
+ record.archived_at
+ ? t('animals.detail.status_archived')
+ : t('animals.detail.status_active'),
+ ],
+ ]
+ return (
+
+
+ {t('animals.detail.identity')}
+
+
+ {rows.map(([label, value]) => (
+
+
- {label}
+ - {value}
+
+ ))}
+
+
+ )
+}
+
+/** /app/animals/:animalId: identity, clients current and former, edit, archive or restore. */
+export default function AnimalDetailRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const navigate = useNavigate()
+ const location = useLocation()
+ const workspaceId = useWorkspaceId()
+ const { animalId = '' } = useParams()
+ const { state, refresh } = useAnimalRecord(animalId)
+ const flash = (location.state as { flash?: AnimalFlash } | null)?.flash
+ const [status, setStatus] = useState(
+ flash ? t(`animals.detail.${flash}`) : null,
+ )
+ const [archiveOpen, setArchiveOpen] = useState(false)
+ const [restoring, setRestoring] = useState(false)
+ const [failure, setFailure] = useState(null)
+
+ // The announcement is read once; a reload of the page does not repeat it.
+ useEffect(() => {
+ if (flash) navigate(location.pathname, { replace: true, state: null })
+ }, [flash, navigate, location.pathname])
+
+ async function restore() {
+ const client = getSupabaseClient()
+ if (restoring || !client) return
+ setRestoring(true)
+ setFailure(null)
+ try {
+ await setAnimalArchived(client, animalId, false)
+ setStatus(t('animals.detail.restored'))
+ refresh()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setRestoring(false)
+ }
+ }
+
+ if (state.status === 'not_found') return
+ if (state.status === 'loading')
+ return (
+
+ {t('animals.detail.loading')}
+
+ )
+ if (state.status === 'error')
+ return (
+
+ {t(`animals.failure.${state.failure}`)}
+
+
+ )
+
+ const record = state.record
+ const archived = record.archived_at !== null
+
+ return (
+
+
+ {t('animals.detail.back')}
+
+
+
+
+ {record.name}
+
+ {archived && {t('animals.archived_badge')}}
+
+
+ {archived ? (
+
+ ) : (
+ <>
+
+ {t('animals.detail.edit')}
+
+
+ >
+ )}
+
+
+
+ {status &&
{status}}
+ {failure && (
+
{t(`animals.failure.${failure}`)}
+ )}
+ {archived && (
+
{t('animals.detail.archived_notice')}
+ )}
+
+
+
+
+
setArchiveOpen(false)}
+ onArchived={() => {
+ setArchiveOpen(false)
+ setStatus(t('animals.detail.archived'))
+ refresh()
+ }}
+ />
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx
new file mode 100644
index 00000000..b2df7811
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx
@@ -0,0 +1,85 @@
+import { Link, useNavigate, useParams } from 'react-router-dom'
+import type { AnimalRecord } from '@faunosteo/supabase'
+import AnimalForm from '@/components/animals/AnimalForm'
+import AnimalNotFound from '@/components/animals/AnimalNotFound'
+import Button from '@/components/ui/Button'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useSpecies } from '@/animals/species'
+import { useAnimalForm } from '@/animals/useAnimalForm'
+import { useAnimalRecord } from '@/animals/useAnimalRecord'
+import { useT } from '@/i18n/useT'
+import type { AnimalFlash } from './AnimalDetailRoute'
+
+function EditForm({ record }: { record: AnimalRecord }) {
+ const t = useT()
+ const navigate = useNavigate()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const activeIds =
+ species.status === 'ready' ? species.labels.map((s) => s.id) : []
+ const form = useAnimalForm({ mode: 'edit', record }, activeIds, (saved) =>
+ navigate(`/app/animals/${saved.animalId}`, {
+ state: { flash: 'updated' satisfies AnimalFlash },
+ }),
+ )
+ useLeaveGuard(form.dirty)
+ return (
+
+ )
+}
+
+/** /app/animals/:animalId/edit: the stored values at their revision; an archived animal is read-only. */
+export default function AnimalEditRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const { animalId = '' } = useParams()
+ const { state, refresh } = useAnimalRecord(animalId)
+
+ if (state.status === 'not_found') return
+ return (
+
+
+ {t('animals.form.edit_title')}
+
+ {state.status === 'loading' && (
+
+ {t('animals.detail.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`animals.failure.${state.failure}`)}
+
+
+ )}
+ {state.status === 'ready' && state.record.archived_at && (
+
+ {t('animals.detail.archived_notice')}
+
+ {t('animals.form.back_to_animal')}
+
+
+ )}
+ {state.status === 'ready' && !state.record.archived_at && (
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx
new file mode 100644
index 00000000..7d218841
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx
@@ -0,0 +1,240 @@
+import { Link } from 'react-router-dom'
+import type { AnimalListItem, SpeciesLabel } from '@faunosteo/supabase'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
+import FormField from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import Notice from '@/components/ui/Notice'
+import Select from '@/components/ui/Select'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { usePageHeading } from '@/app/usePageHeading'
+import { speciesName, useSpecies } from '@/animals/species'
+import { useAnimalList } from '@/animals/useAnimalList'
+import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
+import type { Locale } from '@/i18n/types'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+type Translate = ReturnType
+
+/** « Propriétaires : A, B, C +2 », or « Propriétaire non renseigné » (no placeholder client). */
+function ownersText(animal: AnimalListItem, t: Translate): string {
+ if (animal.current_owner_count === 0) return t('animals.no_owner')
+ const names = animal.current_owners
+ .map((o) =>
+ o.archived
+ ? t('animals.owner_archived').replace('{name}', o.display_name)
+ : o.display_name,
+ )
+ .join(', ')
+ const more = animal.current_owner_count - animal.current_owners.length
+ const list =
+ more > 0
+ ? `${names} ${t('animals.list.owners_more').replace('{count}', String(more))}`
+ : names
+ return t(
+ animal.current_owner_count === 1
+ ? 'animals.list.owner'
+ : 'animals.list.owners',
+ ).replace('{names}', list)
+}
+
+function AnimalRow(props: {
+ animal: AnimalListItem
+ labels: readonly SpeciesLabel[]
+ locale: Locale
+ t: Translate
+}) {
+ const { animal, t } = props
+ const details = [
+ speciesName(
+ props.labels,
+ animal.species_id,
+ animal.species_detail,
+ props.locale,
+ ),
+ animal.breed,
+ t(`animals.sex.${animal.sex}`),
+ ].filter(Boolean)
+ return (
+
+
+
+
+ {animal.name}
+
+ {animal.archived_at && (
+ {t('animals.archived_badge')}
+ )}
+
+
+ {details.join(' · ')}
+
+
+ {ownersText(animal, t)}
+
+
+
+ )
+}
+
+/** /app/animals: search, species filter, the archived toggle (U2) and « Afficher plus » pages (U1). */
+export default function AnimalsListRoute() {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const heading = usePageHeading()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const list = useAnimalList(workspaceId)
+ const { state } = list
+
+ const emptyMessage =
+ list.term || list.speciesId
+ ? t('animals.list.no_results')
+ : list.archived
+ ? t('animals.list.archived_empty')
+ : t('animals.list.empty')
+
+ return (
+
+
+
+ {t('animals.list.title')}
+
+
+ {t('animals.list.new')}
+
+
+
+
+
+ list.setQuery(e.target.value)}
+ maxLength={100}
+ autoComplete="off"
+ aria-describedby="animal-search-hint"
+ />
+
+
+
+
+
+
+
+ {/* The number of rows shown is announced; an empty result announces itself below. */}
+
+ {state.status === 'ready' &&
+ state.rows.length > 0 &&
+ t(
+ state.rows.length === 1
+ ? 'animals.list.count_one'
+ : 'animals.list.count_other',
+ ).replace('{count}', String(state.rows.length))}
+
+
+ {state.status === 'loading' && (
+
+ {t('animals.list.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`animals.failure.${state.failure}`)}
+
+
+ )}
+ {state.status === 'ready' && state.rows.length === 0 && (
+
+
{emptyMessage}
+ {!list.term && !list.speciesId && !list.archived && (
+
+ {t('animals.list.empty_hint')}
+
+ )}
+
+ )}
+ {state.status === 'ready' && state.rows.length > 0 && (
+ <>
+
+ {state.rows.map((animal) => (
+
+ ))}
+
+ {state.moreFailure && (
+
+ {t(`animals.failure.${state.moreFailure}`)}
+
+ )}
+ {state.next && (
+
+
+
+ )}
+ >
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
index ac6cbce3..b9956224 100644
--- a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
+++ b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
@@ -14,6 +14,7 @@ import Button from '@/components/ui/Button'
import ButtonLink from '@/components/ui/ButtonLink'
import Card from '@/components/ui/Card'
import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
import { usePageHeading } from '@/app/usePageHeading'
import { countryName } from '@/clients/countries'
import { useClientRecord } from '@/clients/useClientRecord'
@@ -21,8 +22,8 @@ import { getSupabaseClient } from '@/lib/supabase'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
-/** What a page that saved the client asks this page to announce (no value in it). */
-export type ClientFlash = 'created' | 'updated'
+/** What a page that saved the client, or an animal of it, asks this page to announce (no value in it). */
+export type ClientFlash = 'created' | 'updated' | 'animal_added'
const linkClass =
'text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded-sm'
@@ -102,12 +103,13 @@ function ContactCard({ record }: { record: ClientRecord }) {
)
}
-/** /app/clients/:clientId: identity, contact, animals (read-only), edit, archive or restore. */
+/** /app/clients/:clientId: identity, contact, animals (add, link, open), edit, archive or restore. */
export default function ClientDetailRoute() {
const t = useT()
const heading = usePageHeading()
const navigate = useNavigate()
const location = useLocation()
+ const workspaceId = useWorkspaceId()
const { clientId = '' } = useParams()
const { state, refresh } = useClientRecord(clientId)
const flash = (location.state as { flash?: ClientFlash } | null)?.flash
@@ -225,7 +227,13 @@ export default function ClientDetailRoute() {
)}
-
+
= {
+ name: 'animal-name',
+ species_id: 'animal-species',
+ species_detail: 'animal-species-detail',
+ sex: firstChoiceId('animal-sex', 'male'),
+ breed: 'animal-breed',
+ birth_year: 'animal-birth-year',
+ birth_date: 'animal-birth-date',
+ client: 'animal-client-search',
+ relation_role: firstChoiceId('animal-role', 'owner'),
+ started_on: 'animal-started-on',
+}
+
+export interface AnimalFormProps {
+ form: AnimalFormState
+ workspaceId: string
+ submitLabel: string
+ /** Where « Annuler » leads; the shell asks first while the form holds changes. */
+ cancelTo: string
+}
+
+/**
+ * The animal form, one page on every screen (contract §11.3): identity
+ * (name, species with its detail for « Autre », sex with no default, breed),
+ * birth (a year, or a full date that fills and locks the year: U3), and on
+ * a creation the optional first client with an explicit role. Every field
+ * is labelled, errors sit under their field and the first one takes focus.
+ */
+export default function AnimalForm({
+ form,
+ workspaceId,
+ submitLabel,
+ cancelTo,
+}: AnimalFormProps) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species, retry: retrySpecies } = useSpecies()
+ const { values, errors, relation, relationErrors, phase, stored } = form
+ const labels = species.status === 'ready' ? species.labels : []
+ const today = localDateIso()
+ const chosenText = useRef(null)
+ const shownClient = useRef(relation.client?.id ?? null)
+
+ // Choosing a client focuses the choice; removing it focuses the search that replaces it.
+ useEffect(() => {
+ const id = relation.client?.id ?? null
+ if (id === shownClient.current) return
+ shownClient.current = id
+ if (id) chosenText.current?.focus()
+ else document.getElementById(FIELD_IDS.client)?.focus()
+ }, [relation.client])
+
+ useEffect(() => {
+ if (form.errorRound === 0) return
+ const all = { ...errors, ...relationErrors } as Record
+ const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find(
+ (key) => all[key],
+ )
+ if (first) document.getElementById(FIELD_IDS[first])?.focus()
+ }, [form.errorRound, errors, relationErrors])
+
+ const err = (key: keyof AnimalFormValues) =>
+ translateFieldError(t, errors[key])
+ const relErr = (key: keyof RelationFieldErrors) =>
+ translateFieldError(t, relationErrors[key])
+
+ /** After a conflict: the stored value under each field that differs from the typed one. */
+ const storedHint = (key: keyof AnimalFormValues): string | undefined => {
+ if (!stored) return undefined
+ const value = animalFormValues(stored)[key]
+ if (value === values[key]) return undefined
+ const shown =
+ value === ''
+ ? ''
+ : key === 'species_id'
+ ? speciesName(labels, value, null, locale)
+ : key === 'sex'
+ ? t(`animals.sex.${value}`)
+ : key === 'birth_date'
+ ? formatDate(value, locale)
+ : value
+ return shown
+ ? t('animals.form.stored_value').replace('{value}', shown)
+ : t('animals.form.stored_empty')
+ }
+ const describedBy = (key: keyof AnimalFormValues, hint?: string) =>
+ fieldDescribedBy(FIELD_IDS[key], hint, errors[key])
+
+ function textField(
+ key: 'name' | 'breed' | 'species_detail',
+ label: string,
+ max: number,
+ isRequired: boolean,
+ hint?: string,
+ ) {
+ const shownHint = storedHint(key) ?? hint
+ return (
+
+ form.setField(key)(e.target.value)}
+ maxLength={max}
+ autoComplete="off"
+ aria-invalid={Boolean(errors[key])}
+ aria-describedby={describedBy(key, shownHint)}
+ required={isRequired}
+ />
+
+ )
+ }
+
+ const required = t('animals.form.required')
+ const optional = t('animals.form.optional')
+ const saving = phase.kind === 'saving'
+ const yearLocked = /^\d{4}-\d{2}-\d{2}$/.test(values.birth_date)
+ const yearHint =
+ storedHint('birth_year') ??
+ t(
+ yearLocked
+ ? 'animals.form.birth_year_locked'
+ : 'animals.form.birth_year_hint',
+ )
+ const speciesHint = storedHint('species_id')
+
+ return (
+
+ )
+}
diff --git a/apps/app/src/components/animals/AnimalNotFound.tsx b/apps/app/src/components/animals/AnimalNotFound.tsx
new file mode 100644
index 00000000..e10ebfbc
--- /dev/null
+++ b/apps/app/src/components/animals/AnimalNotFound.tsx
@@ -0,0 +1,27 @@
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useT } from '@/i18n/useT'
+
+/** The same screen for an unknown id, a malformed one and an id of another workspace (contract §11.1). */
+export default function AnimalNotFound() {
+ const t = useT()
+ const heading = usePageHeading()
+ return (
+
+
+ {t('animals.not_found.title')}
+
+
+ {t('animals.not_found.body')}
+
+
+ {t('animals.not_found.back')}
+
+
+ )
+}
diff --git a/apps/app/src/components/animals/ArchiveAnimalDialog.tsx b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx
new file mode 100644
index 00000000..2f434ebc
--- /dev/null
+++ b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx
@@ -0,0 +1,98 @@
+import { useState } from 'react'
+import {
+ classifyRecordError,
+ setAnimalArchived,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import Button from '@/components/ui/Button'
+import Dialog from '@/components/ui/Dialog'
+import Notice from '@/components/ui/Notice'
+import { getSupabaseClient } from '@/lib/supabase'
+import { useT } from '@/i18n/useT'
+
+export interface ArchiveAnimalDialogProps {
+ open: boolean
+ animalId: string
+ onClose: () => void
+ /** Called once the server archived the animal; the page then closes the dialog. */
+ onArchived: () => void
+}
+
+/**
+ * Confirmation before archiving an animal (contract §7.1): its relations are
+ * kept and frozen, no client is archived. Closing it is never a
+ * confirmation, and while the request runs it refuses to close.
+ */
+export default function ArchiveAnimalDialog({
+ open,
+ animalId,
+ onClose,
+ onArchived,
+}: ArchiveAnimalDialogProps) {
+ const t = useT()
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(null)
+
+ const close = () => {
+ if (pending) return
+ setFailure(null)
+ onClose()
+ }
+
+ async function confirm() {
+ const client = getSupabaseClient()
+ if (pending) return
+ if (!client) return setFailure('unavailable')
+ setPending(true)
+ setFailure(null)
+ try {
+ await setAnimalArchived(client, animalId, true)
+ onArchived()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setPending(false)
+ }
+ }
+
+ return (
+
+ }
+ size="sm"
+ >
+ {failure && (
+
+ {t(`animals.failure.${failure}`)}
+
+ )}
+
+ {/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
+
+
+
+
+ )
+}
diff --git a/apps/app/src/components/clients/ClientAnimals.tsx b/apps/app/src/components/clients/ClientAnimals.tsx
index 93276547..44ced86b 100644
--- a/apps/app/src/components/clients/ClientAnimals.tsx
+++ b/apps/app/src/components/clients/ClientAnimals.tsx
@@ -1,98 +1,145 @@
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Link } from 'react-router-dom'
import {
classifyRecordError,
- fetchSpeciesLabels,
listClientAnimals,
type ClientAnimalItem,
type RecordFailureKind,
type RelationCursor,
- type SpeciesLabel,
} from '@faunosteo/supabase'
import Badge from '@/components/ui/Badge'
import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
import Card from '@/components/ui/Card'
import Notice from '@/components/ui/Notice'
+import RelationPanel from '@/components/relations/RelationPanel'
+import { speciesName, useSpecies } from '@/animals/species'
+import type { AnimalCreateState } from '@/app/routes/app/animals/AnimalCreateRoute'
import { getSupabaseClient } from '@/lib/supabase'
import { formatDate } from '@/lib/dates'
-import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
type State =
| { status: 'loading' }
- | {
- status: 'ready'
- rows: ClientAnimalItem[]
- next: RelationCursor | null
- species: SpeciesLabel[]
- }
+ | { status: 'ready'; rows: ClientAnimalItem[]; next: RelationCursor | null }
| { status: 'error'; failure: RecordFailureKind }
-async function loadPage(
- clientId: string,
- after: RelationCursor | null,
- species: SpeciesLabel[] | null,
-) {
- const client = getSupabaseClient()
- if (!client) throw new TypeError('no backend')
- const page = await listClientAnimals(client, clientId, { after })
- // Species names are read only when there is an animal to name.
- const labels =
- species ?? (page.rows.length ? await fetchSpeciesLabels(client) : [])
- return { ...page, species: labels }
+/** One animal of the client with every relation of one group (current or former). */
+interface AnimalGroup {
+ animalId: string
+ rows: ClientAnimalItem[]
}
/**
- * The client's animals, read-only in V1-1.5 (owner choice 2026-10-26): the
- * real relations from list_client_animals, current then former, each with
- * its role. No link and no « ajouter » until the animal screens exist.
+ * The relations come one per role (list_client_animals); the page shows each
+ * animal once per group with its roles, so an owner who also keeps the
+ * horse sees it once. Rows already arrive current first, by animal name.
*/
-export default function ClientAnimals({ clientId }: { clientId: string }) {
+function byAnimal(rows: ClientAnimalItem[], current: boolean): AnimalGroup[] {
+ const groups = new Map()
+ for (const row of rows.filter((r) => r.is_current === current)) {
+ const group = groups.get(row.animal_id)
+ if (group) group.rows.push(row)
+ else groups.set(row.animal_id, { animalId: row.animal_id, rows: [row] })
+ }
+ return [...groups.values()]
+}
+
+const linkClass =
+ 'rounded-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
+
+export interface ClientAnimalsProps {
+ clientId: string
+ workspaceId: string
+ /** An archived client takes no new relation (contract §7.1): no add, no link. */
+ archived: boolean
+ /** A change made here, announced by the page. */
+ onStatus: (message: string) => void
+}
+
+/**
+ * The client's animals from list_client_animals, current then former, each
+ * with the client's roles and their dates when known, linked to the animal's
+ * page. On an active client: « Ajouter un animal » opens the animal form
+ * with this client pre-associated, « Associer un animal existant » links an
+ * animal already recorded.
+ */
+export default function ClientAnimals({
+ clientId,
+ workspaceId,
+ archived,
+ onStatus,
+}: ClientAnimalsProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
const [state, setState] = useState({ status: 'loading' })
const [loadingMore, setLoadingMore] = useState(false)
+ const [panelOpen, setPanelOpen] = useState(false)
+ const linkButton = useRef(null)
+ const panelWasOpen = useRef(false)
+ const generation = useRef(0)
- useEffect(() => {
- let live = true
- loadPage(clientId, null, null)
- .then((page) => live && setState({ status: 'ready', ...page }))
- .catch(
- (error: unknown) =>
- live &&
- setState({ status: 'error', failure: classifyRecordError(error) }),
- )
- return () => {
- live = false
+ const load = useCallback(async () => {
+ const current = ++generation.current
+ const client = getSupabaseClient()
+ try {
+ if (!client) throw new TypeError('no backend')
+ const page = await listClientAnimals(client, clientId)
+ if (current === generation.current)
+ setState({ status: 'ready', rows: page.rows, next: page.next })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
}
}, [clientId])
+ useEffect(() => {
+ // The ref object is stable: bumping it on unmount drops the answer in flight.
+ const requests = generation
+ void load()
+ return () => {
+ requests.current++
+ }
+ }, [load])
+
+ // The panel gave focus to its own heading; when it closes, focus goes back to « Associer ».
+ useEffect(() => {
+ if (panelWasOpen.current && !panelOpen) linkButton.current?.focus()
+ panelWasOpen.current = panelOpen
+ }, [panelOpen])
+
async function more() {
- if (state.status !== 'ready' || !state.next) return
+ const client = getSupabaseClient()
+ if (state.status !== 'ready' || !state.next || !client || loadingMore)
+ return
+ const current = generation.current
setLoadingMore(true)
try {
- const page = await loadPage(clientId, state.next, state.species)
- setState({
- ...state,
- rows: [...state.rows, ...page.rows],
- next: page.next,
+ const page = await listClientAnimals(client, clientId, {
+ after: state.next,
})
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: [...state.rows, ...page.rows],
+ next: page.next,
+ })
} catch (error) {
- setState({ status: 'error', failure: classifyRecordError(error) })
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
} finally {
setLoadingMore(false)
}
}
- const speciesName = (row: ClientAnimalItem, species: SpeciesLabel[]) => {
- const label = species.find((s) => s.id === row.species_id)
- const name = label
- ? pickLocaleLabel(label.name_fr, label.name_en, locale, row.species_id)
- : row.species_id
- return row.species_detail ? `${name} (${row.species_detail})` : name
- }
- const period = (row: ClientAnimalItem) =>
- [
+ const roleText = (row: ClientAnimalItem) => {
+ const role = t(
+ `clients.role.${row.is_current ? '' : 'former_'}${row.relation_role}`,
+ )
+ const dates = [
row.started_on &&
t('clients.animals.since').replace(
'{date}',
@@ -103,17 +150,12 @@ export default function ClientAnimals({ clientId }: { clientId: string }) {
'{date}',
formatDate(row.ended_on, locale),
),
- ]
- .filter(Boolean)
- .join(' · ')
+ ].filter(Boolean)
+ return [role, ...dates].join(' · ')
+ }
- function group(
- rows: ClientAnimalItem[],
- species: SpeciesLabel[],
- current: boolean,
- ) {
- const shown = rows.filter((r) => r.is_current === current)
- if (!shown.length) return null
+ function section(groups: AnimalGroup[], current: boolean) {
+ if (!groups.length) return null
const id = current ? 'client-animals-current' : 'client-animals-former'
return (
@@ -124,70 +166,104 @@ export default function ClientAnimals({ clientId }: { clientId: string }) {
{t(current ? 'clients.animals.current' : 'clients.animals.former')}
- {shown.map((row) => (
- -
-
-
- {row.animal_name}
- {' '}
-
- {speciesName(row, species)}
+ {groups.map(({ animalId, rows }) => {
+ const first = rows[0]
+ return (
+
-
+
+
+ {first.animal_name}
+
+
+ {speciesName(
+ labels,
+ first.species_id,
+ first.species_detail,
+ locale,
+ )}
+
+ {first.animal_archived_at && (
+ {t('animals.archived_badge')}
+ )}
- {row.animal_archived_at && (
- {t('clients.archived_badge')}
- )}
-
-
- {t(
- `clients.role.${current ? '' : 'former_'}${row.relation_role}`,
- )}
- {period(row) && ` · ${period(row)}`}
-
-
- ))}
+
+ {rows.map((row) => (
+ - {roleText(row)}
+ ))}
+
+
+ )
+ })}
)
}
+ const empty = state.status === 'ready' && state.rows.length === 0
+
return (
-
- {t('clients.animals.title')}
-
+
+
+ {t('clients.animals.title')}
+
+ {!archived && !panelOpen && (
+
+
+ {t(empty ? 'clients.animals.add_first' : 'clients.animals.add')}
+
+
+
+ )}
+
{state.status === 'loading' && (
{t('clients.animals.loading')}
)}
{state.status === 'error' && (
- {t(`clients.failure.${state.failure}`)}
+
+ {t(`clients.failure.${state.failure}`)}
+
+
)}
- {state.status === 'ready' && state.rows.length === 0 && (
+ {empty && (
{t('clients.animals.none')}
)}
{state.status === 'ready' && (
<>
- {group(state.rows, state.species, true)}
- {group(state.rows, state.species, false)}
+ {section(byAnimal(state.rows, true), true)}
+ {section(byAnimal(state.rows, false), false)}
{state.next && (
)
}
diff --git a/apps/app/src/components/relations/AnimalRelations.tsx b/apps/app/src/components/relations/AnimalRelations.tsx
new file mode 100644
index 00000000..7ed2ab51
--- /dev/null
+++ b/apps/app/src/components/relations/AnimalRelations.tsx
@@ -0,0 +1,276 @@
+import { useEffect, useRef, useState } from 'react'
+import { Link } from 'react-router-dom'
+import type {
+ AnimalRecord,
+ AnimalRelationItem,
+ RecordFailureKind,
+} from '@faunosteo/supabase'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import Card from '@/components/ui/Card'
+import Notice from '@/components/ui/Notice'
+import RelationPanel from './RelationPanel'
+import {
+ EndRelationDialog,
+ RelationDatesDialog,
+ VoidRelationDialog,
+} from './RelationDialogs'
+import { groupRelations } from '@/relations/groups'
+import { useAnimalRelations } from '@/relations/useAnimalRelations'
+import { formatDate } from '@/lib/dates'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+type Action = 'end' | 'dates' | 'void'
+interface Target {
+ action: Action
+ relation: AnimalRelationItem
+}
+
+const linkClass =
+ 'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
+
+export interface AnimalRelationsProps {
+ animal: AnimalRecord
+ workspaceId: string
+ /** A change made here, announced by the page. */
+ onStatus: (message: string) => void
+}
+
+/**
+ * The clients of an animal (contract §11.1): owners, keepers and contacts,
+ * current then former, with their dates when known; « Propriétaire non
+ * renseigné » when no current owner exists (never a placeholder client).
+ * Voided relations are never read. On an active animal: link a client, end
+ * a relation, correct its dates, or void one entered by mistake; on an
+ * archived animal the relations are read-only (§7.1).
+ */
+export default function AnimalRelations({
+ animal,
+ workspaceId,
+ onStatus,
+}: AnimalRelationsProps) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state, reload } = useAnimalRelations(animal.id)
+ const [panelOpen, setPanelOpen] = useState(false)
+ const [target, setTarget] = useState(null)
+ const [stale, setStale] = useState(null)
+ const addButton = useRef(null)
+ const panelWasOpen = useRef(false)
+ const editable = animal.archived_at === null
+
+ // The panel gave focus to its own heading; when it closes, focus goes back to « Ajouter ».
+ useEffect(() => {
+ if (panelWasOpen.current && !panelOpen) addButton.current?.focus()
+ panelWasOpen.current = panelOpen
+ }, [panelOpen])
+
+ const roleLabel = (r: AnimalRelationItem) =>
+ t(`clients.role.${r.ended_at === null ? '' : 'former_'}${r.relation_role}`)
+ const label = (r: AnimalRelationItem) =>
+ `${r.client.display_name} · ${roleLabel(r)}`
+ const period = (r: AnimalRelationItem) =>
+ [
+ r.started_on &&
+ t('relations.since').replace(
+ '{date}',
+ formatDate(r.started_on, locale),
+ ),
+ r.ended_on &&
+ t('relations.until').replace('{date}', formatDate(r.ended_on, locale)),
+ ]
+ .filter(Boolean)
+ .join(' · ')
+
+ const handlers = {
+ onClose: () => setTarget(null),
+ onDone: async (message: string) => {
+ await reload()
+ setStale(null)
+ onStatus(message)
+ setTarget(null)
+ },
+ onStale: async (failure: RecordFailureKind) => {
+ await reload()
+ setStale(failure)
+ setTarget(null)
+ },
+ }
+
+ function row(r: AnimalRelationItem) {
+ const named = (key: string) =>
+ t('relations.action_named')
+ .replace('{action}', t(key))
+ .replace('{name}', r.client.display_name)
+ .replace('{role}', roleLabel(r).toLowerCase())
+ const action = (kind: Action, key: string) => (
+
+ )
+ return (
+
+
+
+
+ {r.client.display_name}
+
+ {r.client.archived_at && (
+ {t('clients.archived_badge')}
+ )}
+
+
+ {roleLabel(r)}
+ {period(r) && ` · ${period(r)}`}
+
+
+ {r.client.phone && (
+
+ {r.client.phone}
+
+ )}
+ {editable && (
+
+ {r.ended_at === null && action('end', 'relations.end.action')}
+ {action('dates', 'relations.dates.action')}
+ {action('void', 'relations.void.action')}
+
+ )}
+
+ )
+ }
+
+ function group(rows: AnimalRelationItem[], key: string, id: string) {
+ if (!rows.length) return null
+ return (
+
+ )
+ }
+
+ const groups =
+ state.status === 'ready' ? groupRelations(state.relations) : null
+
+ return (
+
+
+
+ {t('relations.title')}
+
+ {editable && !panelOpen && (
+
+ )}
+
+ {state.status === 'loading' && (
+
+ {t('relations.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+
+ {t(`relations.failure.${state.failure}`)}
+
+
+
+ )}
+ {stale && {t(`relations.failure.${stale}`)}}
+ {groups && !groups.hasOwner && (
+
+ {t('animals.no_owner')}
+
+ )}
+ {groups && groups.current.length + groups.former.length === 0 && (
+
+ {t('relations.none')}
+
+ )}
+ {groups &&
+ group(groups.current, 'relations.current', 'animal-relations-current')}
+ {groups &&
+ group(groups.former, 'relations.former', 'animal-relations-former')}
+ {panelOpen && (
+ setPanelOpen(false)}
+ onSaved={async () => {
+ await reload()
+ setStale(null)
+ onStatus(t('relations.added_client'))
+ setPanelOpen(false)
+ }}
+ />
+ )}
+ {target?.action === 'end' && (
+ handlers.onDone(t('relations.end.done'))}
+ />
+ )}
+ {target?.action === 'dates' && (
+ handlers.onDone(t('relations.dates.done'))}
+ />
+ )}
+ {target?.action === 'void' && (
+ handlers.onDone(t('relations.void.done'))}
+ />
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/relations/Pickers.tsx b/apps/app/src/components/relations/Pickers.tsx
new file mode 100644
index 00000000..030d66c7
--- /dev/null
+++ b/apps/app/src/components/relations/Pickers.tsx
@@ -0,0 +1,78 @@
+import type { AnimalListItem, ClientListItem } from '@faunosteo/supabase'
+import RecordPicker from './RecordPicker'
+import { speciesName, useSpecies } from '@/animals/species'
+import { useAnimalChoices, useClientChoices } from '@/relations/choices'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+/** The record a picker handed over: its id and the name to show. */
+export interface Chosen {
+ id: string
+ name: string
+}
+
+/** A client of the workspace, active only, found by the server search. */
+export function ClientPicker(props: {
+ id: string
+ workspaceId: string
+ error?: string
+ onChoose: (chosen: Chosen) => void
+}) {
+ const t = useT()
+ const search = useClientChoices(props.workspaceId)
+ return (
+
+ id={props.id}
+ label={t('relations.picker.client_label')}
+ hint={t('relations.picker.client_hint')}
+ resultsLabel={t('relations.picker.client_results')}
+ emptyLabel={t('relations.picker.client_none')}
+ search={search}
+ toItem={(row) => ({
+ id: row.id,
+ name: row.display_name,
+ detail: [t(`clients.kind.${row.kind}`), row.city]
+ .filter(Boolean)
+ .join(' · '),
+ })}
+ onChoose={(row) => props.onChoose({ id: row.id, name: row.display_name })}
+ error={props.error}
+ />
+ )
+}
+
+/** An animal of the workspace, active only, found by the server search. */
+export function AnimalPicker(props: {
+ id: string
+ workspaceId: string
+ error?: string
+ onChoose: (chosen: Chosen) => void
+}) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const search = useAnimalChoices(props.workspaceId)
+ return (
+
+ id={props.id}
+ label={t('relations.picker.animal_label')}
+ hint={t('relations.picker.animal_hint')}
+ resultsLabel={t('relations.picker.animal_results')}
+ emptyLabel={t('relations.picker.animal_none')}
+ search={search}
+ toItem={(row) => ({
+ id: row.id,
+ name: row.name,
+ detail: [
+ speciesName(labels, row.species_id, row.species_detail, locale),
+ row.breed,
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ })}
+ onChoose={(row) => props.onChoose({ id: row.id, name: row.name })}
+ error={props.error}
+ />
+ )
+}
diff --git a/apps/app/src/components/relations/RecordPicker.tsx b/apps/app/src/components/relations/RecordPicker.tsx
new file mode 100644
index 00000000..e189339e
--- /dev/null
+++ b/apps/app/src/components/relations/RecordPicker.tsx
@@ -0,0 +1,159 @@
+import { useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import Button from '@/components/ui/Button'
+import FormField from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import Notice from '@/components/ui/Notice'
+import { SEARCH_DELAY_MS } from '@/clients/useClientList'
+import { useT } from '@/i18n/useT'
+
+export interface PickerItem {
+ id: string
+ name: string
+ /** One muted line under the name: kind and city, or species and breed. */
+ detail: string
+}
+
+export interface RecordPickerProps {
+ id: string
+ label: string
+ hint: string
+ /** Accessible name of the result list. */
+ resultsLabel: string
+ emptyLabel: string
+ /** The server search (POST): the term never reaches a URL. Stable across renders. */
+ search: (term: string) => Promise
+ /** How a row reads, computed at render so a change of language needs no new search. */
+ toItem: (row: Row) => PickerItem
+ onChoose: (row: Row) => void
+ /** The field's own error (« choisissez un client »). */
+ error?: string
+}
+
+type Results =
+ | { status: 'loading' }
+ | { status: 'ready'; items: Row[] }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/**
+ * Finds one record to link through the server search, the active records
+ * only: a search field, then the first matches as buttons named by the
+ * record. No local copy of the records; an answer to an older term is
+ * dropped. Choosing hands the item to the parent, which replaces the picker.
+ */
+export default function RecordPicker({
+ id,
+ label,
+ hint,
+ resultsLabel,
+ emptyLabel,
+ search,
+ toItem,
+ onChoose,
+ error,
+}: RecordPickerProps) {
+ const t = useT()
+ const [query, setQuery] = useState('')
+ const [term, setTerm] = useState('')
+ const [results, setResults] = useState>({ status: 'loading' })
+ const [attempt, setAttempt] = useState(0)
+ const generation = useRef(0)
+
+ useEffect(() => {
+ const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS)
+ return () => clearTimeout(timer)
+ }, [query])
+
+ useEffect(() => {
+ const current = ++generation.current
+ setResults({ status: 'loading' })
+ search(term)
+ .then((items) => {
+ if (current === generation.current)
+ setResults({ status: 'ready', items })
+ })
+ .catch((failure: unknown) => {
+ if (current === generation.current)
+ setResults({
+ status: 'error',
+ failure: classifyRecordError(failure),
+ })
+ })
+ }, [search, term, attempt])
+
+ const describedBy = error ? `${id}-error` : `${id}-hint`
+
+ return (
+
+
+ setQuery(e.target.value)}
+ maxLength={100}
+ autoComplete="off"
+ aria-invalid={Boolean(error)}
+ aria-describedby={describedBy}
+ />
+
+ {results.status === 'loading' && (
+
+ {t('relations.picker.loading')}
+
+ )}
+ {results.status === 'error' && (
+
+
+ {t(`relations.failure.${results.failure}`)}
+
+
+
+ )}
+ {results.status === 'ready' && results.items.length === 0 && (
+
+ {emptyLabel}
+
+ )}
+ {results.status === 'ready' && results.items.length > 0 && (
+
+ {results.items.map((row) => {
+ const item = toItem(row)
+ return (
+ -
+
+
+ )
+ })}
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/relations/RelationActionDialog.tsx b/apps/app/src/components/relations/RelationActionDialog.tsx
new file mode 100644
index 00000000..ce7e569b
--- /dev/null
+++ b/apps/app/src/components/relations/RelationActionDialog.tsx
@@ -0,0 +1,123 @@
+import { useState, type ReactNode } from 'react'
+import {
+ classifyRecordError,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import Button from '@/components/ui/Button'
+import Dialog from '@/components/ui/Dialog'
+import Notice from '@/components/ui/Notice'
+import { useT } from '@/i18n/useT'
+
+export interface RelationActionHandlers {
+ onClose: () => void
+ /** After a success: the page reloads the relations, announces, then closes the dialog. */
+ onDone: () => Promise
+ /**
+ * The relation changed or left elsewhere (`conflict`, `not_found`): the page
+ * reloads and says so, then closes the dialog; the stale row is never retried.
+ */
+ onStale: (failure: RecordFailureKind) => Promise
+}
+
+export interface RelationActionDialogProps extends RelationActionHandlers {
+ title: string
+ /** Which relation: « Marie Dupont · Propriétaire ». */
+ relationLabel: string
+ body: string
+ confirmLabel: string
+ pendingLabel: string
+ danger?: boolean
+ children?: ReactNode
+ /** Checks the fields; false keeps the dialog open with their errors. */
+ validate?: () => boolean
+ /** The relation RPC; throws a RecordFailure. */
+ action: () => Promise
+}
+
+/**
+ * Confirmation of one relation write (end, dates, void) on the shared
+ * ModalDialog: closing is never confirming; while the write and the reload
+ * that shows it run, the dialog refuses to close, so focus returns once,
+ * after the change is on the page (to the opener, or to its container when
+ * the opener left with the row). Other failures stay in the dialog with the
+ * values typed.
+ */
+export default function RelationActionDialog({
+ title,
+ relationLabel,
+ body,
+ confirmLabel,
+ pendingLabel,
+ danger = false,
+ children,
+ validate,
+ action,
+ onClose,
+ onDone,
+ onStale,
+}: RelationActionDialogProps) {
+ const t = useT()
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(null)
+
+ const close = () => {
+ if (!pending) onClose()
+ }
+
+ async function confirm() {
+ if (pending || (validate && !validate())) return
+ setPending(true)
+ setFailure(null)
+ try {
+ await action()
+ await onDone()
+ } catch (error) {
+ const kind = classifyRecordError(error)
+ if (kind === 'conflict' || kind === 'not_found') await onStale(kind)
+ else setFailure(kind)
+ } finally {
+ setPending(false)
+ }
+ }
+
+ return (
+
+ )
+}
diff --git a/apps/app/src/components/relations/RelationDialogs.tsx b/apps/app/src/components/relations/RelationDialogs.tsx
new file mode 100644
index 00000000..d4684f94
--- /dev/null
+++ b/apps/app/src/components/relations/RelationDialogs.tsx
@@ -0,0 +1,211 @@
+import { useState } from 'react'
+import {
+ endAnimalClientRelation,
+ updateAnimalClientRelation,
+ voidAnimalClientRelation,
+ type AnimalRelationItem,
+} from '@faunosteo/supabase'
+import FormField from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import RelationActionDialog, {
+ type RelationActionHandlers,
+} from './RelationActionDialog'
+import { recordDateIssue } from '@/animals/validation'
+import { localDateIso } from '@/lib/dates'
+import { getSupabaseClient } from '@/lib/supabase'
+import { translateFieldError } from '@/account/validation'
+import { useT } from '@/i18n/useT'
+
+interface RelationDialogProps extends RelationActionHandlers {
+ relation: AnimalRelationItem
+ /** « Marie Dupont · Propriétaire ». */
+ relationLabel: string
+}
+
+function backend() {
+ const client = getSupabaseClient()
+ if (!client) throw new TypeError('no backend')
+ return client
+}
+
+/** The issue of an end date: a record date, and not before a known start. */
+function endIssue(endedOn: string, startedOn: string, today: string) {
+ const issue = recordDateIssue(endedOn, today)
+ if (issue) return issue
+ return startedOn && endedOn && endedOn < startedOn
+ ? 'relations.error.end_before_start'
+ : null
+}
+
+function DateField(props: {
+ id: string
+ label: string
+ value: string
+ error: string | null
+ today: string
+ onChange: (value: string) => void
+}) {
+ const t = useT()
+ return (
+
+ props.onChange(e.target.value)}
+ aria-invalid={Boolean(props.error)}
+ aria-describedby={
+ props.error ? `${props.id}-error` : `${props.id}-hint`
+ }
+ />
+
+ )
+}
+
+/** Ends a current relation, with its real end date when known (N5: never invented). */
+export function EndRelationDialog({
+ relation,
+ relationLabel,
+ ...handlers
+}: RelationDialogProps) {
+ const t = useT()
+ const today = localDateIso()
+ const [endedOn, setEndedOn] = useState('')
+ const [error, setError] = useState(null)
+ return (
+ {
+ const issue = endIssue(endedOn, relation.started_on ?? '', today)
+ setError(issue)
+ if (issue) document.getElementById('relation-ended-on')?.focus()
+ return issue === null
+ }}
+ action={() =>
+ endAnimalClientRelation(backend(), {
+ relationId: relation.id,
+ expectedRevision: relation.revision,
+ endedOn: endedOn || null,
+ })
+ }
+ >
+
+
+ )
+}
+
+/** Corrects the start date, and the end date of an ended relation; client and role never change. */
+export function RelationDatesDialog({
+ relation,
+ relationLabel,
+ ...handlers
+}: RelationDialogProps) {
+ const t = useT()
+ const today = localDateIso()
+ const ended = relation.ended_at !== null
+ const [startedOn, setStartedOn] = useState(relation.started_on ?? '')
+ const [endedOn, setEndedOn] = useState(relation.ended_on ?? '')
+ const [errors, setErrors] = useState<{
+ start: string | null
+ end: string | null
+ }>({ start: null, end: null })
+ return (
+ {
+ const start = recordDateIssue(startedOn, today)
+ const end = ended ? endIssue(endedOn, startedOn, today) : null
+ setErrors({ start, end })
+ const first = start
+ ? 'relation-started-on'
+ : end
+ ? 'relation-ended-on'
+ : null
+ if (first) document.getElementById(first)?.focus()
+ return !start && !end
+ }}
+ action={() =>
+ updateAnimalClientRelation(backend(), {
+ relationId: relation.id,
+ expectedRevision: relation.revision,
+ startedOn: startedOn || null,
+ endedOn: ended ? endedOn || null : null,
+ })
+ }
+ >
+
+ {ended && (
+
+ )}
+
+ )
+}
+
+/**
+ * Voids a relation entered by mistake (N4): it disappears from every page
+ * and list, is kept frozen for the record lifecycle, and cannot come back.
+ * The text says when to use « Terminer » instead.
+ */
+export function VoidRelationDialog({
+ relation,
+ relationLabel,
+ ...handlers
+}: RelationDialogProps) {
+ const t = useT()
+ return (
+
+ voidAnimalClientRelation(backend(), {
+ relationId: relation.id,
+ expectedRevision: relation.revision,
+ })
+ }
+ />
+ )
+}
diff --git a/apps/app/src/components/relations/RelationPanel.tsx b/apps/app/src/components/relations/RelationPanel.tsx
new file mode 100644
index 00000000..cef60fc7
--- /dev/null
+++ b/apps/app/src/components/relations/RelationPanel.tsx
@@ -0,0 +1,237 @@
+import { useEffect, useRef, useState, type FormEvent } from 'react'
+import {
+ classifyRecordError,
+ createAnimalClientRelation,
+ type AnimalRelationRole,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import Button from '@/components/ui/Button'
+import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios'
+import FormField from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import Notice from '@/components/ui/Notice'
+import { AnimalPicker, ClientPicker, type Chosen } from './Pickers'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import {
+ RELATION_ROLES,
+ relationIssues,
+ type RelationFieldErrors,
+} from '@/animals/validation'
+import { generateUuid } from '@/lib/id'
+import { localDateIso } from '@/lib/dates'
+import { getSupabaseClient } from '@/lib/supabase'
+import { useT } from '@/i18n/useT'
+import { translateFieldError } from '@/account/validation'
+
+export type RelationPanelProps = {
+ workspaceId: string
+ /** Called once the server made the relation; the page reloads, then closes the panel. */
+ onSaved: () => Promise
+ onCancel: () => void
+} & (
+ | { pick: 'client'; animalId: string }
+ | { pick: 'animal'; clientId: string }
+)
+
+const PANEL = 'relation-panel'
+const FIELD_IDS = {
+ client: `${PANEL}-search`,
+ relation_role: firstChoiceId(`${PANEL}-role`, 'owner'),
+ started_on: `${PANEL}-started-on`,
+} as const
+
+/**
+ * Links a client and an animal from one of their pages, inside the page (no
+ * modal form, contract §11.4): find the other record, pick the role (none
+ * preselected), the start date when known. One request id per opening of
+ * the panel, sent again on a retry, so a lost answer never makes a second
+ * relation. Both records must be active; the server says so otherwise.
+ */
+export default function RelationPanel(props: RelationPanelProps) {
+ const t = useT()
+ const heading = useRef(null)
+ const chosenText = useRef(null)
+ const [chosen, setChosen] = useState(null)
+ const [role, setRole] = useState('')
+ const [startedOn, setStartedOn] = useState('')
+ const [errors, setErrors] = useState({})
+ const [errorRound, setErrorRound] = useState(0)
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(null)
+ const [requestId] = useState(generateUuid)
+ const inFlight = useRef(false)
+ const today = localDateIso()
+ useLeaveGuard(Boolean(chosen || role || startedOn))
+
+ useEffect(() => heading.current?.focus(), [])
+ useEffect(() => {
+ if (chosen) chosenText.current?.focus()
+ }, [chosen])
+ useEffect(() => {
+ if (errorRound === 0) return
+ const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find(
+ (key) => errors[key],
+ )
+ if (first) document.getElementById(FIELD_IDS[first])?.focus()
+ }, [errorRound, errors])
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ if (inFlight.current) return
+ const issues = relationIssues(
+ {
+ client: chosen && { id: chosen.id, display_name: chosen.name },
+ relation_role: role,
+ started_on: startedOn,
+ },
+ localDateIso(),
+ true,
+ )
+ setErrors(issues)
+ if (Object.keys(issues).length > 0 || !chosen || role === '') {
+ setErrorRound((n) => n + 1)
+ return
+ }
+ const client = getSupabaseClient()
+ if (!client) return setFailure('unavailable')
+ inFlight.current = true
+ setPending(true)
+ setFailure(null)
+ try {
+ await createAnimalClientRelation(client, {
+ animalId: props.pick === 'client' ? props.animalId : chosen.id,
+ clientId: props.pick === 'client' ? chosen.id : props.clientId,
+ requestId,
+ relationRole: role,
+ startedOn: startedOn || null,
+ })
+ await props.onSaved()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ inFlight.current = false
+ setPending(false)
+ }
+ }
+
+ const err = (key: keyof RelationFieldErrors) =>
+ translateFieldError(t, errors[key])
+ const pickLabel =
+ props.pick === 'client'
+ ? 'relations.panel.client_chosen'
+ : 'relations.panel.animal_chosen'
+
+ return (
+
+ )
+}
diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx
index 9cc46a5f..ac0eebc2 100644
--- a/apps/app/src/components/shell/SidebarNav.tsx
+++ b/apps/app/src/components/shell/SidebarNav.tsx
@@ -13,6 +13,7 @@ interface NavItem {
export const NAV_ITEMS: readonly NavItem[] = [
{ to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true },
{ to: '/app/clients', icon: 'users', labelKey: 'shell.nav.clients' },
+ { to: '/app/animals', icon: 'paw', labelKey: 'shell.nav.animals' },
{ to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' },
{
to: '/',
diff --git a/apps/app/src/components/ui/Button.tsx b/apps/app/src/components/ui/Button.tsx
index a5c1a3da..c7cdb8ef 100644
--- a/apps/app/src/components/ui/Button.tsx
+++ b/apps/app/src/components/ui/Button.tsx
@@ -1,9 +1,11 @@
-import type { ButtonHTMLAttributes, ReactNode } from 'react'
+import type { ButtonHTMLAttributes, ReactNode, Ref } from 'react'
export interface ButtonProps extends ButtonHTMLAttributes {
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
size?: 'sm' | 'md' | 'lg'
children?: ReactNode
+ /** React 19 passes it as a prop; it reaches the