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

@@ -0,0 +1,439 @@
import { useEffect, useRef } from 'react'
import { Link } from 'react-router-dom'
import { ANIMAL_FIELD_LIMITS } from '@faunosteo/supabase'
import Button, { buttonClassName } from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import Select from '@/components/ui/Select'
import { ClientPicker } from '@/components/relations/Pickers'
import { speciesName, useSpecies } from '@/animals/species'
import type { AnimalForm as AnimalFormState } from '@/animals/useAnimalForm'
import {
ANIMAL_SEXES,
OTHER_SPECIES,
RELATION_ROLES,
animalFormValues,
type AnimalFormValues,
type RelationFieldErrors,
} from '@/animals/validation'
import { translateFieldError } from '@/account/validation'
import { formatDate, localDateIso } from '@/lib/dates'
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
/** Ids of the controls that take focus on an error, in form order. */
const FIELD_IDS: Record<
keyof AnimalFormValues | keyof RelationFieldErrors,
string
> = {
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<HTMLParagraphElement>(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<string, unknown>
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 (
<FormField
id={FIELD_IDS[key]}
label={label}
optional={t(
isRequired ? 'animals.form.required' : 'animals.form.optional',
)}
hint={shownHint}
error={err(key)}
>
<Input
id={FIELD_IDS[key]}
value={values[key]}
onChange={(e) => form.setField(key)(e.target.value)}
maxLength={max}
autoComplete="off"
aria-invalid={Boolean(errors[key])}
aria-describedby={describedBy(key, shownHint)}
required={isRequired}
/>
</FormField>
)
}
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 (
<form onSubmit={form.submit} noValidate className="space-y-6">
{stored && (
<Notice tone="error">
<p className="font-medium">{t('animals.form.conflict_title')}</p>
<p>{t('animals.form.conflict_body')}</p>
<Button
type="button"
variant="secondary"
size="sm"
className="mt-2"
onClick={form.takeStored}
>
{t('animals.form.conflict_take_stored')}
</Button>
</Notice>
)}
<Card
as="section"
aria-labelledby="animal-identity-title"
className="space-y-5 p-5 sm:p-6"
>
<h2
id="animal-identity-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('animals.form.identity_title')}
</h2>
{textField(
'name',
t('animals.form.name'),
ANIMAL_FIELD_LIMITS.name,
true,
)}
<FormField
id={FIELD_IDS.species_id}
label={t('animals.form.species')}
optional={required}
hint={speciesHint}
error={err('species_id')}
>
<Select
id={FIELD_IDS.species_id}
value={values.species_id}
onChange={(e) => form.setField('species_id')(e.target.value)}
aria-invalid={Boolean(errors.species_id)}
aria-describedby={describedBy('species_id', speciesHint)}
required
>
<option value="">
{species.status === 'ready'
? t('animals.form.species_choose')
: t('animals.form.species_loading')}
</option>
{labels.map((s) => (
<option key={s.id} value={s.id}>
{pickLocaleLabel(s.name_fr, s.name_en, locale, s.id)}
</option>
))}
{/* A stored species that left the active list stays shown on an edit. */}
{values.species_id &&
species.status === 'ready' &&
!labels.some((s) => s.id === values.species_id) && (
<option value={values.species_id}>{values.species_id}</option>
)}
</Select>
</FormField>
{species.status === 'error' && (
<div className="space-y-2">
<Notice tone="error">{t('animals.form.species_failed')}</Notice>
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
onClick={retrySpecies}
>
{t('common.retry')}
</Button>
</div>
)}
{values.species_id === OTHER_SPECIES &&
textField(
'species_detail',
t('animals.form.species_detail'),
ANIMAL_FIELD_LIMITS.speciesDetail,
true,
t('animals.form.species_detail_hint'),
)}
<ChoiceRadios
id="animal-sex"
legend={t('animals.form.sex')}
marker={required}
options={ANIMAL_SEXES.map((value) => ({
value,
label: t(`animals.sex.${value}`),
}))}
value={values.sex}
onChange={(value) => form.setField('sex')(value)}
hint={storedHint('sex') ?? t('animals.form.sex_hint')}
error={err('sex')}
/>
{textField(
'breed',
t('animals.form.breed'),
ANIMAL_FIELD_LIMITS.breed,
false,
)}
</Card>
<Card
as="section"
aria-labelledby="animal-birth-title"
className="space-y-4 p-5 sm:p-6"
>
<h2
id="animal-birth-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('animals.form.birth_title')}
</h2>
<div className="grid gap-4 sm:grid-cols-[10rem_1fr]">
<FormField
id={FIELD_IDS.birth_year}
label={t('animals.form.birth_year')}
optional={optional}
hint={yearHint}
error={err('birth_year')}
>
<Input
id={FIELD_IDS.birth_year}
inputMode="numeric"
autoComplete="off"
value={values.birth_year}
onChange={(e) => form.setField('birth_year')(e.target.value)}
readOnly={yearLocked}
maxLength={4}
aria-invalid={Boolean(errors.birth_year)}
aria-describedby={describedBy('birth_year', yearHint)}
className={yearLocked ? 'bg-[var(--color-surface-strong)]' : ''}
/>
</FormField>
<FormField
id={FIELD_IDS.birth_date}
label={t('animals.form.birth_date')}
optional={optional}
hint={storedHint('birth_date') ?? t('animals.form.birth_date_hint')}
error={err('birth_date')}
>
<Input
id={FIELD_IDS.birth_date}
type="date"
value={values.birth_date}
min="1900-01-01"
max={today}
onChange={(e) => form.setBirthDate(e.target.value)}
aria-invalid={Boolean(errors.birth_date)}
aria-describedby={describedBy('birth_date', 'hint')}
className="sm:max-w-xs"
/>
</FormField>
</div>
</Card>
{form.mode === 'create' && (
<Card
as="section"
aria-labelledby="animal-client-title"
className="space-y-4 p-5 sm:p-6"
>
<div className="space-y-1">
<h2
id="animal-client-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('animals.form.client_title')}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('animals.form.client_hint')}
</p>
</div>
{relation.client ? (
<>
<div className="flex flex-wrap items-center gap-3">
<p
ref={chosenText}
tabIndex={-1}
className="min-w-0 text-sm text-[var(--color-ink)] outline-none"
>
{t('relations.panel.client_chosen')}{' '}
<span className="font-medium">
{relation.client.display_name}
</span>
</p>
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
onClick={() => form.chooseClient(null)}
>
{t('animals.form.client_remove')}
</Button>
</div>
<ChoiceRadios
id="animal-role"
legend={t('relations.panel.role')}
marker={required}
options={RELATION_ROLES.map((value) => ({
value,
label: t(`clients.role.${value}`),
}))}
value={relation.relation_role}
onChange={form.setRelationRole}
error={relErr('relation_role')}
/>
<FormField
id={FIELD_IDS.started_on}
label={t('relations.panel.started_on')}
optional={optional}
hint={t('relations.date_hint')}
error={relErr('started_on')}
>
<Input
id={FIELD_IDS.started_on}
type="date"
value={relation.started_on}
min="1900-01-01"
max={today}
onChange={(e) => form.setStartedOn(e.target.value)}
aria-invalid={Boolean(relationErrors.started_on)}
aria-describedby={
relationErrors.started_on
? `${FIELD_IDS.started_on}-error`
: `${FIELD_IDS.started_on}-hint`
}
className="sm:max-w-xs"
/>
</FormField>
</>
) : (
<ClientPicker
id={FIELD_IDS.client}
workspaceId={workspaceId}
onChoose={(chosen) =>
form.chooseClient({ id: chosen.id, display_name: chosen.name })
}
/>
)}
</Card>
)}
{phase.kind === 'failed' && !stored && (
<Notice tone="error">{t(`animals.failure.${phase.failure}`)}</Notice>
)}
<div className="sticky bottom-0 -mx-4 flex flex-wrap items-center justify-end gap-3 border-t border-[var(--color-border)] bg-[var(--color-bg)] px-4 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0">
<Link
to={cancelTo}
className={buttonClassName('ghost', 'md', 'min-h-11')}
>
{t('common.cancel')}
</Link>
<Button
type="submit"
disabled={saving}
aria-disabled={saving}
className="min-h-11"
>
{saving ? t('animals.form.saving') : submitLabel}
</Button>
</div>
</form>
)
}
@@ -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 (
<Card as="section" className="space-y-3 p-5 sm:p-6">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)]"
>
{t('animals.not_found.title')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('animals.not_found.body')}
</p>
<ButtonLink to="/app/animals" variant="secondary">
{t('animals.not_found.back')}
</ButtonLink>
</Card>
)
}
@@ -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<RecordFailureKind | null>(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 (
<Dialog
open={open}
onClose={close}
title={t('animals.archive.title')}
description={
<p className="text-sm text-[var(--color-ink-muted)]">
{t('animals.archive.body')}
</p>
}
size="sm"
>
{failure && (
<Notice tone="error" className="mt-3">
{t(`animals.failure.${failure}`)}
</Notice>
)}
<div className="mt-4 flex flex-wrap justify-end gap-2">
{/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
<Button
type="button"
variant="ghost"
onClick={close}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button
type="button"
variant="danger"
onClick={() => void confirm()}
aria-disabled={pending}
>
{pending
? t('animals.archive.archiving')
: t('animals.archive.confirm')}
</Button>
</div>
</Dialog>
)
}