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>
)
}
+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>
)
}
@@ -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<Target | null>(null)
const [stale, setStale] = useState<RecordFailureKind | null>(null)
const addButton = useRef<HTMLButtonElement>(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) => (
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
aria-label={named(key)}
onClick={() => setTarget({ action: kind, relation: r })}
>
{t(key)}
</Button>
)
return (
<li key={r.id} className="space-y-2 px-4 py-3">
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<span className="flex min-w-0 flex-wrap items-center gap-2">
<Link
to={`/app/clients/${r.client.id}`}
className={`${linkClass} font-medium break-words`}
>
{r.client.display_name}
</Link>
{r.client.archived_at && (
<Badge tone="warn">{t('clients.archived_badge')}</Badge>
)}
</span>
<span className="text-sm text-[var(--color-ink-muted)]">
{roleLabel(r)}
{period(r) && ` · ${period(r)}`}
</span>
</div>
{r.client.phone && (
<a
href={`tel:${r.client.phone}`}
className={`${linkClass} inline-flex min-h-11 items-center text-sm tabular-nums`}
>
{r.client.phone}
</a>
)}
{editable && (
<div className="flex flex-wrap gap-2">
{r.ended_at === null && action('end', 'relations.end.action')}
{action('dates', 'relations.dates.action')}
{action('void', 'relations.void.action')}
</div>
)}
</li>
)
}
function group(rows: AnimalRelationItem[], key: string, id: string) {
if (!rows.length) return null
return (
<section aria-labelledby={id} className="space-y-2">
<h3
id={id}
className="text-sm font-medium text-[var(--color-ink-muted)]"
>
{t(key)}
</h3>
<ul className="divide-y divide-[var(--color-border)] rounded-xl border border-[var(--color-border)] bg-white">
{rows.map(row)}
</ul>
</section>
)
}
const groups =
state.status === 'ready' ? groupRelations(state.relations) : null
return (
<Card
as="section"
aria-labelledby="animal-relations-title"
className="space-y-4 p-5 sm:p-6"
>
<div className="flex flex-wrap items-center justify-between gap-3">
<h2
id="animal-relations-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('relations.title')}
</h2>
{editable && !panelOpen && (
<Button
ref={addButton}
type="button"
variant="secondary"
className="min-h-11"
onClick={() => setPanelOpen(true)}
>
{t('relations.add_client')}
</Button>
)}
</div>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('relations.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">
{t(`relations.failure.${state.failure}`)}
</Notice>
<Button
type="button"
variant="secondary"
onClick={() => void reload()}
>
{t('common.retry')}
</Button>
</div>
)}
{stale && <Notice tone="error">{t(`relations.failure.${stale}`)}</Notice>}
{groups && !groups.hasOwner && (
<p className="rounded-lg border border-dashed border-[var(--color-border)] px-3 py-2 text-sm text-[var(--color-ink)]">
{t('animals.no_owner')}
</p>
)}
{groups && groups.current.length + groups.former.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('relations.none')}
</p>
)}
{groups &&
group(groups.current, 'relations.current', 'animal-relations-current')}
{groups &&
group(groups.former, 'relations.former', 'animal-relations-former')}
{panelOpen && (
<RelationPanel
pick="client"
animalId={animal.id}
workspaceId={workspaceId}
onCancel={() => setPanelOpen(false)}
onSaved={async () => {
await reload()
setStale(null)
onStatus(t('relations.added_client'))
setPanelOpen(false)
}}
/>
)}
{target?.action === 'end' && (
<EndRelationDialog
relation={target.relation}
relationLabel={label(target.relation)}
{...handlers}
onDone={() => handlers.onDone(t('relations.end.done'))}
/>
)}
{target?.action === 'dates' && (
<RelationDatesDialog
relation={target.relation}
relationLabel={label(target.relation)}
{...handlers}
onDone={() => handlers.onDone(t('relations.dates.done'))}
/>
)}
{target?.action === 'void' && (
<VoidRelationDialog
relation={target.relation}
relationLabel={label(target.relation)}
{...handlers}
onDone={() => handlers.onDone(t('relations.void.done'))}
/>
)}
</Card>
)
}
@@ -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 (
<RecordPicker<ClientListItem>
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 (
<RecordPicker<AnimalListItem>
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}
/>
)
}
@@ -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<Row> {
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<Row[]>
/** 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<Row> =
| { 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<Row>({
id,
label,
hint,
resultsLabel,
emptyLabel,
search,
toItem,
onChoose,
error,
}: RecordPickerProps<Row>) {
const t = useT()
const [query, setQuery] = useState('')
const [term, setTerm] = useState('')
const [results, setResults] = useState<Results<Row>>({ 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 (
<div className="space-y-2">
<FormField id={id} label={label} hint={hint} error={error}>
<Input
id={id}
type="search"
value={query}
onChange={(e) => setQuery(e.target.value)}
maxLength={100}
autoComplete="off"
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
/>
</FormField>
{results.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('relations.picker.loading')}
</p>
)}
{results.status === 'error' && (
<div className="space-y-2">
<Notice tone="error">
{t(`relations.failure.${results.failure}`)}
</Notice>
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
onClick={() => setAttempt((n) => n + 1)}
>
{t('common.retry')}
</Button>
</div>
)}
{results.status === 'ready' && results.items.length === 0 && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{emptyLabel}
</p>
)}
{results.status === 'ready' && results.items.length > 0 && (
<ul
aria-label={resultsLabel}
className="max-h-72 divide-y divide-[var(--color-border)] overflow-y-auto rounded-xl border border-[var(--color-border)] bg-white"
>
{results.items.map((row) => {
const item = toItem(row)
return (
<li key={item.id}>
<button
type="button"
onClick={() => onChoose(row)}
className="flex min-h-11 w-full flex-col items-start gap-0.5 px-4 py-2 text-left hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)]"
>
<span className="font-medium text-[var(--color-ink)]">
{item.name}
</span>
{item.detail && (
<span className="text-sm text-[var(--color-ink-muted)]">
{item.detail}
</span>
)}
</button>
</li>
)
})}
</ul>
)}
</div>
)
}
@@ -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<void>
/**
* 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<void>
}
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<unknown>
}
/**
* 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<RecordFailureKind | null>(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 (
<Dialog
open
onClose={close}
title={title}
description={
<div className="space-y-2 text-sm">
<p className="font-medium text-[var(--color-ink)]">{relationLabel}</p>
<p className="text-[var(--color-ink-muted)]">{body}</p>
</div>
}
size="sm"
>
<div className="mt-3 space-y-3">
{children}
{failure && (
<Notice tone="error">{t(`relations.failure.${failure}`)}</Notice>
)}
</div>
<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 ? 'danger' : 'primary'}
onClick={() => void confirm()}
aria-disabled={pending}
>
{pending ? pendingLabel : confirmLabel}
</Button>
</div>
</Dialog>
)
}
@@ -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 (
<FormField
id={props.id}
label={props.label}
optional={t('animals.form.optional')}
hint={t('relations.date_hint')}
error={translateFieldError(t, props.error ?? undefined)}
>
<Input
id={props.id}
type="date"
value={props.value}
min="1900-01-01"
max={props.today}
onChange={(e) => props.onChange(e.target.value)}
aria-invalid={Boolean(props.error)}
aria-describedby={
props.error ? `${props.id}-error` : `${props.id}-hint`
}
/>
</FormField>
)
}
/** 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<string | null>(null)
return (
<RelationActionDialog
{...handlers}
title={t('relations.end.title')}
relationLabel={relationLabel}
body={t('relations.end.body')}
confirmLabel={t('relations.end.confirm')}
pendingLabel={t('relations.saving')}
validate={() => {
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,
})
}
>
<DateField
id="relation-ended-on"
label={t('relations.end.ended_on')}
value={endedOn}
error={error}
today={today}
onChange={setEndedOn}
/>
</RelationActionDialog>
)
}
/** 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 (
<RelationActionDialog
{...handlers}
title={t('relations.dates.title')}
relationLabel={relationLabel}
body={t('relations.dates.body')}
confirmLabel={t('relations.dates.confirm')}
pendingLabel={t('relations.saving')}
validate={() => {
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,
})
}
>
<DateField
id="relation-started-on"
label={t('relations.dates.started_on')}
value={startedOn}
error={errors.start}
today={today}
onChange={setStartedOn}
/>
{ended && (
<DateField
id="relation-ended-on"
label={t('relations.dates.ended_on')}
value={endedOn}
error={errors.end}
today={today}
onChange={setEndedOn}
/>
)}
</RelationActionDialog>
)
}
/**
* 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 (
<RelationActionDialog
{...handlers}
title={t('relations.void.title')}
relationLabel={relationLabel}
body={t('relations.void.body')}
confirmLabel={t('relations.void.confirm')}
pendingLabel={t('relations.saving')}
danger
action={() =>
voidAnimalClientRelation(backend(), {
relationId: relation.id,
expectedRevision: relation.revision,
})
}
/>
)
}
@@ -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<void>
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<HTMLHeadingElement>(null)
const chosenText = useRef<HTMLParagraphElement>(null)
const [chosen, setChosen] = useState<Chosen | null>(null)
const [role, setRole] = useState<AnimalRelationRole | ''>('')
const [startedOn, setStartedOn] = useState('')
const [errors, setErrors] = useState<RelationFieldErrors>({})
const [errorRound, setErrorRound] = useState(0)
const [pending, setPending] = useState(false)
const [failure, setFailure] = useState<RecordFailureKind | null>(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 (
<form
onSubmit={submit}
noValidate
aria-labelledby={`${PANEL}-title`}
className="space-y-4 border-t border-[var(--color-border)] pt-4"
>
<h3
id={`${PANEL}-title`}
ref={heading}
tabIndex={-1}
className="text-base font-medium text-[var(--color-ink)] outline-none"
>
{t(
props.pick === 'client'
? 'relations.panel.title_client'
: 'relations.panel.title_animal',
)}
</h3>
{chosen ? (
<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(pickLabel)} <span className="font-medium">{chosen.name}</span>
</p>
<Button
type="button"
variant="secondary"
size="sm"
className="min-h-11"
onClick={() => setChosen(null)}
>
{t('relations.panel.change')}
</Button>
</div>
) : props.pick === 'client' ? (
<ClientPicker
id={FIELD_IDS.client}
workspaceId={props.workspaceId}
error={err('client')}
onChoose={setChosen}
/>
) : (
<AnimalPicker
id={FIELD_IDS.client}
workspaceId={props.workspaceId}
error={err('client')}
onChoose={setChosen}
/>
)}
<ChoiceRadios
id={`${PANEL}-role`}
legend={t('relations.panel.role')}
marker={t('animals.form.required')}
options={RELATION_ROLES.map((value) => ({
value,
label: t(`clients.role.${value}`),
}))}
value={role}
onChange={setRole}
error={err('relation_role')}
/>
<FormField
id={FIELD_IDS.started_on}
label={t('relations.panel.started_on')}
optional={t('animals.form.optional')}
hint={t('relations.date_hint')}
error={err('started_on')}
>
<Input
id={FIELD_IDS.started_on}
type="date"
value={startedOn}
min="1900-01-01"
max={today}
onChange={(e) => setStartedOn(e.target.value)}
aria-invalid={Boolean(errors.started_on)}
aria-describedby={
errors.started_on
? `${FIELD_IDS.started_on}-error`
: `${FIELD_IDS.started_on}-hint`
}
className="sm:max-w-xs"
/>
</FormField>
{failure && (
<Notice tone="error">{t(`relations.failure.${failure}`)}</Notice>
)}
<div className="flex flex-wrap justify-end gap-2">
<Button
type="button"
variant="ghost"
className="min-h-11"
onClick={() => !pending && props.onCancel()}
aria-disabled={pending}
>
{t('common.cancel')}
</Button>
<Button type="submit" className="min-h-11" aria-disabled={pending}>
{pending
? t('relations.panel.saving')
: t(
props.pick === 'client'
? 'relations.panel.save_client'
: 'relations.panel.save_animal',
)}
</Button>
</div>
</form>
)
}
@@ -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: '/',
+3 -1
View File
@@ -1,9 +1,11 @@
import type { ButtonHTMLAttributes, ReactNode } from 'react'
import type { ButtonHTMLAttributes, ReactNode, Ref } from 'react'
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
size?: 'sm' | 'md' | 'lg'
children?: ReactNode
/** React 19 passes it as a prop; it reaches the <button> with the rest. */
ref?: Ref<HTMLButtonElement>
}
const VARIANTS: Record<NonNullable<ButtonProps['variant']>, string> = {
+4
View File
@@ -4,15 +4,19 @@ export interface CardProps {
children: ReactNode
className?: string
as?: 'div' | 'section' | 'article'
/** Names a section card by its heading, so it reads as a named region. */
'aria-labelledby'?: string
}
export default function Card({
children,
className = '',
as: Tag = 'div',
'aria-labelledby': labelledBy,
}: CardProps) {
return (
<Tag
aria-labelledby={labelledBy}
className={[
'rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] shadow-sm',
className,
@@ -0,0 +1,86 @@
export interface ChoiceRadiosProps<V extends string> {
/** Prefix of the radio ids: the first one is `${id}-${options[0].value}`. */
id: string
legend: string
/** « obligatoire » or « facultatif », shown beside the legend like FormField. */
marker?: string
options: readonly { value: V; label: string }[]
/** '' when nothing is chosen: no option is preselected. */
value: V | ''
onChange: (value: V) => void
hint?: string
error?: string
}
/** The id of the radio that takes focus when the group is in error. */
export const firstChoiceId = (id: string, first: string) => `${id}-${first}`
/**
* A required choice among a few explicit options, as large touch targets
* (the client kind's look): a fieldset named by its legend, the error under
* it and linked from every radio, nothing checked until the user picks.
*/
export default function ChoiceRadios<V extends string>({
id,
legend,
marker,
options,
value,
onChange,
hint,
error,
}: ChoiceRadiosProps<V>) {
const describedBy = error ? `${id}-error` : hint ? `${id}-hint` : undefined
return (
<fieldset className="space-y-2">
{/* The look of Label (FormField), on the element that names the group. */}
<legend className="mb-1 flex w-full items-baseline justify-between text-sm font-medium text-[var(--color-ink)]">
<span>{legend}</span>
{marker && (
<span className="text-xs font-normal text-[var(--color-ink-muted)]">
{marker}
</span>
)}
</legend>
<div className="grid grid-cols-1 gap-2 min-[400px]:grid-cols-3">
{options.map((option) => (
<label
key={option.value}
className="flex min-h-11 cursor-pointer items-center gap-2 rounded-lg border border-[var(--color-border)] bg-white px-4 text-sm text-[var(--color-ink)] has-[:checked]:border-[var(--color-accent)] has-[:checked]:bg-[var(--color-accent)]/10 has-[:checked]:font-medium has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-accent)]"
>
<input
id={`${id}-${option.value}`}
type="radio"
name={id}
value={option.value}
checked={value === option.value}
onChange={() => onChange(option.value)}
aria-invalid={Boolean(error)}
aria-describedby={describedBy}
className="h-4 w-4 accent-[var(--color-accent)]"
/>
{option.label}
</label>
))}
</div>
{error ? (
<p
id={`${id}-error`}
role="alert"
className="text-sm text-[var(--color-danger)]"
>
{error}
</p>
) : (
hint && (
<p
id={`${id}-hint`}
className="text-xs text-[var(--color-ink-muted)]"
>
{hint}
</p>
)
)}
</fieldset>
)
}
+2
View File
@@ -6,6 +6,7 @@ export type IconName =
| 'dashboard'
| 'user'
| 'users'
| 'paw'
| 'tool'
| 'logout'
| 'eye'
@@ -22,6 +23,7 @@ const PATHS: Record<IconName, string> = {
dashboard: 'M4 4h7v7H4zM13 4h7v4h-7zM13 11h7v9h-7zM4 14h7v6H4z',
user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0',
users: 'M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M16 3.5a4 4 0 0 1 0 7M22 21a7 7 0 0 0-4.5-6.5',
paw: 'M3.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M7.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M13.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M16.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M12 12.5c-2.5 0-5 3.2-5 5.3 0 1.6 1.3 2.4 2.8 2.4 1 0 1.5-.5 2.2-.5s1.2.5 2.2.5c1.5 0 2.8-.8 2.8-2.4 0-2.1-2.5-5.3-5-5.3z',
tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3',
logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9',
eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',