diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx
index 4ceb897b..cc2bc844 100644
--- a/apps/app/src/app/App.tsx
+++ b/apps/app/src/app/App.tsx
@@ -16,6 +16,11 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
import DashboardRoute from './routes/app/DashboardRoute'
import AccountRoute from './routes/app/AccountRoute'
+import RequireWorkspace from './guards/RequireWorkspace'
+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 { useUnsavedGuard } from './useUnsavedGuard'
/** The local tool: unchanged routes, no account needed, shared footer. */
@@ -50,6 +55,12 @@ export function AppRoutes() {
}>
} />
} />
+ }>
+ } />
+ } />
+ } />
+ } />
+
} />
diff --git a/apps/app/src/app/guards/RequireWorkspace.tsx b/apps/app/src/app/guards/RequireWorkspace.tsx
new file mode 100644
index 00000000..309151e8
--- /dev/null
+++ b/apps/app/src/app/guards/RequireWorkspace.tsx
@@ -0,0 +1,62 @@
+import { Fragment } from 'react'
+import { Outlet, useOutletContext } from 'react-router-dom'
+import Button from '@/components/ui/Button'
+import Notice from '@/components/ui/Notice'
+import { useAuthStore } from '@/state/authStore'
+import { useT } from '@/i18n/useT'
+
+interface WorkspaceContext {
+ workspaceId: string
+}
+
+/** The id of the personal workspace, for the routes under RequireWorkspace. */
+export function useWorkspaceId(): string {
+ return useOutletContext().workspaceId
+}
+
+/**
+ * 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.
+ */
+export default function RequireWorkspace() {
+ const t = useT()
+ const workspace = useAuthStore((s) => s.workspace)
+ const refreshWorkspace = useAuthStore((s) => s.refreshWorkspace)
+
+ if (workspace.status === 'ready') {
+ return (
+
+
+
+ )
+ }
+ if (workspace.status === 'idle' || workspace.status === 'loading') {
+ return (
+
+ {t('workspace.loading')}
+
+ )
+ }
+ if (workspace.status === 'inactive' || workspace.status === 'unconfirmed') {
+ return {t(`workspace.${workspace.status}`)}
+ }
+ const message =
+ workspace.status === 'missing'
+ ? t('workspace.missing')
+ : `${t('workspace.error')} ${t(`clients.failure.${workspace.failure}`)}`
+ return (
+
+ {message}
+ void refreshWorkspace().catch(() => undefined)}
+ >
+ {t('common.retry')}
+
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx b/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx
new file mode 100644
index 00000000..f9007f40
--- /dev/null
+++ b/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx
@@ -0,0 +1,40 @@
+import { useNavigate } from 'react-router-dom'
+import ClientForm from '@/components/clients/ClientForm'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useClientForm } from '@/clients/useClientForm'
+import { useT } from '@/i18n/useT'
+import type { ClientFlash } from './ClientDetailRoute'
+
+/** /app/clients/new: one creation intent, one request id, kept for retries. */
+export default function ClientCreateRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const navigate = useNavigate()
+ const workspaceId = useWorkspaceId()
+ const form = useClientForm({ mode: 'create', workspaceId }, (clientId) =>
+ navigate(`/app/clients/${clientId}`, {
+ replace: true,
+ state: { flash: 'created' satisfies ClientFlash },
+ }),
+ )
+ useLeaveGuard(form.dirty)
+
+ return (
+
+
+ {t('clients.form.create_title')}
+
+
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
new file mode 100644
index 00000000..ac6cbce3
--- /dev/null
+++ b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
@@ -0,0 +1,242 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
+import {
+ classifyRecordError,
+ setClientArchived,
+ type ClientRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import ArchiveClientDialog from '@/components/clients/ArchiveClientDialog'
+import ClientAnimals from '@/components/clients/ClientAnimals'
+import ClientNotFound from '@/components/clients/ClientNotFound'
+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 { usePageHeading } from '@/app/usePageHeading'
+import { countryName } from '@/clients/countries'
+import { useClientRecord } from '@/clients/useClientRecord'
+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'
+
+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'
+
+function ContactCard({ record }: { record: ClientRecord }) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const place = [record.postal_code, record.city].filter(Boolean).join(' ')
+ const address = [record.address_line1, record.address_line2, place].filter(
+ Boolean,
+ )
+ const rows: [string, ReactNode][] = []
+ if (record.phone)
+ rows.push([
+ t('clients.detail.phone'),
+
+ {record.phone}
+ ,
+ ])
+ if (record.email)
+ rows.push([
+ t('clients.detail.email'),
+
+ {record.email}
+ ,
+ ])
+ if (address.length)
+ rows.push([
+ t('clients.detail.address'),
+ address.map((line) => (
+
+ {line}
+
+ )),
+ ])
+ if (record.country)
+ rows.push([
+ t('clients.detail.country'),
+ countryName(record.country, locale),
+ ])
+
+ return (
+
+
+ {rows.length === 0 ? (
+
+ {t('clients.detail.no_contact')}
+
+ ) : (
+
+ {rows.map(([label, value]) => (
+
+
{label}
+ {value}
+
+ ))}
+
+ )}
+
+ )
+}
+
+/** /app/clients/:clientId: identity, contact, animals (read-only), edit, archive or restore. */
+export default function ClientDetailRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const navigate = useNavigate()
+ const location = useLocation()
+ const { clientId = '' } = useParams()
+ const { state, refresh } = useClientRecord(clientId)
+ const flash = (location.state as { flash?: ClientFlash } | null)?.flash
+ const [status, setStatus] = useState(
+ flash ? t(`clients.detail.${flash}`) : null,
+ )
+ const [archiveOpen, setArchiveOpen] = useState(false)
+ const [restoring, setRestoring] = useState(false)
+ const [failure, setFailure] = useState(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 setClientArchived(client, clientId, false)
+ setStatus(t('clients.detail.restored'))
+ refresh()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setRestoring(false)
+ }
+ }
+
+ if (state.status === 'not_found') return
+ if (state.status === 'loading')
+ return (
+
+ {t('clients.detail.loading')}
+
+ )
+ if (state.status === 'error')
+ return (
+
+ {t(`clients.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )
+
+ const record = state.record
+ const archived = record.archived_at !== null
+
+ return (
+
+
+ {t('clients.detail.back')}
+
+
+
+
+ {record.display_name}
+
+
+ {t(`clients.kind.${record.kind}`)}
+ {archived && (
+ {t('clients.archived_badge')}
+ )}
+
+
+
+ {archived ? (
+ void restore()}
+ aria-disabled={restoring}
+ >
+ {restoring
+ ? t('clients.detail.restoring')
+ : t('clients.detail.restore')}
+
+ ) : (
+ <>
+
+ {t('clients.detail.edit')}
+
+ setArchiveOpen(true)}
+ >
+ {t('clients.detail.archive')}
+
+ >
+ )}
+
+
+
+ {status &&
{status} }
+ {failure && (
+
{t(`clients.failure.${failure}`)}
+ )}
+ {archived && (
+
{t('clients.detail.archived_notice')}
+ )}
+
+
+
+
+
setArchiveOpen(false)}
+ onArchived={() => {
+ setArchiveOpen(false)
+ setStatus(t('clients.detail.archived'))
+ refresh()
+ }}
+ />
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx b/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx
new file mode 100644
index 00000000..d62311d1
--- /dev/null
+++ b/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx
@@ -0,0 +1,78 @@
+import { Link, useNavigate, useParams } from 'react-router-dom'
+import type { ClientRecord } from '@faunosteo/supabase'
+import ClientForm from '@/components/clients/ClientForm'
+import ClientNotFound from '@/components/clients/ClientNotFound'
+import Button from '@/components/ui/Button'
+import Notice from '@/components/ui/Notice'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useClientForm } from '@/clients/useClientForm'
+import { useClientRecord } from '@/clients/useClientRecord'
+import { useT } from '@/i18n/useT'
+import type { ClientFlash } from './ClientDetailRoute'
+
+function EditForm({ record }: { record: ClientRecord }) {
+ const t = useT()
+ const navigate = useNavigate()
+ const form = useClientForm({ mode: 'edit', record }, (clientId) =>
+ navigate(`/app/clients/${clientId}`, {
+ state: { flash: 'updated' satisfies ClientFlash },
+ }),
+ )
+ useLeaveGuard(form.dirty)
+ return (
+
+ )
+}
+
+/** /app/clients/:clientId/edit: the stored values at their revision; an archived client is read-only. */
+export default function ClientEditRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const { clientId = '' } = useParams()
+ const { state, refresh } = useClientRecord(clientId)
+
+ if (state.status === 'not_found') return
+ return (
+
+
+ {t('clients.form.edit_title')}
+
+ {state.status === 'loading' && (
+
+ {t('clients.detail.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`clients.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )}
+ {state.status === 'ready' && state.record.archived_at && (
+
+ {t('clients.detail.archived_notice')}
+
+ {t('clients.form.back_to_client')}
+
+
+ )}
+ {state.status === 'ready' && !state.record.archived_at && (
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx b/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx
new file mode 100644
index 00000000..363b81e4
--- /dev/null
+++ b/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx
@@ -0,0 +1,180 @@
+import { Link } from 'react-router-dom'
+import type { ClientListItem } 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 { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useClientList } from '@/clients/useClientList'
+import { useT } from '@/i18n/useT'
+
+type Translate = ReturnType
+
+function animalCount(count: number, t: Translate): string {
+ if (count === 0) return t('clients.list.animals_none')
+ return count === 1
+ ? t('clients.list.animals_one')
+ : t('clients.list.animals_other').replace('{count}', String(count))
+}
+
+function ClientRow({ client, t }: { client: ClientListItem; t: Translate }) {
+ const details = [
+ client.city,
+ client.phone,
+ animalCount(client.current_animal_count, t),
+ ].filter(Boolean)
+ return (
+
+
+
+
+ {client.display_name}
+
+ {t(`clients.kind.${client.kind}`)}
+ {client.archived_at && (
+ {t('clients.archived_badge')}
+ )}
+
+
+ {details.join(' · ')}
+
+
+
+ )
+}
+
+/** /app/clients: search, the archived toggle (U2) and « Afficher plus » pages (U1). */
+export default function ClientsListRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const workspaceId = useWorkspaceId()
+ const list = useClientList(workspaceId)
+ const { state } = list
+
+ const emptyMessage = list.term
+ ? t('clients.list.no_results')
+ : list.archived
+ ? t('clients.list.archived_empty')
+ : t('clients.list.empty')
+
+ return (
+
+
+
+ {t('clients.list.title')}
+
+
+ {t('clients.list.new')}
+
+
+
+
+
+ list.setQuery(e.target.value)}
+ maxLength={100}
+ autoComplete="off"
+ aria-describedby="client-search-hint"
+ />
+
+
+ list.setArchived(e.target.checked)}
+ className="h-5 w-5 accent-[var(--color-accent)]"
+ />
+ {t('clients.list.archived_toggle')}
+
+
+
+ {/* The number of rows shown is announced; an empty result announces itself below. */}
+
+ {state.status === 'ready' &&
+ state.rows.length > 0 &&
+ t(
+ state.rows.length === 1
+ ? 'clients.list.count_one'
+ : 'clients.list.count_other',
+ ).replace('{count}', String(state.rows.length))}
+
+
+ {state.status === 'loading' && (
+
+ {t('clients.list.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`clients.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )}
+ {state.status === 'ready' && state.rows.length === 0 && (
+
+
{emptyMessage}
+ {!list.term && !list.archived && (
+
+ {t('clients.list.empty_hint')}
+
+ )}
+
+ )}
+ {state.status === 'ready' && state.rows.length > 0 && (
+ <>
+
+ {state.rows.map((client) => (
+
+ ))}
+
+ {state.moreFailure && (
+
+ {t(`clients.failure.${state.moreFailure}`)}
+
+ )}
+ {state.next && (
+
+ void list.loadMore()}
+ aria-disabled={list.loadingMore}
+ >
+ {list.loadingMore
+ ? t('clients.list.loading_more')
+ : t('clients.list.more')}
+
+
+ )}
+ >
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/useLeaveGuard.ts b/apps/app/src/app/useLeaveGuard.ts
new file mode 100644
index 00000000..9f0e672b
--- /dev/null
+++ b/apps/app/src/app/useLeaveGuard.ts
@@ -0,0 +1,25 @@
+import { useEffect } from 'react'
+import { useLeaveGuardStore } from '@/state/leaveGuardStore'
+
+/**
+ * While `dirty`, a reload, a tab close or a full-page redirect asks first
+ * (beforeunload), and AppLayout asks before following a link of the app. The
+ * declarative router has no navigation blocker: the browser's own back and
+ * forward buttons are not intercepted (contract §11.3).
+ */
+export function useLeaveGuard(dirty: boolean): void {
+ const arm = useLeaveGuardStore((s) => s.arm)
+ useEffect(() => {
+ arm(dirty)
+ return () => arm(false)
+ }, [dirty, arm])
+ useEffect(() => {
+ if (!dirty) return
+ const guard = (event: BeforeUnloadEvent) => {
+ event.preventDefault()
+ event.returnValue = ''
+ }
+ window.addEventListener('beforeunload', guard)
+ return () => window.removeEventListener('beforeunload', guard)
+ }, [dirty])
+}
diff --git a/apps/app/src/app/usePageHeading.ts b/apps/app/src/app/usePageHeading.ts
new file mode 100644
index 00000000..ffec3ba0
--- /dev/null
+++ b/apps/app/src/app/usePageHeading.ts
@@ -0,0 +1,33 @@
+import { useCallback, useRef } from 'react'
+
+/**
+ * Focus moves to the page heading when a page opens (contract §11.5), so a
+ * screen reader starts at the new page and Tab continues from it. The heading
+ * carries tabIndex={-1} and this callback ref; it takes focus once, when it
+ * first appears (a page that loads its record renders it later). A page
+ * opened from the mobile drawer appears while the drawer still holds the page
+ * inert for its exit: the heading then takes focus once that dialog closed
+ * and gave focus back, so it has the last word. The one-shot listener checks
+ * the heading is still on the page; no effect cleanup, which React's
+ * StrictMode would run once before the dialog closes.
+ */
+export function usePageHeading() {
+ const done = useRef(false)
+ return useCallback((element: T | null) => {
+ if (!element || done.current) return
+ done.current = true
+ const modal = document.querySelector('dialog:modal')
+ if (!modal) {
+ element.focus()
+ return
+ }
+ modal.addEventListener(
+ 'close',
+ () =>
+ setTimeout(() => {
+ if (element.isConnected) element.focus()
+ }, 0),
+ { once: true },
+ )
+ }, [])
+}
diff --git a/apps/app/src/clients/countries.ts b/apps/app/src/clients/countries.ts
new file mode 100644
index 00000000..f7e13453
--- /dev/null
+++ b/apps/app/src/clients/countries.ts
@@ -0,0 +1,40 @@
+import type { Locale } from '@/i18n/types'
+
+/**
+ * ISO 3166-1 alpha-2 codes officially assigned (249), committed so the form
+ * never depends on a network list; the names come from the browser's
+ * Intl.DisplayNames in the UI language (contract §5).
+ */
+export const COUNTRY_CODES: readonly string[] = (
+ 'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ ' +
+ 'BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ ' +
+ 'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ ' +
+ 'DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR ' +
+ 'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ' +
+ 'ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ ' +
+ 'LA LB LC LI LK LR LS LT LU LV LY ' +
+ 'MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ ' +
+ 'NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA ' +
+ 'RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ ' +
+ 'TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ ' +
+ 'VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW'
+).split(' ')
+
+export interface CountryOption {
+ code: string
+ label: string
+}
+
+/** Every code with its name in `locale`, sorted by name in that language. */
+export function countryOptions(locale: Locale): CountryOption[] {
+ const names = new Intl.DisplayNames([locale], { type: 'region' })
+ return COUNTRY_CODES.map((code) => ({
+ code,
+ label: names.of(code) ?? code,
+ })).sort((a, b) => a.label.localeCompare(b.label, locale))
+}
+
+/** The country's name in `locale`, or the code when the browser has none. */
+export function countryName(code: string, locale: Locale): string {
+ return new Intl.DisplayNames([locale], { type: 'region' }).of(code) ?? code
+}
diff --git a/apps/app/src/clients/useClientForm.ts b/apps/app/src/clients/useClientForm.ts
new file mode 100644
index 00000000..618ece98
--- /dev/null
+++ b/apps/app/src/clients/useClientForm.ts
@@ -0,0 +1,163 @@
+import { useRef, useState, type FormEvent } from 'react'
+import {
+ classifyRecordError,
+ createClientRecord,
+ fetchClientRecord,
+ updateClientRecord,
+ type ClientRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { generateUuid } from '@/lib/id'
+import {
+ EMPTY_CLIENT_VALUES,
+ clientFieldErrors,
+ clientFormValues,
+ clientSchema,
+ normalizePhoneEntry,
+ type ClientFieldErrors,
+ type ClientFormValues,
+} from './validation'
+
+export type ClientFormTarget =
+ | { mode: 'create'; workspaceId: string }
+ | { mode: 'edit'; record: ClientRecord }
+
+export type ClientFormPhase =
+ | { kind: 'idle' }
+ | { kind: 'saving' }
+ | { kind: 'failed'; failure: RecordFailureKind }
+
+const FIELDS = Object.keys(EMPTY_CLIENT_VALUES) as (keyof ClientFormValues)[]
+
+function sameValues(a: ClientFormValues, b: ClientFormValues): boolean {
+ return FIELDS.every((key) => a[key] === b[key])
+}
+
+/**
+ * The client form: typed values, the D-R7 schema, one save. A create keeps
+ * one request id for the life of the form, so a retry after a lost answer
+ * returns the client already made instead of a second one. An update sends
+ * the revision it was read at; on `conflict` the stored client is read again
+ * and shown beside the typed values, which stay, and the next save applies
+ * them over it knowingly.
+ */
+export function useClientForm(
+ target: ClientFormTarget,
+ onSaved: (clientId: string) => void,
+) {
+ const initial =
+ target.mode === 'edit'
+ ? clientFormValues(target.record)
+ : EMPTY_CLIENT_VALUES
+ const [values, setValues] = useState(initial)
+ const [baseline, setBaseline] = useState(initial)
+ const [errors, setErrors] = useState({})
+ const [errorRound, setErrorRound] = useState(0)
+ const [phase, setPhase] = useState({ kind: 'idle' })
+ const [stored, setStored] = useState(null)
+ const [requestId] = useState(generateUuid)
+ const revision = useRef(target.mode === 'edit' ? target.record.revision : 0)
+ const inFlight = useRef(false)
+
+ const setField = (key: keyof ClientFormValues) => (value: string) =>
+ setValues((v) => ({ ...v, [key]: value }))
+
+ /** Shows the converted phone as soon as the field is left (contract §11.3). */
+ function convertPhone() {
+ const phone = normalizePhoneEntry(values.phone, values.country)
+ if (phone.ok && phone.value && phone.value !== values.phone)
+ setValues((v) => ({ ...v, phone: phone.value as string }))
+ }
+
+ async function readStored(clientId: string) {
+ const client = getSupabaseClient()
+ const record = client
+ ? await fetchClientRecord(client, clientId).catch(() => null)
+ : null
+ if (record) {
+ revision.current = record.revision
+ setStored(record)
+ }
+ }
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ if (inFlight.current) return
+ const parsed = clientSchema.safeParse(values)
+ if (!parsed.success) {
+ setErrors(clientFieldErrors(parsed.error))
+ setErrorRound((n) => n + 1)
+ return
+ }
+ setErrors({})
+ const sent = { ...values, phone: parsed.data.phone ?? '' }
+ setValues(sent)
+ const client = getSupabaseClient()
+ if (!client) {
+ setPhase({ kind: 'failed', failure: 'unavailable' })
+ return
+ }
+ inFlight.current = true
+ setPhase({ kind: 'saving' })
+ try {
+ let clientId: string
+ if (target.mode === 'create') {
+ clientId = (
+ await createClientRecord(client, {
+ workspaceId: target.workspaceId,
+ requestId,
+ fields: parsed.data,
+ })
+ ).id
+ } else {
+ clientId = target.record.id
+ revision.current = (
+ await updateClientRecord(client, {
+ clientId,
+ expectedRevision: revision.current,
+ fields: parsed.data,
+ })
+ ).revision
+ }
+ setBaseline(sent)
+ setPhase({ kind: 'idle' })
+ onSaved(clientId)
+ } 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 = clientFormValues(stored)
+ setValues(next)
+ setBaseline(next)
+ setStored(null)
+ setErrors({})
+ setPhase({ kind: 'idle' })
+ }
+
+ return {
+ values,
+ setField,
+ convertPhone,
+ errors,
+ /** Changes after each refused submit, so the form can focus the first error. */
+ errorRound,
+ phase,
+ /** The stored client after a conflict, shown beside the typed values. */
+ stored,
+ takeStored,
+ dirty: !sameValues(values, baseline),
+ submit,
+ }
+}
+
+export type ClientForm = ReturnType
diff --git a/apps/app/src/clients/useClientList.ts b/apps/app/src/clients/useClientList.ts
new file mode 100644
index 00000000..fbf401dd
--- /dev/null
+++ b/apps/app/src/clients/useClientList.ts
@@ -0,0 +1,107 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ searchClients,
+ type ClientListItem,
+ type NameCursor,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+/** Time without typing before the term is sent: one search per pause, not per key. */
+export const SEARCH_DELAY_MS = 300
+
+export type ClientListState =
+ | { status: 'loading' }
+ | {
+ status: 'ready'
+ rows: ClientListItem[]
+ next: NameCursor | null
+ moreFailure: RecordFailureKind | null
+ }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/**
+ * The clients of the workspace for a term and the archived toggle: the
+ * server searches (search_clients, POST), pages of 25 in name order, « Afficher
+ * plus » appends the next page. An answer to an older term is dropped.
+ */
+export function useClientList(workspaceId: string) {
+ const [query, setQuery] = useState('')
+ const [term, setTerm] = useState('')
+ const [archived, setArchived] = useState(false)
+ const [state, setState] = useState({ 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
+ }
+ searchClients(client, { workspaceId, query: term, 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, 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 searchClients(client, {
+ workspaceId,
+ query: term,
+ 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, archived])
+
+ return {
+ query,
+ setQuery,
+ /** The term the shown rows answer (the typed one after the pause). */
+ term,
+ archived,
+ setArchived,
+ state,
+ loadingMore,
+ loadMore,
+ retry: () => setReload((n) => n + 1),
+ }
+}
diff --git a/apps/app/src/clients/useClientRecord.ts b/apps/app/src/clients/useClientRecord.ts
new file mode 100644
index 00000000..46f76719
--- /dev/null
+++ b/apps/app/src/clients/useClientRecord.ts
@@ -0,0 +1,50 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ fetchClientRecord,
+ type ClientRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+export type ClientRecordState =
+ | { status: 'loading' }
+ | { status: 'ready'; record: ClientRecord }
+ | { status: 'not_found' }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/** One client by id; an unknown id and an id of another workspace are both not_found. */
+export function useClientRecord(clientId: string) {
+ const [state, setState] = useState({ status: 'loading' })
+ const [reload, setReload] = useState(0)
+ const shownId = useRef(null)
+
+ useEffect(() => {
+ let live = true
+ const client = getSupabaseClient()
+ // A refresh of the same client keeps it on screen until the new answer.
+ if (shownId.current !== clientId) setState({ status: 'loading' })
+ shownId.current = clientId
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ fetchClientRecord(client, clientId)
+ .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
+ }
+ }, [clientId, reload])
+
+ const refresh = useCallback(() => setReload((n) => n + 1), [])
+ return { state, refresh }
+}
diff --git a/apps/app/src/clients/validation.ts b/apps/app/src/clients/validation.ts
new file mode 100644
index 00000000..22c29955
--- /dev/null
+++ b/apps/app/src/clients/validation.ts
@@ -0,0 +1,179 @@
+import { z } from 'zod'
+import {
+ CLIENT_FIELD_LIMITS,
+ CONTROL_CHARACTERS,
+ EMAIL_PATTERN,
+ PHONE_E164_PATTERN,
+ codePointLength,
+ type ClientFields,
+ type ClientRecord,
+} from '@faunosteo/supabase'
+import { COUNTRY_CODES } from './countries'
+
+/**
+ * The client form (contract §5, §5.1, §11.3; D-R7): the bounds and patterns
+ * come from field-limits, proven equal to the SQL CHECKs, so the form never
+ * sends what the database refuses. Messages are i18n keys; `|n` carries the
+ * {max} placeholder. Lengths count code points, like char_length.
+ */
+
+export interface ClientFormValues {
+ kind: 'person' | 'organization'
+ display_name: string
+ email: string
+ phone: string
+ address_line1: string
+ address_line2: string
+ postal_code: string
+ city: string
+ country: string
+}
+
+export const EMPTY_CLIENT_VALUES: ClientFormValues = {
+ kind: 'person',
+ display_name: '',
+ email: '',
+ phone: '',
+ address_line1: '',
+ address_line2: '',
+ postal_code: '',
+ city: '',
+ country: '',
+}
+
+/** The form's view of a stored client: null fields become empty inputs. */
+export function clientFormValues(record: ClientRecord): ClientFormValues {
+ return {
+ kind: record.kind,
+ display_name: record.display_name,
+ email: record.email ?? '',
+ phone: record.phone ?? '',
+ address_line1: record.address_line1 ?? '',
+ address_line2: record.address_line2 ?? '',
+ postal_code: record.postal_code ?? '',
+ city: record.city ?? '',
+ country: record.country ?? '',
+ }
+}
+
+/** Without separators: spaces, dots, hyphens, parentheses. */
+function compactPhone(raw: string): string {
+ return raw.replace(/[\s.\-()]/g, '')
+}
+
+export type PhoneEntry =
+ | { ok: true; value: string | null }
+ | { ok: false; error: string }
+
+/**
+ * The phone entry rule of contract §11.3: an international number (+32…) is
+ * kept as typed; a French national number (06 12 34 56 78) becomes +33… only
+ * when the country is empty or France; with another country a national
+ * number is refused and asks for the country code.
+ */
+export function normalizePhoneEntry(raw: string, country: string): PhoneEntry {
+ const compact = compactPhone(raw)
+ if (compact === '') return { ok: true, value: null }
+ if (compact.startsWith('+')) {
+ return PHONE_E164_PATTERN.test(compact)
+ ? { ok: true, value: compact }
+ : { ok: false, error: 'clients.error.phone_format' }
+ }
+ const frenchContext = country === '' || country === 'FR'
+ if (frenchContext && /^0[1-9][0-9]{8}$/.test(compact)) {
+ return { ok: true, value: `+33${compact.slice(1)}` }
+ }
+ return frenchContext
+ ? { ok: false, error: 'clients.error.phone_format' }
+ : { ok: false, error: 'clients.error.phone_country_code' }
+}
+
+/** Trimmed text of at most `max` code points without control characters; '' → null. */
+function optionalText(max: number) {
+ return z
+ .string()
+ .trim()
+ .superRefine((value, ctx) => {
+ if (codePointLength(value) > max)
+ ctx.addIssue({
+ code: 'custom',
+ message: `clients.error.too_long|${max}`,
+ })
+ else if (CONTROL_CHARACTERS.test(value))
+ ctx.addIssue({ code: 'custom', message: 'clients.error.characters' })
+ })
+ .transform((value) => (value === '' ? null : value))
+}
+
+const displayName = z
+ .string()
+ .trim()
+ .superRefine((value, ctx) => {
+ if (value === '')
+ ctx.addIssue({ code: 'custom', message: 'clients.error.required' })
+ else if (codePointLength(value) > CLIENT_FIELD_LIMITS.displayName)
+ ctx.addIssue({
+ code: 'custom',
+ message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.displayName}`,
+ })
+ else if (CONTROL_CHARACTERS.test(value))
+ ctx.addIssue({ code: 'custom', message: 'clients.error.characters' })
+ })
+
+const email = z
+ .string()
+ .trim()
+ .transform((value) => value.toLowerCase())
+ .superRefine((value, ctx) => {
+ if (value === '') return
+ if (codePointLength(value) > CLIENT_FIELD_LIMITS.email)
+ ctx.addIssue({
+ code: 'custom',
+ message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.email}`,
+ })
+ else if (CONTROL_CHARACTERS.test(value) || !EMAIL_PATTERN.test(value))
+ ctx.addIssue({ code: 'custom', message: 'clients.error.email_format' })
+ })
+ .transform((value) => (value === '' ? null : value))
+
+/** Parses the typed values into the nine fields the RPCs take. */
+export const clientSchema = z
+ .object({
+ kind: z.enum(['person', 'organization']),
+ display_name: displayName,
+ email,
+ phone: z.string(),
+ address_line1: optionalText(CLIENT_FIELD_LIMITS.addressLine),
+ address_line2: optionalText(CLIENT_FIELD_LIMITS.addressLine),
+ postal_code: optionalText(CLIENT_FIELD_LIMITS.postalCode),
+ city: optionalText(CLIENT_FIELD_LIMITS.city),
+ country: z
+ .string()
+ .refine(
+ (value) => value === '' || COUNTRY_CODES.includes(value),
+ 'clients.error.country',
+ )
+ .transform((value) => (value === '' ? null : value)),
+ })
+ // A refinement runs even when another field failed, so every error shows at once.
+ .superRefine((values, ctx) => {
+ const phone = normalizePhoneEntry(values.phone, values.country ?? '')
+ if (!phone.ok)
+ ctx.addIssue({ code: 'custom', path: ['phone'], message: phone.error })
+ })
+ .transform((values): ClientFields => {
+ const phone = normalizePhoneEntry(values.phone, values.country ?? '')
+ return { ...values, phone: phone.ok ? phone.value : null }
+ })
+
+export type ClientFieldErrors = Partial>
+
+/** The first message of each field, in form order. */
+export function clientFieldErrors(error: z.ZodError): ClientFieldErrors {
+ const errors: ClientFieldErrors = {}
+ for (const issue of error.issues) {
+ const key = issue.path[0] as keyof ClientFormValues
+ errors[key] ??= issue.message
+ }
+ return errors
+}
diff --git a/apps/app/src/components/clients/ArchiveClientDialog.tsx b/apps/app/src/components/clients/ArchiveClientDialog.tsx
new file mode 100644
index 00000000..25a7be73
--- /dev/null
+++ b/apps/app/src/components/clients/ArchiveClientDialog.tsx
@@ -0,0 +1,160 @@
+import { useEffect, useState } from 'react'
+import {
+ classifyRecordError,
+ fetchClientArchivePreview,
+ setClientArchived,
+ type ClientArchivePreview,
+ 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 ArchiveClientDialogProps {
+ open: boolean
+ clientId: string
+ onClose: () => void
+ /** Called once the server archived the client; the page then closes the dialog. */
+ onArchived: () => void
+}
+
+type Preview =
+ | { status: 'loading' }
+ | { status: 'ready'; preview: ClientArchivePreview }
+ | { status: 'failed' }
+
+/**
+ * Confirmation before archiving (contract §7.1): it lists the active animals
+ * for which this client is the only current owner, then archives through
+ * set_client_archived. Closing it is never a confirmation, and while the
+ * request runs it refuses to close, so focus is restored once, after it.
+ */
+export default function ArchiveClientDialog({
+ open,
+ clientId,
+ onClose,
+ onArchived,
+}: ArchiveClientDialogProps) {
+ const t = useT()
+ const [preview, setPreview] = useState({ status: 'loading' })
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(null)
+
+ useEffect(() => {
+ if (!open) return
+ let live = true
+ setPreview({ status: 'loading' })
+ setFailure(null)
+ const client = getSupabaseClient()
+ if (!client) {
+ setPreview({ status: 'failed' })
+ return
+ }
+ fetchClientArchivePreview(client, clientId)
+ .then((result) => {
+ if (live) setPreview({ status: 'ready', preview: result })
+ })
+ .catch(() => {
+ if (live) setPreview({ status: 'failed' })
+ })
+ return () => {
+ live = false
+ }
+ }, [open, clientId])
+
+ const close = () => {
+ if (!pending) onClose()
+ }
+
+ async function confirm() {
+ const client = getSupabaseClient()
+ if (pending) return
+ if (!client) return setFailure('unavailable')
+ setPending(true)
+ setFailure(null)
+ try {
+ await setClientArchived(client, clientId, true)
+ onArchived()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setPending(false)
+ }
+ }
+
+ const sole = preview.status === 'ready' ? preview.preview : null
+ const others = sole ? sole.count - sole.animals.length : 0
+
+ return (
+
+ {t('clients.archive.body')}
+
+ }
+ size="sm"
+ >
+
+ {preview.status === 'loading' && (
+
+ {t('clients.archive.preview_loading')}
+
+ )}
+ {preview.status === 'failed' && (
+
{t('clients.archive.preview_failed')}
+ )}
+ {sole && sole.count > 0 && (
+
+
+ {sole.count === 1
+ ? t('clients.archive.sole_owner_one')
+ : t('clients.archive.sole_owner_other').replace(
+ '{count}',
+ String(sole.count),
+ )}
+
+
+ {sole.animals.map((animal) => (
+ {animal.name}
+ ))}
+
+ {others > 0 && (
+
+ {t('clients.archive.others').replace('{count}', String(others))}
+
+ )}
+
+ )}
+ {failure && (
+
{t(`clients.failure.${failure}`)}
+ )}
+
+
+ {/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
+
+ {t('common.cancel')}
+
+ void confirm()}
+ aria-disabled={pending}
+ >
+ {pending
+ ? t('clients.archive.archiving')
+ : t('clients.archive.confirm')}
+
+
+
+ )
+}
diff --git a/apps/app/src/components/clients/ClientAnimals.tsx b/apps/app/src/components/clients/ClientAnimals.tsx
new file mode 100644
index 00000000..93276547
--- /dev/null
+++ b/apps/app/src/components/clients/ClientAnimals.tsx
@@ -0,0 +1,201 @@
+import { useEffect, useState } from 'react'
+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 Card from '@/components/ui/Card'
+import Notice from '@/components/ui/Notice'
+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: '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 }
+}
+
+/**
+ * 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.
+ */
+export default function ClientAnimals({ clientId }: { clientId: string }) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const [state, setState] = useState({ status: 'loading' })
+ const [loadingMore, setLoadingMore] = useState(false)
+
+ 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
+ }
+ }, [clientId])
+
+ async function more() {
+ if (state.status !== 'ready' || !state.next) return
+ setLoadingMore(true)
+ try {
+ const page = await loadPage(clientId, state.next, state.species)
+ setState({
+ ...state,
+ rows: [...state.rows, ...page.rows],
+ next: page.next,
+ })
+ } catch (error) {
+ 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) =>
+ [
+ row.started_on &&
+ t('clients.animals.since').replace(
+ '{date}',
+ formatDate(row.started_on, locale),
+ ),
+ row.ended_on &&
+ t('clients.animals.until').replace(
+ '{date}',
+ formatDate(row.ended_on, locale),
+ ),
+ ]
+ .filter(Boolean)
+ .join(' · ')
+
+ function group(
+ rows: ClientAnimalItem[],
+ species: SpeciesLabel[],
+ current: boolean,
+ ) {
+ const shown = rows.filter((r) => r.is_current === current)
+ if (!shown.length) return null
+ const id = current ? 'client-animals-current' : 'client-animals-former'
+ return (
+
+
+ {t(current ? 'clients.animals.current' : 'clients.animals.former')}
+
+
+ {shown.map((row) => (
+
+
+
+ {row.animal_name}
+ {' '}
+
+ {speciesName(row, species)}
+
+ {row.animal_archived_at && (
+ {t('clients.archived_badge')}
+ )}
+
+
+ {t(
+ `clients.role.${current ? '' : 'former_'}${row.relation_role}`,
+ )}
+ {period(row) && ` · ${period(row)}`}
+
+
+ ))}
+
+
+ )
+ }
+
+ return (
+
+
+ {t('clients.animals.title')}
+
+ {state.status === 'loading' && (
+
+ {t('clients.animals.loading')}
+
+ )}
+ {state.status === 'error' && (
+ {t(`clients.failure.${state.failure}`)}
+ )}
+ {state.status === 'ready' && state.rows.length === 0 && (
+
+ {t('clients.animals.none')}
+
+ )}
+ {state.status === 'ready' && (
+ <>
+ {group(state.rows, state.species, true)}
+ {group(state.rows, state.species, false)}
+ {state.next && (
+ void more()}
+ disabled={loadingMore}
+ >
+ {loadingMore
+ ? t('clients.list.loading_more')
+ : t('clients.list.more')}
+
+ )}
+ >
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/clients/ClientForm.tsx b/apps/app/src/components/clients/ClientForm.tsx
new file mode 100644
index 00000000..0b666cba
--- /dev/null
+++ b/apps/app/src/components/clients/ClientForm.tsx
@@ -0,0 +1,305 @@
+import { useEffect, useMemo } from 'react'
+import { Link } from 'react-router-dom'
+import { CLIENT_FIELD_LIMITS } from '@faunosteo/supabase'
+import Button, { buttonClassName } from '@/components/ui/Button'
+import Card from '@/components/ui/Card'
+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 { countryName, countryOptions } from '@/clients/countries'
+import {
+ EMPTY_CLIENT_VALUES,
+ type ClientFormValues,
+} from '@/clients/validation'
+import type { ClientForm as ClientFormState } from '@/clients/useClientForm'
+import { translateFieldError } from '@/account/validation'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+const FIELD_ORDER = Object.keys(
+ EMPTY_CLIENT_VALUES,
+) as (keyof ClientFormValues)[]
+const fieldId = (key: keyof ClientFormValues) =>
+ `client-${key.replace('_', '-')}`
+
+export interface ClientFormProps {
+ form: ClientFormState
+ submitLabel: string
+ /** Where « Annuler » leads; the shell asks first while the form holds changes. */
+ cancelTo: string
+}
+
+/**
+ * The client form, one page on every screen (contract §11.3, §11.4): the kind
+ * first with « Personne » selected, the name whose label follows the kind,
+ * then contact and address. Every field is labelled, errors sit under their
+ * field and the first one takes focus after a refused submit.
+ */
+export default function ClientForm({
+ form,
+ submitLabel,
+ cancelTo,
+}: ClientFormProps) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const countries = useMemo(() => countryOptions(locale), [locale])
+ const { values, errors, phase, stored } = form
+
+ useEffect(() => {
+ if (form.errorRound === 0) return
+ const first = FIELD_ORDER.find((key) => errors[key])
+ if (first) document.getElementById(fieldId(first))?.focus()
+ }, [form.errorRound, errors])
+
+ const err = (key: keyof ClientFormValues) =>
+ translateFieldError(t, errors[key])
+ /** After a conflict: the stored value under each field that differs from the typed one. */
+ const storedHint = (key: keyof ClientFormValues): string | undefined => {
+ if (!stored) return undefined
+ const raw = key === 'country' ? stored.country : stored[key]
+ const value = raw ?? ''
+ if (value === values[key]) return undefined
+ const shown =
+ key === 'country' && value
+ ? countryName(value, locale)
+ : key === 'kind'
+ ? t(`clients.kind.${value}`)
+ : value
+ return shown
+ ? t('clients.form.stored_value').replace('{value}', shown)
+ : t('clients.form.stored_empty')
+ }
+ const describedBy = (key: keyof ClientFormValues, hint?: string) =>
+ fieldDescribedBy(fieldId(key), hint, errors[key])
+
+ function textField(
+ key: keyof ClientFormValues,
+ label: string,
+ max: number,
+ extra: Record = {},
+ ) {
+ const hint = storedHint(key)
+ return (
+
+ form.setField(key)(e.target.value)}
+ maxLength={max}
+ aria-invalid={Boolean(errors[key])}
+ aria-describedby={describedBy(key, hint)}
+ {...extra}
+ />
+
+ )
+ }
+
+ const nameKey = values.kind === 'organization' ? 'organization' : 'person'
+ const nameHint =
+ storedHint('display_name') ?? t(`clients.form.display_name_hint.${nameKey}`)
+ const saving = phase.kind === 'saving'
+
+ return (
+
+ )
+}
diff --git a/apps/app/src/components/clients/ClientNotFound.tsx b/apps/app/src/components/clients/ClientNotFound.tsx
new file mode 100644
index 00000000..d8138274
--- /dev/null
+++ b/apps/app/src/components/clients/ClientNotFound.tsx
@@ -0,0 +1,21 @@
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import { useT } from '@/i18n/useT'
+
+/** The same screen for an unknown id and an id of another workspace (contract §11.1). */
+export default function ClientNotFound() {
+ const t = useT()
+ return (
+
+
+ {t('clients.not_found.title')}
+
+
+ {t('clients.not_found.body')}
+
+
+ {t('clients.not_found.back')}
+
+
+ )
+}
diff --git a/apps/app/src/components/shell/AppLayout.tsx b/apps/app/src/components/shell/AppLayout.tsx
index a4540646..4c684376 100644
--- a/apps/app/src/components/shell/AppLayout.tsx
+++ b/apps/app/src/components/shell/AppLayout.tsx
@@ -1,13 +1,16 @@
-import { useState } from 'react'
-import { Link, Outlet, useLocation } from 'react-router-dom'
+import { useState, type MouseEvent } from 'react'
+import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
+import Button from '@/components/ui/Button'
+import Dialog from '@/components/ui/Dialog'
import Icon from '@/components/ui/Icon'
import MobileDrawer from './MobileDrawer'
import SidebarNav, { NAV_ITEMS } from './SidebarNav'
import SignOutButton from './SignOutButton'
import UserBadge, { AvatarCircle } from './UserBadge'
import { useAuthStore } from '@/state/authStore'
+import { useLeaveGuardStore } from '@/state/leaveGuardStore'
import { useT } from '@/i18n/useT'
/** Title of the current /app page for the top bar, from the nav table. */
@@ -18,20 +21,53 @@ function pageTitleKey(pathname: string): string {
return match?.labelKey ?? 'shell.nav.dashboard'
}
+/** An in-app link a plain click would follow: same origin, same tab, no modifier key. */
+function followedLink(event: MouseEvent): HTMLAnchorElement | null {
+ if (event.defaultPrevented || event.button !== 0) return null
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null
+ const anchor = (event.target as Element).closest('a[href]') as HTMLAnchorElement | null
+ if (!anchor || anchor.target === '_blank' || anchor.origin !== window.location.origin) return null
+ return anchor
+}
+
/**
* Authenticated shell: fixed sidebar on large screens, light top bar with a
- * drawer button below. The page content scrolls on its own.
+ * drawer button below. The page content scrolls on its own. While a page
+ * holds unsaved changes (useLeaveGuard), following any link of the shell or
+ * of the page asks first; staying is the default.
*/
export default function AppLayout() {
const t = useT()
const location = useLocation()
+ const navigate = useNavigate()
const [drawerOpen, setDrawerOpen] = useState(false)
+ const guarded = useLeaveGuardStore((s) => s.armed)
+ const arm = useLeaveGuardStore((s) => s.arm)
+ const [leaveTo, setLeaveTo] = useState(null)
+
+ function askBeforeLeaving(event: MouseEvent) {
+ if (!guarded) return
+ const anchor = followedLink(event)
+ if (!anchor) return
+ event.preventDefault()
+ event.stopPropagation()
+ setLeaveTo(anchor.pathname + anchor.search + anchor.hash)
+ }
+
+ function leave() {
+ const to = leaveTo
+ if (!to) return
+ arm(false)
+ setLeaveTo(null)
+ setDrawerOpen(false)
+ navigate(to)
+ }
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const displayName = profile?.display_name ?? user?.email ?? ''
return (
-
+
@@ -85,6 +121,22 @@ export default function AppLayout() {
setDrawerOpen(false)} />
+ setLeaveTo(null)}
+ title={t('leave.title')}
+ description={{t('leave.body')}
}
+ size="sm"
+ >
+
+ setLeaveTo(null)}>
+ {t('leave.stay')}
+
+
+ {t('leave.confirm')}
+
+
+
)
}
diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx
index 98f9830e..9cc46a5f 100644
--- a/apps/app/src/components/shell/SidebarNav.tsx
+++ b/apps/app/src/components/shell/SidebarNav.tsx
@@ -12,6 +12,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/account', icon: 'user', labelKey: 'shell.nav.account' },
{
to: '/',
@@ -31,7 +32,7 @@ function linkClass(active: boolean): string {
].join(' ')
}
-/** The three destinations of the shell; `onNavigate` closes the mobile drawer. */
+/** The destinations of the shell, in the validated mockup's order; `onNavigate` closes the mobile drawer. */
export default function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
const t = useT()
return (
diff --git a/apps/app/src/components/ui/Icon.tsx b/apps/app/src/components/ui/Icon.tsx
index 0123c7bd..79a5b3cb 100644
--- a/apps/app/src/components/ui/Icon.tsx
+++ b/apps/app/src/components/ui/Icon.tsx
@@ -5,6 +5,7 @@ export type IconName =
| 'close'
| 'dashboard'
| 'user'
+ | 'users'
| 'tool'
| 'logout'
| 'eye'
@@ -20,6 +21,7 @@ const PATHS: Record
= {
close: 'M6 6l12 12M18 6L6 18',
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',
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',
diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts
index 8846d23c..6a77bfc1 100644
--- a/apps/app/src/i18n/en.ts
+++ b/apps/app/src/i18n/en.ts
@@ -362,6 +362,7 @@ export const en: Dict = {
'shell.close_menu': 'Close menu',
'shell.nav.dashboard': 'Dashboard',
'shell.nav.account': 'My account',
+ 'shell.nav.clients': 'Clients',
'shell.nav.local_tool': 'Report tool',
'shell.nav.local_tool_hint': 'No account, PDF export',
'shell.sign_out': 'Sign out',
@@ -489,4 +490,143 @@ export const en: Dict = {
'Photo refused: between 64 and 4096 pixels per side.',
'account.avatar.rejected.processing_error':
'Photo refused: processing failed. Try another image.',
+
+ // V1-1.5 clients, workspace, leave guard
+ 'common.retry': 'Retry',
+ 'workspace.loading': 'Loading your workspace…',
+ 'workspace.inactive':
+ 'Your account is deactivated: your records are not accessible. Contact Faunosteo support.',
+ 'workspace.unconfirmed': 'Confirm your email address to access your records.',
+ 'workspace.missing':
+ 'Your workspace does not answer. Retry; if it persists, contact Faunosteo support.',
+ 'workspace.error': 'Your workspace could not be loaded.',
+ 'clients.failure.not_found': 'This client cannot be found.',
+ 'clients.failure.archived': 'This client is archived: restore it to edit it.',
+ 'clients.failure.conflict': 'This client was changed in the meantime.',
+ 'clients.failure.request_conflict':
+ 'An earlier attempt of this creation carried other values and may already have created the client. Check the client list before trying again.',
+ 'clients.failure.limit_reached':
+ 'Your workspace has reached its maximum number of clients.',
+ 'clients.failure.rate_limited':
+ 'Too many changes in a short time. Try again in a few minutes.',
+ 'clients.failure.invalid_input':
+ 'A value was not accepted. Check the fields.',
+ 'clients.failure.session_expired': 'Your session has expired. Sign in again.',
+ 'clients.failure.network': 'No connection. Check your network, then retry.',
+ 'clients.failure.unavailable':
+ 'The service is not answering right now. Retry.',
+ 'clients.kind.person': 'Person',
+ 'clients.kind.organization': 'Organization',
+ 'clients.archived_badge': 'Archived',
+ 'clients.list.title': 'Clients',
+ 'clients.list.new': 'New client',
+ 'clients.list.search_label': 'Search clients',
+ 'clients.list.search_hint': 'Name, city, email or phone',
+ 'clients.list.archived_toggle': 'Show archived',
+ 'clients.list.loading': 'Loading clients…',
+ 'clients.list.results_label': 'Clients found',
+ 'clients.list.count_one': '1 client shown',
+ 'clients.list.count_other': '{count} clients shown',
+ 'clients.list.empty': 'No clients yet.',
+ 'clients.list.empty_hint': 'Create your first client with “New client”.',
+ 'clients.list.no_results': 'No client matches this search.',
+ 'clients.list.archived_empty': 'No archived clients.',
+ 'clients.list.more': 'Show more',
+ 'clients.list.loading_more': 'Loading…',
+ 'clients.list.animals_none': 'No animals',
+ 'clients.list.animals_one': '1 animal',
+ 'clients.list.animals_other': '{count} animals',
+ 'clients.form.create_title': 'New client',
+ 'clients.form.edit_title': 'Edit client',
+ 'clients.form.kind_legend': 'Client type',
+ 'clients.form.display_name.person': 'Display name',
+ 'clients.form.display_name.organization': 'Organization name',
+ 'clients.form.display_name_hint.person':
+ 'As you say it: “Marie Dupont”, “Mrs Dupont”.',
+ 'clients.form.display_name_hint.organization':
+ 'The name of the organization: “Écurie du Lac”.',
+ 'clients.form.required': 'required',
+ 'clients.form.optional': 'optional',
+ 'clients.form.contact_title': 'Contact details',
+ 'clients.form.address_title': 'Address',
+ 'clients.form.email': 'Email',
+ 'clients.form.phone': 'Phone',
+ 'clients.form.phone_hint':
+ 'With its country code (+32…); a French number (06…) is converted to +33.',
+ 'clients.form.address_line1': 'Address',
+ 'clients.form.address_line2': 'Address line 2',
+ 'clients.form.postal_code': 'Postal code',
+ 'clients.form.city': 'City',
+ 'clients.form.country': 'Country',
+ 'clients.form.country_none': 'Not given',
+ 'clients.form.submit_create': 'Create client',
+ 'clients.form.submit_update': 'Save',
+ 'clients.form.saving': 'Saving…',
+ 'clients.form.back_to_client': 'Back to the client',
+ 'clients.form.conflict_title': 'This client was changed elsewhere.',
+ 'clients.form.conflict_body':
+ 'What you typed is kept and the saved value is shown under each field that differs. “Save” will replace the saved values with yours.',
+ 'clients.form.conflict_take_stored': 'Use the saved values',
+ 'clients.form.stored_value': 'Saved value: {value}',
+ 'clients.form.stored_empty': 'Saved value: empty',
+ 'clients.error.required': 'This field is required.',
+ 'clients.error.too_long': '{max} characters at most.',
+ 'clients.error.characters': 'Character not accepted (tab, line break…).',
+ 'clients.error.email_format': 'Invalid email address.',
+ 'clients.error.phone_format':
+ 'Invalid number: +33 6 12 34 56 78 or 06 12 34 56 78.',
+ 'clients.error.phone_country_code':
+ 'Enter the number with its country code (+32…).',
+ 'clients.error.country': 'Unknown country.',
+ 'clients.detail.loading': 'Loading client…',
+ 'clients.detail.back': '← Clients',
+ 'clients.detail.contact': 'Contact details',
+ 'clients.detail.no_contact': 'No contact details given.',
+ 'clients.detail.phone': 'Phone',
+ 'clients.detail.email': 'Email',
+ 'clients.detail.address': 'Address',
+ 'clients.detail.country': 'Country',
+ 'clients.detail.edit': 'Edit',
+ 'clients.detail.archive': 'Archive',
+ 'clients.detail.restore': 'Restore',
+ 'clients.detail.restoring': 'Restoring…',
+ 'clients.detail.archived_notice':
+ 'This client is archived: the record is read-only. Restore it to edit it.',
+ 'clients.detail.created': 'Client created.',
+ 'clients.detail.updated': 'Changes saved.',
+ 'clients.detail.archived': 'Client archived.',
+ 'clients.detail.restored': 'Client restored.',
+ 'clients.animals.title': 'Animals',
+ 'clients.animals.loading': 'Loading animals…',
+ 'clients.animals.none': 'No animal linked to this client.',
+ 'clients.animals.current': 'Current',
+ 'clients.animals.former': 'Former',
+ 'clients.animals.since': 'since {date}',
+ 'clients.animals.until': 'until {date}',
+ 'clients.role.owner': 'Owner',
+ 'clients.role.keeper': 'Keeper',
+ 'clients.role.contact': 'Contact',
+ 'clients.role.former_owner': 'Former owner',
+ 'clients.role.former_keeper': 'Former keeper',
+ 'clients.role.former_contact': 'Former contact',
+ 'clients.archive.title': 'Archive this client?',
+ 'clients.archive.body':
+ 'The client will be hidden from the lists and the record becomes read-only. Its animals are not archived and its relations are kept. You can restore it at any time.',
+ 'clients.archive.preview_loading': 'Checking linked animals…',
+ 'clients.archive.preview_failed': 'Linked animals could not be checked.',
+ 'clients.archive.sole_owner_one':
+ 'It is the only current owner of this active animal:',
+ 'clients.archive.sole_owner_other':
+ 'It is the only current owner of these {count} active animals:',
+ 'clients.archive.others': 'and {count} more.',
+ 'clients.archive.confirm': 'Archive',
+ 'clients.archive.archiving': 'Archiving…',
+ 'clients.not_found.title': 'Client not found',
+ 'clients.not_found.body':
+ 'This client does not exist or is not available to your account.',
+ 'clients.not_found.back': 'Back to clients',
+ 'leave.title': 'Leave without saving?',
+ 'leave.body': 'The changes in this form will be lost.',
+ 'leave.stay': 'Stay on the page',
+ 'leave.confirm': 'Leave without saving',
}
diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts
index 319712a9..fe462ee7 100644
--- a/apps/app/src/i18n/fr.ts
+++ b/apps/app/src/i18n/fr.ts
@@ -378,6 +378,7 @@ export const fr: Dict = {
'shell.close_menu': 'Fermer le menu',
'shell.nav.dashboard': 'Tableau de bord',
'shell.nav.account': 'Mon compte',
+ 'shell.nav.clients': 'Clients',
'shell.nav.local_tool': 'Outil de bilan',
'shell.nav.local_tool_hint': 'Sans compte, export PDF',
'shell.sign_out': 'Se déconnecter',
@@ -507,4 +508,150 @@ export const fr: Dict = {
'Photo refusée : entre 64 et 4096 pixels de côté.',
'account.avatar.rejected.processing_error':
'Photo refusée : le traitement a échoué. Réessayez avec une autre image.',
+
+ // V1-1.5 clients, workspace, leave guard
+ 'common.retry': 'Réessayer',
+ 'workspace.loading': 'Chargement de votre espace…',
+ 'workspace.inactive':
+ 'Votre compte est désactivé : vos dossiers ne sont pas accessibles. Contactez le support Faunosteo.',
+ 'workspace.unconfirmed':
+ 'Confirmez votre adresse e-mail pour accéder à vos dossiers.',
+ 'workspace.missing':
+ 'Votre espace de travail ne répond pas. Réessayez ; si cela persiste, contactez le support Faunosteo.',
+ 'workspace.error': "Votre espace de travail n'a pas pu être chargé.",
+ 'clients.failure.not_found': 'Ce client est introuvable.',
+ 'clients.failure.archived':
+ 'Ce client est archivé : restaurez-le pour le modifier.',
+ 'clients.failure.conflict': 'Ce client a été modifié entre-temps.',
+ 'clients.failure.request_conflict':
+ "Une tentative précédente de cette création portait d'autres valeurs et a peut-être déjà créé le client. Vérifiez la liste des clients avant de recommencer.",
+ 'clients.failure.limit_reached':
+ 'Le nombre maximal de clients de votre espace est atteint.',
+ 'clients.failure.rate_limited':
+ "Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.",
+ 'clients.failure.invalid_input':
+ "Une valeur n'a pas été acceptée. Vérifiez les champs.",
+ 'clients.failure.session_expired':
+ 'Votre session a expiré. Reconnectez-vous.',
+ 'clients.failure.network':
+ 'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
+ 'clients.failure.unavailable':
+ 'Le service ne répond pas pour le moment. Réessayez.',
+ 'clients.kind.person': 'Personne',
+ 'clients.kind.organization': 'Structure',
+ 'clients.archived_badge': 'Archivé',
+ 'clients.list.title': 'Clients',
+ 'clients.list.new': 'Nouveau client',
+ 'clients.list.search_label': 'Rechercher un client',
+ 'clients.list.search_hint': 'Nom, ville, e-mail ou téléphone',
+ 'clients.list.archived_toggle': 'Afficher les archivés',
+ 'clients.list.loading': 'Chargement des clients…',
+ 'clients.list.results_label': 'Clients trouvés',
+ 'clients.list.count_one': '1 client affiché',
+ 'clients.list.count_other': '{count} clients affichés',
+ 'clients.list.empty': "Aucun client pour l'instant.",
+ 'clients.list.empty_hint':
+ 'Créez votre premier client avec « Nouveau client ».',
+ 'clients.list.no_results': 'Aucun client ne correspond à cette recherche.',
+ 'clients.list.archived_empty': 'Aucun client archivé.',
+ 'clients.list.more': 'Afficher plus',
+ 'clients.list.loading_more': 'Chargement…',
+ 'clients.list.animals_none': 'Aucun animal',
+ 'clients.list.animals_one': '1 animal',
+ 'clients.list.animals_other': '{count} animaux',
+ 'clients.form.create_title': 'Nouveau client',
+ 'clients.form.edit_title': 'Modifier le client',
+ 'clients.form.kind_legend': 'Type de client',
+ 'clients.form.display_name.person': 'Nom affiché',
+ 'clients.form.display_name.organization': 'Dénomination',
+ 'clients.form.display_name_hint.person':
+ 'Tel que vous le dites : « Marie Dupont », « Mme Dupont ».',
+ 'clients.form.display_name_hint.organization':
+ 'Le nom de la structure : « Écurie du Lac ».',
+ 'clients.form.required': 'obligatoire',
+ 'clients.form.optional': 'facultatif',
+ 'clients.form.contact_title': 'Coordonnées',
+ 'clients.form.address_title': 'Adresse',
+ 'clients.form.email': 'E-mail',
+ 'clients.form.phone': 'Téléphone',
+ 'clients.form.phone_hint':
+ 'Avec son indicatif (+32…) ; un numéro français (06…) est converti en +33.',
+ 'clients.form.address_line1': 'Adresse',
+ 'clients.form.address_line2': "Complément d'adresse",
+ 'clients.form.postal_code': 'Code postal',
+ 'clients.form.city': 'Ville',
+ 'clients.form.country': 'Pays',
+ 'clients.form.country_none': 'Non renseigné',
+ 'clients.form.submit_create': 'Créer le client',
+ 'clients.form.submit_update': 'Enregistrer',
+ 'clients.form.saving': 'Enregistrement…',
+ 'clients.form.back_to_client': 'Retour à la fiche',
+ 'clients.form.conflict_title': 'Ce client a été modifié ailleurs.',
+ 'clients.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.',
+ 'clients.form.conflict_take_stored': 'Reprendre les valeurs enregistrées',
+ 'clients.form.stored_value': 'Valeur enregistrée : {value}',
+ 'clients.form.stored_empty': 'Valeur enregistrée : vide',
+ 'clients.error.required': 'Ce champ est obligatoire.',
+ 'clients.error.too_long': '{max} caractères au maximum.',
+ 'clients.error.characters':
+ 'Caractère non accepté (tabulation, saut de ligne…).',
+ 'clients.error.email_format': 'Adresse e-mail invalide.',
+ 'clients.error.phone_format':
+ 'Numéro invalide : +33 6 12 34 56 78 ou 06 12 34 56 78.',
+ 'clients.error.phone_country_code':
+ 'Indiquez le numéro avec son indicatif (+32…).',
+ 'clients.error.country': 'Pays inconnu.',
+ 'clients.detail.loading': 'Chargement du client…',
+ 'clients.detail.back': '← Clients',
+ 'clients.detail.contact': 'Coordonnées',
+ 'clients.detail.no_contact': 'Aucune coordonnée renseignée.',
+ 'clients.detail.phone': 'Téléphone',
+ 'clients.detail.email': 'E-mail',
+ 'clients.detail.address': 'Adresse',
+ 'clients.detail.country': 'Pays',
+ 'clients.detail.edit': 'Modifier',
+ 'clients.detail.archive': 'Archiver',
+ 'clients.detail.restore': 'Restaurer',
+ 'clients.detail.restoring': 'Restauration…',
+ 'clients.detail.archived_notice':
+ 'Ce client est archivé : sa fiche est en lecture seule. Restaurez-le pour la modifier.',
+ 'clients.detail.created': 'Client créé.',
+ 'clients.detail.updated': 'Modifications enregistrées.',
+ 'clients.detail.archived': 'Client archivé.',
+ 'clients.detail.restored': 'Client restauré.',
+ 'clients.animals.title': 'Animaux',
+ 'clients.animals.loading': 'Chargement des animaux…',
+ 'clients.animals.none': 'Aucun animal lié à ce client.',
+ 'clients.animals.current': 'Actuels',
+ 'clients.animals.former': 'Anciens',
+ 'clients.animals.since': 'depuis le {date}',
+ 'clients.animals.until': "jusqu'au {date}",
+ 'clients.role.owner': 'Propriétaire',
+ 'clients.role.keeper': 'Détenteur',
+ 'clients.role.contact': 'Contact',
+ 'clients.role.former_owner': 'Ancien propriétaire',
+ 'clients.role.former_keeper': 'Ancien détenteur',
+ 'clients.role.former_contact': 'Ancien contact',
+ 'clients.archive.title': 'Archiver ce client ?',
+ 'clients.archive.body':
+ 'Le client sera masqué des listes et sa fiche passera en lecture seule. Ses animaux ne sont pas archivés et ses relations sont conservées. Vous pourrez le restaurer à tout moment.',
+ 'clients.archive.preview_loading': 'Vérification des animaux liés…',
+ 'clients.archive.preview_failed':
+ "Les animaux liés n'ont pas pu être vérifiés.",
+ 'clients.archive.sole_owner_one':
+ "C'est le seul propriétaire actuel de cet animal actif :",
+ 'clients.archive.sole_owner_other':
+ "C'est le seul propriétaire actuel de ces {count} animaux actifs :",
+ 'clients.archive.others': 'et {count} de plus.',
+ 'clients.archive.confirm': 'Archiver',
+ 'clients.archive.archiving': 'Archivage…',
+ 'clients.not_found.title': 'Client introuvable',
+ 'clients.not_found.body':
+ "Ce client n'existe pas ou n'est pas accessible depuis votre compte.",
+ 'clients.not_found.back': 'Retour aux clients',
+ 'leave.title': 'Quitter sans enregistrer ?',
+ 'leave.body': 'Les modifications de ce formulaire seront perdues.',
+ 'leave.stay': 'Rester sur la page',
+ 'leave.confirm': 'Quitter sans enregistrer',
}
diff --git a/apps/app/src/state/leaveGuardStore.ts b/apps/app/src/state/leaveGuardStore.ts
new file mode 100644
index 00000000..8477f247
--- /dev/null
+++ b/apps/app/src/state/leaveGuardStore.ts
@@ -0,0 +1,16 @@
+import { create } from 'zustand'
+
+/**
+ * Whether the page holds unsaved changes the user would lose by following a
+ * link of the shell. Armed by useLeaveGuard; read by AppLayout, which asks
+ * before an in-app link click while it is armed.
+ */
+interface LeaveGuardState {
+ armed: boolean
+ arm: (armed: boolean) => void
+}
+
+export const useLeaveGuardStore = create((set) => ({
+ armed: false,
+ arm: (armed) => set({ armed }),
+}))
diff --git a/apps/app/tests/unit/clients.validation.test.ts b/apps/app/tests/unit/clients.validation.test.ts
new file mode 100644
index 00000000..f69c19ef
--- /dev/null
+++ b/apps/app/tests/unit/clients.validation.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from 'vitest'
+import { CLIENT_FIELD_LIMITS } from '@faunosteo/supabase'
+import { COUNTRY_CODES, countryName, countryOptions } from '@/clients/countries'
+import {
+ EMPTY_CLIENT_VALUES,
+ clientFieldErrors,
+ clientSchema,
+ normalizePhoneEntry,
+ type ClientFormValues,
+} from '@/clients/validation'
+
+const parse = (patch: Partial) => clientSchema.safeParse({ ...EMPTY_CLIENT_VALUES, ...patch })
+const errorsOf = (patch: Partial) => {
+ const result = parse(patch)
+ return result.success ? {} : clientFieldErrors(result.error)
+}
+
+describe('client form schema (D-R7 on field-limits)', () => {
+ it('needs only a kind and a display name; empty optionals become null', () => {
+ const result = parse({ display_name: ' Marie Dupont ' })
+ expect(result.success && result.data).toEqual({
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ email: null,
+ phone: null,
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: null,
+ country: null,
+ })
+ })
+
+ it('refuses a missing name and names the field', () => {
+ expect(errorsOf({ display_name: ' ' })).toEqual({ display_name: 'clients.error.required' })
+ })
+
+ it('counts code points like char_length: 120 accepted, 121 refused, astral characters count once', () => {
+ expect(errorsOf({ display_name: 'é'.repeat(120) })).toEqual({})
+ expect(errorsOf({ display_name: '𝄞'.repeat(120) })).toEqual({})
+ expect(errorsOf({ display_name: 'é'.repeat(121) })).toEqual({ display_name: 'clients.error.too_long|120' })
+ expect(errorsOf({ display_name: 'M', city: 'x'.repeat(CLIENT_FIELD_LIMITS.city + 1) })).toEqual({ city: 'clients.error.too_long|80' })
+ expect(errorsOf({ display_name: 'M', postal_code: '9'.repeat(17) })).toEqual({ postal_code: 'clients.error.too_long|16' })
+ expect(errorsOf({ display_name: 'M', address_line1: 'a'.repeat(121) })).toEqual({ address_line1: 'clients.error.too_long|120' })
+ })
+
+ it('refuses control characters, U+2028 included, and trims Unicode spaces', () => {
+ expect(errorsOf({ display_name: 'Tab\there' })).toEqual({ display_name: 'clients.error.characters' })
+ expect(errorsOf({ display_name: 'M', city: 'Line
sep' })).toEqual({ city: 'clients.error.characters' })
+ const result = parse({ display_name: ' Marie ' })
+ expect(result.success && result.data.display_name).toBe('Marie')
+ })
+
+ it('lower-cases the email and checks the shared pattern and its 254 bound', () => {
+ const result = parse({ display_name: 'M', email: ' Marie@Example.TEST ' })
+ expect(result.success && result.data.email).toBe('marie@example.test')
+ expect(errorsOf({ display_name: 'M', email: 'a b@c.de' })).toEqual({ email: 'clients.error.email_format' })
+ expect(errorsOf({ display_name: 'M', email: 'a'.repeat(247) + '@ex.test' })).toEqual({ email: 'clients.error.too_long|254' })
+ expect(errorsOf({ display_name: 'M', email: 'a'.repeat(246) + '@ex.test' })).toEqual({})
+ })
+
+ it('accepts only listed countries and sets none by default', () => {
+ expect(errorsOf({ display_name: 'M', country: 'XX' })).toEqual({ country: 'clients.error.country' })
+ const result = parse({ display_name: 'M', country: 'BE' })
+ expect(result.success && result.data.country).toBe('BE')
+ })
+
+ it('reports every field error at once, the phone included', () => {
+ expect(errorsOf({ display_name: '', phone: '12' })).toEqual({
+ display_name: 'clients.error.required',
+ phone: 'clients.error.phone_format',
+ })
+ })
+
+ it('stores the converted phone', () => {
+ const result = parse({ display_name: 'M', phone: '06 12 34 56 78' })
+ expect(result.success && result.data.phone).toBe('+33612345678')
+ })
+})
+
+describe('phone entry rule (contract §11.3)', () => {
+ it.each([
+ ['06 12 34 56 78', '', { ok: true, value: '+33612345678' }],
+ ['06.12.34.56.78', 'FR', { ok: true, value: '+33612345678' }],
+ ['+32 475 12 34 56', 'BE', { ok: true, value: '+32475123456' }],
+ ['+33 6 12 34 56 78', 'BE', { ok: true, value: '+33612345678' }],
+ ['', 'BE', { ok: true, value: null }],
+ ['0475 12 34 56', 'BE', { ok: false, error: 'clients.error.phone_country_code' }],
+ ['06 12 34 56 78', 'CH', { ok: false, error: 'clients.error.phone_country_code' }],
+ ['0612', '', { ok: false, error: 'clients.error.phone_format' }],
+ ['0032475123456', 'FR', { ok: false, error: 'clients.error.phone_format' }],
+ ['+0612345678', '', { ok: false, error: 'clients.error.phone_format' }],
+ ])('%s with country %s', (raw, country, expected) => {
+ expect(normalizePhoneEntry(raw, country)).toEqual(expected)
+ })
+})
+
+describe('countries', () => {
+ it('commits the 249 ISO 3166-1 alpha-2 codes, unique and upper-case', () => {
+ expect(COUNTRY_CODES).toHaveLength(249)
+ expect(new Set(COUNTRY_CODES).size).toBe(249)
+ expect(COUNTRY_CODES.every((code) => /^[A-Z]{2}$/.test(code))).toBe(true)
+ })
+
+ it('names them in the UI language, sorted by name', () => {
+ expect(countryName('BE', 'fr')).toBe('Belgique')
+ expect(countryName('BE', 'en')).toBe('Belgium')
+ const fr = countryOptions('fr')
+ expect(fr).toHaveLength(249)
+ const labels = fr.map((o) => o.label)
+ expect([...labels].sort((a, b) => a.localeCompare(b, 'fr'))).toEqual(labels)
+ })
+})
diff --git a/apps/app/tests/unit/routes.clients.test.tsx b/apps/app/tests/unit/routes.clients.test.tsx
new file mode 100644
index 00000000..cadc10ea
--- /dev/null
+++ b/apps/app/tests/unit/routes.clients.test.tsx
@@ -0,0 +1,371 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
+import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
+
+const mocks = vi.hoisted(() => ({ fake: null as unknown }))
+vi.mock('@/lib/supabase', () => ({
+ getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
+ isSupabaseConfigured: () => mocks.fake !== null,
+}))
+
+import AppLayout from '@/components/shell/AppLayout'
+import RequireWorkspace from '@/app/guards/RequireWorkspace'
+import ClientsListRoute from '@/app/routes/app/clients/ClientsListRoute'
+import ClientCreateRoute from '@/app/routes/app/clients/ClientCreateRoute'
+import ClientDetailRoute from '@/app/routes/app/clients/ClientDetailRoute'
+import ClientEditRoute from '@/app/routes/app/clients/ClientEditRoute'
+import { SEARCH_DELAY_MS } from '@/clients/useClientList'
+import { useAuthStore, type WorkspaceState } from '@/state/authStore'
+import { useLocaleStore } from '@/state/localeStore'
+import { fr } from '@/i18n/fr'
+
+/**
+ * The client screens on a fake client: states, the calls they make and what
+ * they keep. The RPC signatures are checked by the compiler in
+ * packages/supabase and against real PostgREST in its sandbox suite; the
+ * journeys run in Chromium in e2e/shell/clients.spec.ts.
+ */
+const WS = '11111111-1111-4111-8111-111111111111'
+const ID = '22222222-2222-4222-8222-222222222222'
+
+let fake: FakeSupabase
+
+function listRow(i: number, patch: Record = {}) {
+ return {
+ id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
+ kind: 'person',
+ display_name: `Client ${String(i).padStart(2, '0')}`,
+ city: null,
+ phone: null,
+ email: null,
+ archived_at: null,
+ name_key: `client ${String(i).padStart(2, '0')}`,
+ current_animal_count: 0,
+ ...patch,
+ }
+}
+
+function clientRow(patch: Record = {}) {
+ return {
+ id: ID,
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ email: null,
+ phone: null,
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: 'Lyon',
+ country: null,
+ revision: 1,
+ archived_at: null,
+ created_at: '2026-10-26T10:00:00Z',
+ updated_at: '2026-10-26T10:00:00Z',
+ ...patch,
+ }
+}
+
+/** The page itself, without the shell's top bar (which repeats the page title). */
+const page = () => within(screen.getByRole('main'))
+
+const rpcArgs = (name: string) => fake.rpcCalls.filter(([n]) => n === name).map(([, a]) => a as Record)
+
+function Where() {
+ return {useLocation().pathname}
+}
+
+function mount(path: string, workspace: WorkspaceState = { status: 'ready', id: WS }) {
+ useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), workspace })
+ return render(
+
+
+ }>
+ dashboard} />
+ }>
+ } />
+ } />
+ } />
+ } />
+
+
+
+
+ ,
+ )
+}
+
+beforeEach(() => {
+ useLocaleStore.setState({ locale: 'fr' })
+ fake = createFakeSupabase()
+ fake.tables.clients = []
+ fake.rpcResults.search_clients = { data: [] }
+ fake.rpcResults.list_client_animals = { data: [] }
+ mocks.fake = fake
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('RequireWorkspace', () => {
+ it.each([
+ [{ status: 'loading' }, 'workspace.loading'],
+ [{ status: 'inactive' }, 'workspace.inactive'],
+ [{ status: 'unconfirmed' }, 'workspace.unconfirmed'],
+ [{ status: 'missing' }, 'workspace.missing'],
+ ] as const)('says %o and renders no client screen', (workspace, key) => {
+ mount('/app/clients', workspace)
+ expect(screen.getByText(fr[key])).toBeInTheDocument()
+ expect(page().queryByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeNull()
+ expect(fake.rpcCalls).toEqual([])
+ })
+
+ it('names a read failure and reads again on retry', async () => {
+ fake.tables.workspaces = [{ id: WS, personal_user_id: 'user-1' }]
+ mount('/app/clients', { status: 'error', failure: 'network' })
+ expect(screen.getByText(`${fr['workspace.error']} ${fr['clients.failure.network']}`)).toBeInTheDocument()
+ await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
+ expect(await page().findByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeInTheDocument()
+ })
+
+ it('remounts the screens on another workspace: no row of the previous one stays', async () => {
+ fake.rpcResults.search_clients = { data: [listRow(1, { display_name: 'Client de A' })] }
+ mount('/app/clients')
+ expect(await screen.findByText('Client de A')).toBeInTheDocument()
+ fake.rpcResults.search_clients = { data: [] }
+ act(() => useAuthStore.setState({ workspace: { status: 'loading' } }))
+ expect(screen.queryByText('Client de A')).toBeNull()
+ act(() => useAuthStore.setState({ workspace: { status: 'ready', id: '33333333-3333-4333-8333-333333333333' } }))
+ expect(await screen.findByText(fr['clients.list.empty'])).toBeInTheDocument()
+ expect(screen.queryByText('Client de A')).toBeNull()
+ expect(rpcArgs('search_clients').at(-1)?.workspace_id).toBe('33333333-3333-4333-8333-333333333333')
+ })
+})
+
+describe('client list', () => {
+ it('lists the first page in the workspace, focuses its heading, offers « Afficher plus »', async () => {
+ fake.rpcResults.search_clients = { data: Array.from({ length: 26 }, (_, i) => listRow(i + 1)) }
+ mount('/app/clients')
+ expect(await screen.findByText('Client 01')).toBeInTheDocument()
+ expect(page().getByRole('heading', { level: 1, name: fr['clients.list.title'] })).toHaveFocus()
+ expect(screen.getAllByRole('listitem')).toHaveLength(25)
+ expect(rpcArgs('search_clients')[0]).toMatchObject({ workspace_id: WS, query: '', archived: false, page_size: 26 })
+ fake.rpcResults.search_clients = { data: [listRow(26), listRow(27)] }
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.list.more'] }))
+ expect(await screen.findByText('Client 27')).toBeInTheDocument()
+ expect(screen.getAllByRole('listitem')).toHaveLength(27)
+ expect(rpcArgs('search_clients').at(-1)).toMatchObject({ after_name_key: 'client 25', after_id: listRow(25).id })
+ expect(screen.queryByRole('button', { name: fr['clients.list.more'] })).toBeNull()
+ })
+
+ it('waits for a pause in typing before searching, once', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ mount('/app/clients')
+ await screen.findByText(fr['clients.list.empty'])
+ const before = rpcArgs('search_clients').length
+ const box = screen.getByRole('searchbox', { name: new RegExp(fr['clients.list.search_label']) })
+ for (const value of ['m', 'ma', 'mar', 'mari']) fireEvent.change(box, { target: { value } })
+ await act(() => vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS + 10))
+ await waitFor(() => expect(rpcArgs('search_clients').length).toBe(before + 1))
+ expect(rpcArgs('search_clients').at(-1)?.query).toBe('mari')
+ expect(await screen.findByText(fr['clients.list.no_results'])).toBeInTheDocument()
+ })
+
+ it('switches to the archived clients', async () => {
+ mount('/app/clients')
+ await screen.findByText(fr['clients.list.empty'])
+ fake.rpcResults.search_clients = { data: [listRow(1, { archived_at: '2026-10-26T10:00:00Z' })] }
+ await userEvent.click(screen.getByRole('switch', { name: fr['clients.list.archived_toggle'] }))
+ expect(await screen.findByText(fr['clients.archived_badge'])).toBeInTheDocument()
+ expect(rpcArgs('search_clients').at(-1)?.archived).toBe(true)
+ })
+
+ it('names a failure and retries', async () => {
+ fake.rpcResults.search_clients = { error: { code: '', message: 'FetchError' } }
+ mount('/app/clients')
+ expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument()
+ fake.rpcResults.search_clients = { data: [listRow(1)] }
+ await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
+ expect(await screen.findByText('Client 01')).toBeInTheDocument()
+ })
+})
+
+describe('client creation', () => {
+ it('refuses an empty name and focuses it, without a request', async () => {
+ mount('/app/clients/new')
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person']))
+ expect(name).toHaveFocus()
+ expect(name).toHaveAttribute('aria-invalid', 'true')
+ expect(screen.getByText(fr['clients.error.required'])).toBeInTheDocument()
+ expect(rpcArgs('create_client')).toEqual([])
+ })
+
+ it('sends the same request id again after a lost answer, then opens the client', async () => {
+ fake.rpcResults.create_client = { error: { code: '', message: 'TypeError: fetch failed' } }
+ mount('/app/clients/new')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Marie Dupont')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.phone'])), '06 12 34 56 78')
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument()
+ fake.rpcResults.create_client = { data: { id: ID, revision: 1 } }
+ fake.tables.clients = [clientRow()]
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`))
+ const [first, second] = rpcArgs('create_client')
+ expect(first.create_request_id).toBe(second.create_request_id)
+ expect(first).toMatchObject({ workspace_id: WS, kind: 'person', display_name: 'Marie Dupont', phone: '+33612345678' })
+ expect(await screen.findByText(fr['clients.detail.created'])).toBeInTheDocument()
+ })
+
+ it('a double click sends one creation', async () => {
+ let release: () => void = () => undefined
+ const pending = new Promise((resolve) => (release = resolve))
+ const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise }
+ client.rpc = async (name, args) => {
+ fake.rpcCalls.push([name, args])
+ await pending
+ return { data: { id: ID, revision: 1 }, error: null }
+ }
+ mount('/app/clients/new')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Double')
+ const submit = screen.getByRole('button', { name: fr['clients.form.submit_create'] })
+ fireEvent.click(submit)
+ fireEvent.click(submit)
+ fireEvent.submit(submit.closest('form') as HTMLFormElement)
+ await act(async () => release())
+ expect(rpcArgs('create_client')).toHaveLength(1)
+ })
+
+ it('a new form is a new intent: another request id', async () => {
+ fake.rpcResults.create_client = { error: { code: 'P0001', message: 'rate_limited' } }
+ const first = mount('/app/clients/new')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A')
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ expect(await screen.findByText(fr['clients.failure.rate_limited'])).toBeInTheDocument()
+ first.unmount()
+ mount('/app/clients/new')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A')
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ await screen.findByText(fr['clients.failure.rate_limited'])
+ const ids = rpcArgs('create_client').map((a) => a.create_request_id)
+ expect(ids[0]).not.toBe(ids[1])
+ })
+
+ it('says a divergent replay plainly', async () => {
+ fake.rpcResults.create_client = { error: { code: 'P0001', message: 'request_conflict' } }
+ mount('/app/clients/new')
+ await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'B')
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
+ expect(await screen.findByText(fr['clients.failure.request_conflict'])).toBeInTheDocument()
+ })
+})
+
+describe('client edit', () => {
+ it('on conflict shows the stored value beside the typed one, then saves at the new revision', async () => {
+ fake.tables.clients = [clientRow()]
+ mount(`/app/clients/${ID}/edit`)
+ const city = await screen.findByLabelText(new RegExp(fr['clients.form.city']))
+ await userEvent.clear(city)
+ await userEvent.type(city, 'Annecy')
+ fake.tables.clients = [clientRow({ city: 'Vevey', revision: 2 })]
+ fake.rpcResults.update_client = { error: { code: 'P0001', message: 'conflict' } }
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] }))
+ expect(await screen.findByText(fr['clients.form.conflict_title'])).toBeInTheDocument()
+ expect(city).toHaveValue('Annecy')
+ expect(screen.getByText(fr['clients.form.stored_value'].replace('{value}', 'Vevey'))).toBeInTheDocument()
+ fake.rpcResults.update_client = { data: { revision: 3 } }
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] }))
+ await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`))
+ expect(rpcArgs('update_client').map((a) => a.expected_revision)).toEqual([1, 2])
+ expect(rpcArgs('update_client')[1]).toMatchObject({ city: 'Annecy', email: null })
+ })
+
+ it('an archived client has no form', async () => {
+ fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z' })]
+ mount(`/app/clients/${ID}/edit`)
+ expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: fr['clients.form.submit_update'] })).toBeNull()
+ })
+})
+
+describe('client page', () => {
+ it('shows the same « introuvable » for an unknown id and a malformed one', async () => {
+ mount(`/app/clients/${ID}`)
+ expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument()
+ cleanup()
+ mount('/app/clients/not-an-id')
+ expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument()
+ })
+
+ it('an archived client is read-only and can be restored', async () => {
+ fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })]
+ mount(`/app/clients/${ID}`)
+ expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument()
+ expect(screen.queryByRole('link', { name: fr['clients.detail.edit'] })).toBeNull()
+ fake.rpcResults.set_client_archived = { data: { revision: 3 } }
+ fake.tables.clients = [clientRow({ revision: 3 })]
+ await userEvent.click(screen.getByRole('button', { name: fr['clients.detail.restore'] }))
+ expect(await screen.findByText(fr['clients.detail.restored'])).toBeInTheDocument()
+ expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: false }])
+ expect(await screen.findByRole('link', { name: fr['clients.detail.edit'] })).toBeInTheDocument()
+ })
+
+ it('archives after the confirmation, which refuses to close while the request runs', async () => {
+ fake.tables.clients = [clientRow()]
+ fake.rpcResults.client_archive_preview = {
+ data: { count: 1, animals: [{ id: '44444444-4444-4444-8444-444444444444', name: 'Éclair' }] },
+ }
+ let release: () => void = () => undefined
+ const pending = new Promise((resolve) => (release = resolve))
+ const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise }
+ const rpc = client.rpc.bind(client)
+ client.rpc = async (name, args) => {
+ if (name === 'set_client_archived') {
+ fake.rpcCalls.push([name, args])
+ await pending
+ return { data: { revision: 2 }, error: null }
+ }
+ return rpc(name, args)
+ }
+ mount(`/app/clients/${ID}`)
+ await userEvent.click(await screen.findByRole('button', { name: fr['clients.detail.archive'] }))
+ const dialog = await screen.findByRole('dialog', { name: fr['clients.archive.title'] })
+ expect(await screen.findByText('Éclair')).toBeInTheDocument()
+ expect(screen.getByText(fr['clients.archive.sole_owner_one'])).toBeInTheDocument()
+ await userEvent.click(within(dialog).getByRole('button', { name: fr['clients.archive.confirm'] }))
+ await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] }))
+ expect(dialog).toBeInTheDocument()
+ fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })]
+ await act(async () => release())
+ expect(await screen.findByText(fr['clients.detail.archived'])).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: true }])
+ })
+})
+
+describe('leave guard', () => {
+ it('asks before a link leaves a form with changes; staying keeps them', async () => {
+ mount('/app/clients/new')
+ const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person']))
+ await userEvent.type(name, 'Brouillon')
+ await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] }))
+ expect(await screen.findByRole('dialog', { name: fr['leave.title'] })).toBeInTheDocument()
+ expect(screen.getByTestId('where')).toHaveTextContent('/app/clients/new')
+ await userEvent.click(screen.getByRole('button', { name: fr['leave.stay'] }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(name).toHaveValue('Brouillon')
+ await userEvent.click(screen.getAllByRole('link', { name: fr['shell.nav.dashboard'] })[0])
+ await userEvent.click(await screen.findByRole('button', { name: fr['leave.confirm'] }))
+ await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app$/))
+ })
+
+ it('lets a clean form go without asking', async () => {
+ mount('/app/clients/new')
+ await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] }))
+ await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app\/clients$/))
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+})