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

+29
View File
@@ -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 }
}
+100
View File
@@ -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<SpeciesContextValue | null>(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<SpeciesState>({ 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 (
<SpeciesContext.Provider value={value}>{children}</SpeciesContext.Provider>
)
}
/** The species labels of the workspace; the first page that asks starts the read. */
export function useSpecies(): Omit<SpeciesContextValue, 'request'> {
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
}
+232
View File
@@ -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<AnimalFormValues>(initial)
const [baseline, setBaseline] = useState<AnimalFormValues>(initial)
const [relation, setRelation] = useState(initialRelation)
const [relationBaseline, setRelationBaseline] = useState(initialRelation)
const [errors, setErrors] = useState<AnimalFieldErrors>({})
const [relationErrors, setRelationErrors] = useState<RelationFieldErrors>({})
const [errorRound, setErrorRound] = useState(0)
const [phase, setPhase] = useState<AnimalFormPhase>({ kind: 'idle' })
const [stored, setStored] = useState<AnimalRecord | null>(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<ReturnType<typeof validate>>) {
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<typeof useAnimalForm>
+110
View File
@@ -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<string | null>(null)
const [archived, setArchived] = useState(false)
const [state, setState] = useState<AnimalListState>({ 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),
}
}
+50
View File
@@ -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<AnimalRecordState>({ status: 'loading' })
const [reload, setReload] = useState(0)
const shownId = useRef<string | null>(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 }
}
+253
View File
@@ -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<Record<keyof AnimalFormValues, string>>
/** 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
}
+18 -5
View File
@@ -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() {
<Route element={<AppLayout />}>
<Route index element={<DashboardRoute />} />
<Route path="account" element={<AccountRoute />} />
<Route path="clients" element={<RequireWorkspace />}>
<Route index element={<ClientsListRoute />} />
<Route path="new" element={<ClientCreateRoute />} />
<Route path=":clientId" element={<ClientDetailRoute />} />
<Route path=":clientId/edit" element={<ClientEditRoute />} />
{/* One workspace gate for the records: moving between clients and animals keeps it. */}
<Route element={<RequireWorkspace />}>
<Route path="clients">
<Route index element={<ClientsListRoute />} />
<Route path="new" element={<ClientCreateRoute />} />
<Route path=":clientId" element={<ClientDetailRoute />} />
<Route path=":clientId/edit" element={<ClientEditRoute />} />
</Route>
<Route path="animals">
<Route index element={<AnimalsListRoute />} />
<Route path="new" element={<AnimalCreateRoute />} />
<Route path=":animalId" element={<AnimalDetailRoute />} />
<Route path=":animalId/edit" element={<AnimalEditRoute />} />
</Route>
</Route>
<Route path="*" element={<NotFoundRoute />} />
</Route>
+10 -6
View File
@@ -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 (
<Fragment key={workspace.id}>
<Outlet
context={{ workspaceId: workspace.id } satisfies WorkspaceContext}
/>
<SpeciesProvider>
<Outlet
context={{ workspaceId: workspace.id } satisfies WorkspaceContext}
/>
</SpeciesProvider>
</Fragment>
)
}
@@ -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 (
<AnimalForm
form={form}
workspaceId={workspaceId}
submitLabel={t('animals.form.submit_create')}
cancelTo={origin ? `/app/clients/${origin.id}` : '/app/animals'}
/>
)
}
/** /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<AnimalCreateState> | null)?.clientId
const origin = useOrigin(
typeof passed === 'string' && UUID_PATTERN.test(passed) ? passed : null,
)
return (
<div className="space-y-5">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('animals.form.create_title')}
</h1>
{origin.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('animals.form.origin_loading')}
</p>
)}
{origin.status === 'unavailable' && (
<Notice tone="info">{t('animals.form.origin_unavailable')}</Notice>
)}
{origin.status !== 'loading' && (
<CreateForm origin={origin.status === 'ready' ? origin.client : null} />
)}
</div>
)
}
@@ -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<typeof useT>
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 (
<Card
as="section"
aria-labelledby="animal-identity-title"
className="space-y-4 p-5 sm:p-6"
>
<h2
id="animal-identity-title"
className="font-serif text-xl text-[var(--color-ink)]"
>
{t('animals.detail.identity')}
</h2>
<dl className="grid gap-x-6 gap-y-3 text-sm sm:grid-cols-[9rem_1fr]">
{rows.map(([label, value]) => (
<div key={label} className="contents">
<dt className="text-[var(--color-ink-muted)]">{label}</dt>
<dd className="min-w-0 text-[var(--color-ink)]">{value}</dd>
</div>
))}
</dl>
</Card>
)
}
/** /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<string | null>(
flash ? t(`animals.detail.${flash}`) : null,
)
const [archiveOpen, setArchiveOpen] = useState(false)
const [restoring, setRestoring] = useState(false)
const [failure, setFailure] = useState<RecordFailureKind | null>(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 <AnimalNotFound />
if (state.status === 'loading')
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('animals.detail.loading')}
</p>
)
if (state.status === 'error')
return (
<div className="space-y-3">
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)
const record = state.record
const archived = record.archived_at !== null
return (
<div className="space-y-5">
<Link
to="/app/animals"
className={`${linkClass} inline-flex min-h-11 items-center text-sm`}
>
{t('animals.detail.back')}
</Link>
<header className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-2">
<h1
ref={heading}
tabIndex={-1}
className="outline-none break-words font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{record.name}
</h1>
{archived && <Badge tone="warn">{t('animals.archived_badge')}</Badge>}
</div>
<div className="flex flex-wrap gap-2">
{archived ? (
<Button
type="button"
className="min-h-11"
onClick={() => void restore()}
aria-disabled={restoring}
>
{restoring
? t('animals.detail.restoring')
: t('animals.detail.restore')}
</Button>
) : (
<>
<ButtonLink
to={`/app/animals/${record.id}/edit`}
className="min-h-11"
>
{t('animals.detail.edit')}
</ButtonLink>
<Button
type="button"
variant="secondary"
className="min-h-11"
onClick={() => setArchiveOpen(true)}
>
{t('animals.detail.archive')}
</Button>
</>
)}
</div>
</header>
{status && <Notice tone="success">{status}</Notice>}
{failure && (
<Notice tone="error">{t(`animals.failure.${failure}`)}</Notice>
)}
{archived && (
<Notice tone="info">{t('animals.detail.archived_notice')}</Notice>
)}
<IdentityCard record={record} />
<AnimalRelations
key={`${record.id}:${archived}`}
animal={record}
workspaceId={workspaceId}
onStatus={setStatus}
/>
<ArchiveAnimalDialog
open={archiveOpen}
animalId={record.id}
onClose={() => setArchiveOpen(false)}
onArchived={() => {
setArchiveOpen(false)
setStatus(t('animals.detail.archived'))
refresh()
}}
/>
</div>
)
}
@@ -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 (
<AnimalForm
form={form}
workspaceId={workspaceId}
submitLabel={t('animals.form.submit_update')}
cancelTo={`/app/animals/${record.id}`}
/>
)
}
/** /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 <AnimalNotFound />
return (
<div className="space-y-5">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('animals.form.edit_title')}
</h1>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('animals.detail.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && state.record.archived_at && (
<div className="space-y-3">
<Notice tone="info">{t('animals.detail.archived_notice')}</Notice>
<Link
to={`/app/animals/${state.record.id}`}
className="text-sm underline underline-offset-2"
>
{t('animals.form.back_to_animal')}
</Link>
</div>
)}
{state.status === 'ready' && !state.record.archived_at && (
<EditForm key={state.record.id} record={state.record} />
)}
</div>
)
}
@@ -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<typeof useT>
/** « 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 (
<li>
<Link
to={`/app/animals/${animal.id}`}
className="flex min-h-11 flex-col gap-1 rounded-xl px-4 py-3 hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<span className="flex flex-wrap items-center gap-2">
<span className="min-w-0 truncate font-medium text-[var(--color-ink)]">
{animal.name}
</span>
{animal.archived_at && (
<Badge tone="warn">{t('animals.archived_badge')}</Badge>
)}
</span>
<span className="text-sm text-[var(--color-ink-muted)]">
{details.join(' · ')}
</span>
<span className="text-sm text-[var(--color-ink)]">
{ownersText(animal, t)}
</span>
</Link>
</li>
)
}
/** /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 (
<div className="space-y-5">
<header className="flex flex-wrap items-center justify-between gap-3">
<h1
ref={heading}
tabIndex={-1}
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
>
{t('animals.list.title')}
</h1>
<ButtonLink to="/app/animals/new" className="min-h-11">
{t('animals.list.new')}
</ButtonLink>
</header>
<div className="grid gap-3 sm:grid-cols-[1fr_12rem] lg:grid-cols-[1fr_12rem_auto] lg:items-end">
<FormField
id="animal-search"
label={t('animals.list.search_label')}
hint={t('animals.list.search_hint')}
>
<Input
id="animal-search"
type="search"
value={list.query}
onChange={(e) => list.setQuery(e.target.value)}
maxLength={100}
autoComplete="off"
aria-describedby="animal-search-hint"
/>
</FormField>
<FormField
id="animal-species-filter"
label={t('animals.list.species_filter')}
>
<Select
id="animal-species-filter"
value={list.speciesId ?? ''}
onChange={(e) => list.setSpeciesId(e.target.value || null)}
>
<option value="">{t('animals.list.species_all')}</option>
{labels.map((s) => (
<option key={s.id} value={s.id}>
{pickLocaleLabel(s.name_fr, s.name_en, locale, s.id)}
</option>
))}
</Select>
</FormField>
<label className="flex min-h-11 cursor-pointer items-center gap-3 text-sm text-[var(--color-ink)]">
<input
type="checkbox"
role="switch"
checked={list.archived}
onChange={(e) => list.setArchived(e.target.checked)}
className="h-5 w-5 accent-[var(--color-accent)]"
/>
{t('animals.list.archived_toggle')}
</label>
</div>
{/* The number of rows shown is announced; an empty result announces itself below. */}
<div aria-live="polite" className="sr-only">
{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))}
</div>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('animals.list.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-3">
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
<Button type="button" variant="secondary" onClick={list.retry}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && state.rows.length === 0 && (
<div
role="status"
className="space-y-3 rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center"
>
<p className="text-[var(--color-ink)]">{emptyMessage}</p>
{!list.term && !list.speciesId && !list.archived && (
<p className="text-sm text-[var(--color-ink-muted)]">
{t('animals.list.empty_hint')}
</p>
)}
</div>
)}
{state.status === 'ready' && state.rows.length > 0 && (
<>
<ul
aria-label={t('animals.list.results_label')}
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
>
{state.rows.map((animal) => (
<AnimalRow
key={animal.id}
animal={animal}
labels={labels}
locale={locale}
t={t}
/>
))}
</ul>
{state.moreFailure && (
<Notice tone="error">
{t(`animals.failure.${state.moreFailure}`)}
</Notice>
)}
{state.next && (
<div className="flex justify-center">
<Button
type="button"
variant="secondary"
className="min-h-11"
onClick={() => void list.loadMore()}
aria-disabled={list.loadingMore}
>
{list.loadingMore
? t('animals.list.loading_more')
: t('animals.list.more')}
</Button>
</div>
)}
</>
)}
</div>
)
}
@@ -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() {
)}
<ContactCard record={record} />
<ClientAnimals clientId={record.id} />
<ClientAnimals
key={`${record.id}:${archived}`}
clientId={record.id}
workspaceId={workspaceId}
archived={archived}
onStatus={setStatus}
/>
<ArchiveClientDialog
open={archiveOpen}
@@ -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',
+228
View File
@@ -629,4 +629,232 @@ export const en: Dict = {
'leave.body': 'The changes in this form will be lost.',
'leave.stay': 'Stay on the page',
'leave.confirm': 'Leave without saving',
// V1-1.6 animals and relations
'shell.nav.animals': 'Animals',
'clients.failure.duplicate_relation':
'This client already holds this role, currently, for this animal.',
'clients.failure.already_ended': 'This relation has already ended.',
'clients.detail.animal_added': 'Animal created and linked to this client.',
'clients.animals.add': 'Add an animal',
'clients.animals.add_first': 'Add a first animal',
'clients.animals.link_existing': 'Link an existing animal',
'animals.failure.not_found':
'This animal, or the chosen client, cannot be found.',
'animals.failure.archived':
'This animal, or the chosen client, is archived: restore it to continue.',
'animals.failure.conflict': 'This animal was changed in the meantime.',
'animals.failure.request_conflict':
'An earlier attempt of this creation carried other values and may already have created the animal. Check the animal list before trying again.',
'animals.failure.limit_reached':
'Your workspace has reached its maximum number of animals or relations.',
'animals.failure.rate_limited':
'Too many changes in a short time. Try again in a few minutes.',
'animals.failure.invalid_input':
'A value was not accepted. Check the fields.',
'animals.failure.duplicate_relation':
'This client already holds this role, currently, for this animal.',
'animals.failure.already_ended': 'This relation has already ended.',
'animals.failure.session_expired': 'Your session has expired. Sign in again.',
'animals.failure.network': 'No connection. Check your network, then retry.',
'animals.failure.unavailable':
'The service is not answering right now. Retry.',
'animals.sex.male': 'Male',
'animals.sex.female': 'Female',
'animals.sex.unknown': 'Unknown',
'animals.archived_badge': 'Archived',
'animals.no_owner': 'Owner not entered',
'animals.owner_archived': '{name} (archived)',
'animals.list.title': 'Animals',
'animals.list.new': 'New animal',
'animals.list.search_label': 'Search an animal',
'animals.list.search_hint': 'Name, breed or species detail',
'animals.list.species_filter': 'Species',
'animals.list.species_all': 'All species',
'animals.list.archived_toggle': 'Show archived',
'animals.list.loading': 'Loading animals…',
'animals.list.results_label': 'Animals found',
'animals.list.count_one': '1 animal shown',
'animals.list.count_other': '{count} animals shown',
'animals.list.empty': 'No animal yet.',
'animals.list.empty_hint':
'Create an animal with “New animal”, or from a client’s page.',
'animals.list.no_results': 'No animal matches this search.',
'animals.list.archived_empty': 'No archived animal.',
'animals.list.more': 'Show more',
'animals.list.loading_more': 'Loading…',
'animals.list.owner': 'Owner: {names}',
'animals.list.owners': 'Owners: {names}',
'animals.list.owners_more': 'and {count} more',
'animals.form.create_title': 'New animal',
'animals.form.edit_title': 'Edit the animal',
'animals.form.identity_title': 'Identity',
'animals.form.name': 'Name',
'animals.form.species': 'Species',
'animals.form.species_choose': 'Choose a species',
'animals.form.species_loading': 'Loading species…',
'animals.form.species_failed': 'The species list could not be loaded.',
'animals.form.species_detail': 'Species detail',
'animals.form.species_detail_hint': 'For “Other”: “Ferret”, “Llama”.',
'animals.form.sex': 'Sex',
'animals.form.sex_hint': 'Choose “Unknown” if you do not know.',
'animals.form.breed': 'Breed',
'animals.form.birth_title': 'Birth',
'animals.form.birth_year': 'Year of birth',
'animals.form.birth_year_hint': 'If you know it: 2015.',
'animals.form.birth_year_locked':
'Taken from the full date. Clear the date to change the year.',
'animals.form.birth_date': 'Full date of birth',
'animals.form.birth_date_hint':
'Only if you know the day. The year fills itself in.',
'animals.form.client_title': 'Client',
'animals.form.client_hint':
'Optional: the animal can be created without a client and linked later.',
'animals.form.client_remove': 'Remove this client',
'animals.form.origin_loading': 'Loading the client…',
'animals.form.origin_unavailable':
'The client you came from is no longer available: the animal will be created without a client unless you choose one.',
'animals.form.required': 'required',
'animals.form.optional': 'optional',
'animals.form.submit_create': 'Create the animal',
'animals.form.submit_update': 'Save',
'animals.form.saving': 'Saving…',
'animals.form.back_to_animal': 'Back to the record',
'animals.form.conflict_title': 'This animal was changed elsewhere.',
'animals.form.conflict_body':
'Your entries are kept and the saved value is shown under each field that differs. “Save” will replace the saved values with yours.',
'animals.form.conflict_take_stored': 'Take the saved values',
'animals.form.stored_value': 'Saved value: {value}',
'animals.form.stored_empty': 'Saved value: empty',
'animals.error.required': 'This field is required.',
'animals.error.too_long': '{max} characters at most.',
'animals.error.characters': 'Character not accepted (tab, line break…).',
'animals.error.species': 'Choose a species.',
'animals.error.species_detail': 'Give the species.',
'animals.error.sex': 'Choose the sex, “Unknown” included.',
'animals.error.year_format': 'Four-digit year: 2015.',
'animals.error.year_range': 'The year runs from 1900 to the current year.',
'animals.error.date_format': 'Invalid date.',
'animals.error.date_range':
'The date cannot be in the future, nor before 1900.',
'animals.error.date_year': 'The year does not match the full date.',
'animals.error.client': 'Pick one from the list.',
'animals.error.role': 'Choose the role.',
'animals.age.years_one': '1 year',
'animals.age.years_other': '{count} years',
'animals.age.months_one': '1 month',
'animals.age.months_other': '{count} months',
'animals.age.about': 'about {age}',
'animals.age.under_one': 'under a year',
'animals.detail.loading': 'Loading the animal…',
'animals.detail.back': '← Animals',
'animals.detail.identity': 'Identity',
'animals.detail.species': 'Species',
'animals.detail.sex': 'Sex',
'animals.detail.breed': 'Breed',
'animals.detail.breed_none': 'Not entered',
'animals.detail.birth': 'Birth',
'animals.detail.birth_on': 'On {date}',
'animals.detail.birth_in': 'In {year}',
'animals.detail.birth_unknown': 'Unknown',
'animals.detail.status': 'Status',
'animals.detail.status_active': 'Active',
'animals.detail.status_archived': 'Archived',
'animals.detail.edit': 'Edit',
'animals.detail.archive': 'Archive',
'animals.detail.restore': 'Restore',
'animals.detail.restoring': 'Restoring…',
'animals.detail.archived_notice':
'This animal is archived: its record and its relations are read-only. Restore it to edit them.',
'animals.detail.created': 'Animal created.',
'animals.detail.updated': 'Changes saved.',
'animals.detail.archived': 'Animal archived.',
'animals.detail.restored': 'Animal restored.',
'animals.archive.title': 'Archive this animal?',
'animals.archive.body':
'The animal will be hidden from the lists and its record, relations included, becomes read-only. Its relations are kept and no client is archived. You can restore it at any time.',
'animals.archive.confirm': 'Archive',
'animals.archive.archiving': 'Archiving…',
'animals.not_found.title': 'Animal not found',
'animals.not_found.body':
'This animal does not exist or cannot be reached from your account.',
'animals.not_found.back': 'Back to animals',
'relations.failure.not_found':
'This client, animal or relation cannot be found: it may have been removed in the meantime.',
'relations.failure.archived':
'The animal or the client is archived: restore it to change its relations.',
'relations.failure.conflict':
'This relation was changed or removed in the meantime. The record is up to date: check it before trying again.',
'relations.failure.request_conflict':
'An earlier attempt of this link carried other values and may already have created the relation. Check the record before trying again.',
'relations.failure.limit_reached':
'The maximum number of relations is reached (20 current or 200 in total for an animal).',
'relations.failure.rate_limited':
'Too many changes in a short time. Try again in a few minutes.',
'relations.failure.invalid_input':
'The change was not accepted. Check the dates: not in the future, and the end after the start.',
'relations.failure.duplicate_relation':
'This client already holds this role, currently, for this animal.',
'relations.failure.already_ended': 'This relation has already ended.',
'relations.failure.session_expired':
'Your session has expired. Sign in again.',
'relations.failure.network':
'No connection. Check your network, then retry.',
'relations.failure.unavailable':
'The service is not answering right now. Retry.',
'relations.title': 'Linked clients',
'relations.loading': 'Loading linked clients…',
'relations.none': 'No client linked to this animal.',
'relations.current': 'Current',
'relations.former': 'History',
'relations.since': 'since {date}',
'relations.until': 'until {date}',
'relations.add_client': 'Add a client',
'relations.added_client': 'Client linked to this animal.',
'relations.added_animal': 'Animal linked to this client.',
'relations.saving': 'Saving…',
'relations.date_hint': 'Optional: leave it empty if you do not know it.',
'relations.action_named': '{action}: {name}, {role}',
'relations.panel.title_client': 'Link a client to this animal',
'relations.panel.title_animal': 'Link an animal to this client',
'relations.panel.client_chosen': 'Chosen client:',
'relations.panel.animal_chosen': 'Chosen animal:',
'relations.panel.change': 'Change',
'relations.panel.role': 'Role',
'relations.panel.started_on': 'Start of the relation',
'relations.panel.save_client': 'Link this client',
'relations.panel.save_animal': 'Link this animal',
'relations.panel.saving': 'Saving…',
'relations.picker.client_label': 'Search a client',
'relations.picker.client_hint':
'Active clients: name, city, email or phone',
'relations.picker.client_results': 'Suggested clients',
'relations.picker.client_none': 'No active client matches.',
'relations.picker.animal_label': 'Search an animal',
'relations.picker.animal_hint': 'Active animals: name, breed or species detail',
'relations.picker.animal_results': 'Suggested animals',
'relations.picker.animal_none': 'No active animal matches.',
'relations.picker.loading': 'Searching…',
'relations.end.action': 'End',
'relations.end.title': 'End this relation?',
'relations.end.body':
'It moves to the history, with its end date if you know it. Nothing is deleted.',
'relations.end.ended_on': 'End date',
'relations.end.confirm': 'End the relation',
'relations.end.done': 'Relation ended.',
'relations.dates.action': 'Correct the dates',
'relations.dates.title': 'Correct the dates',
'relations.dates.body':
'The client and the role do not change. An empty date means “unknown”.',
'relations.dates.started_on': 'Start date',
'relations.dates.ended_on': 'End date',
'relations.dates.confirm': 'Save the dates',
'relations.dates.done': 'Dates saved.',
'relations.void.action': 'Entered by mistake',
'relations.void.title': 'Remove a relation entered by mistake?',
'relations.void.body':
'Only if this relation never existed: wrong client, wrong animal or wrong role. It will disappear from the records, the lists and the history without being deleted, and cannot be brought back. For a relation that really ended, use “End”.',
'relations.void.confirm': 'Remove the relation',
'relations.void.done': 'Relation removed (entered by mistake).',
'relations.error.end_before_start': 'The end cannot come before the start.',
}
+234
View File
@@ -654,4 +654,238 @@ export const fr: Dict = {
'leave.body': 'Les modifications de ce formulaire seront perdues.',
'leave.stay': 'Rester sur la page',
'leave.confirm': 'Quitter sans enregistrer',
// V1-1.6 animals and relations
'shell.nav.animals': 'Animaux',
'clients.failure.duplicate_relation':
'Ce client a déjà ce rôle, en cours, pour cet animal.',
'clients.failure.already_ended': 'Cette relation est déjà terminée.',
'clients.detail.animal_added': 'Animal créé et lié à ce client.',
'clients.animals.add': 'Ajouter un animal',
'clients.animals.add_first': 'Ajouter un premier animal',
'clients.animals.link_existing': 'Associer un animal existant',
'animals.failure.not_found':
'Cet animal, ou le client choisi, est introuvable.',
'animals.failure.archived':
'Cet animal, ou le client choisi, est archivé : restaurez-le pour continuer.',
'animals.failure.conflict': 'Cet animal a été modifié entre-temps.',
'animals.failure.request_conflict':
"Une tentative précédente de cette création portait d'autres valeurs et a peut-être déjà créé l'animal. Vérifiez la liste des animaux avant de recommencer.",
'animals.failure.limit_reached':
"Le nombre maximal d'animaux ou de relations de votre espace est atteint.",
'animals.failure.rate_limited':
"Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.",
'animals.failure.invalid_input':
"Une valeur n'a pas été acceptée. Vérifiez les champs.",
'animals.failure.duplicate_relation':
'Ce client a déjà ce rôle, en cours, pour cet animal.',
'animals.failure.already_ended': 'Cette relation est déjà terminée.',
'animals.failure.session_expired':
'Votre session a expiré. Reconnectez-vous.',
'animals.failure.network':
'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
'animals.failure.unavailable':
'Le service ne répond pas pour le moment. Réessayez.',
'animals.sex.male': 'Mâle',
'animals.sex.female': 'Femelle',
'animals.sex.unknown': 'Inconnu',
'animals.archived_badge': 'Archivé',
'animals.no_owner': 'Propriétaire non renseigné',
'animals.owner_archived': '{name} (archivé)',
'animals.list.title': 'Animaux',
'animals.list.new': 'Nouvel animal',
'animals.list.search_label': 'Rechercher un animal',
'animals.list.search_hint': "Nom, race ou précision d'espèce",
'animals.list.species_filter': 'Espèce',
'animals.list.species_all': 'Toutes les espèces',
'animals.list.archived_toggle': 'Afficher les archivés',
'animals.list.loading': 'Chargement des animaux…',
'animals.list.results_label': 'Animaux trouvés',
'animals.list.count_one': '1 animal affiché',
'animals.list.count_other': '{count} animaux affichés',
'animals.list.empty': "Aucun animal pour l'instant.",
'animals.list.empty_hint':
"Créez un animal avec « Nouvel animal », ou depuis la fiche d'un client.",
'animals.list.no_results': 'Aucun animal ne correspond à cette recherche.',
'animals.list.archived_empty': 'Aucun animal archivé.',
'animals.list.more': 'Afficher plus',
'animals.list.loading_more': 'Chargement…',
'animals.list.owner': 'Propriétaire : {names}',
'animals.list.owners': 'Propriétaires : {names}',
'animals.list.owners_more': 'et {count} de plus',
'animals.form.create_title': 'Nouvel animal',
'animals.form.edit_title': "Modifier l'animal",
'animals.form.identity_title': 'Identité',
'animals.form.name': 'Nom',
'animals.form.species': 'Espèce',
'animals.form.species_choose': 'Choisir une espèce',
'animals.form.species_loading': 'Chargement des espèces…',
'animals.form.species_failed':
"La liste des espèces n'a pas pu être chargée.",
'animals.form.species_detail': "Précision de l'espèce",
'animals.form.species_detail_hint': 'Pour « Autre » : « Furet », « Lama ».',
'animals.form.sex': 'Sexe',
'animals.form.sex_hint': 'Choisissez « Inconnu » si vous ne savez pas.',
'animals.form.breed': 'Race',
'animals.form.birth_title': 'Naissance',
'animals.form.birth_year': 'Année de naissance',
'animals.form.birth_year_hint': 'Si vous la connaissez : 2015.',
'animals.form.birth_year_locked':
"Reprise de la date complète. Effacez la date pour modifier l'année.",
'animals.form.birth_date': 'Date de naissance complète',
'animals.form.birth_date_hint':
"Seulement si vous connaissez le jour. L'année se remplit d'elle-même.",
'animals.form.client_title': 'Client',
'animals.form.client_hint':
"Facultatif : l'animal peut être créé sans client et lié plus tard.",
'animals.form.client_remove': 'Retirer ce client',
'animals.form.origin_loading': 'Chargement du client…',
'animals.form.origin_unavailable':
"Le client d'origine n'est plus disponible : l'animal sera créé sans client, sauf si vous en choisissez un.",
'animals.form.required': 'obligatoire',
'animals.form.optional': 'facultatif',
'animals.form.submit_create': "Créer l'animal",
'animals.form.submit_update': 'Enregistrer',
'animals.form.saving': 'Enregistrement…',
'animals.form.back_to_animal': 'Retour à la fiche',
'animals.form.conflict_title': 'Cet animal a été modifié ailleurs.',
'animals.form.conflict_body':
'Vos saisies sont conservées et la valeur enregistrée est indiquée sous chaque champ qui diffère. « Enregistrer » remplacera les valeurs enregistrées par les vôtres.',
'animals.form.conflict_take_stored': 'Reprendre les valeurs enregistrées',
'animals.form.stored_value': 'Valeur enregistrée : {value}',
'animals.form.stored_empty': 'Valeur enregistrée : vide',
'animals.error.required': 'Ce champ est obligatoire.',
'animals.error.too_long': '{max} caractères au maximum.',
'animals.error.characters':
'Caractère non accepté (tabulation, saut de ligne…).',
'animals.error.species': 'Choisissez une espèce.',
'animals.error.species_detail': "Précisez l'espèce.",
'animals.error.sex': 'Choisissez le sexe, « Inconnu » compris.',
'animals.error.year_format': 'Année sur quatre chiffres : 2015.',
'animals.error.year_range': "L'année va de 1900 à l'année en cours.",
'animals.error.date_format': 'Date invalide.',
'animals.error.date_range':
'La date ne peut pas être dans le futur, ni avant 1900.',
'animals.error.date_year': "L'année ne correspond pas à la date complète.",
'animals.error.client': 'Faites un choix dans la liste.',
'animals.error.role': 'Choisissez le rôle.',
'animals.age.years_one': '1 an',
'animals.age.years_other': '{count} ans',
'animals.age.months_one': '1 mois',
'animals.age.months_other': '{count} mois',
'animals.age.about': 'environ {age}',
'animals.age.under_one': "moins d'un an",
'animals.detail.loading': "Chargement de l'animal…",
'animals.detail.back': '← Animaux',
'animals.detail.identity': 'Identité',
'animals.detail.species': 'Espèce',
'animals.detail.sex': 'Sexe',
'animals.detail.breed': 'Race',
'animals.detail.breed_none': 'Non renseignée',
'animals.detail.birth': 'Naissance',
'animals.detail.birth_on': 'Le {date}',
'animals.detail.birth_in': 'En {year}',
'animals.detail.birth_unknown': 'Inconnue',
'animals.detail.status': 'Statut',
'animals.detail.status_active': 'Actif',
'animals.detail.status_archived': 'Archivé',
'animals.detail.edit': 'Modifier',
'animals.detail.archive': 'Archiver',
'animals.detail.restore': 'Restaurer',
'animals.detail.restoring': 'Restauration…',
'animals.detail.archived_notice':
'Cet animal est archivé : sa fiche et ses relations sont en lecture seule. Restaurez-le pour les modifier.',
'animals.detail.created': 'Animal créé.',
'animals.detail.updated': 'Modifications enregistrées.',
'animals.detail.archived': 'Animal archivé.',
'animals.detail.restored': 'Animal restauré.',
'animals.archive.title': 'Archiver cet animal ?',
'animals.archive.body':
"L'animal sera masqué des listes et sa fiche passera en lecture seule, relations comprises. Ses relations sont conservées et aucun client n'est archivé. Vous pourrez le restaurer à tout moment.",
'animals.archive.confirm': 'Archiver',
'animals.archive.archiving': 'Archivage…',
'animals.not_found.title': 'Animal introuvable',
'animals.not_found.body':
"Cet animal n'existe pas ou n'est pas accessible depuis votre compte.",
'animals.not_found.back': 'Retour aux animaux',
'relations.failure.not_found':
'Ce client, cet animal ou cette relation est introuvable : il a peut-être été retiré entre-temps.',
'relations.failure.archived':
"L'animal ou le client est archivé : restaurez-le pour modifier ses relations.",
'relations.failure.conflict':
'Cette relation a été modifiée ou retirée entre-temps. La fiche est à jour : vérifiez-la avant de recommencer.',
'relations.failure.request_conflict':
"Une tentative précédente de cet ajout portait d'autres valeurs et a peut-être déjà créé la relation. Vérifiez la fiche avant de recommencer.",
'relations.failure.limit_reached':
'Le nombre maximal de relations est atteint (20 en cours ou 200 au total pour un animal).',
'relations.failure.rate_limited':
"Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.",
'relations.failure.invalid_input':
"La modification n'a pas été acceptée. Vérifiez les dates : pas dans le futur, et la fin après le début.",
'relations.failure.duplicate_relation':
'Ce client a déjà ce rôle, en cours, pour cet animal.',
'relations.failure.already_ended': 'Cette relation est déjà terminée.',
'relations.failure.session_expired':
'Votre session a expiré. Reconnectez-vous.',
'relations.failure.network':
'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
'relations.failure.unavailable':
'Le service ne répond pas pour le moment. Réessayez.',
'relations.title': 'Clients liés',
'relations.loading': 'Chargement des clients liés…',
'relations.none': 'Aucun client lié à cet animal.',
'relations.current': 'Actuels',
'relations.former': 'Historique',
'relations.since': 'depuis le {date}',
'relations.until': "jusqu'au {date}",
'relations.add_client': 'Ajouter un client',
'relations.added_client': 'Client lié à cet animal.',
'relations.added_animal': 'Animal associé à ce client.',
'relations.saving': 'Enregistrement…',
'relations.date_hint':
'Facultative : laissez vide si vous ne la connaissez pas.',
'relations.action_named': '{action} : {name}, {role}',
'relations.panel.title_client': 'Lier un client à cet animal',
'relations.panel.title_animal': 'Associer un animal à ce client',
'relations.panel.client_chosen': 'Client choisi :',
'relations.panel.animal_chosen': 'Animal choisi :',
'relations.panel.change': 'Changer',
'relations.panel.role': 'Rôle',
'relations.panel.started_on': 'Début de la relation',
'relations.panel.save_client': 'Lier ce client',
'relations.panel.save_animal': 'Associer cet animal',
'relations.panel.saving': 'Enregistrement…',
'relations.picker.client_label': 'Rechercher un client',
'relations.picker.client_hint':
'Clients actifs : nom, ville, e-mail ou téléphone',
'relations.picker.client_results': 'Clients proposés',
'relations.picker.client_none': 'Aucun client actif ne correspond.',
'relations.picker.animal_label': 'Rechercher un animal',
'relations.picker.animal_hint':
"Animaux actifs : nom, race ou précision d'espèce",
'relations.picker.animal_results': 'Animaux proposés',
'relations.picker.animal_none': 'Aucun animal actif ne correspond.',
'relations.picker.loading': 'Recherche…',
'relations.end.action': 'Terminer',
'relations.end.title': 'Terminer cette relation ?',
'relations.end.body':
"Elle passera dans l'historique, avec sa date de fin si vous la connaissez. Rien n'est supprimé.",
'relations.end.ended_on': 'Date de fin',
'relations.end.confirm': 'Terminer la relation',
'relations.end.done': 'Relation terminée.',
'relations.dates.action': 'Corriger les dates',
'relations.dates.title': 'Corriger les dates',
'relations.dates.body':
'Le client et le rôle ne changent pas. Une date vide veut dire « inconnue ».',
'relations.dates.started_on': 'Date de début',
'relations.dates.ended_on': 'Date de fin',
'relations.dates.confirm': 'Enregistrer les dates',
'relations.dates.done': 'Dates enregistrées.',
'relations.void.action': 'Erreur de saisie',
'relations.void.title': 'Retirer une relation saisie par erreur ?',
'relations.void.body':
"Seulement si cette relation n'a jamais existé : mauvais client, mauvais animal ou mauvais rôle. Elle disparaîtra des fiches, des listes et de l'historique sans être supprimée, et ne pourra pas être rétablie. Pour une relation qui a réellement pris fin, utilisez « Terminer ».",
'relations.void.confirm': 'Retirer la relation',
'relations.void.done': 'Relation retirée (erreur de saisie).',
'relations.error.end_before_start': 'La fin ne peut pas précéder le début.',
}
+7
View File
@@ -4,6 +4,13 @@ export function todayIso(): string {
return new Date().toISOString().slice(0, 10)
}
/** The device's local date as YYYY-MM-DD: what « not in the future » means in a form (contract §9.3). */
export function localDateIso(date: Date = new Date()): string {
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${date.getFullYear()}-${month}-${day}`
}
export function nowIso(): string {
return new Date().toISOString()
}
+50
View File
@@ -0,0 +1,50 @@
import { useCallback } from 'react'
import {
searchAnimals,
searchClients,
type AnimalListItem,
type ClientListItem,
} from '@faunosteo/supabase'
import { getSupabaseClient } from '@/lib/supabase'
/** Matches shown at once: enough to pick from, the term narrows the rest. */
const CHOICES = 8
function backend() {
const client = getSupabaseClient()
if (!client) throw new TypeError('no backend')
return client
}
/** Active clients of the workspace for a term; only an active client can be linked (§7.1). */
export function useClientChoices(workspaceId: string) {
return useCallback(
async (term: string): Promise<ClientListItem[]> =>
(
await searchClients(backend(), {
workspaceId,
query: term,
archived: false,
pageSize: CHOICES,
})
).rows,
[workspaceId],
)
}
/** Active animals of the workspace for a term, every species. */
export function useAnimalChoices(workspaceId: string) {
return useCallback(
async (term: string): Promise<AnimalListItem[]> =>
(
await searchAnimals(backend(), {
workspaceId,
query: term,
speciesId: null,
archived: false,
pageSize: CHOICES,
})
).rows,
[workspaceId],
)
}
+34
View File
@@ -0,0 +1,34 @@
import type { AnimalRelationItem } from '@faunosteo/supabase'
const ROLE_ORDER = { owner: 0, keeper: 1, contact: 2 } as const
const byName = (a: AnimalRelationItem, b: AnimalRelationItem) =>
a.client.display_name.localeCompare(b.client.display_name) ||
a.id.localeCompare(b.id)
/**
* An animal's relations for its page: the current ones by role (owners
* first) then client name; the former ones, most recently ended first.
* `ended_at` orders the history only; the end date shown is `ended_on`.
*/
export function groupRelations(relations: readonly AnimalRelationItem[]) {
const current = relations
.filter((r) => r.ended_at === null)
.sort(
(a, b) =>
ROLE_ORDER[a.relation_role] - ROLE_ORDER[b.relation_role] ||
byName(a, b),
)
const former = relations
.filter((r) => r.ended_at !== null)
.sort(
(a, b) =>
(b.ended_at ?? '').localeCompare(a.ended_at ?? '') || byName(a, b),
)
return {
current,
former,
/** No current owner: the page says « Propriétaire non renseigné », never a placeholder client. */
hasOwner: current.some((r) => r.relation_role === 'owner'),
}
}
@@ -0,0 +1,54 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import {
classifyRecordError,
fetchAnimalRelations,
type AnimalRelationItem,
type RecordFailureKind,
} from '@faunosteo/supabase'
import { getSupabaseClient } from '@/lib/supabase'
export type AnimalRelationsState =
| { status: 'loading' }
| { status: 'ready'; relations: AnimalRelationItem[] }
| { status: 'error'; failure: RecordFailureKind }
/**
* The relations of one animal (voided ones never come back). `reload`
* resolves once the new answer is on screen, so a confirmation can stay open
* until the change it made is shown; the rows stay visible meanwhile. An
* answer older than the last request, or arriving after unmount, is dropped.
*/
export function useAnimalRelations(animalId: string) {
const [state, setState] = useState<AnimalRelationsState>({
status: 'loading',
})
const generation = useRef(0)
const reload = useCallback(async () => {
const current = ++generation.current
const client = getSupabaseClient()
if (!client) {
setState({ status: 'error', failure: 'unavailable' })
return
}
try {
const relations = await fetchAnimalRelations(client, animalId)
if (current === generation.current)
setState({ status: 'ready', relations })
} catch (error) {
if (current === generation.current)
setState({ status: 'error', failure: classifyRecordError(error) })
}
}, [animalId])
useEffect(() => {
// The ref object is stable: bumping it on unmount drops the answer in flight.
const requests = generation
void reload()
return () => {
requests.current++
}
}, [reload])
return { state, reload }
}
@@ -0,0 +1,349 @@
import { describe, expect, it } from 'vitest'
import type { AnimalRelationItem } from '@faunosteo/supabase'
import { animalAge } from '@/animals/age'
import {
EMPTY_ANIMAL_VALUES,
animalFieldErrors,
animalSchema,
recordDateIssue,
relationIssues,
withBirthDate,
type AnimalFormValues,
} from '@/animals/validation'
import { groupRelations } from '@/relations/groups'
const TODAY = '2026-10-26'
const SPECIES = ['equine', 'canine', 'other']
const BASE: AnimalFormValues = {
...EMPTY_ANIMAL_VALUES,
name: 'Tornado',
species_id: 'equine',
sex: 'female',
}
const parse = (patch: Partial<AnimalFormValues>, today = TODAY) =>
animalSchema({ speciesIds: SPECIES, today }).safeParse({ ...BASE, ...patch })
const errorsOf = (patch: Partial<AnimalFormValues>, today = TODAY) => {
const result = parse(patch, today)
return result.success ? {} : animalFieldErrors(result.error)
}
describe('animal form schema (D-R7 on field-limits)', () => {
it('needs name, species and sex; empty optionals become null; name trimmed', () => {
const result = parse({ name: ' Tornado ' })
expect(result.success && result.data).toEqual({
name: 'Tornado',
species_id: 'equine',
species_detail: null,
sex: 'female',
breed: null,
birth_year: null,
birth_date: null,
})
})
it('refuses an empty form field by field, sex included (no default)', () => {
expect(
animalSchema({ speciesIds: SPECIES, today: TODAY }).safeParse(
EMPTY_ANIMAL_VALUES,
).success,
).toBe(false)
const result = animalSchema({
speciesIds: SPECIES,
today: TODAY,
}).safeParse(EMPTY_ANIMAL_VALUES)
expect(result.success ? {} : animalFieldErrors(result.error)).toEqual({
name: 'animals.error.required',
species_id: 'animals.error.species',
sex: 'animals.error.sex',
})
})
it('counts name code points: 80 accepted, 81 refused, astral counts once', () => {
expect(errorsOf({ name: 'é'.repeat(80) })).toEqual({})
expect(errorsOf({ name: '𝄞'.repeat(80) })).toEqual({})
expect(errorsOf({ name: 'é'.repeat(81) })).toEqual({
name: 'animals.error.too_long|80',
})
})
it('refuses control characters in the name and the breed', () => {
expect(errorsOf({ name: 'Tor\tnado' })).toEqual({
name: 'animals.error.characters',
})
expect(errorsOf({ breed: 'Pur\nsang' })).toEqual({
breed: 'animals.error.characters',
})
})
it('bounds the breed to 80', () => {
expect(errorsOf({ breed: 'a'.repeat(80) })).toEqual({})
expect(errorsOf({ breed: 'a'.repeat(81) })).toEqual({
breed: 'animals.error.too_long|80',
})
})
it('accepts only the allowed species', () => {
expect(errorsOf({ species_id: 'dragon' })).toEqual({
species_id: 'animals.error.species',
})
})
it('« other » needs a detail; any other species drops a leftover detail', () => {
expect(errorsOf({ species_id: 'other' })).toEqual({
species_detail: 'animals.error.species_detail',
})
expect(
errorsOf({ species_id: 'other', species_detail: 'f'.repeat(81) }),
).toEqual({
species_detail: 'animals.error.too_long|80',
})
const ferret = parse({ species_id: 'other', species_detail: ' Furet ' })
expect(ferret.success && ferret.data.species_detail).toBe('Furet')
const horse = parse({ species_id: 'equine', species_detail: 'Furet' })
expect(horse.success && horse.data.species_detail).toBeNull()
})
it('takes the three sexes, « inconnu » included', () => {
for (const sex of ['male', 'female', 'unknown'] as const)
expect(errorsOf({ sex })).toEqual({})
expect(errorsOf({ sex: 'x' as never })).toEqual({
sex: 'animals.error.sex',
})
})
it('keeps the five birth states of D6b', () => {
const none = parse({})
expect(
none.success && [none.data.birth_year, none.data.birth_date],
).toEqual([null, null])
const year = parse({ birth_year: '2015' })
expect(
year.success && [year.data.birth_year, year.data.birth_date],
).toEqual([2015, null])
const full = parse({ birth_year: '2015', birth_date: '2015-04-12' })
expect(
full.success && [full.data.birth_year, full.data.birth_date],
).toEqual([2015, '2015-04-12'])
expect(errorsOf({ birth_year: '2016', birth_date: '2015-04-12' })).toEqual({
birth_year: 'animals.error.date_year',
})
expect(errorsOf({ birth_date: '2015-04-12' })).toEqual({
birth_year: 'animals.error.date_year',
})
})
it('refuses malformed years and dates', () => {
expect(errorsOf({ birth_year: '15' })).toEqual({
birth_year: 'animals.error.year_format',
})
expect(errorsOf({ birth_year: '20a5' })).toEqual({
birth_year: 'animals.error.year_format',
})
expect(errorsOf({ birth_year: '2015', birth_date: '2015-02-30' })).toEqual({
birth_date: 'animals.error.date_format',
})
expect(errorsOf({ birth_year: '2015', birth_date: '12/04/2015' })).toEqual({
birth_date: 'animals.error.date_format',
})
})
it('bounds the year from 1900 to the current local year', () => {
expect(errorsOf({ birth_year: '1900' })).toEqual({})
expect(errorsOf({ birth_year: '1899' })).toEqual({
birth_year: 'animals.error.year_range',
})
expect(errorsOf({ birth_year: '2026' })).toEqual({})
expect(errorsOf({ birth_year: '2027' })).toEqual({
birth_year: 'animals.error.year_range',
})
})
it('refuses a date in the future or before 1900', () => {
expect(errorsOf({ birth_year: '2026', birth_date: TODAY })).toEqual({})
expect(errorsOf({ birth_year: '2026', birth_date: '2026-10-27' })).toEqual({
birth_date: 'animals.error.date_range',
})
expect(
errorsOf({ birth_year: '1899', birth_date: '1899-12-31' }),
).toMatchObject({
birth_date: 'animals.error.date_range',
})
})
})
describe('withBirthDate (U3)', () => {
it('fills the year from a complete date', () => {
expect(
withBirthDate({ ...BASE, birth_year: '2010' }, '2015-04-12'),
).toMatchObject({
birth_year: '2015',
birth_date: '2015-04-12',
})
})
it('keeps the year when the date is cleared or incomplete', () => {
const filled = withBirthDate(BASE, '2015-04-12')
expect(withBirthDate(filled, '')).toMatchObject({
birth_year: '2015',
birth_date: '',
})
expect(
withBirthDate({ ...BASE, birth_year: '2012' }, '2015-04'),
).toMatchObject({ birth_year: '2012' })
})
})
describe('recordDateIssue', () => {
it('accepts empty, a real date up to today; refuses the rest', () => {
expect(recordDateIssue('', TODAY)).toBeNull()
expect(recordDateIssue('1900-01-01', TODAY)).toBeNull()
expect(recordDateIssue(TODAY, TODAY)).toBeNull()
expect(recordDateIssue('1899-12-31', TODAY)).toBe(
'animals.error.date_range',
)
expect(recordDateIssue('2026-10-27', TODAY)).toBe(
'animals.error.date_range',
)
expect(recordDateIssue('2024-02-30', TODAY)).toBe(
'animals.error.date_format',
)
expect(recordDateIssue('2024-02-29', TODAY)).toBeNull()
expect(recordDateIssue('soon', TODAY)).toBe('animals.error.date_format')
})
})
describe('relationIssues', () => {
const client = { id: 'c1', display_name: 'Marie' }
it('no client: nothing to check, unless the client is the point of the form', () => {
expect(
relationIssues(
{ client: null, relation_role: '', started_on: '' },
TODAY,
false,
),
).toEqual({})
expect(
relationIssues(
{ client: null, relation_role: '', started_on: '' },
TODAY,
true,
),
).toEqual({
client: 'animals.error.client',
})
})
it('a chosen client needs a role; the start date follows the record date rules', () => {
expect(
relationIssues(
{ client, relation_role: '', started_on: '' },
TODAY,
false,
),
).toEqual({
relation_role: 'animals.error.role',
})
expect(
relationIssues(
{ client, relation_role: 'owner', started_on: '' },
TODAY,
true,
),
).toEqual({})
expect(
relationIssues(
{ client, relation_role: 'keeper', started_on: '2026-10-27' },
TODAY,
true,
),
).toEqual({
started_on: 'animals.error.date_range',
})
})
})
describe('animalAge (display only)', () => {
it('from a full date: months under a year, whole years after', () => {
expect(animalAge(2026, '2026-04-27', TODAY)).toEqual({
unit: 'month',
count: 5,
about: false,
})
expect(animalAge(2025, '2025-10-26', TODAY)).toEqual({
unit: 'year',
count: 1,
about: false,
})
expect(animalAge(2015, '2015-10-27', TODAY)).toEqual({
unit: 'year',
count: 10,
about: false,
})
})
it('from a year only: about N years, 0 for this year', () => {
expect(animalAge(2015, null, TODAY)).toEqual({
unit: 'year',
count: 11,
about: true,
})
expect(animalAge(2026, null, TODAY)).toEqual({
unit: 'year',
count: 0,
about: true,
})
})
it('nothing for unknown or future births', () => {
expect(animalAge(null, null, TODAY)).toBeNull()
expect(animalAge(2027, null, TODAY)).toBeNull()
expect(animalAge(2026, '2026-11-01', TODAY)).toBeNull()
})
})
function relation(
id: string,
patch: Partial<AnimalRelationItem> & { name?: string },
): AnimalRelationItem {
const { name = 'Client', ...rest } = patch
return {
id,
relation_role: 'owner',
started_on: null,
ended_on: null,
ended_at: null,
revision: 1,
client: {
id: `c-${id}`,
kind: 'person',
display_name: name,
phone: null,
email: null,
archived_at: null,
},
...rest,
}
}
describe('groupRelations', () => {
it('current by role then name, former most recently ended first', () => {
const groups = groupRelations([
relation('1', { relation_role: 'contact', name: 'Alice' }),
relation('2', { relation_role: 'owner', name: 'Zoé' }),
relation('3', { relation_role: 'keeper', name: 'Bob' }),
relation('4', { relation_role: 'owner', name: 'Anne' }),
relation('5', { name: 'Old', ended_at: '2020-01-01T00:00:00Z' }),
relation('6', { name: 'Recent', ended_at: '2024-01-01T00:00:00Z' }),
])
expect(groups.current.map((r) => r.id)).toEqual(['4', '2', '3', '1'])
expect(groups.former.map((r) => r.id)).toEqual(['6', '5'])
expect(groups.hasOwner).toBe(true)
})
it('no current owner with only keepers or former owners', () => {
expect(
groupRelations([relation('1', { relation_role: 'keeper' })]).hasOwner,
).toBe(false)
expect(
groupRelations([relation('1', { ended_at: '2024-01-01T00:00:00Z' })])
.hasOwner,
).toBe(false)
expect(groupRelations([]).hasOwner).toBe(false)
})
})
File diff suppressed because it is too large. Load diff