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:
1 parent
e22357630f
commit
930499cd25
36 files changed
+5579
-113
No files matched your search
@@ -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>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user