feat(app): animal screens, relation panels, animals on the client page

Routes /app/animals, new, :animalId, edit under one workspace gate; list with
species filter; form (D-R7, U3 birth, no default sex or role, optional first
client); page with current and former relations, end, dates, void; client page
links its animals, adds one pre-associated, links an existing one. Card now
passes aria-labelledby, which it silently dropped.
This commit is contained in:
bchanot committed 2026-10-26 17:11:28 +01:00
1 parent e22357630f
commit 930499cd25
36 files changed
+5579 -113

No files matched your search

+186 -97
View File
@@ -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<string, AnimalGroup>()
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<State>({ status: 'loading' })
const [loadingMore, setLoadingMore] = useState(false)
const [panelOpen, setPanelOpen] = useState(false)
const linkButton = useRef<HTMLButtonElement>(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 (
<section aria-labelledby={id} className="space-y-2">
@@ -124,70 +166,104 @@ export default function ClientAnimals({ clientId }: { clientId: string }) {
{t(current ? 'clients.animals.current' : 'clients.animals.former')}
</h3>
<ul className="divide-y divide-[var(--color-border)] rounded-xl border border-[var(--color-border)] bg-white">
{shown.map((row) => (
<li
key={row.relation_id}
className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 px-4 py-3"
>
<span className="min-w-0">
<span className="font-medium text-[var(--color-ink)]">
{row.animal_name}
</span>{' '}
<span className="text-sm text-[var(--color-ink-muted)]">
{speciesName(row, species)}
{groups.map(({ animalId, rows }) => {
const first = rows[0]
return (
<li key={animalId} className="space-y-1 px-4 py-3">
<span className="flex flex-wrap items-center gap-2">
<Link to={`/app/animals/${animalId}`} className={linkClass}>
{first.animal_name}
</Link>
<span className="text-sm text-[var(--color-ink-muted)]">
{speciesName(
labels,
first.species_id,
first.species_detail,
locale,
)}
</span>
{first.animal_archived_at && (
<Badge tone="warn">{t('animals.archived_badge')}</Badge>
)}
</span>
{row.animal_archived_at && (
<Badge className="ml-2">{t('clients.archived_badge')}</Badge>
)}
</span>
<span className="text-sm text-[var(--color-ink-muted)]">
{t(
`clients.role.${current ? '' : 'former_'}${row.relation_role}`,
)}
{period(row) && ` · ${period(row)}`}
</span>
</li>
))}
<ul className="text-sm text-[var(--color-ink)]">
{rows.map((row) => (
<li key={row.relation_id}>{roleText(row)}</li>
))}
</ul>
</li>
)
})}
</ul>
</section>
)
}
const empty = state.status === 'ready' && state.rows.length === 0
return (
<Card
as="section"
aria-labelledby="client-animals-title"
className="space-y-4 p-5 sm:p-6"
>
<h2
id="client-animals-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('clients.animals.title')}
</h2>
<div className="flex flex-wrap items-center justify-between gap-3">
<h2
id="client-animals-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('clients.animals.title')}
</h2>
{!archived && !panelOpen && (
<div className="flex flex-wrap gap-2">
<ButtonLink
to="/app/animals/new"
state={{ clientId } satisfies AnimalCreateState}
className="min-h-11"
>
{t(empty ? 'clients.animals.add_first' : 'clients.animals.add')}
</ButtonLink>
<Button
ref={linkButton}
type="button"
variant="secondary"
className="min-h-11"
onClick={() => setPanelOpen(true)}
>
{t('clients.animals.link_existing')}
</Button>
</div>
)}
</div>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('clients.animals.loading')}
</p>
)}
{state.status === 'error' && (
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
<div className="space-y-3">
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
<Button type="button" variant="secondary" onClick={() => void load()}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && state.rows.length === 0 && (
{empty && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('clients.animals.none')}
</p>
)}
{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 && (
<Button
type="button"
variant="secondary"
className="min-h-11"
onClick={() => void more()}
disabled={loadingMore}
aria-disabled={loadingMore}
>
{loadingMore
? t('clients.list.loading_more')
@@ -196,6 +272,19 @@ export default function ClientAnimals({ clientId }: { clientId: string }) {
)}
</>
)}
{panelOpen && (
<RelationPanel
pick="animal"
clientId={clientId}
workspaceId={workspaceId}
onCancel={() => setPanelOpen(false)}
onSaved={async () => {
await load()
onStatus(t('relations.added_animal'))
setPanelOpen(false)
}}
/>
)}
</Card>
)
}