diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md
index 59dbad20..00c3c7f0 100644
--- a/.claude/memory/decisions.md
+++ b/.claude/memory/decisions.md
@@ -535,3 +535,56 @@ Status: principle active; C4/C5/C6 + V1-1 orientations pending ratification; P0
BDR-041 point (2) names Professional Verification "Step 11"; IMPLEMENTATION_PLAN numbers it Step 9 (Step 10 cabinets, Step 11 entitlement skeleton). Plan numbering kept. BDR-041 left as written (append-only); this entry supersedes its step number only, rest of BDR-041 unchanged. Docs cite Step 9: plan Step 7 note, V1-1 contract §5.2, OPEN_QUESTIONS C6.
Status: active.
+
+## BDR-073 | 2026-10-25 | V1-1 business decisions ratified by owner (BDR-071 proposals → approved)
+
+Decision (owner brief « V1-1 : ratification des décisions métier et préparation de l'implémentation »): D1 UI term « Clients », client = natural person or structure, Propriétaire/Détenteur/Contact = relation roles ≠ identity, no platform role reused as animal owner. D2/C4 `workspaces` + `workspace_members`, one personal workspace per practitioner, cabinet workspaces later w/o destructive transfer, no global directory, no cross-practitioner visibility, no sharing/invitations/cabinet perms in V1-1. D3 person | structure. D4 required = display name (person) / dénomination (structure), rest optional, no silent default country, no forced email/phone. D4a optional first/last names allowed, display name stays required reference, contract sets priority rule. D5 exactly 9 contract species + « Autre » w/ required detail; species ≠ sheet; equine draft never auto-published. D6 required name, species, sex w/ explicit unknown; optional breed, full birth date when known, year alone; D6a extras (neutering, identification, colour, notes, death date) + weight, photo deferred; no full vet record. D6b year never becomes date, precision kept, CHECK + tests. D7 many-to-many w/ explicit role, co-ownership, animal w/o owner OK, always in valid workspace, no fake client, never cross-workspace. D7a history: start date when known + nullable `ended_at`; no incoherent current duplicates, successive allowed; owner/keeper change never deletes history silently. D8 archive read-only reversible, relations kept, no cascade client→animals, archive ≠ erasure, no retention invented. D9/D9a temporary DEV guard vs account deletion leaving incoherent data, never permanent ban; lifecycle later. C5 V1-1 writes = practitioner in own personal workspace; finished bilans never changed silently. C6 email confirmed ≠ pro verified ≠ platform role; verification = Step 9. D16 staff no ordinary access, no admin screen, no impersonation/support access in V1-1; exceptional access = separate audited policy before publication. D15 technical caps ≠ commercial quotas; thresholds proposed before RPCs. Naming: explicit nomenclature, no generic `owner_id`.
+Still open: D10-D14, D17 (UI); technical design (SQL/RLS/RPC, N1-N9, D15 thresholds, U1-U3) awaits owner validation at V1-1 preparation checkpoint; no migration before. Contract restructured: verification now §6.2 (BDR-072 cites old §5.2).
+Alt: keep proposals open; global client record (2026-10-08 plan Step 12); `owner_user_id` column instead of workspaces.
+Status: active. Branch `feature/v1-1-clients-animals` off develop 5502617. Contract `docs/development/V1-1_OWNERS_ANIMALS.md` §13.1.
+
+## BDR-074 | 2026-10-25 | V1-1 architecture + N1-N9 validated by owner; V1-1.1 M1 workspaces built in isolation
+
+Decision (owner brief « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces »): V1-1 model accepted as target (workspaces + members, one personal ws per practitioner, cabinets later as shared ws, no organizations table, isolation per ws, clients person|structure, animals per ws, N-N relations, composite FKs, D-R7 TS forms + SQL CHECK boundary, RLS at creation, RPC writes). 6-step split accepted; only V1-1.1 authorised. N1 9 species + other, rows not enum, ids unchanged (Rust species_id free string, SQL CHECK fits). N2 no first/last names. N3 client notes deferred. N4 CHANGED: logical voiding (`voided_at`, `void_animal_client_relation`) ≠ end; voided never shown current/former, no invented `ended_on`, minimised audit; delete RPC dropped. N5 dates optional, never invented, ordered; CHECKs written in contract §5.3. N6 caps approved, write budget PER WORKSPACE (1000/h, 5000/day), concurrency-safe (no bare count+insert), mechanism fixed with M2. N7 service_role minimisation w/o claiming admin paths closed; existing tables/global privileges untouched. N8 sex none preselected. N9 no staff general view; audit = technical ids, op, time, result, bounded correlation; metadata `{workspace_id}` only (relation_role dropped). D10-D14, D17, U1-U3 stay contract-level; tab-bar contradiction → V1-1.3.
+M1 as built (`20261025100000_workspaces.sql`): creation = server init in sign-up tx (trigger on profiles → `private.ensure_personal_workspace` one-statement CTE, ON CONFLICT on named unique `workspaces_personal_user_unique`); deferred constraint triggers `workspaces_personal_holder`/`workspace_members_personal_holder` (personal ws = exactly its account as holder, any writer); backfill once; `caller_workspace_ids` (active + email confirmed, auth.uid only) EXECUTE authenticated; `writable_workspace_ids` EXECUTE none; revoke all incl. service_role on new tables/functions; log_event correlation cap + NOT VALID CHECK.
+Deviations: `packages/supabase/src/workspaces.ts` → V1-1.2 (no consumer); `db:reset && db:test` on DEV replaced by isolated sandbox (owner kept DEV untouched).
+Alt: workspace created at first authorised login (client-triggered, forgeable timing, partial-state risk); invariant only by grants (owner-role bugs undetected); per-actor budget (cabinet-blind).
+Status: active. M1 not applied to DEV (owner action, SUPABASE.md §3.3). Contract §5.3, §8.1, §9, §10, §13.2.
+
+## BDR-075 | 2026-10-25 | V1-1.1 validated; V1-1.2 M2 clients built: budget counter, divergent replay, C-lower fold, sandbox tool
+
+Decision (owner brief « Validation V1-1.1 et autorisation V1-1.2 Données clients »): V1-1.1 accepted (M1, grants, RLS, tests); MEDIUM scanner findings non-blocking, trust boundary kept documented; service_role / GoTrue admin indirect access never claimed closed. Sandbox tool kept in repo: `scripts/db-sandbox.sh` (`pnpm db:sandbox`), rootless, loopback, own ports, no volume, generated secrets outside Git, CLI runners via `--db-url`. M1 on DEV = owner procedure (SUPABASE.md §3.3), not Claude.
+M2 as built (`20261025110000_clients.sql`): budget = owner's transactional counter per workspace: `private.workspace_write_budgets` row upserted by `private.consume_write_budget`, fixed UTC hour/day windows (restart at 1 in a new window; 1000th passes, 1001st `rate_limited`; up to 2000 across an hour boundary, day 5000 holds), called LAST in every write RPC → lock order workspace → (animal → client in M3) → budget, no cycle; refused / replayed / no-op not counted (rollback). Divergent replay: `create_request_digest` (sha256 of normalised content, not API-readable) → `request_conflict`. Fold = unaccent then `lower(... collate "C")` (ASCII only) for PGlite/ICU parity. `search_clients` without `current_animal_count` until M3. Text rule via `private.is_clean_text`. Access layer → V1-1.5.
+Measured: search 20k clients p95 21 ms (no trigram index); held budget row delays only its workspace.
+Alt: count audit rows per workspace (needs index on metadata, count+insert race without extra lock); rolling windows (owner chose UTC windows); accept divergent replay as replay (silent divergence).
+Status: active. M1+M2 not on DEV.
+
+## BDR-076 | 2026-10-25 | V1-1.2 validated; V1-1.3 UI foundations: native modal dialog, Playwright + axe on sandbox
+
+Decision (owner brief « Validation V1-1.2 et autorisation V1-1.3 Socle UI »): V1-1.2 accepted (M1+M2 on isolated stack, budget 1000/h 5000/day UTC fixed windows, not to reopen without defect). D13 built on platform `` + `showModal()` (`components/ui/ModalDialog.tsx`): no a11y primitive in deps, browser modal = proven one, no hand-written trap. Never self-closes: Escape keydown cancelled → onClose, cancel → onClose, forced close reported. First tabbable focused explicitly. Restore after commit (microtask) to opener else first control of nearest surviving container. Tab past last control → browser UI one step (platform; kept). Dialog: aria-labelledby + optional description. Drawer on same primitive, closes at lg. D14: Playwright 1.64.1 + axe 4.14.0 exact dev deps. Owner choices this run: e2e backend = sandbox (not DEV), `pnpm e2e:ui` + `pnpm e2e:shell`, drawer aligned, check:all runs e2e:ui if Chromium present else SKIPPED. D11: no tab bar in V1-1.3, three-way comparison in contract §11.6, decision before V1-1.6.
+Alt: `inert` + custom Tab loop (artisanal, contract's first wording); focus-trap / Radix (new dep); e2e on DEV (writes sessions to existing accounts); route-stubbed backend (not real GoTrue).
+Status: active. Contract §11.6, BROWSER_TESTS.md.
+
+## BDR-077 | 2026-10-26 | V1-1.3 validated; V1-1.4 M3 animals + relations built: states, caps, lock order, scoped axe exceptions
+
+Decision (owner brief « Validation V1-1.3 et autorisation V1-1.4 Animaux et relations »): V1-1.3 accepted (native dialog, Playwright + axe, defects fixed); no JS focus trap without shown defect; D11 still open, 3 options before V1-1.6, none default. M3 `20261026100000_animals_relations.sql` as built (contract §8.3): species 8 + other rows (equine unchanged, rows not enum, Rust untouched); animals w/ D6b CHECKs, sex no default; relations w/ composite FKs (not deferrable), partial unique index current = `ended_at` and `voided_at` null; states current / ended (date known or unknown, `ended_at` discriminates, no contract change) / voided (frozen, shown nowhere). Caps: current ≤ 20 excludes ended+voided; totals 200/animal + 100 000/ws count every row (create-void loop bounded). `create_animal` + relation = 2 budget units (2 audit rows), relation reuses animal request id. Relation replay answered before `archived` (idempotence). Lock order M2+M3: workspace → animal → relation → client → budget last; relation RPCs read target ws unlocked among writable first (no lock outside ws). `search_animals` filter = `species_filter` (PG forbids param named like output col). `list_client_animals` cursor `sort_key` = '0'/'1' + name_key. Helpers `utc_tomorrow(timestamptz)` (pure, testable 31 Dec), parsers, `lock_relation_for_write`. No id-immutability trigger: privileged SQL may repoint within ws / move relation-less animal (§4 evolution path); composite FKs forbid cross-ws. Access layer → UI steps. Brief §2 follow-ups: axe KNOWN = rule + selector + opening markup + route; check:all prints PASSED / SKIPPED / NOT RUN, FAILED stage on error.
+Alt: 1 budget unit per create_animal (undercounts audit rows); totals excluding voided (unbounded create-void loop); replay after archived check (retry of committed create fails); trigger freezing ids (blocks §4 transfer path); keep `^dl$` route-free exceptions (new screens inherit).
+Status: active. M1-M3 not on DEV; procedure SUPABASE.md §3.3 (owner runs).
+
+## BDR-078 | 2026-10-26 | V1-1.4 validated; V1-1.5 client screens: owner U1/U2 choices, workspace in authStore, leave guard on links
+
+Decision (owner brief « Validation V1-1.4 et autorisation V1-1.5 Interface Clients »): V1-1.4 accepted (species_filter + replay order in scope). Owner choices asked before UI: U1 « Afficher plus » keyset (25 + 1 probe row, no count), U2 one « Afficher les archivés » switch, client page animals read-only (list_client_animals, no link/add), « premier animal » section → V1-1.6. Built: access layer `packages/supabase/src/{records,workspaces,clients,species}.ts` (closed RecordFailure = §9.4 kinds + session_expired + network; Zod on RPC answers; read by id explicit columns, non-uuid → null w/o request); personal workspace in authStore (loading/ready/inactive/unconfirmed/missing/error; account change resets profile+roles+avatar+workspace in one set; late answers of previous user dropped; ready kept during same-user re-read); RequireWorkspace remounts routes per workspace; leave guard = beforeunload + AppLayout capture on in-app links (ModalDialog), back/forward not interceptable (documented); heading focus on open (callback ref, waits drawer close); request id per form mount via generateUuid (getRandomValues; LAN http has no randomUUID). Shell suite: no HTML reporter (kept typed passwords).
+Alt: numbered pages (needs count), tabs for archived, data-router migration for blocking, global data cache lib, storing search term (PII) to survive back nav.
+Status: active. Client screens not checked on DEV (M1-M3 not applied; owner).
+
+## BDR-079 | 2026-10-26 | V1-1.5 validated; V1-1.6 animal screens: D11 drawer only, first animal from client page, no default role, in-page link panel
+
+Decision (owner brief « Validation V1-1.5 et autorisation V1-1.6 Interface Animaux et clôture »): V1-1.5 accepted; reserves kept as product follow-up (search not kept on back, E.164 display, back/forward not guarded); no complex navigation manager for them. D11 = drawer only for V1-1, mockup tab bar not reproduced (later UX subject, mockup unchanged). Owner answers before UI: first animal from client page (« Ajouter un (premier) animal » → /app/animals/new, client id in navigation state, never URL, re-read and checked active; one atomic create_animal with relation; client form untouched); no relation role preselected (like sex N8); link client/animal = in-page panel (no modal form, contract §11.4), end/dates/void = ModalDialog confirmations pending until write + reload; U3 = full date fills and locks year. D12 tiles outside brief → not built, stays open. Built: access `animals.ts`, `relations.ts` (relations read by one select with client embedded via `animal_client_relations_client_fk`, `voided_at is null`, limit 200); one RequireWorkspace above clients + animals holding SpeciesProvider (species read once per workspace, dropped on account change); conflict/not_found on a relation write → reload + stale message (voided elsewhere surfaces as conflict: lock order archived → revision → voided). No new business rule in TS or Rust: RPCs decide, TS = D-R7 checks + display.
+Alt: section in client create form with two-call resume (contract §11.1 text; changes client form); role owner preselected; relation forms in modal or new routes; client id in query string; per-component species fetch; new `voided` failure kind (needs M3 change).
+Status: active. Not checked on DEV (M1-M3 pending, owner).
+
+## BDR-080 | 2026-10-26 | V1-1.6 validated; DEV procedure: restore check on sandbox, fingerprints, e2e:avatar out of the run
+
+Decision (owner brief « Validation finale V1-1 et préparation de la recette DEV »): V1-1.6 + V1-1 closure limits accepted; Claude reads DEV only, owner runs backup, `migration up`, acceptance, merge go. SUPABASE.md §3.3 rewritten: SQL through read-only helpers (`default_transaction_read_only`), step 2 counts + md5 row fingerprints + structure counts saved, Storage bytes by `docker cp …:/mnt -` tar, step 3b restore into `restore_check_v1_1` on sandbox db (same image) instead of DEV server, post.sql (workspaces, holders, species, grants, pgtap), before/after diff with exact expected deltas, `supabase status -o env | grep API_URL` (default output prints keys). `e2e:avatar` removed from run: writes beyond fixture. Browser acceptance = brief §11 (19 lines).
+Alt: createdb scratch on DEV server (rehearsed form, but writes DEV server, typo risk on dropdb); throwaway postgres container (unrehearsed init); cold volume copy (stops DEV, restore = volume overwrite); keep e2e:avatar (touches bob + purge queue).
+Status: active. Steps 0-4 not run on DEV (owner).
diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md
index e559e1b8..ecab2742 100644
--- a/.claude/memory/evals.md
+++ b/.claude/memory/evals.md
@@ -247,3 +247,52 @@ Action: LRN-078, LRN-079; rerun gate after any post-check edit; run `pnpm audit`
Method: P0 doc census + V1-1 contract drafting; inventory `.claude/audits/2026-10-25-functional-inventory.md` cross-checked with RUST_ARCHITECTURE_REVIEW Annex A.
Anomaly: inventory criterion 4 placed validation rules (formats, lengths, required fields) in `crates/core` behind wasm facade. D-R7: form constraints stay TypeScript (Zod, i18n keys), SQL CHECK = integrity boundary, constants module + PGlite parity test against `pg_constraint`. Contradiction caught and corrected before V1-1 implementation contract; no code written on it.
Action: V1-1 contract §1 + §8.3 follow D-R7. Check every proposal against Annex A D-R rows before writing it.
+
+## EVAL-035 | 2026-10-25 | V1-1 design draft: 3 fresh challengers found 3 false security claims
+
+Method: plan-challenger ×3 (correctness, robustness, simplicity) on `V1-1_OWNERS_ANIMALS.md` before owner checkpoint; evidence read from migrations, harness, worker config, react-router dist.
+Anomaly: draft claimed (1) N7 service_role revoke → "D16 holds at key level" (false: service key = GoTrue admin key → magic link / set password → user session); (2) identical 42501 while reusing `require_actor()` (two messages); (3) audit growth bounded (false: `log_event` stores attacker-sized `x-correlation-id`). Also phone search vs E.164 broken, OR search unindexable, backfill untestable, multi-call create duplicates, relation RPCs race, useBlocker needs data router.
+Action: all integrated into contract §6.3, §8-§12, §14 + TODO. Claims about key/role reach need proof via the auth admin API too, not only PostgREST grants.
+
+## EVAL-036 | 2026-10-25 | V1-1.1 M1 workspaces: gates and isolated real stack
+
+Method: fresh verifier on contract `.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md` + fresh security auditor (semgrep 3 rulesets + hand SQL review), PGlite + sandbox runs, 5 mutations of M1 (email check, ON CONFLICT, correlation cap, foreign-member guard, service_role EXECUTE) all caught by 012.
+Result: security PASS (2 MEDIUM scanner false positives: policy via helper, not raw auth.uid(); LOWs = table names in 42501, residual admin paths, NOT VALID CHECK, pre-existing bounded revoke reason). Verifier C1-C8 MET, C9 UNVERIFIABLE (forbidden to read DEV) → closed by `supabase migration list --local` (M1 remote empty).
+Anomalies: first mutation run misread (sed indentation miss, crash not printed) → rerun with crash capture; concurrency script pipefail printed false "UNEXPECTED" after real ERROR → fixed. GoTrue 500 on same-email concurrent sign-up = GoTrue race on users_email_partial_key, not M1.
+Action: contract for gates should name a read-only way to check DEV state (migration list) so C9-type clauses are verifiable.
+
+## EVAL-037 | 2026-10-25 | V1-1.2 M2 clients: gates, mutations, sandbox hardening
+
+Method: fresh verifier (contract 2026-10-25-v1-1-2-clients.md) + fresh security auditor; 5 M2 mutations (divergent replay, workspace auth, `_` escape, N9 filter, hourly limit) all caught by 013; real image fresh + upgrade (M2 alone, M1+M2 together).
+Result: security PASS (MEDIUM: secrets on argv in db-sandbox.sh, fixture password literal, policy false positive; LOW: empty-secret fallback risk, state dir in repo, uncapped cursor, no read limit). Verifier ECARTS(2): BDR-075 uncommitted (committed after), fresh-mode real run not reproducible by it (rerun after hardening: 661 PASS, types match, 28/28).
+Fixes applied: secrets via env files + PGPASSWORD name only, password-free --db-url, load_secrets refuses incomplete file, state dir refused in repo. Accepted: fixture password literal (sandbox only), uncapped cursor (bounded by name_key compare), read rate limit (deploy notes RR-5).
+Anomalies: Write tool turned `
/
` escapes into raw chars (broke a JS regex) → check new files for raw line separators; prettier over tests/ touched 3 unrelated files → restored; real image adds GRANT hint to table denials.
+Action: write Unicode escapes via shell/python when exact bytes matter.
+
+## EVAL-038 | 2026-10-25 | V1-1.3 UI foundations + db:sandbox final check
+
+Method: sandbox scripted check (fresh, upgrade, types, argv scan of /proc cmdlines, negative args/secrets/state dir, DEV fingerprint before/after); 6 mutations on dialog/drawer/avatar; fresh verifier (contract 2026-10-25-v1-1-3-ui-foundations.md) + fresh security auditor.
+Result: sandbox 40/42 first pass → defect `up` bad mode/version started 4 containers + secrets before refusing → fixed 57922e0, 15/15 rerun, upgrade rerun green, DEV unchanged. Mutations: 5/6 caught at once; M5 (confirmation closed before removal) missed until RPC slowed. Verifier CONFORME 8/8. Security PASS (MEDIUM pre-existing fixture password literal; LOW seed SQL interpolation of generated values, env breadth to webServer, refused URLs unmasked → fixed). check:all green 23:41:29; e2e:ui 26, e2e:shell 6, vitest app 458.
+Anomalies: axe pre-existing serious findings (switcher, top-bar link label-in-name, dashboard dl) → KNOWN list + RR-7; the shell suite found a real focus defect in AvatarSection.
+Action: keep mutation pass for browser tests; slow async backends in focus tests.
+
+## EVAL-039 | 2026-10-26 | V1-1.4 M3 animals + relations: gates, mutations, four migration states
+
+Method: 14 mutations of M3 (PGlite pgTAP; M9 swapped into the sandbox, restored, md5 checked); 4 sandbox states (fresh, pre-M1→M1..M3, pre-M1→M1→M2+M3, M1+M2→M3): pgTAP 919, types --check, sandbox suites 46; e2e:ui 26, e2e:shell 6; import:equine --check 0 diff; check:all green 01:11:05 (e2e:ui PASSED, e2e:shell NOT RUN line); fresh verifier (contract 2026-10-26-v1-1-4-animals-relations.md) + fresh security auditor.
+Result: verifier CONFORME 11/11; security PASS (MEDIUM: sandbox fixture password literal pre-existing, policy-via-helper false positive; LOW: authz read then lock not re-checked (no membership change in V1-1), no-op/replay unmetered (as M2), reads reachable by GET (app convention), service_role ALL on species pre-existing). Mutations 12/14 caught first pass; M6 (voided-only link counted) + M9 (foreign client locked) survived → tests added (533a1c4), both caught after.
+Anomalies: pgTAP 014 green at first run (suspicious) → mutations proved it bites; axe route regex assumed /app/dashboard, dashboard is /app → shell suite failed until fixed (counter-mutations confirm scoping); permission layer refused sourcing sandbox secrets in shell → rehearsal via SQL + container env.
+Action: keep lock-wait probes for cross-tenant RPCs (LRN-084); check real route table before path-scoped test rules.
+
+## EVAL-040 | 2026-10-26 | V1-1.5 client screens: gates, three verifier rounds, report check
+
+Method: unit (supabase 92, app 509), access layer vs real PostgREST (sandbox 54), Chromium e2e:shell 42 (36 client journeys), mutations on app (request id per submit, double-click guard, late-answer guard, account reset, re-read loading) all caught; visual pass desktop+375 via temp capture spec; impeccable detect 0; report scan (decoded embedded zip); check:all green twice (02:04:48, 02:15:51); import:equine 0 diff; pgTAP 919; types match. Fresh security auditor + verifier ×3.
+Result: security PASS (LOW: test SQL interpolation of sandbox uuids); noted USER_UPDATED reset of workspace unmounting forms → fixed e1c1980. Verifier 1 ECARTS (not-found heading unfocused → fixed 567ad40), verifier 2 ECARTS (docs counts uncommitted; floor assert drop of moved signIn → CLARIFICATIONS), verifier 3 CONFORME 11/11.
+Anomalies: Prettier over whole src reformatted 39 files → restored, edits re-applied on originals; duplicate h1 (pre-existing top bar) broke selectors; StrictMode ran listener cleanup; drawer exit kept page inert; shell HTML report held typed passwords (BROWSER_TESTS claim false since V1-1.3) → reporter removed; permission layer refused rm -rf via variable (correct) and secrets sourcing.
+Action: format new files only; dispatch verifier after committing docs; scan reports by content.
+
+## EVAL-041 | 2026-10-26 | V1-1.6 animal screens and relations: gates, three verifier rounds
+
+Method: access layer by fork (unit 35, real PostgREST sandbox 7); screens unit tests by fork (57); Chromium e2e:shell 82 (animals 40), 3 full runs; 12 unit + 2 browser mutations all caught; visual pass desktop+375 (one batch fix: relation actions bordered); impeccable detect 0; check:all green 17:19:26; import:equine 0 diff; pgTAP 919; types match; DEV restore step rehearsed on sandbox (counts equal, 26 expected privilege errors). Fresh security auditor + verifier ×3.
+Result: security PASS (MEDIUM pre-existing sandbox literal pw; LOW trace override by argv). Verifier 1 ECARTS: client journey failed after passing (late replay of the animal-section reload added by V1-1.6) → dropLateReplays for every shell spec. Verifier 2 ECARTS: pgTAP 014 #237 regex `20[0-9]{2}-` matched a workspace uuid on long-lived sandbox (latent V1-1.4 false positive; would stop DEV db:test) → metadata minus workspace_id. Verifier 3 CONFORME 12/12.
+Anomalies: Card dropped aria-labelledby since Step 7 (TS ignores hyphenated props; LRN-087); useT unstable in deps (LRN-088); en substring matches (Male/Female, Save/saved) → exact; safety check refused rm inside sh -c (not bypassed; dump left for owner).
+Action: run the whole shell suite (not just the new spec) before the verifier; scope pgTAP regexes away from uuids; never chain rm into sh -c.
diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md
index 3241d5af..4f818e74 100644
--- a/.claude/memory/journal.md
+++ b/.claude/memory/journal.md
@@ -396,3 +396,63 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp
## 2026-10-25 (P0 arbitration, branch chore/p0-doc-realignment)
- Owner created `chore/p0-doc-realignment` off develop by hand, P0 edits carried over; finalised on it. Owner orientations D1-D9, D16, C4-C6 into V1-1 contract as proposals (§9.1), sub-choices D4a/D6a/D6b/D7a/D9a, open D10-D15/D17. Contract fixes vs brief: no owner required on animal (was last-owner rule), birth year + optional date (was date + precision), display name sole required client field, staff access = no mechanism (was impersonation pointer).
- README split public 0.1.0 / develop / DEV-only / planned; CHANGELOG Unreleased note; DEPLOY status notice + CSP "not production-ready" markers (RR-5 keeps fixes). BDR-071, BDR-072 (BDR-041 step fix), EVAL-034. nginx `/species/` = code debt, untouched. No migration, code, manifest. STOP at checkpoint, merge on owner go.
+
+## 2026-10-25 (V1-1 ratification + preparation, branch feature/v1-1-clients-animals)
+- Owner ratified V1-1 business decisions (BDR-073). Branch via gitflow lib off develop 5502617, pushed. Contract rewritten: approved §13.1, nomenclature §3, SQL M1-M3, RLS/helpers/RPCs §9, D15 thresholds §10, UI §11, tests §12, N1-N9 + D10-D14/D17/U1-U3 open, 6 steps in TODO.
+- 3 challengers: CONCERNS, findings integrated (EVAL-035). Stop at checkpoint: no migration, no dependency, no Supabase DEV change.
+
+## 2026-10-25 (V1-1.1 workspaces, branch feature/v1-1-clients-animals)
+- Owner validated V1-1 architecture + N1-N9 (BDR-074; N4 voiding, N6 budget per workspace, N9 ids-only audit). Built M1 `20261025100000_workspaces.sql` + pgTAP 012 (85) + config test; commits 7bf4fb6 (code), 0f8c983 (docs).
+- Isolated sandbox (DEV images, own net, loopback ports, no volume): fresh + upgrade paths, 531 pgTAP, concurrency, 33 HTTP checks; types generated there (sslmode=disable). DEV untouched (migration list: M1 local only).
+- Gates: security PASS (0 HIGH), verifier ECARTS(1) = C9 unverifiable by it, closed by read-only migration list. rust:check + check:all green. STOP at checkpoint; M1 on DEV = owner action (SUPABASE.md §3.3).
+
+## 2026-10-25 (V1-1.2 clients, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.1, authorised V1-1.2 + kept sandbox. M1 closure: official `gen types` against sandbox = 0 diff; `scripts/db-sandbox.sh` committed (08abe42), DEV procedure rehearsed incl. backup/restore (5ed1f01); LRN-080/081.
+- M2 clients (4adbfcb): RPCs, search, budget counter, N9 filter; pgTAP 013 (130), parity test, sandbox suite 28; real image adds a GRANT hint on table denials (PGlite not) → tests compare state+message there. Prettier over tests/ reformatted 3 unrelated files → restored before commit.
+
+## 2026-10-25 (V1-1.3 UI foundations, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.2, authorised V1-1.3. db:sandbox final check: defect bad `up` args → fixed 57922e0; fresh + upgrade + types + argv + DEV fingerprint green.
+- Built ModalDialog (native dialog), Dialog/drawer on it, Playwright + axe suites (e2e:ui 26, e2e:shell 6 on sandbox), check:all stage; shell suite found AvatarSection focus loss → fixed 8371aa0. D11 compared, no tab bar. BDR-076, LRN-082, EVAL-038.
+- Verifier CONFORME, security PASS, check:all green. STOP at checkpoint, no V1-1.4, no merge.
+
+## 2026-10-26 (V1-1.4 animals and relations, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.3, authorised V1-1.4. M3 `20261026100000_animals_relations.sql` (b54c8e5): species 8+other, animals, relations current/ended/voided, 7 write RPCs + 3 reads, search_clients count; pgTAP 014 (258), parity, sandbox suite 18; sandbox `up upgrade ` (2dc04bc).
+- 14 mutations, 2 gaps closed (533a1c4); 4 migration states green; axe exceptions scoped (ba3a51e), check:all statuses (d7845b7); docs + DEV procedure to M3, not run (bc6a7dd). BDR-077, LRN-083/084, EVAL-039.
+- Verifier CONFORME 11/11, security PASS, check:all green. STOP at checkpoint: no V1-1.5, no DEV, no merge.
+
+## 2026-10-26 (V1-1.5 client screens, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.4, authorised V1-1.5. Owner choices: U1 « Afficher plus », U2 archived toggle, animals read-only, first-animal section → V1-1.6. Built access layer (a0e0699), workspace in authStore (ff028ec), screens (b38e627), Chromium journeys (d33a8f6), docs (ae0bd3f, d8e86a4).
+- Fixes from gates: shell HTML report kept passwords (db81928), re-read unmounted forms (e1c1980), not-found heading focus (567ad40). BDR-078, LRN-085/086, EVAL-040.
+- Security PASS, verifier CONFORME 11/11 (3rd round), check:all green. STOP at checkpoint: no V1-1.6, DEV untouched, no merge.
+
+## 2026-10-26 (V1-1.6 animal screens and relations, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.5, D11 = drawer only. Owner choices: first animal from client page, no role default, in-page link panel, U3 lock. Built access layer (e223576), screens (930499c), Chromium journeys (3e968ee), docs + closure inventory + DEV restore check (e215e9b).
+- Gate fixes: shared late-replay drop for shell specs, pgTAP 014 uuid-as-date false positive. BDR-079, LRN-087/088/089, EVAL-041.
+- Security PASS, verifier CONFORME 12/12 (3rd round), check:all green, e2e:shell 82. STOP at checkpoint: no merge, no V1-2, DEV untouched (M1-M3 pending).
+
+## 2026-10-26 (V1-1 DEV integration checkpoint prep, branch feature/v1-1-clients-animals)
+- Owner validated V1-1.6 + closure limits. Read-only DEV preflight: 9 applied, M1-M3 pending only, no V1-1 object, types drift 24 names, 6 accounts = 6 profiles, 2 objects / 11 volume files. Git clean = origin, develop/main/release untouched.
+- SUPABASE.md §3.3 rewritten (read-only helpers, fingerprints, storage tar, restore check on sandbox, post.sql, failure + restore effects, acceptance 19 lines); restore comparison rehearsed on sandbox, identical. BDR-080, LRN-090. Rehearsal dump already gone.
+- STOP: backup, migration up, acceptance, merge = owner.
+
+## 2026-10-26 (V1-1.7 owner brief: preflight accepted)
+- Owner accepted preflight, keeps backup/restore/migration/acceptance. Classified 26 restore errors: pg_restore errors, not negative tests (18 ALTER DEFAULT PRIVILEGES, 7 GRANT ... WITH GRANT OPTION, 1 COPY vault.secrets). DEV vault 0 (read-only check).
+- §3.3 hardened: pg_restore exit + full message/command set, vault count, exit codes, pgtap after db:test, object query. Exit status of earlier rehearsal not recorded. STOP: owner runs steps 0-4.
+
+## 2026-10-26 (V1-1.7 restore check closed before owner run)
+- 26 vs 28: my report double-counted (pg_reload_conf/pg_stat_statements_reset inside "7 GRANT"); log = 26. Rehearsal 2 sandbox, 4 variants, real exit codes; retained filtered TOC + single transaction, exit 0, rows + privileges identical. DEV D=21 → 29 exclusions expected.
+- §3.3 step 2/3b rewritten, replayed verbatim on sandbox. LRN-091. STOP: owner runs steps 0-4.
+
+## 2026-10-27 (V1-1.7 DEV preflight + backup + restore check, owner-authorized steps 0-3b)
+- Preflight ok (vault 0, D=21, 28+15 lines = 2026-10-26, M1-M3 pending). pg_dump + storage tar ok outside Git, mode 600, dump sha256 kept.
+- 3b run 1 exit 1: role supabase_functions_admin missing in sandbox. Owner authorized option A: NOLOGIN role sandbox only. Run 2 exit 0, empty log, 28+15 identical, scratch DB dropped, DEV unchanged. LRN-092. STOP: awaiting owner go for step 4.
+
+## 2026-10-27 (V1-1.7 M1-M3 on DEV, db:test, pgTAP 007/010 fix)
+- Owner-authorized: migration up exit 0 (M1-M3 only), post checks ok. db:test DEV exit 1: 007 storage collision, 010 13 due purges; DEV unchanged.
+- Fix 007/010 (owner option 2): sandbox B1 reproduced DEV failures, B2 latent (jobs, leftovers, stale uploads: 15 fails old). New: A + B PASS 921; 11 mutations detected A + B, same as old. Verifier + security gates. LRN-093. DEV rerun awaits owner go.
+- CLAUDE.md split: 11 sections → .claude/rules/ (docker, i18n, annotation-rendering, schemas, stores, pdf, sheet-content, database, environments, storage, sheet-model), always-on Memory files 31.9k → 27.2k, project row 22.3k → 17.7k; commit 7a75974 on feature/v1-1-clients-animals (user choice). Folder structure 13.4 KB + Architecture 6.6 KB stay always-on. Proof: fresh session, Read one file per rule, then `jq -c 'select(.memory_type=="Project" and (.file_path|contains("/.claude/rules/")))' ~/.claude/logs/instructions-loaded.jsonl | tail`.
+
+## 2026-10-27 (V1-1 post-acceptance: RESP-01 fix, AVATAR-01 diagnosis)
+- Owner recette: 19 lines FR detailed, EN global + 4 at 375 px, isolation ok. RESP-01 global scroll = owner browser zoom (owner DEV measures). Real defect found on sandbox: long account e-mail widens dashboard cards (implicit grid track). Fix DashboardRoute + `e2e/shell/responsive.spec.ts` (fails on old code). LRN-094.
+- AVATAR-01 = class A: DEV worker stopped, row `uploaded` waits, message by design (STORAGE §4.4). Sandbox repro with temp gateway + worker on sandbox net: clean in 1.1 s. Side finding (pre-V1-1): full reload doesn't resume the waiting row, new save supersedes it. DEV read-only only.
+- Owner closure 2026-10-27: RESP-01 counter-check 6 PASS → closed; AVATAR-01 class A non-blocking, DEV worker stays off, Alice's waiting upload kept; AVATAR-02 ticket in TODO (no Gitea CLI). Pre-merge checkpoint, no merge.
diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md
index a4c4a8f4..264e4472 100644
--- a/.claude/memory/learnings.md
+++ b/.claude/memory/learnings.md
@@ -573,3 +573,81 @@ Apply: any engine deletion (R-phases): map every case first, "oracle covers it"
Context: R5.7 C6. After removing anatomy, `tsx` stayed in pnpm-lock.yaml as vite's optional peer (`optional: true`, no importer, no bin); `pnpm install` keeps it, `dedupe --check` clean; only hand edit/override would drop name. Contract said "tsx gone" → false NOT-MET.
Pattern: prove use by `pnpm why -r` path + importer blocks + manifest/script/source census, not lockfile name grep. Never hand-edit lockfile or add override just to drop a name.
Apply: dependency-removal clauses state objective (no declared dep, no script, no import), allow transitive/optional peers; census guards declared deps and `optional: true`. Owner validated 2026-10-25.
+
+## LRN-080 | 2026-10-25 | Throwaway Supabase stack beside DEV: test migrations, grants, sign-up and HTTP without touching DEV
+
+Shown on this host (Docker rootless, daemon ip 127.0.0.1, CLI 2.120, images postgres 17.11.0.004, gotrue v2.197.0, storage v1.79.36, postgrest v16.4, mailpit v1.31.3): own network + `-p 127.0.0.1:<57xxx>` per service, no `-v` (images declare no VOLUME → nothing to drop at teardown, `docker rm -f` of literal names suffices). db needs the CLI's role-password init (`/etc/postgresql.schema.sql` via `--entrypoint sh -c`); GoTrue + storage-api migrate their schemas on start; then the CLI's own runners take `--db-url`: `migration up` (records history like DEV), `test db` (pg_prove, rows unchanged), `gen types`. Upgrade path = `--workdir` copy holding the older migrations, then `migration up` from the repo. Real sessions prove what PGlite cannot: concurrency (two psql sessions), GoTrue sign-up/confirm via Mailpit API, PostgREST role refusals, residual GoTrue-admin path. `pg_dump -Fc` as postgres with the container's `$POSTGRES_PASSWORD` dumps auth data too; restore with `--no-owner` keeps every row, prints only managed-object privilege errors.
+Limits: one host; not a hosted project; vault/realtime/edge absent; CLI may change bind/runner behaviour across versions.
+Apply: `scripts/db-sandbox.sh` (`pnpm db:sandbox`) for every migration step; DEV changes stay owner actions.
+
+## LRN-081 | 2026-10-25 | `supabase gen types --db-url` to the sandbox needs `?sslmode=disable`
+
+CLI 2.120 against the sandbox PostgreSQL (127.0.0.1:57432, image 17.11.0.004, no TLS configured): without the option → `DbConnectError … tls error (The server does not support SSL connections)` and the error JSON lands on stdout (piping it to prettier gives a confusing syntax error). With `?sslmode=disable` the output matched the committed `database.types.ts` byte for byte for the pre-existing schema (same generator as `--local`). Same URL works for `migration up`, `test db`. Not checked: other CLI versions, TLS-enabled targets (keep TLS there).
+Apply: any `--db-url` to a local non-TLS Postgres; never pipe generator output without checking the exit code.
+
+## LRN-082 | 2026-10-25 | Native modal `` in Chromium: three traps, one test blind spot
+
+Shown on Chromium 156 (Playwright 1.64.1): (1) Escape cancelled only via `cancel` event → second Escape without user activation closes anyway (close-watcher anti-abuse); `preventDefault` on keydown Escape stops the close request entirely. (2) Initial focus = scrollable panel when content long, first button otherwise → focus first tabbable explicitly. (3) Tab past last control → `document.hasFocus()` false one step (browser UI), then back to first; page never reached. happy-dom: showModal only sets `open` (no inert, no focus) → unit tests prove wiring only. Exit animation (motion, 180 ms) masked async focus loss: a fast sandbox RPC settled before unmount, test green with defect → slow the RPC via `page.route` + `route.fallback()` to discriminate. axe color-contrast false positives while entrance animation runs → wait `document.getAnimations()` settled.
+Apply: any modal or async confirmation test; mutation-check browser tests.
+
+## LRN-083 | 2026-10-26 | PL/pgSQL traps met writing M3
+
+(1) A parameter cannot share a name with a `returns table` output column (`species_id` filter vs output): CREATE fails "parameter name used more than once" → rename the parameter. (2) SQL `or` does not promise left-to-right: `p !~ '^[0-9]{4}$' or p::integer > …` can cast first and raise 22P02 echoing the value → two IF statements. (3) `'2015-02-30'::date` raises 22008, not 22P02 → catch `data_exception` (class 22). (4) pgTAP audit rows of one transaction share `occurred_at` (now()) → order also by `action collate "C"`: ICU sorts `_` before `.`, C the reverse.
+Apply: any plpgsql RPC parsing text input; any pgTAP string_agg over same-transaction rows.
+
+## LRN-084 | 2026-10-26 | FK backstop hides an authorisation-order bug; only a lock-wait probe shows it
+
+Context: M3 mutation M9 removed the workspace filter on the client lookup in `create_animal_client_relation`. pgTAP stayed green: the composite FK refused the row and the RPC mapped it to the same `not_found`. Real effect: B's call took FOR SHARE on A's client → B waited on A's lock (timing side channel, cross-tenant contention). Caught only by sandbox test: A holds the row FOR UPDATE 2 s, B's refusal must answer < 1 s (measured 15 ms; mutated 1 749 ms).
+Apply: for every RPC that locks rows, a real-session test where the victim holds the locks and the attacker's refusal must be fast; equal error text alone does not prove "no lock outside the workspace".
+
+## LRN-085 | 2026-10-26 | Focus after drawer navigation: page inert during exit animation, StrictMode cleanup kills listeners
+
+Context: V1-1.5 page heading focus on open. Drawer (native modal dialog + motion exit 200 ms) keeps page inert → heading.focus() fails; then dialog close restores focus to menu button. Fix: callback ref on heading; if `dialog:modal` present, one-shot `close` listener + setTimeout(0) → focus after ModalDialog's microtask restore. Trap: useEffect cleanup removing the listener ran in React StrictMode's simulated unmount (dev) → listener gone; keep one-shot listener, check `isConnected`, no cleanup. Also: a page that renders its h1 after loading needs a callback ref, not a mount effect. Traced with a temporary focusin/close logger spec.
+Apply: any focus-on-navigation or focus handoff next to a modal with exit animation; never rely on effect cleanup for listeners that must survive StrictMode.
+
+## LRN-086 | 2026-10-26 | Playwright HTML report keeps every typed value in step titles
+
+Context: V1-1.5 report check. `locator.fill(value)` step titles hold the value; the shell suite's HTML report (embedded base64 zip) held the throwaway accounts' passwords, contrary to BROWSER_TESTS.md ("no trace" was thought enough). Found by decoding the zip in memory and counting fixture patterns.
+Apply: suites typing secrets → `reporter: [['list']]` (no html, no trace); audit reports by decoding the embedded zip, not by grepping the html. Also: never run Prettier on a whole src tree here (EVAL-037 repeat) — format new files only.
+
+## LRN-087 | 2026-10-26 | TS does not type-check hyphenated props on components: Card dropped aria-labelledby silently
+
+Context: V1-1.6 e2e locator `section[aria-labelledby=…]` found nothing. `Card` (props children/className/as) ignored `aria-labelledby`; TypeScript accepts any `aria-*`/`data-*` attribute on a component without declaring it, so every V1-1.5 section card shipped unnamed; axe never flags an unnamed section (no violation), unit tests queried by heading text. Fixed by declaring and passing the prop.
+Apply: wrapper components that render landmarks must declare and forward `aria-*` explicitly; test named regions by role + name (`getByRole('region', {name})` or the attribute selector), not only by heading text.
+
+## LRN-088 | 2026-10-26 | useT() returns a new function each render: never a dependency of a data effect
+
+Context: V1-1.6 record picker. A search callback formatting rows with `t` would change every render → effect re-runs → request loop. Fix: search callbacks depend on ids only (`useCallback([workspaceId])`) and return raw rows; a `toItem(row)` prop formats at render (a language switch needs no new search).
+Apply: in this app, keep `t`/dict out of `useCallback`/`useEffect` deps of anything that fetches; format at render. Same for any hook returning fresh functions.
+
+## LRN-089 | 2026-10-26 | Playwright on the sandbox: late replays fail after the test; axe target-size flags controls under a sticky bar
+
+Context: V1-1.6 e2e. (1) `routeToSandbox` replays with `route.fetch` then `fulfill`; a request still in flight when the last assertion passed hit « Fetch response has been disposed » at context close → test failed after success. Fix: `afterEach(context.unrouteAll({ behavior: 'ignoreErrors' }))`; and end tests on a state that needs the last reload (e.g. relations reloaded). (2) At 375 px, axe `target-size` failed on 44 px buttons partly under the sticky top bar when the page was scrolled to the bottom state under test; scanning after `scrollTo(0,0)` passes; documented as a limit, not hidden.
+Apply: suites that proxy requests in route handlers → unrouteAll ignoreErrors per test; phone axe scans of bottom-of-page states → scan from top and say why in BROWSER_TESTS.
+
+## LRN-090 | 2026-10-26 | Supabase CLI 2.120 side effects on a shared local stack: test db, status, migration up
+
+Context: V1-1 DEV preflight, CLI read from bundled binary strings, not docs. (1) `supabase test db` runs `create extension if not exists pgtap with schema extensions`, then `drop extension if exists pgtap` only when absent before: transient DDL; interrupted run leaves pgtap. (2) `supabase status` default output prints SERVICE_ROLE_KEY, SECRET_KEY, JWT_SECRET; `-o env | grep '^API_URL='` safe. (3) `pnpm db:types:check` without `-s` adds 2 `>` header lines from pnpm → count drift with `pnpm -s`. (4) pg_dump -Fc of `postgres` restored `--no-owner` into scratch db of same image: 26 privilege refusals only (vault, pg_stat_statements_reset, pg_reload_conf, default privileges, grant options); md5 of `t::text` per table (timezone UTC) identical after restore → good restore proof. (5) Storage file backend keeps bytes in container volume `/mnt`; DEV had 11 files for 2 rows (reset leftovers).
+Apply: any procedure on DEV → read CLI behaviour from installed binary; read-only SQL via PGOPTIONS default_transaction_read_only; compare fingerprints, not only counts.
+
+## LRN-091 | 2026-10-26 | Restore with "expected errors" never validated by message count; filter TOC, exit 0
+
+Context: V1-1 restore check. LRN-090 (4) called 26 pg_restore errors "privilege refusals" and report double-counted them (28): wrong frame. Real: 26 TOC entries `postgres` cannot replay under `--no-owner` on same Supabase image: 18 DEFAULT ACL of supabase_admin/supabase_auth_admin, 5 vault ACL (grant option to self), ACL pg_reload_conf + pg_stat_statements_reset, COPY vault.secrets = data load fail, lossless only with vault empty. Each failing entry also carries other grants (service_role, anon). `--no-acl` loses app grants; `--exit-on-error` alone stops at COPY. Fix: `pg_restore --list` → exclude exact entries by anchored regex → count per kind must equal catalog prediction (D default ACL rows + 8) → `--use-list --single-transaction --exit-on-error` → exit 0, empty log, rows md5 + effective ACL (`acldefault`) identical. pg_dump drops ACL equal to default → compare effective, not stored. Expected count is per-instance: DEV D=21 vs sandbox 18 (supabase_functions schema).
+Apply: any restore check → real exit status from shell, every failing command classified (object, cause, data impact), conditions explicit (empty table), prefer filtered TOC with exit 0; derive expected exclusions from target catalog, never from rehearsal host; never widen pattern to go green.
+
+## LRN-092 | 2026-10-27 | Restore rehearsal on sandbox dump proves nothing about DEV-only objects; first real-dump run
+
+Context: V1-1 step 3b, first run on real DEV dump. Filtered TOC (29 = D+8) right, but exit 1: `GRANT USAGE ON SCHEMA supabase_functions` names cluster role `supabase_functions_admin`, absent in sandbox (roles are cluster-level, not in dump). Rehearsal on sandbox dump (LRN-091) could not see it. Fix: NOLOGIN no-privilege role in sandbox only → exit 0, empty log, 28+15 identical.
+Apply: restore check on real dump before trusting rehearsal; roles named by ACL/owner entries must exist in target cluster (`--no-owner` needs name, not powers); never widen exclusions, fix the target; create minimal role, never copy login/CREATEROLE/password.
+
+## LRN-093 | 2026-10-27 | pgTAP on a used stack: global queue counts and fixed seed keys break; lease base work in-tx, scope to fixture
+
+Context: `db:test` on DEV after M1-M3. 007 inserted seed drawing key already uploaded (unique collision, 4 assertions never run); 010 counted 13 DEV due purge rows. Audit found more: claim_avatar_jobs takes oldest uploaded row, leftovers sweep whole bucket, expire_pending_uploads counts all stale rows. Clean sandbox / PGlite never show it.
+Fix: 007 seed key in pg_temp table, confirmation cleared in-tx, insert only if absent + assertion "object once"; 010 section 0 leases base's due purges + jobs and expires stale uploads in-tx (capped loop) + setup assertion, leftovers by fixture key prefix. Proof: reproduce on sandbox with fictitious conditions first, mutation run (mutation + suite body in one rolled-back tx) on clean and loaded base, old vs new detection sets compared.
+Apply: SQL test touching a worker queue or shared bucket → neutralise or scope pre-existing work inside the test tx, never count globally; validate on a sandbox seeded like the target before running on it.
+
+## LRN-094 | 2026-10-27 | "Page scrolls sideways at 375 px": measure before CSS; zoom fakes it, implicit grid track hides a real one
+
+Context: V1-1 DEV acceptance RESP-01. Owner saw whole-page sideways scroll everywhere at 375 px (DevTools responsive). Sandbox sweep (Chromium mobile + desktop with scrollbars shown via `ignoreDefaultArgs: ['--hide-scrollbars']`, WebKit iPhone, Firefox; 280-430 px) found none at 375; owner then measured DEV with a console snippet (cw/sw + topmost offending boxes, classes only): no overflow without zoom → browser zoom was the cause. Same sweep with long account e-mails found a real defect: dashboard `grid gap-4 md:grid-cols-2` has no explicit column below md → implicit `auto` track = cards' min-content → `truncate` e-mail never truncates, cards past screen from ~31 chars at 320 px.
+Fix: `grid-cols-1` (minmax(0,1fr)) + e-mail wraps (`min-w-0 [overflow-wrap:anywhere]`). Test sweeps 320-430 + desktop with long values, proven failing on old code.
+Apply: overflow report → ask how observed (zoom, preset, device type), give owner a read-only console probe for DEV, reproduce with realistic max-length values on sandbox; a grid used as a single column on phones needs `grid-cols-1`, else one unbreakable value widens every card.
diff --git a/.claude/rules/annotation-rendering.md b/.claude/rules/annotation-rendering.md
new file mode 100644
index 00000000..da4f39ea
--- /dev/null
+++ b/.claude/rules/annotation-rendering.md
@@ -0,0 +1,14 @@
+---
+paths: ["crates/core/src/anatomy/**", "docs/ANNOTATION-RENDERING.md"]
+---
+
+# Annotation rendering
+- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the markers are
+ drawn from the document (the Rust core, `crates/core/src/anatomy`, for the canvas since R3, the PDF since R4 and
+ the pipeline's review drawings since R5), with the attributes listed there
+- Every SVG the product draws goes through the core's one reader (`anatomy::svg::read_svg`): caps before any parse,
+ allowlist, reference graph; a product drawing with anything removed is refused at load, never repaired
+- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
+ and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
+- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
+ and annotations); no graphic redesign without prior validation
diff --git a/.claude/rules/database.md b/.claude/rules/database.md
new file mode 100644
index 00000000..14d4b318
--- /dev/null
+++ b/.claude/rules/database.md
@@ -0,0 +1,20 @@
+---
+paths: ["supabase/migrations/**", "supabase/tests/**", "packages/supabase/**", "apps/app/src/state/authStore.ts"]
+---
+
+# Database (Supabase)
+- The auth session lives in the Supabase client (localStorage, PKCE); the app reads it through `state/authStore.ts` only. Profile columns the user may edit are the column grants in the profiles migrations; never widen them from the client.
+- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
+ statuses (practitioner/student/professor come from verification, cabinet roles from
+ organization_members). Never add a professional status to `platform_role`.
+- Every `public` table: RLS enabled, `revoke all` from API roles then exact grants,
+ separate policies per command, no `using (true)` for anon/authenticated (test-enforced).
+- Writes that change privileges or sensitive state go through a security-definer RPC
+ that checks `auth.uid()` and calls `private.log_event()`. Never a direct table policy.
+- Helpers in `private` are `security definer`, `set search_path = ''`, EXECUTE revoked
+ from public and granted only to the roles that evaluate them.
+- A migration is never edited once applied. Each migration ships its pgTAP file with
+ allowed AND denied cases, and a regenerated `database.types.ts`.
+- The browser holds the anon key only. The `service_role` key value never appears in env.js, .env.example or code;
+ operator scripts under `packages/*/scripts/` read it from the environment and are never bundled.
+- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
diff --git a/.claude/rules/docker.md b/.claude/rules/docker.md
new file mode 100644
index 00000000..83f4dcab
--- /dev/null
+++ b/.claude/rules/docker.md
@@ -0,0 +1,28 @@
+---
+paths: ["Dockerfile", "docker-compose.yml", ".dockerignore", "docker/**"]
+---
+
+# Docker commands
+
+```bash
+# Build image
+docker build -t faunosteo .
+
+# Build an image that embeds the reference DRAFT sheet (preview only, never the default)
+docker build --build-arg SHEET_BUNDLE=draft -t faunosteo .
+
+# Run with compose (reads .env for APP_* vars)
+docker compose up --build
+
+# Stop
+docker compose down
+```
+
+Naming convention: every Docker resource Faunosteo owns is prefixed `faunosteo_`
+when the name is configurable (container `faunosteo_app`, Compose project
+`faunosteo`); the Supabase CLI imposes `supabase__faunosteo`, documented
+as a limit in DEPLOY.md "Docker resource naming". Never rename a resource that
+holds data without keeping its volume.
+
+Note: no global pnpm needed. `corepack enable` once (reads `packageManager`),
+or call `corepack pnpm `. Root scripts resolve `node_modules/.bin/pnpm`.
diff --git a/.claude/rules/environments.md b/.claude/rules/environments.md
new file mode 100644
index 00000000..c2662b49
--- /dev/null
+++ b/.claude/rules/environments.md
@@ -0,0 +1,15 @@
+---
+paths: ["scripts/dev-env.sh", "scripts/supabase.sh", "docker/dev-gateway/**", "docs/development/ENVIRONMENTS.md", "supabase/config.toml"]
+---
+
+# Environments and LAN access (docs/development/ENVIRONMENTS.md)
+- The owner tests from other devices of the private network, never on the Ubuntu machine: every test surface
+ (app, Supabase API, Mailpit, Studio) is addressed by the DEV origin (`scripts/dev-env.sh`, `FAUNOSTEO_DEV_HOST`),
+ never by `127.0.0.1` / `localhost`, never hard-coded in a source (the automated browser suites are not a
+ surface for other devices: their dev servers and the sandbox stay on 127.0.0.1). The Supabase CLI runs only through
+ `scripts/supabase.sh` (`pnpm db:*`, `pnpm supabase`): config.toml reads the origin with `env()`.
+- Exposure (least privilege, `pnpm dev:net-check`): LAN gets Vite 5173, the Supabase API 54321 and Mailpit
+ behind basic auth through the DEV gateway (`pnpm dev:gateway`, nginx, `faunosteo_dev_gateway`, 54325). The CLI
+ forces 0.0.0.0 on 54322 PostgreSQL, 54323 Studio, 54324 raw Mailpit: closed on the LAN interface by host UFW
+ rules (owner action, ENVIRONMENTS.md §3.2); SSH tunnel for Studio; the worker publishes no port. Nothing is exposed to the Internet; no production infrastructure
+ is touched from this repository. Rust is built natively; Docker runs services, the worker, sandbox tests and images.
diff --git a/.claude/rules/i18n.md b/.claude/rules/i18n.md
new file mode 100644
index 00000000..1c9a1103
--- /dev/null
+++ b/.claude/rules/i18n.md
@@ -0,0 +1,13 @@
+---
+paths: ["apps/app/src/i18n/**", "apps/app/src/state/localeStore.ts", "apps/app/src/pdf/labels.ts", "apps/app/src/auth/validation.ts", "apps/app/src/account/validation.ts"]
+---
+
+# i18n
+- All user-facing strings live in `src/i18n/fr.ts` and `src/i18n/en.ts` (flat `Record`)
+- Key convention: ` .` — e.g. `common.cancel`, `home.new_report.title`, `pdf.subject`
+- Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV
+- Get the translate function in any component: `const t = useT()` then `t('common.cancel')`
+- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match; while signed in, `services/localeSync.ts` writes it to `profiles.locale` and applies the account locale on sign-in
+- Form validation messages are i18n keys returned by the Zod schemas (`src/auth/validation.ts`, `src/account/validation.ts`), translated next to the field; GoTrue messages never reach the screen (`auth.failure.*`)
+- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
+- PDF static labels (section headings, metadata) live in `apps/app/src/pdf/labels.ts` (`defaultPdfLabels`, 25 keys, moved verbatim from the engine at R4.6) and are archived in the envelope; the app dicts hold no `pdf.*` key
diff --git a/.claude/rules/pdf.md b/.claude/rules/pdf.md
new file mode 100644
index 00000000..344a3a3c
--- /dev/null
+++ b/.claude/rules/pdf.md
@@ -0,0 +1,11 @@
+---
+paths: ["crates/core/src/pdf/**", "apps/app/src/pdf/**"]
+---
+
+# PDF
+- A4 portrait: 595.28 × 841.89 pt
+- No raw URLs in PDF output — abbreviated citations only
+- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report
+- The writer (`crates/core/src/pdf/write`, since R4.6; the TypeScript engine deleted at R4.8) takes no clock and no I/O; rasterisation is the browser's, one raster per core request; every SVG it composes went through the core's one reader. The export is an incremental session (OD-2): the file is written as the rasters arrive, held once, handed out in parts; never accumulate rasters or build the file twice
+- Page layout is frozen by the Step 6 goldens and the R4 oracles (O1 draw logs, O2 PDFs): any visible change needs a user decision and a golden regeneration; the R4 digests (`goldens/r4/pdf.*.sha256`) pin the writer's own bytes and are rewritten only for a declared structural change, with the O2 comparisons re-run
+- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
diff --git a/.claude/rules/schemas.md b/.claude/rules/schemas.md
new file mode 100644
index 00000000..c411d8a2
--- /dev/null
+++ b/.claude/rules/schemas.md
@@ -0,0 +1,17 @@
+---
+paths: ["crates/core/src/domain/**", "packages/core-wasm/tests/n-1/**"]
+---
+
+# Schemas
+- The data contracts live in Rust since R2 (`crates/core/src/domain/{sheet,report,archive}`, Zod semantics
+ reproduced: strict where Zod was strict, optional absent, nullable required, Zod schema field order);
+ `packages/domain` was deleted at R5.7; its byte-identical Zod copy under `packages/core-wasm/tests/n-1` is the
+ permanent N-1 reader. Never change a contract
+ without bumping the version on a breaking change (additive optional fields keep it); a change touches the
+ Rust struct, the regenerated ts-rs types and the N-1 test
+- Every report entering the store comes from the core (new report, draft restore, import, reducer outputs);
+ form values are plain assignments (D-R7)
+- Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
+ `mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
+ (`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
+ v1 and unknown versions are refused with a typed error
diff --git a/.claude/rules/sheet-content.md b/.claude/rules/sheet-content.md
new file mode 100644
index 00000000..39046636
--- /dev/null
+++ b/.claude/rules/sheet-content.md
@@ -0,0 +1,9 @@
+---
+paths: ["supabase/seed/anatomical-sheets/**"]
+---
+
+# Anatomical sheet content
+- The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content
+ change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section)
+- The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically
+ validated and a production build carries no sheet unless that flag is set on purpose
diff --git a/.claude/rules/sheet-model.md b/.claude/rules/sheet-model.md
new file mode 100644
index 00000000..0bcba0ae
--- /dev/null
+++ b/.claude/rules/sheet-model.md
@@ -0,0 +1,17 @@
+---
+paths: ["crates/core/src/domain/sheet/**", "docs/development/ANATOMICAL_SHEET_MODEL.md", "supabase/seed/anatomical-sheets/**", "crates/core/src/bin/upload_sheet_assets/**"]
+---
+
+# Anatomical sheet model (crates/core/src/domain/sheet + migration 20261008110000)
+- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs.
+- Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the
+ explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime.
+- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then
+ `publish_sheet_version`. Integrity rule codes are shared by `validate_sheet_document` (Rust core) and
+ `private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table.
+- Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`.
+- Official equine sheet = generated seed `draft/` (`pnpm import:equine --out` into an empty folder, then reviewed and copied; never edit `legacy-import/` or `draft/` by hand;
+ `curation_draft` / `curation_review` fail on drift, `pnpm import:equine --check` lists it). Every content change goes through `curation/changes.json` (traced in CHANGELOG.md).
+ It is a DRAFT until a platform admin publishes it after business review of `REVIEW-REPORT.md`.
+- Sheet SVG bytes live in Storage bucket `anatomical-sheet-assets` as `.svg`; uploads are an operator task
+ (`pnpm assets:upload ` with the service key in env), never from the browser.
diff --git a/.claude/rules/storage.md b/.claude/rules/storage.md
new file mode 100644
index 00000000..355be6ac
--- /dev/null
+++ b/.claude/rules/storage.md
@@ -0,0 +1,17 @@
+---
+paths: ["docs/development/STORAGE.md", "crates/worker/**", "supabase/migrations/**"]
+---
+
+# Files and Storage (migration 20261013100000, docs/development/STORAGE.md)
+- `public.assets` is the authority over every user file: status, owner, keys, lease. Every write is an RPC; the browser
+ reads its own rows through an explicit column list (`select=*` is refused: lease columns are not granted).
+- Object keys are server-built from uuids (`profiles///avatar.webp`, `quarantine///upload`);
+ policies on `storage.objects` compare whole strings through `assets` and pin one bucket literal each (census test).
+ A quarantine object is never readable by an API role; a final key is never writable by the browser.
+- New buckets stay closed (row only, no policy) until their step writes the rules; `anatomical-sheet-assets` keeps its own policy.
+- The worker holds the service key; the decode child has an empty environment, no file, no network, and is the only
+ process that decodes untrusted bytes. The parent checks the container header only. Rejections are closed codes.
+- Deletions are row-driven: terminal rows enqueue their keys (48 h / 1 h grace), the sweeper serves the queue and the
+ quarantine leftovers; a clean row's object is never deleted. Backups: dump first, files within 48 h.
+- Avatar UI follows the validated mockup: photo in Mon compte (Informations personnelles), sidebar, drawer and top bar
+ link to Mon compte; JPEG / PNG / WebP only, never SVG; no signed URL for the owner-only avatar (download under RLS).
diff --git a/.claude/rules/stores.md b/.claude/rules/stores.md
new file mode 100644
index 00000000..23bc8d2c
--- /dev/null
+++ b/.claude/rules/stores.md
@@ -0,0 +1,9 @@
+---
+paths: ["apps/app/src/state/**"]
+---
+
+# Stores
+- No direct store mutation outside Zustand actions
+- No business logic in components — delegate to store actions
+- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded, by the core) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits); osteo:quarantine:{draft,archive} (an unreadable text set aside, a draft with its archive, an occupied slot never replaced, never dropped) and osteo:quarantine:draft-pre-rebase (the raw draft of a rebase that flagged items); a text whose set-aside fails is held in place (resolution panel, no new session over it), never removed or overwritten implicitly
+- localStorage key: osteo:lastPractitioner (practitioner prefill cache)
diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md
index 07f38948..e85307ca 100644
--- a/.claude/tasks/TODO.md
+++ b/.claude/tasks/TODO.md
@@ -368,7 +368,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
---
## Product roadmap V1 (owner 2026-10-25 « Validation de l'inventaire et cadrage P0 / V1-1 »)
-Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheets served from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 cross-cutting mobile + a11y pass (a11y and security apply at every step). C4/C5/C6 and the V1-1 orientations (owner brief « P0 : arbitrages documentaires et finalisation du contrat V1-1 ») = proposed, awaiting ratification. No migration, component, API or table before the owner ratifies the V1-1 contract; no merge into main, no release/0.2.0 change, no deploy, no Supabase DEV change; equine draft stays unpublished.
+Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheets served from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 cross-cutting mobile + a11y pass (a11y and security apply at every step). C4/C5/C6 and the V1-1 business decisions ratified 2026-10-25 (BDR-073). No migration, component, API, dependency or table before the owner validates the V1-1 technical design at the preparation checkpoint; no merge into main or develop without the owner's go, no release/0.2.0 change, no deploy, no Supabase DEV change; equine draft stays unpublished.
- [x] P0 docs realignment (docs only; branch `chore/p0-doc-realignment` created by the owner off develop, the working-tree edits carried over; merge into develop on the owner's go only)
- [x] census of stale text in active docs (worker Node / Edge Functions, step numbers, roles, Step 13 "published", deleted tools, OPEN_QUESTIONS statuses)
- [x] IMPLEMENTATION_PLAN: roadmap V1 section, step statuses, D-R9 in Steps 8/15/19/21/23/24/26, Step 13 DoD draft-only, deleted tools, Step 22 D-R8
@@ -379,7 +379,157 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet
- [x] merged into develop 2026-10-25 (no-ff dae74e0, owner go); V1-1 waits for ratification of contract §9
- [x] V1-1 functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` (no code); correction: inventory criterion 4 (validation in crates/core) contradicted D-R7 → form constraints TS + SQL CHECK + parity test (EVAL-034)
- [x] owner orientations D1-D9, D16, C4-C6 integrated as proposals (§9.1, SQL / permission impact marked); sub-choices D4a, D6a, D6b, D7a, D9a (§9.2); D10-D15, D17 kept open (§9.3); legal basis, client information, retention framed before public exposure (§9.4)
- - [ ] owner ratification of §9.1, answers to §9.2 and D15 → first migration on a `feature/` branch
+ - [x] owner ratification 2026-10-25 (brief « V1-1 : ratification des décisions métier et préparation de l'implémentation », BDR-073): D1-D9a, C4-C6, D16, D15 principle, naming
+- [ ] V1-1 clients and animals: branch `feature/v1-1-clients-animals` (gitflow start off develop 5502617, pushed); contract `docs/development/V1-1_OWNERS_ANIMALS.md` (§3 nomenclature, §8 SQL, §9 RLS/RPC, §10 D15, §11 UI, §12 tests, §13 decisions). Each step = commits on this branch; owner validates after V1-1.1 and after the first UI step; merge into develop only on the owner's go. Gates every step: `pnpm typecheck && pnpm test:run && pnpm lint`; SQL steps also `pnpm db:reset && pnpm db:test`, `pnpm db:types:check`; UI steps through the design toolchain (Build UI) following `docs/design/`.
+ - [x] V1-1.0 preparation (docs only): branch checks (develop = origin/develop 5502617, tree clean, P0 merged dae74e0; two stale R5.6 rehearsal worktrees in an old session scratchpad hold edits, left untouched); contract statuses approved; nomenclature; SQL schema M1-M4; helpers, RLS, RPCs, failures, definer statement; D15 thresholds; journeys, forms, a11y; pgTAP/e2e/Playwright plan; decisions N1-N9, D10-D14, D17, U1-U3; BDR-073; OPEN_QUESTIONS C4/C5/C6/Q6; plan Step 10/12 notes; DOMAIN_MAP, CLAUDE.md, README, TEST_STRATEGY citations; 3 fresh plan challengers (correctness, robustness, simplicity: CONCERNS, findings integrated: search keys, phone search, GoTrue admin path, correlation header cap, idempotent creates, locks, identical errors, backfill function, behavioural parity, Chromium-only V1-1, beforeunload guard, derived values, 6 steps / 3 migrations)
+ - [x] CHECKPOINT: owner validated the contract architecture + N1-N9 2026-10-25 (brief « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces »); D10-D14, D17, U1-U3 stay contract-level until their UI steps; only V1-1.1 authorised
+ - [ ] V1-1.1 Workspaces foundation (owner brief 2026-10-25; isolated test DB only, DEV stack untouched, stop at checkpoint)
+ - [x] contract: N1-N9 as decided (N4 voiding instead of deletion, N6 budget per workspace + concurrency rule, N7 effective-privilege wording, N9 metadata list), M1 as-built notes
+ - [x] M1 `20261025100000_workspaces.sql`: enums, tables, deferred personal-holder invariant, `ensure_personal_workspace` + trigger + backfill, helpers, `log_event` correlation cap + NOT VALID CHECK, grants (service_role included), RLS
+ - [x] pgTAP `012_workspaces.sql` + `001_schema.sql` census; schema-types map; config test (`enable_confirmations`, schemas)
+ - [x] isolated real stack in the scratchpad (own network, loopback ports only): migrations from zero, pgTAP, GoTrue sign-up + confirmation, PostgREST role probes, concurrency + idempotence, seed accounts
+ - [x] types regenerated from the isolated DB; `pnpm typecheck && pnpm test:run && pnpm lint`
+ - [x] docs: SUPABASE.md §3.3 (+ DEV procedure), BACKEND_ARCHITECTURE §4.1/§4.2, TEST_STRATEGY counts, IMPLEMENTATION_PLAN note, CLAUDE.md; BDR-074, journal
+ - [x] fresh verifier + security audit on M1; `pnpm rust:check`, `pnpm check:all`; commits pushed; checkpoint report (owner validated V1-1.1 2026-10-25, brief « Validation V1-1.1 et autorisation V1-1.2 Données clients »)
+ - Deviation from the line below: `packages/supabase/src/workspaces.ts` deferred to V1-1.2 (no consumer before the clients access layer; brief authorises M1 + tests)
+ - Objective: every account has exactly one personal workspace, readable by itself only, with the helpers every later table uses; audit rows no longer sized by the caller
+ - Depends: checkpoint
+ - Files: `supabase/migrations/_workspaces.sql`; `supabase/tests/012_workspaces.sql`; `supabase/tests/001_schema.sql` (tables, RLS, privileges, helper census); `packages/supabase/src/database.types.ts` (regenerated); `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspace`) + `src/index.ts`; `packages/supabase/tests/db/schema-types.test.ts`; config test (`enable_confirmations = true`); `docs/development/SUPABASE.md`
+ - Migration M1: enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; `private.caller_workspace_ids`, `private.writable_workspace_ids`, trigger `private.create_personal_workspace` after insert on profiles, `private.backfill_personal_workspaces()` called once; `private.log_event` redefined (same signature, `x-correlation-id` kept only if `^[A-Za-z0-9-]{1,64}$`) + NOT VALID CHECK; revoke all (public, anon, authenticated, service_role) + column grants; RLS
+ - Tests: trigger; backfill function on a profile inserted with the trigger disabled (idempotent); one personal workspace per account; A/B isolation; unconfirmed, deactivated, platform staff, anon, service_role see nothing; empty account deletion removes its workspace; oversized/malformed correlation header stored null; helper census (prosecdef, search_path, ACL); PGlite + real stack
+ - Acceptance: gates green; every account of `seed.sql` has one workspace + holder row after `pnpm db:reset`
+ - Security: no platform-role branch; no `using (true)`; helpers `search_path = ''`, EXECUTE only where evaluated; email confirmation checked in SQL; `log_event` callers unchanged
+ - Stop if: `auth.users` join behaves differently on PGlite and the real stack; the profiles trigger interferes with `handle_new_auth_user` or sign-up; an existing policy would need editing beyond the `log_event` redefinition
+ - [ ] V1-1.2 Clients data (owner brief 2026-10-25; isolated stack only; DEV untouched; stop at checkpoint before V1-1.3)
+ - [x] M1 closure: types re-checked with the official generator against an isolated DB holding M1 (diff 0); sandbox tool committed (`scripts/db-sandbox.sh`, `pnpm db:sandbox`: rootless, loopback, own ports, no volume, generated secrets outside Git, fresh + upgrade, official `supabase test db` / `gen types` via `--db-url`); owner DEV procedure for M1 (target, history, backup incl. auth, restore check, `db:test` non-destructive check) rehearsed on the sandbox; LRN-080/081
+ - [x] M2 `_clients.sql`: unaccent, `private.fold_text`, `client_kind`, `clients` (+ `create_request_digest` for divergent replays), budget table + `private.consume_write_budget` (UTC fixed hour/day windows, row lock, last lock taken), RPCs create/update/set_archived/search, N9 audit policy, grants, RLS
+ - [x] pgTAP 013; harness loads unaccent; `field-limits.ts` + behavioural parity test; types; census
+ - [x] sandbox suite (vitest, real GoTrue/PostgREST sessions): M1 regression, clients HTTP, concurrency (creates, replay, divergent replay, stale revision, archive/restore race, budget limits, no deadlock), 20 000-client search timing
+ - [x] docs: contract (budget, divergent replay, search_clients without current_animal_count until M3), SUPABASE.md, TEST_STRATEGY, BDR-075, journal
+ - [x] fresh verifier + security audit (PASS; ECARTS closed); sandbox hardened; rust:check, check:all green; checkpoint
+ - Deviation: access layer `clients.ts` + workspace read move to V1-1.5 (first consumer; brief §6 scope lists no access layer)
+ - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack
+ - Depends: V1-1.1; N2, N3, N6, N9 decided
+ - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated
+ - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.consume_write_budget(p_workspace_id)` (N6: per workspace, UTC hour/day windows, budget row lock taken last; contract §9.3, §10); enum `client_kind`; `clients` (`name_key`, `search_key`, `phone_digits`, `create_request_id`); `create_client`, `update_client`, `set_client_archived`, `search_clients`; N9 condition on `audit_logs_select_admin`; grants; RLS
+ - Tests: contract §12.1 rows for clients (whole-error identity, no lock outside the workspace, archived before conflict, replayed request id, caps, budgets, audit without values, search accents/case/backslash/phone formats/keyset); parity test; e2e cross-account + service key refused + GoTrue admin delete; search time on 20 000 clients recorded
+ - Acceptance: gates green; e2e green on the local stack; measurement written in the contract
+ - Security: constraint and parse errors caught inside RPCs; text parameters parsed in the body; search through POST; definer census
+ - Stop if: `unaccent` cannot load on PGlite or the CLI stack; the measurement is above 100 ms p95 (index decision for the owner); a CHECK cannot be mirrored in TypeScript
+ - [ ] V1-1.3 UI foundations (owner brief 2026-10-25 « Validation V1-1.2 et autorisation V1-1.3 Socle UI »; no M3, no client/animal screen, DEV untouched, stop at checkpoint)
+ - [x] V1-1.2 closure: db:sandbox final check (fresh, upgrade, types, argv scan, negative cases, DEV fingerprint); defect `up` bad args started containers → fixed 57922e0, rerun green
+ - [x] owner choices 2026-10-25: e2e backend = isolated stack (Playwright routes Supabase calls to `pnpm db:sandbox`); scripts `pnpm e2e:ui` (no backend) + `pnpm e2e:shell` (sandbox); MobileDrawer on the same modal mechanism; check:all runs e2e:ui when the pinned Chromium is installed, else an explicit SKIPPED line
+ - [x] `ModalDialog` primitive on native `` + `showModal()` (platform inertness, Escape via keydown/cancel → onClose, consumer decides, opener restore + nearest-container fallback, scroll lock CSS); `Dialog` on it (aria-labelledby title, optional `description` → aria-describedby); confirmation consumers pass their message as description; `MobileDrawer` on it (closes at lg)
+ - [x] unit tests (happy-dom: wiring only): Escape/cancel/close/backdrop → onClose, never self-close, name + description, restore + fallback; existing suites green
+ - [x] Playwright + axe dev deps pinned (license, transitive census), Chromium download (no sudo); configs `e2e/playwright.{ui,shell}.config.ts`, Vite on 127.0.0.1 dedicated ports, request allowlist (anything else aborted and fails the test)
+ - [x] e2e:ui: harness page `e2e/harness/dialog.html` (dev server only, not in the build): open, initial focus, Tab/Shift+Tab, containment, Escape allowed/refused (twice), close button, restore, opener gone, background inert + no scroll, name/description, long content, 375 px, no horizontal overflow, axe FR/EN; local tool dialogs (disclaimer, edit infos) desktop + 375
+ - [x] e2e:shell: fictitious account through the sandbox admin API, clean avatar seeded; login → dashboard, drawer at 375 (containment, Escape, restore), avatar remove dialog (name, description, Escape, confirm → opener gone → fallback), FR/EN, axe, request URLs free of fixture values
+ - [x] defect found by the shell suite: the photo confirmation closed before the removal, focus fell on the page once the button vanished → confirmation open until settled, deferred restore, sr-only file input out of the tab order (8371aa0); mutation-checked with a slowed RPC
+ - Deviation: contract §12.5 said DEV origin; suites run on loopback servers against the isolated stack (owner choice); TODO line "users through the admin API, DEV origin, service key from env" superseded
+ - [x] check:all stage; docs (contract D13/D14 final + D11 note, TEST_STRATEGY, browser tests doc, SUPABASE §5.1 e2e-shell, CLAUDE.md map + commands); D11 three-way comparison
+ - [x] gates: typecheck, test:run, lint, e2e:ui, e2e:shell, rust:check, check:all; fresh verifier + security audit; commits pushed; checkpoint report (verifier CONFORME 8/8, security PASS, check:all green 23:41:29; refused URLs masked after audit LOW)
+ - Objective: real-browser harness and accessible dialogs before the first screens
+ - Depends: D13, D14 approved
+ - Files: `apps/app/package.json` + `pnpm-lock.yaml` (`@playwright/test`, `@axe-core/playwright`, dev only); `apps/app/playwright.config.ts` (Chromium desktop + 375×667); `apps/app/e2e/` (fixtures: users through the admin API, DEV origin, service key from env never committed); `apps/app/src/components/ui/Dialog.tsx` (`inert` + restore to opener) + tests; root script (name to confirm)
+ - Migration: none
+ - Tests: Dialog containment, Escape, focus restore; editor dialogs unchanged; Playwright smoke (login → dashboard) with axe and the request-URL check
+ - Acceptance: smoke green; axe 0 serious/critical on the smoke screens, or pre-existing violations listed under RR-7
+ - Security: dependencies named with purpose; lockfile reviewed; no secret in fixtures or reports
+ - Stop if: the Chromium download is refused or fails (owner decides); a fix outside V1-1 scope would be needed for axe
+ - [ ] V1-1.4 Animals and relations data (owner brief 2026-10-26 « Validation V1-1.3 et autorisation V1-1.4 Animaux et relations »; isolated stack only; DEV untouched; no screen; stop at checkpoint before V1-1.5)
+ - [x] V1-1.3 closure: owner validated (CONFORME 8/8, security PASS, check:all green)
+ - [x] V1-1.3 follow-ups asked by the brief §2 (test code only): axe KNOWN exceptions scoped to their route and node html so a new screen never inherits them; check:all prints an explicit PASSED / SKIPPED (env missing) / NOT RUN line per browser suite, failure stays a stop
+ - [x] M3 `20261026100000_animals_relations.sql`: species rows (8 + other) + table comment; `animal_sex`, `animal_relation_role`; `animals` (+ `create_request_digest`), `animal_client_relations` (composite FKs, partial unique index current = not ended and not voided, digest); `private.latest_record_date(timestamptz)` (tomorrow UTC, testable); RPCs `create_animal` (optional initial relation, 2 audited writes), `update_animal`, `set_animal_archived`, `create_animal_client_relation`, `end_animal_client_relation`, `update_animal_client_relation`, `void_animal_client_relation`; reads `search_animals`, `list_client_animals` (cursor `sort_key` = current/former prefix + name_key), `client_archive_preview`; `search_clients` dropped and recreated with `current_animal_count`; lock order workspace → animal → relation → client → budget; caps 20 000 animals, 20 current / 200 total per animal, 100 000 per workspace (every row counts toward the totals, voided and ended included); grants, RLS
+ - [x] pgTAP `014_animals_relations.sql` (258); 013 alias list for the new search column; schema-types map; field-limits (animal name, breed, species detail, birth year, date floor) + parity test
+ - [x] db-sandbox `up upgrade []` so the three migration states run (+ an M1+M2 base → M3): fresh; pre-M1 → M1..M3; pre-M1 → M1 (backfill) → M2+M3
+ - [x] sandbox suite `animals.sandbox.ts` (18): per-role HTTP, identical refusals, concurrency (replays, divergent replay, identical relations race, end/void race, caps under concurrency, shared budget clients+animals, relation create vs client archive, mixed burst no deadlock), D9a via GoTrue admin delete
+ - [x] types regenerated from the sandbox; gates (typecheck, test:run, lint, db:sandbox test-db/test/types --check in 3 states, e2e suites, import:equine --check, rust:check, check:all)
+ - [x] mutations of M3: 14, all caught (M6 voided-only count and M9 foreign client lock only after the tests were strengthened)
+ - [x] fresh verifier CONFORME 11/11 + security audit PASS (0 HIGH)
+ - [x] docs: contract §8.3 as built, SUPABASE.md §3.3 DEV procedure to M3 (not run) + §3.5, TEST_STRATEGY, CLAUDE.md, plan note, backend table
+ - [x] BDR-077, LRN-083/084, EVAL-039, journal; commits pushed; checkpoint report
+ - Deviation: access layer `{animals,relations}.ts` moves to the UI steps (first consumer), as `clients.ts` did at V1-1.2
+ - Objective: animals with the ten species rows and the D6b birth model, relations with history, never across workspaces
+ - Depends: V1-1.2; N1, N4, N5, N8 decided
+ - Files: `supabase/migrations/_animals_relations.sql`; `supabase/tests/014_animals_relations.sql`; `field-limits.ts` + parity test; `packages/supabase/src/{animals,relations}.ts`; e2e extended; types regenerated
+ - Migration M3: species rows (9 + `other`), table comment; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations` (composite FKs, partial unique index, request ids); `create_animal` (optional initial relation), `update_animal`, `set_animal_archived`, `search_animals`, relation create/end/update/void (N4: `voided_at`, `void_animal_client_relation`, never delete); `list_client_animals`, `client_archive_preview`; grants; RLS
+ - Tests: five birth states; `species_detail` iff `other`; inactive species; dates incl. 31 December UTC; cross-workspace refused by RPC (42501) and by FK; duplicates and the concurrent race; successive relations; archived interactions (§7.1) under locks; caps per animal and per workspace; derived values; D9a (account with records cannot be deleted, empty one is); report, sheet and editor species ids unaffected
+ - Acceptance: gates green; e2e green; local tool and PDF unchanged
+ - Security: same whole error for every foreign id; FK proof independent of the RPC; animal-then-client lock order
+ - Stop if: N1, N4, N5 or N8 undecided; any change needed in report, sheet or editor code; the D9a guard blocks a flow the owner did not foresee
+ - [ ] V1-1.5 Clients UI (owner brief 2026-10-26 « Validation V1-1.4 et autorisation V1-1.5 Interface Clients »; isolated stack only; no animal screen; stop at checkpoint before V1-1.6)
+ - [x] V1-1.4 closure: owner validated (CONFORME 11/11, security PASS); species_filter + replay order accepted
+ - [x] owner choices 2026-10-26: U1 « Afficher plus » (keyset, page of 25 + 1 probe); U2 « Archivés » toggle; client page animals = read-only list (list_client_animals, no link, no add); « premier animal » section deferred to V1-1.6
+ - [x] access layer `packages/supabase/src/{workspaces,clients,species,records}.ts`: personal workspace read, client reads/RPCs with explicit columns, keyset cursors, closed RecordFailure kinds (contract §9.4 + network, session_expired), Zod-checked RPC results; unit tests + real-PostgREST sandbox test of the same functions
+ - [x] authStore: personal workspace state (loading / ready / inactive / unconfirmed / missing / error) loaded with the account; identity change clears profile, roles, avatar, workspace at once and drops late responses of a previous user
+ - [x] app: routes /app/clients, /new, /:clientId, /:clientId/edit behind a workspace gate (remount per workspace); list (debounced search, toggle, « Afficher plus », states); detail (contact links, archived read-only, animals read-only, archive dialog with preview, restore); form (D-R7 schema on field-limits, phone entry rule, ISO country list via Intl.DisplayNames, request id per intent, conflict shows saved values, archived refusal); leave guard (beforeunload + in-app link clicks in the shell + Cancel; browser back not interceptable, documented); nav entry after Tableau de bord (mockup order); FR/EN
+ - [x] unit tests (schema, phone rule, countries, access mapping, store identity change, routes states, archive dialog, conflict, guard) + Playwright `e2e/shell/clients.spec.ts` on the sandbox (journeys, two accounts, pagination, keyboard, FR/EN, 375, axe without inherited exceptions, conflict, retry idempotence, error states, URLs free of fixture values)
+ - [x] gates (typecheck, test:run, lint, build, e2e:ui, e2e:shell, db:sandbox test-db/test/types --check, import:equine --check, rust:check, check:all), impeccable detect, fresh verifier + security audit
+ - [x] docs: contract §11.7 as built, FRONTEND_ARCHITECTURE, BROWSER_TESTS, SUPABASE §3.3 note, design README, CLAUDE.md map; BDR, EVAL, journal; commits pushed; checkpoint
+ - [x] gate fixes: shell HTML report removed (kept typed passwords), ready workspace kept during re-read, not-found heading focus; security PASS, verifier CONFORME 11/11 (round 3); check:all green 02:15:51
+ - Deviation: leave guard extended from Cancel to every in-app link; search term not kept on back navigation; phones shown E.164
+ - Pending owner: M1-M3 on DEV (SUPABASE.md §3.3) before the LAN check; D11 decision before V1-1.6
+ - Objective: list and search, create, edit, detail, archive and restore clients, FR/EN, phone and computer, keyboard
+ - Depends: V1-1.2, V1-1.3, V1-1.4 (client page lists animals); D11, U1, U2
+ - Files: `apps/app/src/app/App.tsx` (routes); `apps/app/src/app/routes/app/clients/*`; `apps/app/src/clients/{validation,useClientForm}.ts`; `apps/app/src/components/clients/*`; `SidebarNav.tsx`, `MobileDrawer.tsx`; `apps/app/src/i18n/{fr,en}.ts`; tests; `apps/app/e2e/clients.spec.ts`
+ - Migration: none
+ - Tests: schemas per rule (i18n keys, code points, email pattern, phone conversion); country select from `Intl.DisplayNames`; list states; archive with preview and dialog; conflict keeping typed values; beforeunload + cancel guard; not-found for unknown and forbidden ids; Playwright client journeys + keyboard-only + cross-account + request URLs + axe
+ - Acceptance: gates + Playwright green; owner check on phone and computer over the LAN
+ - Security: only `packages/supabase` reaches the API; explicit column lists; no text filter in GET URLs; failures phrased by closed kinds
+ - Stop if: the mockup lacks a pattern the screens need (propose, ask, never invent a direction); a visible choice not covered by §11
+ - [x] V1-1.6 Animals and relations UI, navigation and closure — VALIDATED by the owner 2026-10-26 (brief « Validation finale V1-1 et préparation de la recette DEV »; owner brief 2026-10-26 « Validation V1-1.5 et autorisation V1-1.6 Interface Animaux et clôture »; isolated stack only; DEV untouched; stop at checkpoint before merge, V1-2 and DEV)
+ - [x] V1-1.5 closure: owner validated (CONFORME 11/11, security PASS, check:all green); reserves accepted for V1-1 (search not kept on back, E.164 display, back/forward not guarded), kept in product follow-up
+ - [x] owner decisions 2026-10-26: D11 drawer only for V1-1 (no tab bar, mockup kept as later UX subject); first animal from the client page (« Ajouter un animal » → /app/animals/new, client passed in navigation state, never the URL; one atomic create_animal); no relation role preselected; relation add as an in-page panel (no modal form), end / dates / void as ModalDialog confirmations; U3 date fills and locks the year; D12 tiles not in the brief's scope → not built, reported
+ - [x] access layer: records.ts + `duplicate_relation`, `already_ended`; `animals.ts` (search POST with probe row and species_filter, read by id with explicit columns and uuid gate, create with optional initial relation, update, archive); `relations.ts` (an animal's relations by one select with the client embedded, voided left out, explicit columns; create, end, dates, void); unit tests + real-PostgREST sandbox suite
+ - [x] app foundations: one RequireWorkspace above clients and animals; species labels loaded once per workspace mount (context, dropped on account change); local-date helper; « Animaux » nav entry after Clients; i18n FR/EN
+ - [x] animal form: schema on field-limits (D-R7: name, species from the active rows, detail iff other, sex required with no default, breed, birth year/date U3, start date), optional initial client (picker on search_clients, role required once a client is chosen, start date), request id per intent, conflict with stored values, leave guard; create and edit routes
+ - [x] animal list: debounced POST search, species filter, archived toggle, « Afficher plus », current owners or « Propriétaire non renseigné », states
+ - [x] animal page: identity, species, sex, breed, birth with its precision, status; relations current / former (voided never shown), client links and `tel:`; add panel, end (optional date), dates, void (erroneous entry, final) dialogs pending until settled; archive / restore; archived read-only; same « introuvable » for unknown / foreign / malformed ids
+ - [x] client page: animals as links grouped per animal with their roles, « Ajouter un animal » (pre-associated), « Associer un animal existant » panel (search_animals), none on an archived client
+ - [x] unit tests (schema, birth, other, sex, relation fields, access mapping, screens: states, idempotent retry, conflict, archive, relations, counts, session) + Playwright `e2e/shell/animals.spec.ts` (brief §17 items 1-24, FR/EN, desktop + 375, axe, URLs free of fixture values)
+ - [x] gates (typecheck, test:run, lint, build, e2e:ui, e2e:shell, db:sandbox test-db/test/types --check, import:equine --check, rust:check, check:all), counter-checks, impeccable detect, fresh verifier + security audit
+ - [x] local gates: typecheck, lint, test:run (60 + 127 + 566), e2e:shell 82, db:sandbox test-db 919 / types match / test 61, import:equine --check 0 diff, check:all green 17:19:26 (rust:check, build, e2e:ui PASSED), impeccable detect 0; counter-checks 12 unit + 2 browser all caught
+ - [x] fresh verifier + security audit: security PASS (MEDIUM pre-existing sandbox literal password, LOWs); verifier ECARTS (client journey late replay → dropLateReplays) → ECARTS (pgTAP 014 #237 uuid read as date → test fixed) → CONFORME 12/12
+ - Found: `Card` dropped `aria-labelledby` since Step 7 (V1-1.5 section cards unnamed), fixed; Button takes `ref`
+ - Moved to the DEV integration checkpoint below: M1-M3 on DEV, browser acceptance, merge go; the rehearsal dump is no longer on disk (checked 2026-10-26)
+ - Follow-up at merge: CHANGELOG Unreleased entry for V1-1 (the section describes develop only)
+ - [x] docs: contract §11.8 as built + D11 + closure inventory, SUPABASE.md §3.3 DEV procedure reviewed, FRONTEND_ARCHITECTURE, BROWSER_TESTS, TEST_STRATEGY, design README (tab bar not reproduced), CLAUDE.md; BDR, EVAL, journal; commits pushed; checkpoint (brief §23, 23 points)
+ - Objective: animal screens, relation panels on both pages, journeys 1 to 7, D11 navigation, D12 tiles, Definition of Done (contract §12.6)
+ - Depends: V1-1.5; U3, D11, D12
+ - Files: `apps/app/src/app/routes/app/animals/*`; `apps/app/src/animals/*`; `apps/app/src/components/{animals,relations}/*`; `AppLayout.tsx`, `DashboardRoute.tsx`; i18n; tests; `apps/app/e2e/{animals,relations}.spec.ts`; `docs/design/README.md`, `CLAUDE.md`, contract "as built", `SUPABASE.md`, CHANGELOG Unreleased
+ - Migration: none
+ - Tests: birth input states; « Autre »; « Propriétaire non renseigné »; two-call creation resumed after a failure; end, correct, remove a relation; archived animal frozen; tiles from live counts; Playwright journeys 1-7 + axe; full suites
+ - Acceptance: `pnpm check:all`; `pnpm db:reset && pnpm db:test`; fresh verifier + security gates; owner LAN check → merge only on the owner's go
+ - Security: as V1-1.5; final RPC surface census for RR-4; guardrails on the new tables
+ - Stop if: any gate red; any finding HIGH/CRITICAL; as V1-1.5
+ - [ ] V1-1 DEV integration checkpoint (owner brief 2026-10-26 « Validation finale V1-1 et préparation de la recette DEV »; Claude reads DEV only; backup, migration, acceptance and merge are owner actions; no new feature, no migration, no merge)
+ - [x] git: branch = origin 9f585e9, clean; develop 5502617, main 605ee7c, release/0.2.0 f8d9425 = origin; branch adds exactly M1-M3
+ - [x] read-only DEV preflight (session forced read-only): 9 applied + M1-M3 pending, nothing remote-only, no linked project, no V1-1 object present, types drift = 24 names added 0 removed, 6 accounts = 6 profiles, storage 2 objects / 11 volume files, purge queue 13 due
+ - [x] scripts read: supabase.sh / dev-env.sh (local CLI, no remote), CLI 2.120.0 `test db` creates + drops pgtap, `supabase status` prints keys, e2e:avatar writes beyond its fixture (temp account, bob sign-in, purge-queue drain)
+ - [x] SUPABASE.md §3.3 corrected: read-only helpers, counts + md5 fingerprints, Storage bytes tar, restore check on the sandbox (not the DEV server), post-migration SQL, test effects, failure handling, restore effects; browser acceptance aligned on the brief §11 (19 lines); restore comparison rehearsed on the sandbox (identical, 26 privilege refusals)
+ - [x] owner brief 2026-10-26 « V1-1.7 validation du préflight »: preflight accepted, owner runs backup + M1-M3. 26 restore errors classified = pg_restore errors, NOT negative tests (25 ACL on Supabase-managed objects + COPY vault.secrets, lossless only with vault empty); §3.3 now checks pg_restore exit (1) + full message/command set, vault count (step 2), migration up + db:test exit, pgtap after db:test, object query for failure; acceptance lines 9 (no duplicate current relation) and 17 (session change, same browser)
+ - [x] owner brief « dernière correction de la validation des sauvegardes »: 26 vs 28 = report double count (log has 26); rehearsal 2 on sandbox (156 MB, 4 variants, real exit codes): `--no-owner` exit 1 / 26 errors, `--no-acl` exit 1 + app grants lost, `--exit-on-error` exit 1 at COPY, filtered TOC + `--single-transaction --exit-on-error` exit 0, 28 rows + 15 privilege lines identical; §3.3 step 2 adds privs.sql + managed.sql (vault 0, D default ACL), step 3b = filtered list (D + 8 entries, DEV D=21 → 29), doc block replayed verbatim exit 0; DEV + sandbox unchanged; LRN-091
+ - [x] steps 0-3b run by Claude on the owner's authorization (2026-10-27): preflight = 2026-10-26, vault 0, D 21; dump + Storage tar in `~/faunosteo-backups` (600, dump sha256); restore check run 1 exit 1 (role `supabase_functions_admin` missing in the sandbox), owner option A (NOLOGIN role, sandbox only), run 2 exit 0, 28 + 15 lines identical; LRN-092
+ - [x] step 4 run by Claude on the owner's authorization: `migration up` exit 0, exactly M1-M3; post.sql, counts deltas, types check all as expected; DEV data unchanged
+ - [ ] `pnpm db:test` on DEV: run 1 exit 1 (919 planned, 915 run, 914 passed: 007 storage collision, 010 13 due purge entries; 012-014 passed; DEV unchanged, pgtap absent after)
+ - [x] 007 + 010 made independent of the base's data (007: seed key only, confirmation cleared in-tx, 20 assertions; 010: section 0 leases the base's queued work in-tx, leftovers by fixture prefix, 141); sandbox A clean + B DEV-like and latent conditions: old FAIL reproduced, new PASS 921; 11 mutations detected on A and B (same set as the old suites); LRN-093
+ - [x] rerun on DEV on the owner's go (2026-10-27): exit 0, 14 suites, 921 assertions, 83 integrity lines identical before/after, pgtap absent after
+ - [x] owner: browser acceptance on DEV (2026-10-27): 19 lines FR detailed, EN validated as a whole + 4 lines at 375 px recorded, isolation A/B/owner; RESP-01 closed (fixed a70166e, owner counter-check 6 PASS); AVATAR-01 class A, non-blocking (DEV worker stays stopped, Alice's `uploaded` row kept)
+ - [ ] post-acceptance fixes (owner brief « corrections post-recette RESP-01 et diagnostic AVATAR-01»; no DEV write, no worker on DEV, no migration, no merge)
+ - [x] RESP-01: owner's global overflow = browser zoom (owner's manual DEV measures, no zoom: /app and /app/clients 375 + 320 no overflow); real defect shown on the sandbox: dashboard grid has no explicit column below md, its implicit `auto` track takes the cards' min-content, the account card's e-mail never truncates → overflow from ~31 chars at 320 px, 44 chars overflow 320-430 px. Fix: explicit one-column track, e-mail wraps instead of being cut
+ - [x] RESP-01 tests: e2e:shell responsive sweep 320/360/375/390/430 + desktop, FR/EN, long content (dashboard, client list/new/edit/page, animal list/new/edit/page, archive dialogs, drawer), e-mail fully visible
+ - [x] AVATAR-01: read-only DEV (clean photo kept, attempt `uploaded` 0 attempts + quarantine object, superseded one `deleted`, worker stopped 10 days) = STORAGE.md §4 step 4 by design; isolated repro on the sandbox: worker stopped → 30 s → message + row `uploaded`; worker on the sandbox network → `clean`; classified A (expected without a worker; side finding pre-V1-1: a full reload does not resume the waiting row); open until the owner decides how DEV runs the worker
+ - [x] gates: check:all, fresh verifier, security audit; docs (recette registry, SUPABASE.md acceptance note), registries; commit + push. Done: check:all exit 0 (cargo 1548 passed / 3 ignored, vitest 566 + 127 + 60, e2e:ui 26), e2e:shell sandbox 86 passed, responsive 4/4 after the fixture domain fix; verifier CONFORME 8/8; security PASS (2 LOW: fixture domain applied, pre-existing uuid interpolation noted); LRN-094. Next: owner counter-check of the dashboard at 375 px on DEV
+ - [ ] after the owner's results: fixes if any (branch, gates, fresh verifier + security), CHANGELOG Unreleased, TODO closure, final report; merge only on the owner's explicit go
+ - Owner cleanup (optional): rehearsal leftovers `/tmp/claude-1000/-home-bchanot-Documents-faunosteo/8d6890e5-060c-431d-b99f-545f2e315333/scratchpad/rehearsal/` (3 small files, fictitious data); the backup folder `~/faunosteo-backups` is kept until the acceptance is validated
+- [ ] AVATAR-02 (ticket, out of V1-1; not created in Gitea: no Gitea CLI or token on this machine, `gh` is GitHub only) « Reprendre le suivi d'une photo en attente après rechargement de la page »
+ - Context: avatar processing is asynchronous (STORAGE.md §4): begin → quarantine upload → confirm (`uploaded`) → worker → `clean` / `rejected`; the page polls its own row 1 s, 30 s at most
+ - Repro (isolated stack only): upload a photo, leave the row `uploaded` (worker stopped), full page reload before processing
+ - Observed: AvatarSection mounts before the auth store has read the rows (`avatar` null) → phase idle, old photo shown, « Modifier » / « Supprimer » enabled, no polling; a new save supersedes the waiting row (`deleted`). An in-app return resumes. Pre-V1-1 (Step 8 / R1 mount logic)
+ - Expected: once the rows arrive, find the active waiting asset, resume its polling, show a coherent state; never create a second upload nor replace the first by the resume itself
+ - Cases: worker stopped (long-processing message, honest wording), processing finished during the reload (`clean` shown, no stale message), `rejected` (message per code), `deleted` / superseded, read errors per the closed AssetFailure kinds; own rows only (RLS unchanged)
+ - Tests: unit (store arrives after mount), e2e:shell on the sandbox with the worker stopped and running (gateway + worker on the sandbox network, as the AVATAR-01 repro); never DEV
+ - Limits: frontend only; no Storage contract, RPC, RLS, worker or migration change without owner approval
- [ ] Code debt (not P0, no change on the doc branch): `docker/nginx.conf` still has `location /species/` (public/species deleted at Step 5); remove with its own `chore/` or `bugfix/` branch
## Release readiness track (owner 2026-10-25, distinct from the functional roadmap; nothing here authorises a release or exposure)
@@ -390,7 +540,7 @@ Inventory: `.claude/audits/2026-10-25-functional-inventory.md`. Each item: treat
- [ ] RR-4 API trust boundaries: direct export API trusted for what it declares (RUST.md §11.22), `export_from_envelope` L6, RPC surface review (authenticated 17, service_role 9, anon 0), worker service key readable by the docker group (DEPLOY.md)
- [ ] RR-5 production configuration: CSP example in DEPLOY.md lacks `'wasm-unsafe-eval'` and the Supabase `connect-src`; compose publishes 8080 on all interfaces while DEPLOY says 127.0.0.1 (rootful Docker bypasses UFW); stale no-backend DEPLOY sections; Q2 hosting; production SMTP, FR auth email templates, captcha, OAuth ids; DEV hardening (demo keys, 54321 on LAN)
- [ ] RR-6 dependencies and images: base images by tag only (pin digests), cosign, workflow actions by tag, CI never run (BDR-047), release-images never executed
-- [ ] RR-7 accessibility: WCAG target to set; dialog focus trap/restore, close button 24 px, canvas zones keyboard-unreachable, no axe test, D2/D5 Context7 items (RUST.md §10.14)
+- [ ] RR-7 accessibility: WCAG target to set; dialog focus trap/restore (done V1-1.3, native modal dialog), close button 24 px, canvas zones keyboard-unreachable, axe test (done V1-1.3: e2e:ui, e2e:shell), D2/D5 Context7 items (RUST.md §10.14). Pre-existing serious axe findings let through by exact node in `apps/app/e2e/support/browser.ts` KNOWN_VIOLATIONS: LanguageSwitcher label-in-name (« FR » shown, « Passer en français » announced), top bar account link label-in-name (display name shown, « Mon compte » announced), DashboardRoute `dl` with a status row lacking dt/dd. Seen outside the scanned states: ObservationCard header `nested-interactive` + label-in-name (editor with an observation); moderate: duplicate `main` landmarks (App + routes), no h1 on Home
- [ ] RR-8 mobile and end-to-end: real-browser e2e for sign-up, login, account, avatar, full editor flow, export, locale, mobile drawer (TEST_STRATEGY §1 `apps/app/e2e`); per-check device results (J1/J2 recorded as a whole)
- [ ] RR-9 release 0.2.0 fate (Steps 3–6 on TS engines, 341 commits behind develop): ship, supersede, or rebase; sheet bundle default `none`
- [ ] RR-10 census tools maintenance (LOW `#[ignore]` positions) and controlled oracle evolution on a new anatomical changeset
diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md
new file mode 100644
index 00000000..97fa6607
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md
@@ -0,0 +1,58 @@
+# CONTRACT: V1-1.1 Workspaces (M1), owner brief 2026-10-25 « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces »
+
+- branch `feature/v1-1-clients-animals`, base 5d734be; code commit 7bf4fb6
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §3, §4, §8 (M1 sketch), §9.1, §9.2, §9.5, §10, §12.1
+- diff under review: `git diff 5d734be..HEAD -- supabase packages/supabase`
+- isolated real-stack evidence: `/tmp/claude-1000/-home-bchanot-Documents-faunosteo/55c1fd3e-1c33-4c77-8509-9cd3ca683a18/scratchpad/sandbox/`
+ (`RESULTS.md`; scripts `up.sh`, `tap.sh`, `concurrency.sh`, `http.mjs`, `down.sh`; containers `faunosteo_m1sandbox_*`
+ running, same images as the DEV stack). `tap.sh` and `node http.mjs` may be re-run (rolled back / unique emails);
+ `concurrency.sh` inserts fixed ids and runs once per sandbox. The DEV stack (`supabase_*_faunosteo`) must not be touched.
+
+## Clauses
+
+C1. **Scope.** One migration only, `supabase/migrations/20261025100000_workspaces.sql` (M1). No M2/M3 object (no clients,
+animals, relations, species rows, unaccent, fold_text, write budget, write RPC), no React screen, no Playwright, no cabinet
+feature, no change to crates/, no change to an existing migration file, no change to existing tables' grants or policies
+except the `private.log_event` redefinition and the NOT VALID CHECK on `audit.audit_logs.correlation_id`.
+
+C2. **Model.** Enums `workspace_kind` = {personal} and `workspace_member_role` = {holder} only (no unused cabinet role);
+`workspaces(id, kind, personal_user_id unique → profiles on delete cascade, created_at)` with CHECK personal ⇔
+personal_user_id not null; `workspace_members(workspace_id → workspaces cascade, user_id → profiles cascade, member_role,
+created_at, PK (workspace_id, user_id))`, index on user_id. No `owner_id`; names as in contract §3. No archive column:
+a workspace follows its account (deletion cascades; M2's `on delete restrict` will block it when records exist, D9a).
+
+C3. **Creation.** Server-side only: trigger after insert on `profiles` → `private.ensure_personal_workspace(uuid)`, which
+writes workspace and holder membership in one statement with ON CONFLICT on the unique key (atomic, idempotent, race-safe);
+`private.backfill_personal_workspaces()` covers existing profiles, idempotent, called once by the migration after the
+trigger exists. No API role can call either. Works with the existing sign-up chain (GoTrue → `handle_new_auth_user` →
+profile → workspace, one transaction); the workspace exists before email confirmation and stays unreadable until then.
+
+C4. **Integrity.** A deferred constraint trigger refuses at commit, whatever role writes: a personal workspace without its
+holder, a foreign member in a personal workspace, the removal of the holder alone, the transfer of a personal workspace to
+another account. Cabinets are not constrained. Error messages carry no id or personal data.
+
+C5. **Access rule.** `private.caller_workspace_ids()`: no parameter, `auth.uid()` only, member + `profiles.active` +
+`auth.users.email_confirmed_at is not null`; security definer, `search_path = ''`, owner postgres, EXECUTE for
+`authenticated` only. `private.writable_workspace_ids()`: same restricted to holder, EXECUTE for nobody. No platform-role
+branch anywhere (D16). The private schema stays out of PostgREST (`config.toml` schemas = public, pinned by a test).
+
+C6. **RLS and privileges.** RLS enabled on both tables; one SELECT policy each, for `authenticated`, through
+`caller_workspace_ids()`, no `using (true)`; no write policy. `revoke all` from public, anon, authenticated, service_role,
+then column SELECT grants to authenticated only. Every new function: `revoke all` from public, anon, authenticated,
+service_role; security definer; `search_path = ''`; owner postgres. Effective privileges tested for anon, authenticated and
+service_role (SQL refusal 42501 distinct from an empty RLS result).
+
+C7. **Audit (N9).** `private.log_event` keeps its signature, privileges and callers; `x-correlation-id` stored only when it
+matches `^[A-Za-z0-9-]{1,64}$`, else null; `audit_logs_correlation_id_format` CHECK NOT VALID on new rows. Append-only kept.
+
+C8. **Tests.** pgTAP `supabase/tests/012_workspaces.sql` covers: creation with the account, holder membership, failed sign-up
+leaves nothing, idempotence, uniqueness, FK/PK refusals, backfill (trigger disabled) and its idempotence, the commit
+invariant, A/B isolation, refusal for unconfirmed (then access after confirmation), deactivated, platform staff, anon,
+service_role, parameter usurpation (filters by other ids, inserts naming others), direct calls of private functions, the
+privilege/definer/owner census, the empty account deletion, the correlation cap. `001_schema.sql` census updated;
+`schema-types.test.ts` and `database.types.ts` (regenerated, only M1 additions); `config.test.ts` pins
+`enable_confirmations = true`, anonymous sign-ins off, schemas = public. All green on PGlite (`pnpm test:run`) and on the
+isolated real stack from zero and on the upgrade path (sandbox `RESULTS.md`), with real concurrency evidence.
+
+C9. **Limits.** Nothing applied to the DEV stack; no merge into develop; main and release/0.2.0 untouched; no deploy;
+no real personal data in fixtures.
diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md b/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md
new file mode 100644
index 00000000..b1047d95
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md
@@ -0,0 +1,59 @@
+# CONTRACT: V1-1.2 Clients data (M2) + M1 closure, owner brief 2026-10-25 « Validation V1-1.1 et autorisation V1-1.2 Données clients »
+
+- branch `feature/v1-1-clients-animals`, base 6bf6978 (V1-1.1 validated); commits 08abe42 (sandbox tool + M1 suite),
+ 5ed1f01 (DEV procedure docs), 2c0531d (memory), 4adbfcb (M2 code), f8bd1b6 (docs)
+- diff under review: `git diff 6bf6978..f8bd1b6 -- scripts supabase packages package.json docs`
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §5, §5.1, §8.2, §9, §10, §12, §13.2
+- isolated stack: `pnpm db:sandbox` (scripts/db-sandbox.sh, SUPABASE.md §5.1) is UP (upgrade mode, M1+M2 applied over
+ older data). Allowed: `pnpm db:sandbox test-db`, `pnpm db:sandbox types --check`, `pnpm db:sandbox test`,
+ `echo "" | pnpm db:sandbox sql`. The DEV stack (`supabase_*_faunosteo`) must not be touched except
+ `pnpm supabase migration list --local` (read-only).
+
+## Clauses
+
+C1. **Scope.** M2 only: `supabase/migrations/20261025110000_clients.sql`. No M3 object (animals, relations, species
+rows, animal enums), no React screen or route, no V1-1.3 tooling (Playwright, Dialog), no change to crates/, no edit of an
+existing migration, no change to existing tables' grants or policies except the N9 condition on `audit_logs_select_admin`.
+
+C2. **M1 closure.** The committed `database.types.ts` equals the official generator's output (`supabase gen types
+typescript --schema public`, through Prettier) against an isolated database holding the migrations; no hand edit; types
+cover exactly the public schema objects of M1 and M2.
+
+C3. **Sandbox tool.** `scripts/db-sandbox.sh`: rootless Docker, ports on 127.0.0.1 only and distinct from DEV, no volume
+created or removed, cleanup by literal `faunosteo_dbsandbox_*` names only, secrets generated outside the repository and
+never printed or committed, image versions pinned and documented, fresh and upgrade modes, every Supabase CLI call with
+an explicit sandbox `--db-url` (none can reach DEV).
+
+C4. **DEV procedure (doc only).** SUPABASE.md §3.3: target check, migration history, only V1-1 migrations pending,
+accounts count, backup including auth data stored outside Git and checked, application without reset and without
+`db push`, `migration repair` or destructive command, `db:test` shown non-destructive, post-checks (history, workspaces,
+duplicates, privileges, types, e2e:avatar), stop conditions, no secret printed. Claude applied nothing to DEV.
+
+C5. **Clients model.** person | organization; `display_name` required, no first/last name, no notes; optional contacts;
+no default country; workspace FK `on delete restrict`; text rules and bounds as contract §5/§5.1; no sensitive extra
+field; `field-limits.ts` constants proven equal to the SQL CHECKs by a behavioural parity test (bounds, code points,
+control ranges, patterns; TypeScript never accepts what SQL refuses).
+
+C6. **RPCs.** `create_client`, `update_client`, `set_client_archived` (definer) and `search_clients` (invoker): identity
+from `auth.uid()` only via `writable_workspace_ids` / RLS (active profile, confirmed email); same whole error for a
+foreign and an unknown id; parse errors and constraint violations → `invalid_input` without echo; idempotent create,
+divergent replay → `request_conflict`; stale revision → `conflict`; archived read-only (`archived` before `conflict`);
+restore allowed; no-op writes nothing; EXECUTE only for authenticated; search_path empty; owner postgres; audit rows
+ids only (`{workspace_id}`), hidden from platform staff (N9).
+
+C7. **Budget and caps.** Transactional counter per workspace (owner §9): UTC hour/day windows documented (zone, reset,
+boundaries); 1 000/h, 5 000/day, 20 000 clients; increment and write in one transaction; refused, replayed and no-op
+calls not counted; concurrency-safe; stable lock order documented (workspace, animal, client, budget last); lock scope
+per workspace, measured.
+
+C8. **Search.** POST RPC, 25 default / 100 max page, ≤ 100-character term, deterministic order `(name_key, id)` with
+keyset, LIKE wildcards escaped, phone search, no leak of another workspace through rows, counts or pages; index exists;
+20 000-client timing recorded.
+
+C9. **Tests.** pgTAP `013_clients.sql` + `001` census green on PGlite and on the isolated real image (fresh and upgrade);
+sandbox suite: real authenticated sessions per role (A, B, anon key, service key, deactivated, unconfirmed), concurrent
+creates, replays, divergent replay race, stale revision race, archive/restore race, budget at the limit under
+concurrency, no deadlock; M1 regression (workspaces, backfill, auth/profile). `pnpm test:run` green.
+
+C10. **Docs and limits.** Contract §8.2 as built + deviations, SUPABASE.md §3.4/§5.1, TEST_STRATEGY, BDR-075, LRN-080/081
+(scoped, no duplicate). No merge, main and release/0.2.0 untouched, no deploy, fixtures fictitious.
diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-3-ui-foundations.md b/.claude/tasks/contracts/2026-10-25-v1-1-3-ui-foundations.md
new file mode 100644
index 00000000..2617e3cc
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-25-v1-1-3-ui-foundations.md
@@ -0,0 +1,57 @@
+# CONTRACT: V1-1.3 UI foundations + V1-1.2 closure, owner brief 2026-10-25 « Validation V1-1.2 et autorisation V1-1.3 Socle UI »
+
+- branch `feature/v1-1-clients-animals`, base 5bc6631 (V1-1.2 validated); commits 57922e0 (sandbox fix), 6f885ec (dialog),
+ 72ee9f9 (Playwright UI suite), 8371aa0 (photo confirmation focus), e3a2b3e (shell suite), 9b2a4bc (check:all), 9cd33f1 (docs)
+- diff under review: `git diff 5bc6631..9cd33f1 -- apps scripts package.json pnpm-lock.yaml .gitignore docs CLAUDE.md`
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §11.5, §11.6 (as built), §12.5, §13.3; `docs/development/BROWSER_TESTS.md`
+- owner choices of 2026-10-25 (asked during the run): e2e backend = isolated stack (not DEV); public commands `pnpm e2e:ui` +
+ `pnpm e2e:shell`; MobileDrawer on the same modal mechanism; check:all runs e2e:ui when the pinned Chromium is installed, else SKIPPED
+- isolated stack: `pnpm db:sandbox` is UP (fresh). Allowed: `pnpm db:sandbox test-db`, `pnpm db:sandbox types --check`,
+ `pnpm db:sandbox test`, `pnpm e2e:shell`, `echo "" | pnpm db:sandbox sql`. `pnpm check:all` may be running in the
+ background and owns port 5191 while it does: do not run `pnpm e2e:ui` unless `ss -ltn | grep 5191` is empty. The DEV stack
+ (`supabase_*_faunosteo`) must not be touched except `pnpm supabase migration list --local` (read-only). Never `pnpm dev`.
+
+## Clauses
+
+C1. **Scope.** No migration, no M3 object, no client or animal screen or route, no change under `crates/`, `supabase/migrations`,
+`supabase/tests`; no V1-1.4 work; no tab bar; mockups under `docs/design/` unchanged; no new runtime dependency (only dev
+dependencies of `apps/app`); no merge, `main` / `develop` / `release/0.2.0` untouched.
+
+C2. **Sandbox final check (V1-1.2 closure).** `scripts/db-sandbox.sh`: an unknown `up` mode, a missing or malformed upgrade
+version (not 14 digits) is refused before any container or secret exists; the new `e2e-shell` command and the refactored `test`
+command pass the endpoints and keys through the environment (no secret on any argv), call `load_secrets` first (missing or
+incomplete secrets refused), and reach only sandbox URLs; ports stay on 127.0.0.1; no volume; cleanup by literal names unchanged.
+
+C3. **ModalDialog (D13).** `apps/app/src/components/ui/ModalDialog.tsx` uses the native `` + `showModal()` (no focus-trap
+library, no hand-written Tab loop); never closes itself: Escape keydown cancelled (`preventDefault`) and turned into `onClose`,
+`cancel` cancelled and turned into `onClose`, a platform-forced `close` reported to `onClose` only when the dialog is really closed;
+initial focus on the first tabbable control; focus restored after the commit to the opener, else to the first tabbable control of
+the opener's nearest surviving container; StrictMode remount does not steal focus or close the dialog; IME composition ignored.
+
+C4. **Consumers.** `Dialog` named by `aria-labelledby` (its h2), optional `description` → `aria-describedby`; visual output of the
+existing dialogs unchanged (same classes, same spacing); the four confirmations (AvatarSection, ReplaceSessionDialog,
+HeldSessionPanel, DisclaimerDialog) pass their message as description; MobileDrawer on ModalDialog, named « Navigation principale »,
+closes at the `lg` breakpoint; AvatarSection keeps its confirmation open while the removal is in flight (Escape, Cancel, backdrop
+refused) and closes when it settles; its sr-only file input is out of the tab order; the page does not scroll behind a modal
+(`html:has(dialog:modal)` in `styles/index.css`).
+
+C5. **Dependencies (D14).** `@playwright/test` 1.64.1 and `@axe-core/playwright` 4.14.0 exact, devDependencies of `apps/app`
+only; lockfile adds exactly @playwright/test, playwright, playwright-core, @axe-core/playwright, axe-core (licenses Apache-2.0 /
+MPL-2.0); no install script added to the repo; no `sudo`, no `--with-deps`.
+
+C6. **Browser suites.** `apps/app/e2e`: two configs, dev servers on 127.0.0.1:5191 / 5192 with `--strictPort` and
+`reuseExistingServer: false`; the UI server has an empty Supabase connection; the shell server uses the `.invalid` fake origin and
+the sandbox anon key; an automatic request guard aborts every request outside the allowlist and fails the test; fixture values
+checked against request URLs and masked in reports; the shell suite keeps no trace; the test page `e2e/harness/dialog.html` is not
+part of the production build (`vite build` input is `index.html` only); accounts fictitious, random, sandbox only.
+
+C7. **Tests prove the brief §9 list in Chromium.** Open, initial focus, Tab and Shift+Tab, containment (never the page; one browser
+UI step at the wrap is the platform's), Escape allowed, Escape refused twice, close button, restore, vanished opener (test page and
+real shell with a slow removal), background inert (focus, click, scroll), name and description, long content, 375 px, no horizontal
+overflow, axe zero serious/critical outside the three listed pre-existing nodes, FR and EN, a representative test in the real
+`/app` shell. Vitest suites green; existing suites unchanged in behaviour.
+
+C8. **Gates and docs.** `pnpm typecheck`, `pnpm test:run`, `pnpm lint`, `pnpm e2e:ui`, `pnpm e2e:shell`, `pnpm check:all` green
+(check:all includes rust-check.sh); docs updated: contract §11.6 (D13 final, D14 as built, D11 three-way comparison with
+consequences for Clients and Animaux), §12.5 deviation, BROWSER_TESTS.md (prerequisites, commands, limits incl. WebKit/Safari),
+TEST_STRATEGY, SUPABASE §5.1, CLAUDE.md. Pre-existing axe findings named in TODO RR-7.
diff --git a/.claude/tasks/contracts/2026-10-26-v1-1-4-animals-relations.md b/.claude/tasks/contracts/2026-10-26-v1-1-4-animals-relations.md
new file mode 100644
index 00000000..de3d2e93
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-26-v1-1-4-animals-relations.md
@@ -0,0 +1,83 @@
+# CONTRACT: V1-1.4 Animals and relations (M3) + V1-1.3 follow-ups, owner brief 2026-10-26 « Validation V1-1.3 et autorisation V1-1.4 Animaux et relations »
+
+- branch `feature/v1-1-clients-animals`, base 0826ecf (V1-1.3 validated); commits 2dc04bc (sandbox upgrade
+ ``), b54c8e5 (M3 code), 533a1c4 (tests strengthened after mutations), ba3a51e (axe exceptions scoped),
+ d7845b7 (check:all statuses), bc6a7dd (docs)
+- diff under review: `git diff 0826ecf..bc6a7dd -- supabase packages scripts apps/app/e2e docs CLAUDE.md`
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §3, §5, §5.2-§5.4, §6, §7.1, §8, §8.3, §9, §10,
+ §12, §13.2 (N1, N4, N5, N6, N7, N8, N9)
+- isolated stack: `pnpm db:sandbox` (scripts/db-sandbox.sh, SUPABASE.md §5.1) is UP (upgrade mode: M1 + M2 base,
+ then M3). Allowed: `pnpm db:sandbox test-db`, `pnpm db:sandbox types --check`, `pnpm db:sandbox test`,
+ `echo "" | pnpm db:sandbox sql`, `pnpm --filter @faunosteo/supabase test:run` (PGlite).
+ Not allowed: `pnpm check:all`, builds, `pnpm wasm:build` (a check:all run is in progress), `db:sandbox up/down`.
+ The DEV stack (`supabase_*_faunosteo`) must not be touched except `pnpm supabase migration list --local`
+ (read-only).
+
+## Clauses
+
+C1. **Scope.** One new migration, `supabase/migrations/20261026100000_animals_relations.sql`; no other migration
+added or edited. No React screen, route, form or navigation change; no access layer for animals or relations
+(moved to the UI steps, as `clients.ts` at V1-1.2); no change under `crates/`; no sheet published or linked to a
+species. V1-1.3 follow-ups limited to test code (`apps/app/e2e/support/browser.ts`), `scripts/check-all.sh` and docs.
+
+C2. **Species.** Exactly the nine species of contract §5.4 plus `other`, with the ids, names and order listed
+there; `equine` unchanged; rows of `public.species`, not an enum; the Rust domain untouched; the table comment
+says a row does not mean a sheet exists.
+
+C3. **Animal model.** Every animal in one workspace (`on delete restrict`); required name (1-80, text rule),
+species (active row), sex (`male|female|unknown`, no default); optional breed (≤ 80), `birth_year`
+(1900-2100 CHECK, not after tomorrow's UTC year in the RPC), `birth_date` (≥ 1900-01-01, not after tomorrow UTC,
+requires `birth_year` equal to its year); no date invented from a year; `species_detail` required with `other`,
+refused otherwise; no column beyond contract §5.2 (no photo, weight, coat, identification, neutering, death,
+notes).
+
+C4. **Relations.** Many-to-many with `relation_role` owner|keeper|contact; animal without relation allowed;
+several owners allowed; composite foreign keys `(workspace_id, animal_id)` and `(workspace_id, client_id)`, not
+deferrable, so no row joins two workspaces whatever writes it (RPC, privileged SQL, later reference update,
+concurrency); at most one current row per (animal, client, role) by a partial unique index on rows with
+`ended_at` and `voided_at` null; current / ended (date known or unknown, told apart by `ended_at`) / voided as in
+contract §8.3; `ended_on` only with `ended_at`, ordered after `started_on`, no default dates; voiding keeps every
+value, sets `voided_at`, freezes the row, removes it from lists, derived values, the current index and the current
+cap; no deletion path through the API.
+
+C5. **RPCs and privileges.** The ten functions of contract §9.3 for animals and relations plus `search_clients`
+recreated with `current_animal_count` (deviation: `search_animals` filter named `species_filter`, §8.3). Write
+RPCs: security definer, `search_path = ''`, owner postgres, identity from `auth.uid()` through
+`private.writable_workspace_ids()` (active profile, confirmed email, holder); the same whole 42501 `not_found` for a
+foreign and an unknown id; no lock taken in another workspace; order archived → revision → rules; parse and
+constraint errors → `invalid_input` without the value; idempotent creates, divergent replay `request_conflict`;
+audit rows `{workspace_id}` only, hidden from platform staff (N9). Reads: security invoker (RLS). EXECUTE:
+`authenticated` only on the public functions, nobody on the new private helpers; `anon` and `service_role` hold no
+table or function privilege on M3 objects (N7); RLS on both tables, one SELECT policy each through
+`caller_workspace_ids()`, no platform-role branch.
+
+C6. **Budget, caps, locks.** The M2 counter `private.consume_write_budget` shared by clients, animals and
+relations (no table-specific budget), 1 000 / hour, 5 000 / day, UTC windows; refused, replayed and no-op calls not
+counted; `create_animal` with its relation counts two writes. Caps 20 000 animals and 100 000 relations per
+workspace, 20 current and 200 total relations per animal, counted under locks; voided and ended rows count in
+the totals, not in the current cap. Lock order consistent across M2 and M3 as in contract §8.3 (workspace, animal,
+relation, client, budget last); concurrency and absence of deadlock tested.
+
+C7. **Reads.** Pages 25 by default and 100 at most (`list_client_animals` 50 / 100), terms ≤ 100 characters,
+deterministic keyset order, LIKE wildcards escaped, POST only; no row, count or page of another workspace;
+`current_animal_count` = distinct active animals of current non-voided relations; `current_owners` /
+`current_owner_count` per contract §9.3 (voided and ended left out, archived owners flagged);
+`client_archive_preview` per §9.3; M2 behaviour of `search_clients` otherwise unchanged.
+
+C8. **D-R7 parity.** `packages/supabase/src/field-limits.ts` holds the animal bounds and the year and date floors;
+`tests/db/field-limits.test.ts` proves by behaviour (valid, at the bound, past it, control characters, Unicode
+code points) that TypeScript never accepts what SQL refuses.
+
+C9. **Tests.** pgTAP `014_animals_relations.sql` plus 001-013 green on PGlite and on the isolated real image;
+sandbox suites (workspaces, clients, animals) green with real GoTrue and PostgREST sessions; the four migration
+states of contract §8.3 claimed green; types in `database.types.ts` equal to the generator's output against the
+sandbox (`pnpm db:sandbox types --check`), no hand edit; the mutation claims of §8.3 plausible from the test code.
+
+C10. **V1-1.3 follow-ups.** Each axe exception matches rule, selector, opening markup and route, so a new screen
+or element is not masked; `check:all` states PASSED / SKIPPED (environment missing) / NOT RUN per browser suite,
+a running suite that fails stops it with FAILED and a non-zero exit; `pnpm e2e:ui` and `pnpm e2e:shell` remain
+independent commands.
+
+C11. **Docs and limits.** Contract §8.3 as built; SUPABASE.md §3.3 procedure from DEV's current state to M3
+(backup, history check, no reset, not run) and §3.5; TEST_STRATEGY; CLAUDE.md. Commits pushed; no merge; main and
+release/0.2.0 untouched; DEV untouched; fixtures fictitious.
diff --git a/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md b/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md
new file mode 100644
index 00000000..ae19db1c
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md
@@ -0,0 +1,75 @@
+# CONTRACT: V1-1.5 Clients UI, owner brief 2026-10-26 « Validation V1-1.4 et autorisation V1-1.5 Interface Clients »
+
+- branch `feature/v1-1-clients-animals`, base 6251051 (V1-1.4 validated); commits a0e0699 (access layer), ff028ec
+ (workspace state), b38e627 (client screens), d33a8f6 (Playwright journeys), db81928 (shell report fix), ae0bd3f (docs)
+- diff under review: `git diff 6251051..HEAD -- packages apps docs CLAUDE.md` (HEAD includes e1c1980 workspace kept during a re-read, 567ad40 not-found heading focus, and the docs count update)
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §5.1, §7.1, §9.3, §9.4, §11 (§11.7 as built), §12.4, §12.5
+- owner choices recorded in TODO (V1-1.5) and contract §11.7: U1 « Afficher plus », U2 archived toggle, animals
+ read-only on the client page, « premier animal » section deferred to V1-1.6
+- isolated stack `pnpm db:sandbox` is UP. Allowed: `pnpm db:sandbox test`, `pnpm db:sandbox test-db`,
+ `pnpm db:sandbox types --check`, `pnpm e2e:shell`, `pnpm --filter @faunosteo/supabase test:run`,
+ `pnpm --filter @faunosteo/app exec vitest run`, typecheck and lint, read-only SQL through `pnpm db:sandbox sql`.
+ Not allowed: `pnpm check:all` and builds (a run is in progress), `db:sandbox up/down`, anything on the DEV stack
+ except `pnpm supabase migration list --local`.
+
+## Clauses
+
+C1. **Scope.** Client screens and their data access only: no animal screen, route or form, no `animals.ts` or
+`relations.ts` access module, no migration, no change under `crates/` or `supabase/`, no mobile tab bar, no
+dashboard tiles, no change to the validated mockups. Existing files changed only where the clients need it
+(App routes, AppLayout guard, SidebarNav entry, Icon, i18n, authStore, lib/id, e2e support).
+
+C2. **Access layer.** `packages/supabase/src/{records,workspaces,clients,species}.ts`: only the authorised RPCs and
+reads (search/list/preview through POST RPCs, read by id with an explicit column list, no `select=*`, no text
+filter in a GET URL); pagination contract (25 default, ≤ 100, keyset, one probe row); generated types used for
+argument names; failures folded into closed kinds keeping not_found, archived, conflict, request_conflict,
+limit_reached, rate_limited, invalid_input, session_expired, network, unavailable; nothing distinguishes a foreign
+id from an unknown one; no service key; the workspace id is a context the server re-checks, never an authorisation.
+
+C3. **Personal workspace and identity.** Read after sign-in, never created by the browser; states session absent
+(RequireAuth), unconfirmed, inactive, loading, ready, missing, error each rendered; a change of account clears the
+previous account's profile, roles, avatar and workspace at once, and late answers of the previous account are
+dropped; the client routes remount per workspace, so no row of a previous session shows.
+
+C4. **List.** Search through the backend only (no client-side engine), debounced, ≤ 100 characters; 25 per page
+with « Afficher plus »; deterministic order; archived toggle; status badges; access to the page; empty, loading,
+network error with retry; reload after changes; no private value in URLs or logs.
+
+C5. **Form.** Person | organization, display name required, no first/last name, optional contacts, no default
+country, no notes; bounds and patterns from `field-limits.ts` (D-R7), code points, control characters, Unicode;
+phone entry rule of contract §11.3; FR/EN messages; submitting state; double-click guard; one create_request_id per
+creation intent reused on retry, a new form a new id, request_conflict explicit; update with the expected revision,
+no silent overwrite, conflict understandable with the saved values; archived refusal.
+
+C6. **Archive and restore.** Confirmation through the shared Dialog/ModalDialog (closing is not confirming,
+refuses to close while pending, focus D13 kept), preview of sole-owned active animals, no deletion, no cascade to
+animals, read-only archived page, restore through the RPC.
+
+C7. **Client page.** Contract fields; `tel:` and `mailto:`; animals read-only from `list_client_animals` (no link,
+no add, no invented data); `current_animal_count` from the backend in the list; same « introuvable » for unknown,
+foreign and malformed ids.
+
+C8. **Navigation, design, accessibility.** Clients entry in sidebar and drawer in the mockup's order, existing
+navigation kept, no tab bar; existing components and tokens reused; labels, visible focus, errors announced next
+to fields, first error focused, page heading focused on open; 375 px without horizontal overflow; FR/EN; the new
+pages pass axe without any KNOWN exception applying to their own elements.
+
+C9. **Unsaved changes.** `beforeunload` while dirty; in-app links ask first (ModalDialog), staying keeps the
+values; what the router cannot intercept (browser back/forward) documented, not claimed.
+
+C10. **Tests.** Unit tests (access layer call shapes and failure mapping; schema; store identity change; screens:
+states, retry idempotence, new intent, conflict, archived, archive dialog pending, leave guard, double click);
+the access layer against real PostgREST (`clients-access.sandbox.ts`); Chromium journeys on the sandbox
+(`e2e/shell/clients.spec.ts`: create, search, edit, archive, filter, restore, pagination, keyboard, two accounts,
+conflict, retry, errors, leave guard, language, desktop + 375, axe); request URLs free of fixture values; suites
+green when run.
+
+C11. **Reports and docs.** No private data in test reports beyond fictitious fixtures (the shell HTML report that
+kept typed passwords removed); contract §11.7, BROWSER_TESTS, TEST_STRATEGY, SUPABASE.md, FRONTEND_ARCHITECTURE,
+design README, CLAUDE.md updated; commits pushed; no merge; main and release/0.2.0 untouched; DEV untouched.
+
+## CLARIFICATIONS
+
+- FLOOR ASSERT_DROP `apps/app/e2e/shell/shell.spec.ts` (2 → 0 assertion lines): the `signIn` helper, with its two
+ `expect` lines, moved verbatim to `apps/app/e2e/support/shell.ts` so both shell specs share it; both specs still
+ await it, no assertion is lost. Authorised.
diff --git a/.claude/tasks/contracts/2026-10-26-v1-1-6-animals-ui.md b/.claude/tasks/contracts/2026-10-26-v1-1-6-animals-ui.md
new file mode 100644
index 00000000..36cb974b
--- /dev/null
+++ b/.claude/tasks/contracts/2026-10-26-v1-1-6-animals-ui.md
@@ -0,0 +1,102 @@
+# CONTRACT: V1-1.6 Animals and relations UI, owner brief 2026-10-26 « Validation V1-1.5 et autorisation V1-1.6 Interface Animaux et clôture »
+
+- branch `feature/v1-1-clients-animals`, base 3c2b503 (V1-1.5 validated); commits e223576 (access layer), 930499c
+ (screens), 3c2b503..HEAD also holds 3e968ee (Playwright journeys, sandbox e2e argument passthrough) and e215e9b (docs)
+- diff under review: `git diff 3c2b503..HEAD -- packages apps docs scripts CLAUDE.md`
+- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §5.2, §5.3, §5.4, §7.1, §9.3, §9.4, §11.1 to §11.5,
+ §11.8 (as built), §13.3, §15 (closure inventory); owner decisions recorded in §11.8 and TODO: D11 drawer only, first
+ animal from the client page in one `create_animal` call, no role preselected, relation add as an in-page panel, end /
+ dates / void as confirmations, U3 date fills and locks the year; D12 not in the brief
+- isolated stack `pnpm db:sandbox` is UP. Allowed: `pnpm db:sandbox test`, `pnpm db:sandbox test-db`,
+ `pnpm db:sandbox types --check`, `pnpm db:sandbox e2e-shell [spec] [--project ...] [--grep ...]`,
+ `pnpm --filter @faunosteo/supabase test:run`, `pnpm --filter @faunosteo/app exec vitest run`, typecheck and lint,
+ read-only SQL through `pnpm db:sandbox sql`. Not allowed: `pnpm check:all` and builds, `db:sandbox up/down`, any
+ file change, anything on the DEV stack except `pnpm supabase migration list --local`.
+
+## Clauses
+
+C1. **Scope.** Animal screens, relation panels and dialogs, the client page's animal section, their data access, tests
+and docs only: no migration, nothing under `supabase/` or `crates/`, no bilan link (V1-3), no sheet shown, no cabinet,
+no tab bar, no dashboard tiles, no weight / photo / coat / identification / neutering / death date / notes field, no
+redesign of the client screens (the client page's animal section and the shared `Card` / `Button` fixes aside).
+
+C2. **Access layer.** `packages/supabase/src/{animals,relations}.ts` and the `records.ts` additions: writes only
+through the M3 RPCs (no direct insert, update or delete on a record table); reads by id with explicit column lists,
+never `select=*`; searches through POST RPCs (no term in a URL); the relations read by animal id with `voided_at is
+null` and a bound; generated argument names; Zod-checked answers; closed failure kinds including `duplicate_relation`
+and `already_ended`; a non-uuid id makes no request; a foreign id reads as unknown; no service key.
+
+C3. **Routes and isolation.** `/app/animals`, `/new`, `/:animalId`, `/:animalId/edit` behind the workspace gate
+(remount per workspace, no data of a previous account shown); the same « Animal introuvable » for unknown, foreign and
+malformed ids; no private value or business identifier in a URL query (the origin client travels in the navigation
+state and is read again and checked active before being pre-associated); the workspace id is a context, never an
+authorisation.
+
+C4. **Form (D-R7).** Name, species, sex required; sex with no preselected value; species from the active rows only;
+the detail required for « Autre » and never sent for another species; breed optional; birth year or full date (D6b),
+a full date fills and locks the year (U3), no year turned into a date, not in the future (device date), not before
+1900; bounds and patterns from `field-limits.ts`; errors under their field, first error focused; one
+`create_request_id` per creation intent reused on a retry; `conflict` keeps the typed values and shows the stored
+ones; leave guard.
+
+C5. **Creation with a first client.** Optional; one atomic `create_animal` call carrying `client_id`,
+`relation_role` and `started_on` (never two calls); the role explicit with none preselected; the pre-associated client
+removable before saving; a lost answer retried with the same request id gives one animal and one relation.
+
+C6. **Animal page.** Identity, species, sex, breed, birth with its known precision, status; current relations then the
+history, roles, client links, phones as `tel:`, dates only when known (`ended_at` never shown as a date); « Propriétaire
+non renseigné » without a current owner, never a placeholder client; voided relations shown nowhere; actions only on an
+active animal; archive and restore through the shared dialog, archived page read-only, no client archived.
+
+C7. **Relation writes.** Add (both active, explicit role, optional start), end with an optional real date not before
+the start, correct dates, void explained as an erroneous entry and final, never a physical deletion; every write sends
+the revision it read; `duplicate_relation`, `conflict`, `already_ended`, `archived`, `limit_reached`, `rate_limited`,
+`session_expired`, `network` phrased distinctly; a stale relation (`conflict`, `not_found`) reloads the relations;
+confirmations refuse to close while pending and return focus after the change is shown, also when the opener left.
+
+C8. **Client page.** Animals from `list_client_animals` once per animal and group with every role and dates, linked to
+the animal page; « Ajouter un (premier) animal » with the client pre-associated; « Associer un animal existant » panel;
+none on an archived client; the contractual `current_animal_count` of the list unchanged; ended relations shown as
+former, voided ones nowhere.
+
+C9. **Navigation, design, accessibility.** « Animaux » after « Clients » in the sidebar and the drawer, drawer only (no
+tab bar); existing components and tokens; labels, visible focus, errors announced, heading focused on page open; 375 px
+without horizontal overflow; FR/EN key parity; the new pages pass axe without any KNOWN exception applying to their own
+elements; the two phone states scanned from the top of the page are justified in BROWSER_TESTS.md §6.
+
+C10. **Tests.** Unit (access mapping and call shapes, schema and display rules, screens: states, request id reuse,
+conflict, archive, relations, client page, session gate); the access layer against real PostgREST
+(`animals-access.sandbox.ts`); Chromium journeys `e2e/shell/animals.spec.ts` (brief §17 items 1 to 24, FR/EN, desktop
+and 375, axe, request URLs free of fixture values); existing suites green; counter-checks recorded in §11.8.
+
+C11. **Reports, docs, git.** No private data in reports, traces or logs beyond fictitious fixtures (shell suite: no
+trace, no HTML report); contract §11.8, §13.3, §14, §15, SUPABASE.md §3.3 (restore check, DEV browser acceptance),
+BROWSER_TESTS, TEST_STRATEGY, FRONTEND_ARCHITECTURE, design README, CLAUDE.md updated; commits pushed; no merge; `main`,
+`develop` and `release/0.2.0` untouched; DEV untouched (M1 to M3 still pending there).
+
+C12. **Technology boundary.** No business rule re-implemented in TypeScript that PostgreSQL already enforces beyond the
+D-R7 form checks; no artificial Rust/wasm call; the boundary choice written in §11.8.
+
+## CLARIFICATIONS
+
+- Owner brief §17 (not on disk), items 1 to 24, and where `e2e/shell/animals.spec.ts` covers them: 1 sign-in and
+ workspace (every test's `signIn` + `openAnimals`); 2 empty list, 3 creation without owner, 5 search, 6 species
+ filter, 7 consultation, 8 edit, 10 archive and restore (test « empty list, an « Autre » … restore »); 4 creation with
+ an initial relation, 11 creation from a client page, 12 linking an existing animal (« from a client page … »); 13
+ several owners, 14 normal end, 15 voiding, 16 duplicate refused (« animal page: co-owners … »); 17 two accounts, 18
+ change of session (« two accounts and a change of session »); 19 keyboard (« keyboard only »); 9 revision conflict
+ (« a concurrent edit »); 23 retry after a lost answer (« a lost answer »); 24 network errors (« failures … »); 20
+ FR/EN (every test in both languages, plus « the animal pages follow a change of language »); 21 desktop and 375
+ (both projects); 22 axe on the new pages (every state). Pagination: « pages of 25 ».
+- Restore of an archived animal is one button with no confirmation, as on the validated client page (V1-1.5); only
+ archiving is confirmed.
+- Verifier round 1 (ECARTS C10): the client journey failed intermittently on a late replay after its restore (the
+ client page now reloads its animals). Fixed: `dropLateReplays` in `e2e/support/sandbox.ts`, called after each test
+ by the three shell specs; the client journey ends on the reloaded animal section; `e2e:shell` 82/82 three runs in a
+ row.
+- Verifier round 2 (ECARTS C10): pgTAP 014 #237 « no name, role, breed or date in the audit rows » failed on the
+ long-lived sandbox: its date pattern `20[0-9]{2}-` matched a workspace uuid (`…2012-…`) in the metadata of a real
+ row (a false positive, latent since V1-1.4, that would also have stopped the owner's DEV procedure at `db:test`).
+ Authorised exception to C1 (test file only, no migration): the pattern now reads the metadata without
+ `workspace_id` (the test before it proves that key is the only one), still over every audit row; counter-checked
+ (uuid alone: false; a name or a date added: true); pgTAP 919/919 on the sandbox and on PGlite.
diff --git a/.gitignore b/.gitignore
index 499350c1..cd21f45e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,6 +30,7 @@ Thumbs.db
coverage/
playwright-report/
test-results/
+blob-report/
.nyc_output/
# Cache
@@ -69,3 +70,4 @@ packages/core-wasm/pkg-proofs/
# DEV gateway credentials (generated by scripts/dev-gateway.sh)
docker/dev-gateway/htpasswd
docker/dev-gateway/mailpit-password
+!.claude/rules/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d615e6e3..b986e4bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,10 @@ Steps 0 to 8 and the Rust migration R0 to R5 included. `release/0.2.0` (Steps
on that branch and reaches this file only if the release is finished (TODO
RR-9).
+### Fixed (2026-10-27, V1-1 DEV acceptance, RESP-01)
+
+- The dashboard no longer scrolls sideways on a phone when the account e-mail is long: the card grid has one explicit column below the `md` breakpoint, so the cards keep the screen's width, and the e-mail wraps instead of being cut (a long one was truncated on desktop and pushed the cards past a 320 to 430 px screen from about 31 characters). `e2e/shell/responsive.spec.ts` checks nine shell pages, the archive confirmations and the drawer at 320 to 430 px and on desktop, in French and English.
+
### Removed (2026-10-25, Rust R5.7: the TypeScript pipeline and domain packages)
- `packages/anatomy` (legacy importer, curation pipeline, TypeScript renderer, `import-equine` CLI) and `packages/domain` (Zod schemas and rules) are deleted, with the TypeScript upload script `packages/supabase/scripts/upload-sheet-assets.ts` and the scripts `pnpm import:equine:legacy` and `assets:upload:legacy`. The Rust core does all of it: `pnpm import:equine` and `pnpm assets:upload` are unchanged for the user. `@xmldom/xmldom` leaves the lockfile; `tsx` is no longer a dependency of any package (pnpm keeps it only as an optional peer of vite); root Prettier stays (`pnpm format`, `db:types`).
diff --git a/CLAUDE.md b/CLAUDE.md
index 4c137f25..1e4b83d1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -45,11 +45,16 @@ importer, curation, migration map, review files, seed SQL, upload tool) into the
(feature `curation`); R5.6 switched the sheet fingerprint to `sha256-rfc8785-validated-v1`;
R5.7 deleted `packages/anatomy` and `packages/domain` (`RUST.md` §11.23, test ledger
`crates/core/tests/curation/LEDGER.tsv`).
-MVP species: equine only. Open-source MIT.
+MVP species: equine only for anatomical sheets (V1-1.4 records ten species of animals; no sheet beyond the equine draft). Open-source MIT.
Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1-2 sheets from Supabase,
V1-3 cloud bilans, V1-4 stored PDF and sharing, V1-5 mobile and accessibility pass
(`docs/development/IMPLEMENTATION_PLAN.md` §0; V1-1 contract `docs/development/V1-1_OWNERS_ANIMALS.md`:
-owner orientations proposed, awaiting ratification; nothing built).
+business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on
+`feature/v1-1-clients-animals` V1-1.1 to V1-1.5 (validated) and V1-1.6 are built: migrations `20261025100000_workspaces.sql`,
+`20261025110000_clients.sql` and `20261026100000_animals_relations.sql` (contract §8.3), tested on PGlite and the isolated stack
+`pnpm db:sandbox`, not applied to Supabase DEV; V1-1.3 the native modal dialog (D13) and the Playwright + axe suites
+(D14, `docs/development/BROWSER_TESTS.md`); V1-1.5 the client screens (`/app/clients`, contract §11.7) and V1-1.6
+the animal screens and the relations (`/app/animals`, contract §11.8; D11: drawer only, no tab bar) on the isolated stack).
---
@@ -69,6 +74,7 @@ owner orientations proposed, awaiting ratification; nothing built).
| SVG raster | native Image/canvas (no dependency) | — |
| Animation | motion | 11 |
| Tests | vitest + happy-dom + @testing-library/react | 3.x |
+| Browser tests | @playwright/test (Chromium 1248) + @axe-core/playwright, pinned dev deps of apps/app (`docs/development/BROWSER_TESTS.md`) | 1.64.1 / 4.14.0 |
| Backend | Supabase (PostgreSQL 17, GoTrue, PostgREST) — CLI pinned as root devDependency | CLI 2.120 |
| DB client | @supabase/supabase-js (packages/supabase) | 2.x |
| SQL tests | pgTAP under supabase/tests, run by `supabase test db` and by PGlite (Dockerless) | PGlite 0.3 |
@@ -121,6 +127,7 @@ pnpm db:reset # replay from zero
pnpm db:test # pgTAP on the real stack
pnpm db:types # regenerate packages/supabase/src/database.types.ts
pnpm db:types:check # CI diff
+pnpm db:sandbox up fresh|up upgrade []|test-db|types [--check]|test|e2e-shell|down # throwaway stack (SUPABASE.md §5.1): migrations tested without touching DEV
# Reference sheet in the app: the dev server bundles the curated draft; a build does not
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
@@ -143,40 +150,20 @@ pnpm worker:image # Docker only: runtime image faunosteo_worker:dev (distro
pnpm e2e:avatar # scripts/avatar-e2e.sh: worker container against the local stack + packages/supabase/tests/e2e (real-stack avatar flow)
```
-## Docker commands
-
-```bash
-# Build image
-docker build -t faunosteo .
-
-# Build an image that embeds the reference DRAFT sheet (preview only, never the default)
-docker build --build-arg SHEET_BUNDLE=draft -t faunosteo .
-
-# Run with compose (reads .env for APP_* vars)
-docker compose up --build
-
-# Stop
-docker compose down
-```
-
-Naming convention: every Docker resource Faunosteo owns is prefixed `faunosteo_`
-when the name is configurable (container `faunosteo_app`, Compose project
-`faunosteo`); the Supabase CLI imposes `supabase__faunosteo`, documented
-as a limit in DEPLOY.md "Docker resource naming". Never rename a resource that
-holds data without keeping its volume.
-
-Note: no global pnpm needed. `corepack enable` once (reads `packageManager`),
-or call `corepack pnpm `. Root scripts resolve `node_modules/.bin/pnpm`.
-
----
-
## Test commands
```bash
pnpm test:run # vitest run — all tests, single pass, CI-safe
pnpm test # vitest watch — dev loop
+pnpm e2e:ui # Playwright Chromium, no backend: Dialog test page + local tool dialogs, desktop + 375 px, axe (in check:all when the pinned Chromium is installed)
+pnpm e2e:shell # Playwright Chromium against `pnpm db:sandbox` (must be up): sign-in, dashboard, photo confirmation, phone drawer, client, animal and relation journeys; never DEV (`pnpm db:sandbox e2e-shell [--grep]` for one file)
```
+Browser suites (`apps/app/e2e`, `docs/development/BROWSER_TESTS.md`): Chromium only until V1-5,
+`pnpm --filter @faunosteo/app exec playwright install chromium` once (no sudo, never `--with-deps`);
+loopback dev servers of their own (5191, 5192, `--strictPort`, never reused); every request outside the
+suite's allowlist is aborted and fails the test; the shell suite keeps no trace (session tokens).
+
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. The 612 legacy catalog leaves run through the v2 → v3 migration
in the core (`crates/core/tests/curation_leaves.rs`, against the draft document) and the app (sheet index + PDF roundtrip). Setup: `apps/app/tests/setup.ts` imports
@@ -210,7 +197,10 @@ faunosteo/
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
│ │ ├─ routes/auth/{Login,Signup,ForgotPassword,ResetPassword,AuthCallback}Route.tsx
│ │ ├─ routes/app/{Dashboard,Account}Route.tsx ← behind RequireAuth, inside AppLayout
-│ │ ├─ guards/{RequireAuth,RedirectIfSignedIn,SessionLoading}.tsx
+│ │ ├─ routes/app/clients/{ClientsList,ClientCreate,ClientDetail,ClientEdit}Route.tsx ← V1-1.5, behind RequireWorkspace
+│ │ ├─ routes/app/animals/{AnimalsList,AnimalCreate,AnimalDetail,AnimalEdit}Route.tsx ← V1-1.6, same RequireWorkspace; the first client arrives in the navigation state, never the URL
+│ │ ├─ guards/{RequireAuth,RedirectIfSignedIn,SessionLoading,RequireWorkspace}.tsx ← RequireWorkspace: personal workspace ready, remount per workspace, species labels (SpeciesProvider)
+│ │ ├─ useLeaveGuard.ts + usePageHeading.ts ← unsaved changes (beforeunload + in-app links via AppLayout); heading focus on page open
│ │ └─ providers/{ConfigProvider,AuthProvider}.tsx ← AppConfig context; session + locale sync start
│ ├─ auth/{validation,redirects,useAuthFailureMessage}.ts ← Zod schemas (i18n keys), safe next path, failure phrasing
│ ├─ account/{validation,useProfileForm}.ts ← account section schemas + one-save form hook
@@ -226,13 +216,17 @@ faunosteo/
│ │ ├─ index.ts ← getDict(locale)
│ │ └─ useT.ts ← useT() hook (reads localeStore)
│ ├─ state/
-│ │ ├─ authStore.ts ← session, user, profile, roles, recovery flag (onAuthStateChange)
+│ │ ├─ authStore.ts ← session, user, profile, roles, recovery flag, personal workspace state (onAuthStateChange; reset on account change)
+│ │ ├─ leaveGuardStore.ts ← armed while a page holds unsaved changes
│ │ ├─ reportStore.ts ← Zustand store (Report v3, core-built reports, actions answer { ok }) + persistence.ts (raw texts, quarantine keys)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
+│ ├─ clients/{validation,countries,useClientForm,useClientList,useClientRecord}.ts ← client form schema on field-limits (D-R7), ISO list, page-local hooks
+│ ├─ animals/{validation,age,species,useAnimalForm,useAnimalList,useAnimalRecord}.ts(x) ← animal form schema (D-R7, U3 birth, no default sex or role), display age, species context
+│ ├─ relations/{groups,choices,useAnimalRelations}.ts ← an animal's relations (current / former), stable picker searches
│ ├─ anatomy/drawing.ts ← the core's composed view (`view.canvas`) → DOMParser → importNode (R3; no sanitiser here)
│ ├─ components/
-│ │ ├─ ui/{Button,ButtonLink,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Icon,FormField,Notice}.tsx
+│ │ ├─ ui/{Button,ButtonLink,Card,Dialog,ModalDialog,Input,Label,Select,Textarea,Badge,Chip,ChoiceRadios,Icon,FormField,Notice}.tsx ← ModalDialog: native showModal (D13), Dialog and MobileDrawer on it
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
@@ -241,6 +235,9 @@ faunosteo/
│ │ │ ConclusionPanel,NextAppointmentPicker,CoreUnavailable,HeldSessionPanel,ReplaceSessionDialog}.tsx
│ │ ├─ brand/{Brand,AppHeader,Footer,LanguageSwitcher,HomeSpaceLink}.tsx
│ │ ├─ auth/{AuthLayout,OAuthButtons,PasswordField,UnavailableNotice,AuthLink}.tsx
+│ │ ├─ clients/{ClientForm,ClientAnimals,ArchiveClientDialog,ClientNotFound}.tsx
+│ │ ├─ animals/{AnimalForm,ArchiveAnimalDialog,AnimalNotFound}.tsx
+│ │ ├─ relations/{AnimalRelations,RelationPanel,RelationActionDialog,RelationDialogs,RecordPicker,Pickers}.tsx ← in-page link panel, end / dates / void confirmations
│ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx
│ │ └─ account/{SectionCard,SaveRow,AvatarSection,PersonalInfoForm,ProfessionalInfoForm,PreferencesForm,SecurityPanel,RoleBadges}.tsx
│ ├─ account/avatarTransport.ts ← magic-byte sniff (never SVG), createImageBitmap → canvas ≤ 1024 px → JPEG transport blob
@@ -253,6 +250,7 @@ faunosteo/
├─ tests/
│ ├─ setup.ts
│ └─ unit/*.test.ts
+├─ e2e/ ← Playwright (V1-1.3): playwright.{ui,shell}.config.ts, support/{browser,sandbox,shell,records}.ts, ui/*.spec.ts, shell/*.spec.ts, harness/dialog.{html,tsx} (dev server only, never built)
├─ docker/
│ ├─ entrypoint.sh ← injects env.js at container start
│ └─ nginx.conf ← SPA fallback + PORT envsubst
@@ -269,11 +267,12 @@ faunosteo/
│ (packages/domain and packages/anatomy deleted at R5.7: their sources resolve at 756b7ef, crates/core/tests/curation/{FILES,LEDGER}.tsv)
├─ packages/supabase/ ← @faunosteo/supabase
│ ├─ src/{index,client,database.types,anatomical-sheets,assets}.ts ← typed client, generated types, publish gate, avatar flow (closed AssetFailure kinds)
+│ ├─ src/{records,workspaces,clients,species,animals,relations,field-limits}.ts ← V1-1 record access (closed RecordFailure kinds, keyset pages), D-R7 bounds
│ ├─ tests/e2e/avatar-flow.e2e.ts + vitest.e2e.config.ts ← real-stack end-to-end (`pnpm e2e:avatar`), skipped without the stack env
│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test
├─ supabase/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
-│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs)
+│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets, storage, sheet_document_schema_v2, profiles_professional, files_foundation (assets, buckets, avatar policies, purge queue, RPCs), workspaces (V1-1.1: personal workspace per account, access helpers), clients (V1-1.2: client RPCs and search, write budget per workspace), animals_relations (V1-1.4: species rows, animals, relations with history and voiding, their RPCs and reads)
│ ├─ seed/anatomical-sheets/equine/
│ │ ├─ legacy-sources/ ← the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input, never edited)
│ │ ├─ legacy-import/ ← GENERATED baseline: document, id map, IMPORT-REPORT, SVG copies (no SQL)
@@ -390,16 +389,6 @@ Database (Supabase)
- Code: English (variable names, function names, comments, docs)
- Never mix: no French variable names, no raw French/English string literals in JSX — use `useT()`
-### i18n
-- All user-facing strings live in `src/i18n/fr.ts` and `src/i18n/en.ts` (flat `Record`)
-- Key convention: ` .` — e.g. `common.cancel`, `home.new_report.title`, `pdf.subject`
-- Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV
-- Get the translate function in any component: `const t = useT()` then `t('common.cancel')`
-- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match; while signed in, `services/localeSync.ts` writes it to `profiles.locale` and applies the account locale on sign-in
-- Form validation messages are i18n keys returned by the Zod schemas (`src/auth/validation.ts`, `src/account/validation.ts`), translated next to the field; GoTrue messages never reach the screen (`auth.failure.*`)
-- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
-- PDF static labels (section headings, metadata) live in `apps/app/src/pdf/labels.ts` (`defaultPdfLabels`, 25 keys, moved verbatim from the engine at R4.6) and are archived in the envelope; the app dicts hold no `pdf.*` key
-
### Identity strings
- NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE
- Always read from ConfigProvider via useConfig()
@@ -408,107 +397,6 @@ Database (Supabase)
### Design references
- `docs/design/` holds the owner-validated mockups (Step 7 file = target for the whole SaaS shell: sidebar entries, dashboard tiles, Mon compte tabs, mobile tab bar). Any new screen follows them; elements they show that no step has built yet are listed in `docs/design/README.md` with their owning step. A redesign needs a new validated file there first.
-### Annotation rendering
-- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the markers are
- drawn from the document (the Rust core, `crates/core/src/anatomy`, for the canvas since R3, the PDF since R4 and
- the pipeline's review drawings since R5), with the attributes listed there
-- Every SVG the product draws goes through the core's one reader (`anatomy::svg::read_svg`): caps before any parse,
- allowlist, reference graph; a product drawing with anything removed is refused at load, never repaired
-- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
- and the annotation's fields (`laterality`, `vertebral_region_code`, `opens_view_id`)
-- Marker look (radii, opacities, strokes) is renderer style; colours are document data (`color` on categories
- and annotations); no graphic redesign without prior validation
-
-### Schemas
-- The data contracts live in Rust since R2 (`crates/core/src/domain/{sheet,report,archive}`, Zod semantics
- reproduced: strict where Zod was strict, optional absent, nullable required, Zod schema field order);
- `packages/domain` was deleted at R5.7; its byte-identical Zod copy under `packages/core-wasm/tests/n-1` is the
- permanent N-1 reader. Never change a contract
- without bumping the version on a breaking change (additive optional fields keep it); a change touches the
- Rust struct, the regenerated ts-rs types and the N-1 test
-- Every report entering the store comes from the core (new report, draft restore, import, reducer outputs);
- form values are plain assignments (D-R7)
-- Report version 3: zones by `(annotationId, viewId)`, findings by `(findingZoneId, path)`, severities
- `mild|moderate|severe`, `sheet` reference; v2 is migrated through `report-migration-map.json`
- (`migrateReportV2ToV3`, never throws on content, `unresolved: true` marks what the sheet no longer holds);
- v1 and unknown versions are refused with a typed error
-
-### Stores
-- No direct store mutation outside Zustand actions
-- No business logic in components — delegate to store actions
-- sessionStorage keys: osteo:draft (auto-saved on every change, v3; a v2 draft is migrated and a stale draft rebased on restore once the sheet is loaded, by the core) and osteo:archive (the imported archive envelope, written only on import / new report / reset, never on edits); osteo:quarantine:{draft,archive} (an unreadable text set aside, a draft with its archive, an occupied slot never replaced, never dropped) and osteo:quarantine:draft-pre-rebase (the raw draft of a rebase that flagged items); a text whose set-aside fails is held in place (resolution panel, no new session over it), never removed or overwritten implicitly
-- localStorage key: osteo:lastPractitioner (practitioner prefill cache)
-
-### PDF
-- A4 portrait: 595.28 × 841.89 pt
-- No raw URLs in PDF output — abbreviated citations only
-- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report
-- The writer (`crates/core/src/pdf/write`, since R4.6; the TypeScript engine deleted at R4.8) takes no clock and no I/O; rasterisation is the browser's, one raster per core request; every SVG it composes went through the core's one reader. The export is an incremental session (OD-2): the file is written as the rasters arrive, held once, handed out in parts; never accumulate rasters or build the file twice
-- Page layout is frozen by the Step 6 goldens and the R4 oracles (O1 draw logs, O2 PDFs): any visible change needs a user decision and a golden regeneration; the R4 digests (`goldens/r4/pdf.*.sha256`) pin the writer's own bytes and are rewritten only for a declared structural change, with the O2 comparisons re-run
-- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
-
-### Anatomical sheet content
-- The findings catalog, the vertebral regions and the markers are the canonical sheet document; every content
- change goes through `supabase/seed/anatomical-sheets/equine/curation/changes.json` (see the sheet model section)
-- The curated draft is the reference content in development (`SHEET_BUNDLE=draft`); it is not medically
- validated and a production build carries no sheet unless that flag is set on purpose
-
-### Database (Supabase)
-- The auth session lives in the Supabase client (localStorage, PKCE); the app reads it through `state/authStore.ts` only. Profile columns the user may edit are the column grants in the profiles migrations; never widen them from the client.
-- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
- statuses (practitioner/student/professor come from verification, cabinet roles from
- organization_members). Never add a professional status to `platform_role`.
-- Every `public` table: RLS enabled, `revoke all` from API roles then exact grants,
- separate policies per command, no `using (true)` for anon/authenticated (test-enforced).
-- Writes that change privileges or sensitive state go through a security-definer RPC
- that checks `auth.uid()` and calls `private.log_event()`. Never a direct table policy.
-- Helpers in `private` are `security definer`, `set search_path = ''`, EXECUTE revoked
- from public and granted only to the roles that evaluate them.
-- A migration is never edited once applied. Each migration ships its pgTAP file with
- allowed AND denied cases, and a regenerated `database.types.ts`.
-- The browser holds the anon key only. The `service_role` key value never appears in env.js, .env.example or code;
- operator scripts under `packages/*/scripts/` read it from the environment and are never bundled.
-- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
-
-### Environments and LAN access (docs/development/ENVIRONMENTS.md)
-- The owner tests from other devices of the private network, never on the Ubuntu machine: every test surface
- (app, Supabase API, Mailpit, Studio) is addressed by the DEV origin (`scripts/dev-env.sh`, `FAUNOSTEO_DEV_HOST`),
- never by `127.0.0.1` / `localhost`, never hard-coded in a source. The Supabase CLI runs only through
- `scripts/supabase.sh` (`pnpm db:*`, `pnpm supabase`): config.toml reads the origin with `env()`.
-- Exposure (least privilege, `pnpm dev:net-check`): LAN gets Vite 5173, the Supabase API 54321 and Mailpit
- behind basic auth through the DEV gateway (`pnpm dev:gateway`, nginx, `faunosteo_dev_gateway`, 54325). The CLI
- forces 0.0.0.0 on 54322 PostgreSQL, 54323 Studio, 54324 raw Mailpit: closed on the LAN interface by host UFW
- rules (owner action, ENVIRONMENTS.md §3.2); SSH tunnel for Studio; the worker publishes no port. Nothing is exposed to the Internet; no production infrastructure
- is touched from this repository. Rust is built natively; Docker runs services, the worker, sandbox tests and images.
-
-### Files and Storage (migration 20261013100000, docs/development/STORAGE.md)
-- `public.assets` is the authority over every user file: status, owner, keys, lease. Every write is an RPC; the browser
- reads its own rows through an explicit column list (`select=*` is refused: lease columns are not granted).
-- Object keys are server-built from uuids (`profiles///avatar.webp`, `quarantine///upload`);
- policies on `storage.objects` compare whole strings through `assets` and pin one bucket literal each (census test).
- A quarantine object is never readable by an API role; a final key is never writable by the browser.
-- New buckets stay closed (row only, no policy) until their step writes the rules; `anatomical-sheet-assets` keeps its own policy.
-- The worker holds the service key; the decode child has an empty environment, no file, no network, and is the only
- process that decodes untrusted bytes. The parent checks the container header only. Rejections are closed codes.
-- Deletions are row-driven: terminal rows enqueue their keys (48 h / 1 h grace), the sweeper serves the queue and the
- quarantine leftovers; a clean row's object is never deleted. Backups: dump first, files within 48 h.
-- Avatar UI follows the validated mockup: photo in Mon compte (Informations personnelles), sidebar, drawer and top bar
- link to Mon compte; JPEG / PNG / WebP only, never SVG; no signed URL for the owner-only avatar (download under RLS).
-
-### Anatomical sheet model (crates/core/src/domain/sheet + migration 20261008110000)
-- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs.
-- Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the
- explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime.
-- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then
- `publish_sheet_version`. Integrity rule codes are shared by `validate_sheet_document` (Rust core) and
- `private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table.
-- Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`.
-- Official equine sheet = generated seed `draft/` (`pnpm import:equine --out` into an empty folder, then reviewed and copied; never edit `legacy-import/` or `draft/` by hand;
- `curation_draft` / `curation_review` fail on drift, `pnpm import:equine --check` lists it). Every content change goes through `curation/changes.json` (traced in CHANGELOG.md).
- It is a DRAFT until a platform admin publishes it after business review of `REVIEW-REPORT.md`.
-- Sheet SVG bytes live in Storage bucket `anatomical-sheet-assets` as `.svg`; uploads are an operator task
- (`pnpm assets:upload ` with the service key in env), never from the browser.
-
### Component stubs
- Scaffold stubs render ComponentName placeholder
- Replace stub body entirely when implementing — no partial edits on stubs
@@ -612,3 +500,7 @@ Examples:
- `test(schema): cover Report version literal`
- `feat(store): implement addObservation`
- `feat(anatomy): parse data-anno-id from SVG`
+
+## Path-scoped rules
+Project rules live in `.claude/rules/.md` and load on Read of a file
+matching their `paths:` (never at session start): docker, i18n, annotation-rendering, schemas, stores, pdf, sheet-content, database, environments, storage, sheet-model.
diff --git a/README.md b/README.md
index edd3c01c..b82a902b 100644
--- a/README.md
+++ b/README.md
@@ -39,12 +39,12 @@ Q2):
Planned, not implemented (roadmap in
`docs/development/IMPLEMENTATION_PLAN.md` §0): V1-1 clients and animals (its
-contract awaits the owner's ratification), V1-2 sheets served from Supabase,
-V1-3 bilans stored in the cloud with history, V1-4 stored PDFs and authorised
-sharing, V1-5 mobile and accessibility pass; then professional verification,
-cabinets, entitlements, agenda, public site and the rest of the plan. Nothing
-on `develop` authorises a release: the release readiness track (TODO RR-1 to
-RR-10) comes first.
+business decisions ratified, technical design awaiting validation), V1-2
+sheets served from Supabase, V1-3 bilans stored in the cloud with history,
+V1-4 stored PDFs and authorised sharing, V1-5 mobile and accessibility pass;
+then professional verification, cabinets, entitlements, agenda, public site and
+the rest of the plan. Nothing on `develop` authorises a release: the release
+readiness track (TODO RR-1 to RR-10) comes first.
---
diff --git a/apps/app/e2e/harness/dialog.html b/apps/app/e2e/harness/dialog.html
new file mode 100644
index 00000000..a4009d0e
--- /dev/null
+++ b/apps/app/e2e/harness/dialog.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+ Dialog harness
+
+
+
+
+
+
diff --git a/apps/app/e2e/harness/dialog.tsx b/apps/app/e2e/harness/dialog.tsx
new file mode 100644
index 00000000..62b15716
--- /dev/null
+++ b/apps/app/e2e/harness/dialog.tsx
@@ -0,0 +1,134 @@
+/**
+ * Test page for the shared Dialog in a real browser (e2e/ui/dialog.spec.ts).
+ * Served by the Vite dev server only (`/e2e/harness/dialog.html`); the build
+ * has a single entry, index.html, so this page never ships. Each scenario is a
+ * case of the D13 contract, not a product journey: `?lang=en` picks the language.
+ */
+import { StrictMode, useState } from 'react'
+import { createRoot } from 'react-dom/client'
+import '@/styles/index.css'
+import Button from '@/components/ui/Button'
+import Dialog from '@/components/ui/Dialog'
+import { useLocaleStore } from '@/state/localeStore'
+import type { Locale } from '@/i18n/types'
+
+const lang: Locale =
+ new URLSearchParams(location.search).get('lang') === 'en' ? 'en' : 'fr'
+useLocaleStore.setState({ locale: lang })
+document.documentElement.lang = lang
+
+type Scenario = 'basic' | 'long' | 'guarded' | 'vanishing' | null
+
+function Background({ onOpen }: { onOpen: (scenario: Scenario) => void }) {
+ const [clicks, setClicks] = useState(0)
+ return (
+
+ )
+}
+
+function Harness() {
+ const [scenario, setScenario] = useState(null)
+ const [busy, setBusy] = useState(true)
+ const [item, setItem] = useState(true)
+ const close = () => setScenario(null)
+ return (
+
+ Dialog harness
+
+
+ setItem(true)}>
+ Add item
+
+ {item && (
+ setScenario('vanishing')}>
+ Remove item
+
+ )}
+
+ {/* Taller than any viewport: the page would scroll if the dialog let it. */}
+
+
+ Three controls follow.
}
+ >
+
+ First
+ Second
+ Done
+
+
+
+
+ {Array.from({ length: 60 }, (_, i) => (
+
+ Paragraph {i + 1}: long content that the panel scrolls on its own.
+
+ ))}
+ End of content
+
+
+ !busy && close()}
+ title="Guarded dialog"
+ description={Closing is refused while the box is checked.
}
+ >
+
+ setBusy(e.target.checked)}
+ />
+ Busy
+
+
+
+ The button that opened this dialog disappears.}
+ size="sm"
+ >
+
+ {
+ setItem(false)
+ close()
+ }}
+ >
+ Confirm removal
+
+
+
+
+ )
+}
+
+createRoot(document.getElementById('root') as HTMLElement).render(
+
+
+ ,
+)
diff --git a/apps/app/e2e/playwright.shell.config.ts b/apps/app/e2e/playwright.shell.config.ts
new file mode 100644
index 00000000..a05cad07
--- /dev/null
+++ b/apps/app/e2e/playwright.shell.config.ts
@@ -0,0 +1,49 @@
+/**
+ * `pnpm e2e:shell` (scripts/db-sandbox.sh e2e-shell): the authenticated /app
+ * shell in Chromium against the isolated stack of `pnpm db:sandbox`, never DEV.
+ * The dev server is built with a Supabase URL that resolves nowhere and runs
+ * on a loopback port of its own; e2e/support/sandbox.ts replays its calls on
+ * the sandbox. No trace and no HTML report are kept: they would hold the
+ * session tokens and the typed passwords.
+ */
+import { defineConfig } from '@playwright/test'
+import type { GuardOptions } from './support/browser'
+import { PROJECTS } from './support/browser'
+
+const ORIGIN = 'http://127.0.0.1:5192'
+const FAKE_SUPABASE_ORIGIN = 'http://sandbox.faunosteo.invalid'
+const anonKey = process.env.SANDBOX_ANON_KEY
+if (!anonKey)
+ throw new Error(
+ 'SANDBOX_ANON_KEY missing: run pnpm e2e:shell (the sandbox must be up)',
+ )
+
+export default defineConfig({
+ testDir: './shell',
+ outputDir: './test-results/shell',
+ fullyParallel: true,
+ forbidOnly: true,
+ retries: 0,
+ // No HTML report: its step titles would keep what the test typed, the
+ // fictitious accounts' passwords included. The terminal and the failure
+ // screenshots stay.
+ reporter: [['list']],
+ use: {
+ baseURL: ORIGIN,
+ allowedOrigins: [ORIGIN, FAKE_SUPABASE_ORIGIN],
+ trace: 'off',
+ screenshot: 'only-on-failure',
+ },
+ projects: PROJECTS,
+ webServer: {
+ command: 'node_modules/.bin/vite --host 127.0.0.1 --port 5192 --strictPort',
+ cwd: '..',
+ url: `${ORIGIN}/`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ env: {
+ VITE_SUPABASE_URL: FAKE_SUPABASE_ORIGIN,
+ VITE_SUPABASE_ANON_KEY: anonKey,
+ },
+ },
+})
diff --git a/apps/app/e2e/playwright.ui.config.ts b/apps/app/e2e/playwright.ui.config.ts
new file mode 100644
index 00000000..4b61a066
--- /dev/null
+++ b/apps/app/e2e/playwright.ui.config.ts
@@ -0,0 +1,40 @@
+/**
+ * `pnpm e2e:ui`: Chromium against a Vite dev server with no backend, on a
+ * loopback port of its own (never the owner's `pnpm dev` on 5173, never
+ * reused): the Dialog test page and the local tool. docs/development/BROWSER_TESTS.md.
+ */
+import { defineConfig } from '@playwright/test'
+import type { GuardOptions } from './support/browser'
+import { PROJECTS } from './support/browser'
+
+const ORIGIN = 'http://127.0.0.1:5191'
+
+export default defineConfig({
+ testDir: './ui',
+ // The local tool runs the core: a missing or stale module stops the run (pnpm wasm:build).
+ globalSetup: '../../../packages/core-wasm/tests/global-setup.ts',
+ outputDir: './test-results/ui',
+ fullyParallel: true,
+ forbidOnly: true,
+ retries: 0,
+ reporter: [
+ ['list'],
+ ['html', { outputFolder: './playwright-report/ui', open: 'never' }],
+ ],
+ use: {
+ baseURL: ORIGIN,
+ allowedOrigins: [ORIGIN],
+ trace: 'retain-on-failure',
+ screenshot: 'only-on-failure',
+ },
+ projects: PROJECTS,
+ webServer: {
+ command: 'node_modules/.bin/vite --host 127.0.0.1 --port 5191 --strictPort',
+ cwd: '..',
+ url: `${ORIGIN}/`,
+ reuseExistingServer: false,
+ timeout: 120_000,
+ // No backend: an empty connection keeps any .env value out of this server.
+ env: { VITE_SUPABASE_URL: '', VITE_SUPABASE_ANON_KEY: '' },
+ },
+})
diff --git a/apps/app/e2e/shell/animals.spec.ts b/apps/app/e2e/shell/animals.spec.ts
new file mode 100644
index 00000000..a5884d48
--- /dev/null
+++ b/apps/app/e2e/shell/animals.spec.ts
@@ -0,0 +1,1031 @@
+import { randomUUID } from 'node:crypto'
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import type { Dict } from '@/i18n/types'
+import { formatDate } from '@/lib/dates'
+import type { Locator, Page, TestInfo } from '@playwright/test'
+import { sql } from '../../../../packages/supabase/tests/sandbox/stack'
+import {
+ expect,
+ expectAccessible,
+ expectNoHorizontalOverflow,
+ test,
+} from '../support/browser'
+import {
+ createAccount,
+ dropLateReplays,
+ routeToSandbox,
+ sandboxUrl,
+} from '../support/sandbox'
+import {
+ literal,
+ seedAnimal,
+ seedClient,
+ seedRelation,
+} from '../support/records'
+import { signIn } from '../support/shell'
+
+// V1-1.6 animals and relations on the isolated stack: contract §11.2 journeys
+// 1 to 7 and the owner brief's list (empty list, creation with and without a
+// client, search, species filter, edit, concurrent edit, archive and restore,
+// first animal from a client page, linking an existing animal, co-owners, the
+// end and the voiding of a relation, a refused duplicate, two accounts, a
+// change of session, keyboard only, a retry after a lost answer, network
+// failures, a change of language), in FR and EN, desktop and 375 px, axe on
+// every state. Every fixture is fictitious and made per test.
+
+const LANGUAGES = [
+ ['fr', fr],
+ ['en', en],
+] as const
+
+const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
+const tagOf = () => randomUUID().slice(0, 8)
+
+/** Follows an entry of the shell's navigation: the sidebar, or the drawer on a phone. */
+async function navigate(page: Page, dict: Dict, info: TestInfo, key: string) {
+ if (isPhone(info)) {
+ await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
+ await page
+ .getByRole('dialog', { name: dict['shell.nav_label'] })
+ .getByRole('navigation')
+ .getByRole('link', { name: dict[key] })
+ .click()
+ } else {
+ await page
+ .getByRole('navigation', { name: dict['shell.nav_label'] })
+ .getByRole('link', { name: dict[key] })
+ .click()
+ }
+}
+
+async function openAnimals(page: Page, dict: Dict, info: TestInfo) {
+ await navigate(page, dict, info, 'shell.nav.animals')
+ await expect(page).toHaveURL(/\/app\/animals$/)
+ await expect(heading(page, dict['animals.list.title'])).toBeFocused()
+}
+
+async function signOut(page: Page, dict: Dict, info: TestInfo) {
+ if (isPhone(info)) {
+ await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
+ await page
+ .getByRole('dialog', { name: dict['shell.nav_label'] })
+ .getByRole('button', { name: dict['shell.sign_out'] })
+ .click()
+ } else {
+ await page.getByRole('button', { name: dict['shell.sign_out'] }).click()
+ }
+ await expect(page).toHaveURL(/\/$/)
+}
+
+const heading = (page: Page, name: string) =>
+ page.getByRole('main').getByRole('heading', { level: 1, name })
+
+const listRows = (page: Page, dict: Dict) =>
+ page
+ .getByRole('list', { name: dict['animals.list.results_label'] })
+ .getByRole('listitem')
+
+const relationsCard = (page: Page) =>
+ page.locator('section[aria-labelledby="animal-relations-title"]')
+
+/** The accessible name of a relation action: « Terminer : Marie Dupont, propriétaire ». */
+const actionName = (
+ dict: Dict,
+ action: string,
+ client: string,
+ roleKey: string,
+) =>
+ dict['relations.action_named']
+ .replace('{action}', dict[action])
+ .replace('{name}', client)
+ .replace('{role}', dict[roleKey].toLowerCase())
+
+/** Picks a record in the in-page search of a relation panel or of the form. */
+async function pick(scope: Page | Locator, label: string, term: string) {
+ await scope.getByRole('searchbox', { name: label }).fill(term)
+ await scope.getByRole('button', { name: new RegExp(`^${term}`) }).click()
+}
+
+const count = (query: string) => sql(`select count(*) from ${query}`)
+
+/**
+ * axe from the top of the page: a state reached at the bottom of a phone page
+ * leaves the first controls under the sticky top bar, which axe's target-size
+ * rule measures as cut; at rest on the page nothing sits under the bar.
+ */
+async function expectAccessibleFromTop(page: Page, state: string) {
+ await page.evaluate(() => window.scrollTo(0, 0))
+ await expectAccessible(page, state)
+}
+
+for (const [locale, dict] of LANGUAGES) {
+ test.describe(`animals (${locale})`, () => {
+ test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
+ test.beforeEach(async ({ context }) => {
+ await routeToSandbox(context)
+ })
+ test.afterEach(async ({ context }) => {
+ await dropLateReplays(context)
+ })
+
+ test('empty list, an « Autre » with no owner, search, species filter, edit, archive, archived filter, restore', async ({
+ page,
+ requests,
+ }, info) => {
+ const tag = tagOf()
+ const name = `Furet Fictif ${tag}`
+ const horse = `Cheval Témoin ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ horse,
+ tag,
+ 'Furet',
+ 'Albinos',
+ )
+ await signIn(page, account, dict)
+ await openAnimals(page, dict, info)
+ await expect(page.getByText(dict['animals.list.empty'])).toBeVisible()
+ await expectAccessible(page, 'the empty animal list')
+ await expectNoHorizontalOverflow(page, 'the empty animal list')
+
+ await page.getByRole('link', { name: dict['animals.list.new'] }).click()
+ await expect(page).toHaveURL(/\/app\/animals\/new$/)
+ await expect(
+ heading(page, dict['animals.form.create_title']),
+ ).toBeFocused()
+ for (const sex of ['male', 'female', 'unknown'])
+ await expect(
+ page.getByRole('radio', {
+ name: dict[`animals.sex.${sex}`],
+ exact: true,
+ }),
+ ).not.toBeChecked()
+ const species = page.getByRole('combobox', {
+ name: dict['animals.form.species'],
+ })
+ await expect(species).toHaveValue('')
+ await expectAccessible(page, 'the new animal form')
+ await expectNoHorizontalOverflow(page, 'the new animal form')
+
+ await page.getByLabel(dict['animals.form.name']).fill(name)
+ await species.selectOption('other')
+ await page.getByLabel(dict['animals.form.species_detail']).fill('Furet')
+ await page
+ .getByRole('radio', { name: dict['animals.sex.unknown'], exact: true })
+ .check()
+ const year = page.getByLabel(dict['animals.form.birth_year'])
+ const date = page.getByLabel(dict['animals.form.birth_date'])
+ await year.fill('2020')
+ await date.fill('2021-06-15')
+ await expect(year).toHaveValue('2021')
+ await expect(year).toHaveAttribute('readonly', '')
+ await date.fill('')
+ await expect(year).toHaveValue('2021')
+ await expect(year).not.toHaveAttribute('readonly', '')
+ await date.fill('2021-06-15')
+ await expectAccessible(page, 'the filled animal form')
+ await page
+ .getByRole('button', { name: dict['animals.form.submit_create'] })
+ .click()
+
+ await expect(page).toHaveURL(/\/app\/animals\/[0-9a-f-]{36}$/)
+ await expect(heading(page, name)).toBeFocused()
+ await expect(page.getByText(dict['animals.detail.created'])).toBeVisible()
+ const main = page.getByRole('main')
+ await expect(main).toContainText(
+ `${locale === 'fr' ? 'Autre' : 'Other'} (Furet)`,
+ )
+ await expect(main).toContainText(
+ dict['animals.detail.birth_on'].replace(
+ '{date}',
+ formatDate('2021-06-15', locale),
+ ),
+ )
+ await expect(page.getByText(dict['animals.no_owner'])).toBeVisible()
+ await expect(page.getByText(dict['relations.none'])).toBeVisible()
+ await expectAccessible(page, 'the animal page')
+ await expectNoHorizontalOverflow(page, 'the animal page')
+
+ await page
+ .getByRole('link', { name: dict['animals.detail.edit'] })
+ .click()
+ await expect(page.getByLabel(dict['animals.form.name'])).toHaveValue(name)
+ await expect(
+ page.getByRole('radio', {
+ name: dict['animals.sex.unknown'],
+ exact: true,
+ }),
+ ).toBeChecked()
+ await page.getByLabel(dict['animals.form.breed']).fill('Albinos')
+ await page
+ .getByRole('button', {
+ name: dict['animals.form.submit_update'],
+ exact: true,
+ })
+ .click()
+ await expect(page.getByText(dict['animals.detail.updated'])).toBeVisible()
+ await expect(main).toContainText('Albinos')
+
+ await seedAnimal(account, horse)
+ await page
+ .getByRole('link', { name: dict['animals.detail.back'] })
+ .click()
+ await expect(listRows(page, dict)).toHaveCount(2)
+ const search = page.getByRole('searchbox', {
+ name: dict['animals.list.search_label'],
+ })
+ await search.fill(`furet fictif ${tag}`)
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(name)
+ await expect(listRows(page, dict).first()).toContainText(
+ dict['animals.no_owner'],
+ )
+ await search.fill('albinos')
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await search.fill('')
+ const filter = page.getByRole('combobox', {
+ name: dict['animals.list.species_filter'],
+ })
+ await filter.selectOption('equine')
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(horse)
+ await filter.selectOption('other')
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(name)
+ await filter.selectOption('canine')
+ await expect(
+ page.getByText(dict['animals.list.no_results']),
+ ).toBeVisible()
+ await expectAccessible(page, 'a filtered animal list')
+ await filter.selectOption('')
+ await expect(listRows(page, dict)).toHaveCount(2)
+ await listRows(page, dict)
+ .filter({ hasText: name })
+ .getByRole('link')
+ .click()
+
+ const archive = page.getByRole('button', {
+ name: dict['animals.detail.archive'],
+ })
+ await archive.click()
+ const dialog = page.getByRole('dialog', {
+ name: dict['animals.archive.title'],
+ })
+ await expect(dialog).toHaveAccessibleDescription(
+ dict['animals.archive.body'],
+ )
+ await expectAccessible(page, 'the animal archive confirmation')
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ await expect(archive).toBeFocused()
+ await archive.click()
+ await dialog
+ .getByRole('button', {
+ name: dict['animals.archive.confirm'],
+ exact: true,
+ })
+ .click()
+ await expect(dialog).toBeHidden()
+ await expect(
+ page.getByText(dict['animals.detail.archived'], { exact: true }),
+ ).toBeVisible()
+ await expect(
+ page.getByText(dict['animals.detail.archived_notice']),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: dict['animals.detail.edit'] }),
+ ).toHaveCount(0)
+ await expect(
+ page.getByRole('button', { name: dict['relations.add_client'] }),
+ ).toHaveCount(0)
+ expect(
+ await sql(
+ `select archived_at is not null from public.animals where name = ${literal(name)}`,
+ ),
+ ).toBe('t')
+
+ await page
+ .getByRole('link', { name: dict['animals.detail.back'] })
+ .click()
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await page
+ .getByRole('switch', { name: dict['animals.list.archived_toggle'] })
+ .check()
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(
+ dict['animals.archived_badge'],
+ )
+ await expectAccessible(page, 'the archived animals')
+ await listRows(page, dict).first().getByRole('link').click()
+ await page
+ .getByRole('button', { name: dict['animals.detail.restore'] })
+ .click()
+ await expect(
+ page.getByText(dict['animals.detail.restored']),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: dict['animals.detail.edit'] }),
+ ).toBeVisible()
+ // The relations are read again for the restored animal: editable again.
+ await expect(
+ relationsCard(page).getByRole('button', {
+ name: dict['relations.add_client'],
+ }),
+ ).toBeVisible()
+ await expect(page.getByText(dict['relations.none'])).toBeVisible()
+ })
+
+ test('pages of 25 with « Afficher plus », in name order', async ({
+ page,
+ requests,
+ }, info) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ const ws = await sql(
+ `select id from public.workspaces where personal_user_id = ${literal(account.id)}`,
+ )
+ await sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+ select ${literal(ws)}, 'Animal Paginé ' || lpad(i::text, 2, '0'), 'canine', 'male', gen_random_uuid(), '\\x00'
+ from generate_series(1, 30) i`)
+ await signIn(page, account, dict)
+ await openAnimals(page, dict, info)
+ await expect(listRows(page, dict)).toHaveCount(25)
+ await expect(listRows(page, dict).first()).toContainText(
+ 'Animal Paginé 01',
+ )
+ await expect(listRows(page, dict).nth(24)).toContainText(
+ 'Animal Paginé 25',
+ )
+ await page
+ .getByRole('button', { name: dict['animals.list.more'] })
+ .click()
+ await expect(listRows(page, dict)).toHaveCount(30)
+ await expect(listRows(page, dict).nth(29)).toContainText(
+ 'Animal Paginé 30',
+ )
+ await expect(
+ page.getByRole('button', { name: dict['animals.list.more'] }),
+ ).toHaveCount(0)
+ await expectNoHorizontalOverflow(page, 'a long animal list')
+ })
+
+ test('from a client page: a first animal pre-associated as owner, then an existing animal linked', async ({
+ page,
+ requests,
+ }) => {
+ const tag = tagOf()
+ const client = `Marie Fictive ${tag}`
+ const filly = `Pouliche Fictive ${tag}`
+ const existing = `Cheval Existant ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ client,
+ filly,
+ existing,
+ tag,
+ '612345678',
+ )
+ const clientId = await seedClient(account, client, {
+ phone: '+33612345678',
+ })
+ await seedAnimal(account, existing)
+ await signIn(page, account, dict)
+ await page.goto(`/app/clients/${clientId}`)
+ await expect(heading(page, client)).toBeFocused()
+ await expect(page.getByText(dict['clients.animals.none'])).toBeVisible()
+
+ await page
+ .getByRole('link', { name: dict['clients.animals.add_first'] })
+ .click()
+ await expect(page).toHaveURL(/\/app\/animals\/new$/)
+ await expect(
+ heading(page, dict['animals.form.create_title']),
+ ).toBeFocused()
+ await expect(page.getByRole('main')).toContainText(client)
+ for (const role of ['owner', 'keeper', 'contact'])
+ await expect(
+ page.getByRole('radio', {
+ name: dict[`clients.role.${role}`],
+ exact: true,
+ }),
+ ).not.toBeChecked()
+ await expectAccessible(page, 'the animal form with its client')
+ await page.getByLabel(dict['animals.form.name']).fill(filly)
+ await page
+ .getByRole('combobox', { name: dict['animals.form.species'] })
+ .selectOption('equine')
+ await page
+ .getByRole('radio', { name: dict['animals.sex.female'], exact: true })
+ .check()
+ const submit = page.getByRole('button', {
+ name: dict['animals.form.submit_create'],
+ })
+ await submit.click()
+ await expect(page.getByText(dict['animals.error.role'])).toBeVisible()
+ await expect(
+ page.getByRole('radio', {
+ name: dict['clients.role.owner'],
+ exact: true,
+ }),
+ ).toBeFocused()
+ await page
+ .getByRole('radio', { name: dict['clients.role.owner'], exact: true })
+ .check()
+ await submit.click()
+
+ await expect(page).toHaveURL(new RegExp(`/app/clients/${clientId}$`))
+ await expect(
+ page.getByText(dict['clients.detail.animal_added']),
+ ).toBeVisible()
+ await expect(page.getByRole('link', { name: filly })).toBeVisible()
+ await expect(page.getByRole('main')).toContainText(
+ dict['clients.role.owner'],
+ )
+ expect(
+ await count(
+ `public.animal_client_relations r join public.animals a on a.id = r.animal_id
+ where a.name = ${literal(filly)} and r.client_id = ${literal(clientId)}
+ and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null`,
+ ),
+ ).toBe('1')
+
+ const link = page.getByRole('button', {
+ name: dict['clients.animals.link_existing'],
+ })
+ await link.click()
+ const panel = page.getByRole('form', {
+ name: dict['relations.panel.title_animal'],
+ })
+ await expect(
+ panel.getByRole('heading', {
+ name: dict['relations.panel.title_animal'],
+ }),
+ ).toBeFocused()
+ await pick(panel, dict['relations.picker.animal_label'], existing)
+ await panel
+ .getByRole('radio', { name: dict['clients.role.keeper'], exact: true })
+ .check()
+ await panel
+ .getByLabel(dict['relations.panel.started_on'])
+ .fill('2024-03-01')
+ await expectAccessible(page, 'the link-an-animal panel')
+ await expectNoHorizontalOverflow(page, 'the link-an-animal panel')
+ await panel
+ .getByRole('button', { name: dict['relations.panel.save_animal'] })
+ .click()
+ await expect(page.getByText(dict['relations.added_animal'])).toBeVisible()
+ await expect(link).toBeFocused()
+ await expect(page.getByRole('link', { name: existing })).toBeVisible()
+ await expect(page.getByRole('main')).toContainText(
+ dict['clients.animals.since'].replace(
+ '{date}',
+ formatDate('2024-03-01', locale),
+ ),
+ )
+ await expectAccessibleFromTop(page, 'the client page with its animals')
+
+ await page.getByRole('link', { name: filly }).click()
+ await expect(heading(page, filly)).toBeFocused()
+ const card = relationsCard(page)
+ await expect(card.getByRole('link', { name: client })).toBeVisible()
+ await expect(
+ card.getByRole('link', { name: '+33612345678' }),
+ ).toHaveAttribute('href', 'tel:+33612345678')
+ await expect(page.getByText(dict['animals.no_owner'])).toHaveCount(0)
+ })
+
+ test('animal page: co-owners, a keeper structure, a duplicate refused, a mistake voided, the sale ended with its date', async ({
+ page,
+ requests,
+ }) => {
+ const tag = tagOf()
+ const mare = `Jument Vendue ${tag}`
+ const former = `Ancien Propriétaire ${tag}`
+ const buyer = `Nouvelle Propriétaire ${tag}`
+ const stable = `Écurie du Lac ${tag}`
+ const wrong = `Client Erroné ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ mare,
+ former,
+ buyer,
+ stable,
+ wrong,
+ tag,
+ )
+ const animalId = await seedAnimal(account, mare)
+ const formerId = await seedClient(account, former)
+ await seedClient(account, buyer)
+ await seedClient(account, stable, { kind: 'organization' })
+ await seedClient(account, wrong)
+ await seedRelation(account, animalId, formerId, 'owner', '2018-04-01')
+ await signIn(page, account, dict)
+ await page.goto(`/app/animals/${animalId}`)
+ await expect(heading(page, mare)).toBeFocused()
+ const card = relationsCard(page)
+ const add = card.getByRole('button', {
+ name: dict['relations.add_client'],
+ })
+
+ async function link(clientName: string, roleKey: string) {
+ await add.click()
+ const panel = page.getByRole('form', {
+ name: dict['relations.panel.title_client'],
+ })
+ await pick(panel, dict['relations.picker.client_label'], clientName)
+ await panel
+ .getByRole('radio', { name: dict[roleKey], exact: true })
+ .check()
+ await panel
+ .getByRole('button', { name: dict['relations.panel.save_client'] })
+ .click()
+ return panel
+ }
+
+ await link(buyer, 'clients.role.owner')
+ await expect(page.getByText(dict['relations.added_client'])).toBeVisible()
+ await expect(add).toBeFocused()
+ const current = card.locator(
+ 'section[aria-labelledby="animal-relations-current"]',
+ )
+ await expect(current.getByRole('link', { name: former })).toBeVisible()
+ await expect(current.getByRole('link', { name: buyer })).toBeVisible()
+
+ const duplicate = await link(buyer, 'clients.role.owner')
+ await expect(
+ duplicate.getByText(dict['relations.failure.duplicate_relation']),
+ ).toBeVisible()
+ await expectAccessibleFromTop(page, 'a refused duplicate')
+ await duplicate
+ .getByRole('button', { name: dict['common.cancel'] })
+ .click()
+ await expect(add).toBeFocused()
+
+ await link(stable, 'clients.role.keeper')
+ await expect(current.getByRole('link', { name: stable })).toBeVisible()
+ await link(wrong, 'clients.role.contact')
+ await expect(current.getByRole('link', { name: wrong })).toBeVisible()
+
+ await card
+ .getByRole('button', {
+ name: actionName(
+ dict,
+ 'relations.void.action',
+ wrong,
+ 'clients.role.contact',
+ ),
+ })
+ .click()
+ const voiding = page.getByRole('dialog', {
+ name: dict['relations.void.title'],
+ })
+ await expect(voiding).toContainText(dict['relations.void.body'])
+ await expectAccessible(page, 'the void confirmation')
+ await voiding
+ .getByRole('button', { name: dict['relations.void.confirm'] })
+ .click()
+ await expect(voiding).toBeHidden()
+ await expect(page.getByText(dict['relations.void.done'])).toBeVisible()
+ await expect(card.getByRole('link', { name: wrong })).toHaveCount(0)
+ await expect(card.locator(':focus')).toHaveCount(1)
+ expect(
+ await count(
+ `public.animal_client_relations r join public.clients c on c.id = r.client_id
+ where c.display_name = ${literal(wrong)} and r.voided_at is not null`,
+ ),
+ ).toBe('1')
+
+ await card
+ .getByRole('button', {
+ name: actionName(
+ dict,
+ 'relations.end.action',
+ former,
+ 'clients.role.owner',
+ ),
+ })
+ .click()
+ const ending = page.getByRole('dialog', {
+ name: dict['relations.end.title'],
+ })
+ await expect(ending).toContainText(dict['relations.end.body'])
+ await ending.getByLabel(dict['relations.end.ended_on']).fill('2017-01-01')
+ await ending
+ .getByRole('button', { name: dict['relations.end.confirm'] })
+ .click()
+ await expect(
+ ending.getByText(dict['relations.error.end_before_start']),
+ ).toBeVisible()
+ await expect(
+ ending.getByLabel(dict['relations.end.ended_on']),
+ ).toBeFocused()
+ await ending.getByLabel(dict['relations.end.ended_on']).fill('2025-09-30')
+ await expectAccessible(page, 'the end confirmation')
+ await ending
+ .getByRole('button', { name: dict['relations.end.confirm'] })
+ .click()
+ await expect(ending).toBeHidden()
+ await expect(page.getByText(dict['relations.end.done'])).toBeVisible()
+ await expect(card.locator(':focus')).toHaveCount(1)
+ const history = card.locator(
+ 'section[aria-labelledby="animal-relations-former"]',
+ )
+ await expect(history).toContainText(dict['clients.role.former_owner'])
+ await expect(history).toContainText(
+ dict['relations.until'].replace(
+ '{date}',
+ formatDate('2025-09-30', locale),
+ ),
+ )
+ await expect(current.getByRole('link', { name: former })).toHaveCount(0)
+ await expectAccessible(page, 'an animal with its history')
+ await expectNoHorizontalOverflow(page, 'an animal with its history')
+
+ await history.getByRole('link', { name: former }).click()
+ await expect(heading(page, former)).toBeFocused()
+ const formerGroup = page.locator(
+ 'section[aria-labelledby="client-animals-former"]',
+ )
+ await expect(formerGroup.getByRole('link', { name: mare })).toBeVisible()
+ await expect(formerGroup).toContainText(dict['clients.role.former_owner'])
+ })
+
+ test('two accounts and a change of session: nothing of A reaches B', async ({
+ page,
+ requests,
+ }, info) => {
+ const secret = `Animal Secret ${tagOf()}`
+ const a = await createAccount(locale, false)
+ const b = await createAccount(locale, false)
+ requests.forbid(
+ a.email,
+ a.password,
+ b.email,
+ b.password,
+ b.displayName,
+ secret,
+ )
+ const id = await seedAnimal(a, secret)
+ await signIn(page, b, dict)
+ await openAnimals(page, dict, info)
+ await expect(page.getByText(dict['animals.list.empty'])).toBeVisible()
+ await page
+ .getByRole('searchbox', { name: dict['animals.list.search_label'] })
+ .fill(secret)
+ await expect(
+ page.getByText(dict['animals.list.no_results']),
+ ).toBeVisible()
+ for (const path of [
+ `/app/animals/${id}`,
+ `/app/animals/${id}/edit`,
+ `/app/animals/${randomUUID()}`,
+ '/app/animals/not-an-id',
+ ]) {
+ await page.goto(path)
+ await expect(
+ heading(page, dict['animals.not_found.title']),
+ ).toBeFocused()
+ await expect(page.getByText(secret)).toHaveCount(0)
+ }
+ await expectAccessible(page, 'the animal not found screen')
+
+ await signOut(page, dict, info)
+ await signIn(page, a, dict)
+ await openAnimals(page, dict, info)
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(secret)
+ await signOut(page, dict, info)
+ await page.goto(`/app/animals/${id}`)
+ await expect(page).toHaveURL(/\/login/)
+ await expect(page.getByText(secret)).toHaveCount(0)
+ await signIn(page, b, dict)
+ await openAnimals(page, dict, info)
+ await expect(page.getByText(dict['animals.list.empty'])).toBeVisible()
+ await expect(page.getByText(secret)).toHaveCount(0)
+ })
+
+ test('keyboard only: create an animal, a refused submit focuses its field', async ({
+ page,
+ requests,
+ }, info) => {
+ const name = `Clavier Fictif ${tagOf()}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ )
+ await signIn(page, account, dict)
+ await openAnimals(page, dict, info)
+ await page.keyboard.press('Tab')
+ await expect(
+ page.getByRole('link', { name: dict['animals.list.new'] }),
+ ).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(
+ heading(page, dict['animals.form.create_title']),
+ ).toBeFocused()
+ await page.keyboard.press('Tab')
+ const field = page.getByLabel(dict['animals.form.name'])
+ await expect(field).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(page.getByText(dict['animals.error.required'])).toBeVisible()
+ await expect(field).toBeFocused()
+ await expect(field).toHaveAttribute('aria-invalid', 'true')
+ await expectAccessible(page, 'the animal form with errors')
+ await page.keyboard.type(name)
+ await page.keyboard.press('Tab')
+ const species = page.getByRole('combobox', {
+ name: dict['animals.form.species'],
+ })
+ await expect(species).toBeFocused()
+ // The select's type-ahead: the first letters of the localized name.
+ await page.keyboard.type(locale === 'fr' ? 'Chien' : 'Dog')
+ await expect(species).toHaveValue('canine')
+ await page.keyboard.press('Tab')
+ const male = page.getByRole('radio', {
+ name: dict['animals.sex.male'],
+ exact: true,
+ })
+ await expect(male).toBeFocused()
+ await page.keyboard.press('Space')
+ await expect(male).toBeChecked()
+ await page.keyboard.press('Shift+Tab')
+ await page.keyboard.press('Shift+Tab')
+ await expect(field).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(heading(page, name)).toBeFocused()
+ })
+
+ test('a concurrent edit: the saved values beside the typed ones, then a knowing save', async ({
+ page,
+ requests,
+ }) => {
+ const name = `Révision Fictive ${tagOf()}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ )
+ const id = await seedAnimal(account, name)
+ await signIn(page, account, dict)
+ await page.goto(`/app/animals/${id}/edit`)
+ const breed = page.getByLabel(dict['animals.form.breed'])
+ await expect(page.getByLabel(dict['animals.form.name'])).toHaveValue(name)
+ await breed.fill('Selle Français')
+ await sql(
+ `update public.animals set breed = 'Pur-sang', revision = revision + 1 where id = ${literal(id)}`,
+ )
+ const save = page.getByRole('button', {
+ name: dict['animals.form.submit_update'],
+ exact: true,
+ })
+ await save.click()
+ await expect(
+ page.getByText(dict['animals.form.conflict_title']),
+ ).toBeVisible()
+ await expect(breed).toHaveValue('Selle Français')
+ await expect(
+ page.getByText(
+ dict['animals.form.stored_value'].replace('{value}', 'Pur-sang'),
+ ),
+ ).toBeVisible()
+ await expectAccessible(page, 'the animal conflict')
+ await save.click()
+ await expect(page.getByText(dict['animals.detail.updated'])).toBeVisible()
+ expect(
+ await sql(
+ `select breed || '/' || revision from public.animals where id = ${literal(id)}`,
+ ),
+ ).toBe('Selle Français/3')
+ })
+
+ test('a lost answer: the retry sends the same request id, one animal and one relation exist', async ({
+ page,
+ requests,
+ }) => {
+ const tag = tagOf()
+ const client = `Reprise Cliente ${tag}`
+ const name = `Reprise Animal ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ client,
+ name,
+ )
+ const clientId = await seedClient(account, client)
+ await signIn(page, account, dict)
+ const sent: string[] = []
+ await page.route('**/rest/v1/rpc/create_animal', async (route) => {
+ sent.push(
+ JSON.parse(route.request().postData() ?? '{}').create_request_id,
+ )
+ if (sent.length > 1) return route.fallback()
+ // The server creates the animal and its relation; the answer never reaches the page.
+ await route.fetch({ url: sandboxUrl(route.request().url()) ?? '' })
+ await route.abort('failed')
+ })
+ await page.goto(`/app/clients/${clientId}`)
+ await page
+ .getByRole('link', { name: dict['clients.animals.add_first'] })
+ .click()
+ await page.getByLabel(dict['animals.form.name']).fill(name)
+ await page
+ .getByRole('combobox', { name: dict['animals.form.species'] })
+ .selectOption('feline')
+ await page
+ .getByRole('radio', { name: dict['animals.sex.male'], exact: true })
+ .check()
+ await page
+ .getByRole('radio', { name: dict['clients.role.owner'], exact: true })
+ .check()
+ const submit = page.getByRole('button', {
+ name: dict['animals.form.submit_create'],
+ })
+ await submit.click()
+ await expect(
+ page.getByText(dict['animals.failure.network']),
+ ).toBeVisible()
+ const made = `public.animals a join public.animal_client_relations r on r.animal_id = a.id
+ where a.name = ${literal(name)} and r.client_id = ${literal(clientId)}`
+ expect(await count(made)).toBe('1')
+ await submit.click()
+ await expect(heading(page, client)).toBeVisible()
+ expect(sent).toHaveLength(2)
+ expect(sent[0]).toBe(sent[1])
+ expect(await count(made)).toBe('1')
+ expect(await count(`public.animals where name = ${literal(name)}`)).toBe(
+ '1',
+ )
+ })
+
+ test('failures: a list retries, a failed relation write stays in its dialog, an archived client is refused', async ({
+ page,
+ requests,
+ }, info) => {
+ const tag = tagOf()
+ const name = `Réseau Animal ${tag}`
+ const owner = `Réseau Client ${tag}`
+ const other = `Archivée Ensuite ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ owner,
+ other,
+ tag,
+ )
+ const animalId = await seedAnimal(account, name)
+ const ownerId = await seedClient(account, owner)
+ const otherId = await seedClient(account, other)
+ await seedRelation(account, animalId, ownerId, 'owner')
+ await signIn(page, account, dict)
+ let failing = true
+ await page.route('**/rest/v1/rpc/search_animals', (route) =>
+ failing ? route.abort('failed') : route.fallback(),
+ )
+ await openAnimals(page, dict, info)
+ await expect(
+ page.getByText(dict['animals.failure.network']),
+ ).toBeVisible()
+ failing = false
+ await page.getByRole('button', { name: dict['common.retry'] }).click()
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await listRows(page, dict).first().getByRole('link').click()
+ await expect(heading(page, name)).toBeFocused()
+
+ let endFailing = true
+ await page.route('**/rest/v1/rpc/end_animal_client_relation', (route) =>
+ endFailing ? route.abort('failed') : route.fallback(),
+ )
+ const card = relationsCard(page)
+ await card
+ .getByRole('button', {
+ name: actionName(
+ dict,
+ 'relations.end.action',
+ owner,
+ 'clients.role.owner',
+ ),
+ })
+ .click()
+ const ending = page.getByRole('dialog', {
+ name: dict['relations.end.title'],
+ })
+ await ending.getByLabel(dict['relations.end.ended_on']).fill('2025-01-15')
+ await ending
+ .getByRole('button', { name: dict['relations.end.confirm'] })
+ .click()
+ await expect(
+ ending.getByText(dict['relations.failure.network']),
+ ).toBeVisible()
+ await expect(
+ ending.getByLabel(dict['relations.end.ended_on']),
+ ).toHaveValue('2025-01-15')
+ endFailing = false
+ await ending
+ .getByRole('button', { name: dict['relations.end.confirm'] })
+ .click()
+ await expect(ending).toBeHidden()
+ await expect(page.getByText(dict['relations.end.done'])).toBeVisible()
+
+ await card
+ .getByRole('button', { name: dict['relations.add_client'] })
+ .click()
+ const panel = page.getByRole('form', {
+ name: dict['relations.panel.title_client'],
+ })
+ await pick(panel, dict['relations.picker.client_label'], other)
+ await panel
+ .getByRole('radio', { name: dict['clients.role.contact'], exact: true })
+ .check()
+ await sql(
+ `update public.clients set archived_at = now() where id = ${literal(otherId)}`,
+ )
+ await panel
+ .getByRole('button', { name: dict['relations.panel.save_client'] })
+ .click()
+ await expect(
+ panel.getByText(dict['relations.failure.archived']),
+ ).toBeVisible()
+ await expect(
+ panel.getByRole('radio', {
+ name: dict['clients.role.contact'],
+ exact: true,
+ }),
+ ).toBeChecked()
+ })
+
+ test('the animal pages follow a change of language', async ({
+ page,
+ requests,
+ }, info) => {
+ const tag = tagOf()
+ const name = `Animal Bilingue ${tag}`
+ const owner = `Client Bilingue ${tag}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ owner,
+ )
+ const animalId = await seedAnimal(account, name, 'canine', 'male')
+ await seedRelation(
+ account,
+ animalId,
+ await seedClient(account, owner),
+ 'owner',
+ )
+ await signIn(page, account, dict)
+ await openAnimals(page, dict, info)
+ const other = locale === 'fr' ? en : fr
+ await page
+ .getByRole('button', {
+ name: dict[
+ locale === 'fr' ? 'lang.switch_to_en' : 'lang.switch_to_fr'
+ ],
+ })
+ .click()
+ await expect(
+ page.getByRole('link', { name: other['animals.list.new'] }),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('combobox', {
+ name: other['animals.list.species_filter'],
+ }),
+ ).toBeVisible()
+ await expect(listRows(page, other).first()).toContainText(
+ other['animals.sex.male'],
+ )
+ await expect(listRows(page, other).first()).toContainText(
+ other['animals.list.owner'].replace('{names}', owner),
+ )
+ await expectAccessible(page, 'the animal list after a change of language')
+ await listRows(page, other).first().getByRole('link').click()
+ await expect(relationsCard(page)).toContainText(other['relations.title'])
+ await expect(relationsCard(page)).toContainText(
+ other['clients.role.owner'],
+ )
+ })
+ })
+}
diff --git a/apps/app/e2e/shell/clients.spec.ts b/apps/app/e2e/shell/clients.spec.ts
new file mode 100644
index 00000000..57307757
--- /dev/null
+++ b/apps/app/e2e/shell/clients.spec.ts
@@ -0,0 +1,604 @@
+import { randomUUID } from 'node:crypto'
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import type { Dict } from '@/i18n/types'
+import type { Page, TestInfo } from '@playwright/test'
+import { sql } from '../../../../packages/supabase/tests/sandbox/stack'
+import {
+ expect,
+ expectAccessible,
+ expectNoHorizontalOverflow,
+ test,
+} from '../support/browser'
+import {
+ createAccount,
+ dropLateReplays,
+ routeToSandbox,
+ sandboxUrl,
+ workspaceOf,
+ type SandboxAccount,
+} from '../support/sandbox'
+import { signIn } from '../support/shell'
+
+// V1-1.5 clients on the isolated stack: the journeys of contract §11.2 that
+// concern clients, keyboard only, two accounts, pages, a concurrent edit, a
+// retry after a lost answer, network failures and the leave guard, in FR and
+// EN, desktop and 375 px. Every fixture is fictitious and made per test.
+
+const LANGUAGES = [
+ ['fr', fr],
+ ['en', en],
+] as const
+
+const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
+
+/** A client row written as postgres in the account's workspace (setup, not the subject). */
+async function seedClient(
+ account: SandboxAccount,
+ displayName: string,
+ city: string | null = null,
+) {
+ const ws = await workspaceOf(account)
+ return sql(`insert into public.clients (workspace_id, kind, display_name, city, create_request_id, create_request_digest)
+ values ('${ws}', 'person', '${displayName}', ${city ? `'${city}'` : 'null'}, gen_random_uuid(), '\\x00') returning id`)
+}
+
+async function openClients(page: Page, dict: Dict, info: TestInfo) {
+ if (isPhone(info)) {
+ await page.getByRole('button', { name: dict['shell.open_menu'] }).click()
+ await page
+ .getByRole('dialog', { name: dict['shell.nav_label'] })
+ .getByRole('navigation')
+ .getByRole('link', { name: dict['shell.nav.clients'] })
+ .click()
+ } else {
+ await page
+ .getByRole('navigation', { name: dict['shell.nav_label'] })
+ .getByRole('link', { name: dict['shell.nav.clients'] })
+ .click()
+ }
+ await expect(page).toHaveURL(/\/app\/clients$/)
+ await expect(
+ page
+ .getByRole('main')
+ .getByRole('heading', { level: 1, name: dict['clients.list.title'] }),
+ ).toBeFocused()
+}
+
+const listRows = (page: Page, dict: Dict) =>
+ page
+ .getByRole('list', { name: dict['clients.list.results_label'] })
+ .getByRole('listitem')
+
+for (const [locale, dict] of LANGUAGES) {
+ test.describe(`clients (${locale})`, () => {
+ test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
+ test.beforeEach(async ({ context }) => {
+ await routeToSandbox(context)
+ })
+ test.afterEach(async ({ context }) => {
+ await dropLateReplays(context)
+ })
+
+ test('empty list, create, find, open, edit, archive, archived filter, restore', async ({
+ page,
+ requests,
+ }, info) => {
+ const tag = randomUUID().slice(0, 8)
+ const name = `Écurie Fictive ${tag}`
+ const email = `contact-${tag}@exemple.test`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ email,
+ `Fictive ${tag}`,
+ '612345678',
+ )
+ await signIn(page, account, dict)
+ await openClients(page, dict, info)
+
+ await expect(page.getByText(dict['clients.list.empty'])).toBeVisible()
+ await expectAccessible(page, 'the empty client list')
+ await expectNoHorizontalOverflow(page, 'the empty client list')
+
+ await page.getByRole('link', { name: dict['clients.list.new'] }).click()
+ await expect(page).toHaveURL(/\/app\/clients\/new$/)
+ await expect(
+ page.getByRole('main').getByRole('heading', {
+ level: 1,
+ name: dict['clients.form.create_title'],
+ }),
+ ).toBeFocused()
+ await expect(
+ page.getByRole('radio', { name: dict['clients.kind.person'] }),
+ ).toBeChecked()
+ await expect(
+ page.getByRole('combobox', { name: dict['clients.form.country'] }),
+ ).toHaveValue('')
+ await expectAccessible(page, 'the new client form')
+ await expectNoHorizontalOverflow(page, 'the new client form')
+
+ await page
+ .getByRole('radio', { name: dict['clients.kind.organization'] })
+ .check()
+ await page
+ .getByLabel(dict['clients.form.display_name.organization'])
+ .fill(name)
+ await page
+ .getByLabel(dict['clients.form.email'])
+ .fill(email.toUpperCase())
+ const phone = page.getByLabel(dict['clients.form.phone'])
+ await phone.fill('06 12 34 56 78')
+ await phone.blur()
+ await expect(phone).toHaveValue('+33612345678')
+ await page.getByLabel(dict['clients.form.city']).fill('Lyon')
+ await page
+ .getByRole('combobox', { name: dict['clients.form.country'] })
+ .selectOption('FR')
+ await page
+ .getByRole('button', { name: dict['clients.form.submit_create'] })
+ .click()
+
+ await expect(page).toHaveURL(/\/app\/clients\/[0-9a-f-]{36}$/)
+ await expect(
+ page.getByRole('main').getByRole('heading', { level: 1, name }),
+ ).toBeFocused()
+ await expect(page.getByText(dict['clients.detail.created'])).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: '+33612345678' }),
+ ).toHaveAttribute('href', 'tel:+33612345678')
+ await expect(page.getByRole('link', { name: email })).toHaveAttribute(
+ 'href',
+ `mailto:${email}`,
+ )
+ await expect(page.getByText(dict['clients.animals.none'])).toBeVisible()
+ await expectAccessible(page, 'the client page')
+ await expectNoHorizontalOverflow(page, 'the client page')
+
+ await page
+ .getByRole('link', { name: dict['clients.detail.edit'] })
+ .click()
+ await expect(
+ page.getByLabel(dict['clients.form.display_name.organization']),
+ ).toHaveValue(name)
+ await page.getByLabel(dict['clients.form.city']).fill('Annecy')
+ await page
+ .getByRole('button', {
+ name: dict['clients.form.submit_update'],
+ exact: true,
+ })
+ .click()
+ await expect(page.getByText(dict['clients.detail.updated'])).toBeVisible()
+ await expect(page.getByText('Annecy')).toBeVisible()
+
+ await page
+ .getByRole('link', { name: dict['clients.detail.back'] })
+ .click()
+ const search = page.getByRole('searchbox', {
+ name: dict['clients.list.search_label'],
+ })
+ for (const term of [
+ `ecurie fictive ${tag}`,
+ '06 12 34',
+ email.toUpperCase(),
+ ]) {
+ await search.fill(term)
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(name)
+ }
+ await search.fill(`zzz-${tag}`)
+ await expect(
+ page.getByText(dict['clients.list.no_results']),
+ ).toBeVisible()
+ await search.fill('')
+ await expect(listRows(page, dict).first()).toContainText(
+ dict['clients.list.animals_none'],
+ )
+ await listRows(page, dict).first().getByRole('link').click()
+
+ const archiveButton = page.getByRole('button', {
+ name: dict['clients.detail.archive'],
+ })
+ await archiveButton.click()
+ const dialog = page.getByRole('dialog', {
+ name: dict['clients.archive.title'],
+ })
+ await expect(dialog).toBeVisible()
+ await expect(dialog).toHaveAccessibleDescription(
+ dict['clients.archive.body'],
+ )
+ await expect(dialog.getByRole('status')).toHaveCount(0)
+ await expectAccessible(page, 'the archive confirmation')
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ await expect(archiveButton).toBeFocused()
+ await archiveButton.click()
+ await dialog
+ .getByRole('button', {
+ name: dict['clients.archive.confirm'],
+ exact: true,
+ })
+ .click()
+ await expect(dialog).toBeHidden()
+ await expect(
+ page.getByText(dict['clients.detail.archived'], { exact: true }),
+ ).toBeVisible()
+ await expect(
+ page.getByText(dict['clients.detail.archived_notice']),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: dict['clients.detail.edit'] }),
+ ).toHaveCount(0)
+ expect(
+ await sql(
+ `select archived_at is not null from public.clients where display_name = '${name}'`,
+ ),
+ ).toBe('t')
+
+ await page
+ .getByRole('link', { name: dict['clients.detail.back'] })
+ .click()
+ await expect(page.getByText(dict['clients.list.empty'])).toBeVisible()
+ await page
+ .getByRole('switch', { name: dict['clients.list.archived_toggle'] })
+ .check()
+ await expect(listRows(page, dict)).toHaveCount(1)
+ await expect(listRows(page, dict).first()).toContainText(
+ dict['clients.archived_badge'],
+ )
+ await expectAccessible(page, 'the archived filter')
+ await listRows(page, dict).first().getByRole('link').click()
+ await page
+ .getByRole('button', { name: dict['clients.detail.restore'] })
+ .click()
+ await expect(
+ page.getByText(dict['clients.detail.restored']),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('link', { name: dict['clients.detail.edit'] }),
+ ).toBeVisible() // The animal section is read again for the restored client.
+ await expect(page.getByText(dict['clients.animals.none'])).toBeVisible()
+ })
+
+ test('pages of 25 with « Afficher plus », in name order', async ({
+ page,
+ requests,
+ }, info) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ for (let i = 1; i <= 30; i++)
+ await seedClient(account, `Client Paginé ${String(i).padStart(2, '0')}`)
+ await signIn(page, account, dict)
+ await openClients(page, dict, info)
+ await expect(listRows(page, dict)).toHaveCount(25)
+ await expect(listRows(page, dict).first()).toContainText(
+ 'Client Paginé 01',
+ )
+ await expect(listRows(page, dict).nth(24)).toContainText(
+ 'Client Paginé 25',
+ )
+ await page
+ .getByRole('button', { name: dict['clients.list.more'] })
+ .click()
+ await expect(listRows(page, dict)).toHaveCount(30)
+ await expect(listRows(page, dict).nth(29)).toContainText(
+ 'Client Paginé 30',
+ )
+ await expect(
+ page.getByRole('button', { name: dict['clients.list.more'] }),
+ ).toHaveCount(0)
+ await expectNoHorizontalOverflow(page, 'a long client list')
+ })
+
+ test('keyboard only: create a client, a refused submit focuses its field', async ({
+ page,
+ requests,
+ }, info) => {
+ const name = `Clavier Fictif ${randomUUID().slice(0, 8)}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ )
+ await signIn(page, account, dict)
+ await openClients(page, dict, info)
+ await page.keyboard.press('Tab')
+ await expect(
+ page.getByRole('link', { name: dict['clients.list.new'] }),
+ ).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(
+ page.getByRole('main').getByRole('heading', {
+ level: 1,
+ name: dict['clients.form.create_title'],
+ }),
+ ).toBeFocused()
+ await page.keyboard.press('Tab')
+ await expect(
+ page.getByRole('radio', { name: dict['clients.kind.person'] }),
+ ).toBeFocused()
+ await page.keyboard.press('Tab')
+ const field = page.getByLabel(dict['clients.form.display_name.person'])
+ await expect(field).toBeFocused()
+ await page.keyboard.press('Enter')
+ await expect(page.getByText(dict['clients.error.required'])).toBeVisible()
+ await expect(field).toBeFocused()
+ await expect(field).toHaveAttribute('aria-invalid', 'true')
+ await expectAccessible(page, 'the form with an error')
+ await page.keyboard.type(name)
+ await page.keyboard.press('Enter')
+ await expect(
+ page.getByRole('main').getByRole('heading', { level: 1, name }),
+ ).toBeFocused()
+ })
+
+ test('two accounts: nothing of A reaches B, a foreign id reads as unknown', async ({
+ page,
+ requests,
+ }, info) => {
+ const secret = `Client Secret ${randomUUID().slice(0, 8)}`
+ const a = await createAccount(locale, false)
+ const b = await createAccount(locale, false)
+ requests.forbid(
+ a.email,
+ a.password,
+ b.email,
+ b.password,
+ b.displayName,
+ secret,
+ )
+ const id = await seedClient(a, secret, 'Lyon')
+ await signIn(page, b, dict)
+ await openClients(page, dict, info)
+ await expect(page.getByText(dict['clients.list.empty'])).toBeVisible()
+ await page
+ .getByRole('searchbox', { name: dict['clients.list.search_label'] })
+ .fill(secret)
+ await expect(
+ page.getByText(dict['clients.list.no_results']),
+ ).toBeVisible()
+ for (const path of [
+ `/app/clients/${id}`,
+ `/app/clients/${id}/edit`,
+ `/app/clients/${randomUUID()}`,
+ '/app/clients/not-an-id',
+ ]) {
+ await page.goto(path)
+ await expect(
+ page.getByRole('main').getByRole('heading', {
+ level: 1,
+ name: dict['clients.not_found.title'],
+ }),
+ ).toBeFocused()
+ await expect(page.getByText(secret)).toHaveCount(0)
+ }
+ await expectAccessible(page, 'the client not found screen')
+ })
+
+ test('a concurrent edit: the saved values beside the typed ones, then a knowing save', async ({
+ page,
+ requests,
+ }) => {
+ const name = `Révision Fictive ${randomUUID().slice(0, 8)}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ )
+ const id = await seedClient(account, name, 'Lyon')
+ await signIn(page, account, dict)
+ await page.goto(`/app/clients/${id}/edit`)
+ const city = page.getByLabel(dict['clients.form.city'])
+ await expect(city).toHaveValue('Lyon')
+ await city.fill('Annecy')
+ await sql(
+ `update public.clients set city = 'Vevey', revision = revision + 1 where id = '${id}'`,
+ )
+ await page
+ .getByRole('button', {
+ name: dict['clients.form.submit_update'],
+ exact: true,
+ })
+ .click()
+ await expect(
+ page.getByText(dict['clients.form.conflict_title']),
+ ).toBeVisible()
+ await expect(city).toHaveValue('Annecy')
+ await expect(
+ page.getByText(
+ dict['clients.form.stored_value'].replace('{value}', 'Vevey'),
+ ),
+ ).toBeVisible()
+ expect(
+ await sql(
+ `select city || '/' || revision from public.clients where id = '${id}'`,
+ ),
+ ).toBe('Vevey/2')
+ await expectAccessible(page, 'the conflict')
+ await page
+ .getByRole('button', {
+ name: dict['clients.form.submit_update'],
+ exact: true,
+ })
+ .click()
+ await expect(page.getByText(dict['clients.detail.updated'])).toBeVisible()
+ expect(
+ await sql(
+ `select city || '/' || revision from public.clients where id = '${id}'`,
+ ),
+ ).toBe('Annecy/3')
+ })
+
+ test('a lost answer: the retry sends the same request id and one client exists', async ({
+ page,
+ requests,
+ }) => {
+ const name = `Reprise Fictive ${randomUUID().slice(0, 8)}`
+ const account = await createAccount(locale, false)
+ requests.forbid(
+ account.email,
+ account.password,
+ account.displayName,
+ name,
+ )
+ await signIn(page, account, dict)
+ const sent: string[] = []
+ await page.route('**/rest/v1/rpc/create_client', async (route) => {
+ sent.push(
+ JSON.parse(route.request().postData() ?? '{}').create_request_id,
+ )
+ if (sent.length > 1) return route.fallback()
+ // The server creates the client; its answer never reaches the page.
+ await route.fetch({ url: sandboxUrl(route.request().url()) ?? '' })
+ await route.abort('failed')
+ })
+ await page.goto('/app/clients/new')
+ await page.getByLabel(dict['clients.form.display_name.person']).fill(name)
+ const submit = page.getByRole('button', {
+ name: dict['clients.form.submit_create'],
+ })
+ await submit.click()
+ await expect(
+ page.getByText(dict['clients.failure.network']),
+ ).toBeVisible()
+ expect(
+ await sql(
+ `select count(*) from public.clients where display_name = '${name}'`,
+ ),
+ ).toBe('1')
+ await submit.click()
+ await expect(
+ page.getByRole('main').getByRole('heading', { level: 1, name }),
+ ).toBeVisible()
+ expect(sent).toHaveLength(2)
+ expect(sent[0]).toBe(sent[1])
+ expect(
+ await sql(
+ `select count(*) from public.clients where display_name = '${name}'`,
+ ),
+ ).toBe('1')
+ })
+
+ test('a failed list says so and retries; a failed save keeps the form', async ({
+ page,
+ requests,
+ }, info) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ await seedClient(account, 'Client Réseau')
+ await signIn(page, account, dict)
+ let failing = true
+ await page.route('**/rest/v1/rpc/search_clients', (route) =>
+ failing ? route.abort('failed') : route.fallback(),
+ )
+ await openClients(page, dict, info)
+ await expect(
+ page.getByText(dict['clients.failure.network']),
+ ).toBeVisible()
+ failing = false
+ await page.getByRole('button', { name: dict['common.retry'] }).click()
+ await expect(listRows(page, dict)).toHaveCount(1)
+
+ await page.route('**/rest/v1/rpc/create_client', (route) =>
+ route.fulfill({
+ status: 400,
+ contentType: 'application/json',
+ body: '{"code":"P0001","message":"rate_limited"}',
+ }),
+ )
+ await page.goto('/app/clients/new')
+ await page
+ .getByLabel(dict['clients.form.display_name.person'])
+ .fill('Client Limité')
+ await page
+ .getByRole('button', { name: dict['clients.form.submit_create'] })
+ .click()
+ await expect(
+ page.getByText(dict['clients.failure.rate_limited']),
+ ).toBeVisible()
+ await expect(
+ page.getByLabel(dict['clients.form.display_name.person']),
+ ).toHaveValue('Client Limité')
+ })
+
+ test('unsaved changes: a link asks first, staying keeps them', async ({
+ page,
+ requests,
+ }, info) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ await signIn(page, account, dict)
+ await page.goto('/app/clients/new')
+ const field = page.getByLabel(dict['clients.form.display_name.person'])
+ await field.fill('Brouillon Fictif')
+ const cancel = page.getByRole('link', { name: dict['common.cancel'] })
+ await cancel.click()
+ const dialog = page.getByRole('dialog', { name: dict['leave.title'] })
+ await expect(dialog).toBeVisible()
+ await expectAccessible(page, 'the leave confirmation')
+ await dialog.getByRole('button', { name: dict['leave.stay'] }).click()
+ await expect(dialog).toBeHidden()
+ await expect(page).toHaveURL(/\/app\/clients\/new$/)
+ await expect(field).toHaveValue('Brouillon Fictif')
+ await expect(cancel).toBeFocused()
+
+ if (isPhone(info)) {
+ await page
+ .getByRole('button', { name: dict['shell.open_menu'] })
+ .click()
+ await page
+ .getByRole('dialog', { name: dict['shell.nav_label'] })
+ .getByRole('navigation')
+ .getByRole('link', { name: dict['shell.nav.dashboard'] })
+ .click()
+ } else {
+ await page
+ .getByRole('navigation', { name: dict['shell.nav_label'] })
+ .getByRole('link', { name: dict['shell.nav.dashboard'] })
+ .click()
+ }
+ await expect(dialog).toBeVisible()
+ await dialog.getByRole('button', { name: dict['leave.confirm'] }).click()
+ await expect(page).toHaveURL(/\/app\/?$/)
+ await expect(page.getByRole('dialog')).toHaveCount(0)
+ })
+
+ test('the list follows a change of language', async ({
+ page,
+ requests,
+ }, info) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ await seedClient(account, 'Client Bilingue')
+ await signIn(page, account, dict)
+ await openClients(page, dict, info)
+ const other = locale === 'fr' ? en : fr
+ await page
+ .getByRole('button', {
+ name: dict[
+ locale === 'fr' ? 'lang.switch_to_en' : 'lang.switch_to_fr'
+ ],
+ })
+ .click()
+ await expect(
+ page.getByRole('link', { name: other['clients.list.new'] }),
+ ).toBeVisible()
+ await expect(
+ page.getByRole('searchbox', {
+ name: other['clients.list.search_label'],
+ }),
+ ).toBeVisible()
+ await expect(listRows(page, other).first()).toContainText(
+ other['clients.kind.person'],
+ )
+ await expectAccessible(page, 'the list after a change of language')
+ })
+ })
+}
diff --git a/apps/app/e2e/shell/responsive.spec.ts b/apps/app/e2e/shell/responsive.spec.ts
new file mode 100644
index 00000000..d7f95d83
--- /dev/null
+++ b/apps/app/e2e/shell/responsive.spec.ts
@@ -0,0 +1,162 @@
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import type { Dict } from '@/i18n/types'
+import type { Page, TestInfo } from '@playwright/test'
+import {
+ expect,
+ expectNoHorizontalOverflow,
+ focusOwner,
+ test,
+} from '../support/browser'
+import {
+ createAccount,
+ dropLateReplays,
+ routeToSandbox,
+} from '../support/sandbox'
+import { seedAnimal, seedClient, seedRelation } from '../support/records'
+import { signIn } from '../support/shell'
+
+// RESP-01 (V1-1 DEV acceptance): no page of the shell scrolls sideways, from
+// 320 to 430 px on the phone project and at the desktop width, with long
+// realistic values in both languages; the dashboard shows the whole e-mail of
+// the account (a long one used to widen the cards past the screen).
+
+const LANGUAGES = [
+ ['fr', fr],
+ ['en', en],
+] as const
+
+const PHONE_WIDTHS = [320, 360, 375, 390, 430]
+
+const LONG = {
+ localPart: 'prenom.nom-compose.praticienne-fictive',
+ client: 'Recette Client Au Nom Particulièrement Long Pour Les Petits Écrans',
+ clientEmail: 'prenom.nom-compose.recette@cabinet-veterinaire-exemple.example.org',
+ address: 'Chemin de la Recette Responsive, Lieu-dit Les Petits Écrans',
+ city: 'Saint-Rémy-de-Provence-sur-Recette',
+ structure: 'Écurie Recette Structure Responsive Organisation',
+ animal: 'Recette Animal Au Nom Très Long Pour Les Écrans Étroits',
+}
+
+const isPhone = (info: TestInfo) => info.project.name === 'chromium-375'
+
+/** Opens a page and waits for its heading and its reads. */
+async function open(page: Page, path: string) {
+ await page.goto(path)
+ await expect(page.locator('main h1').first()).toBeVisible()
+ await page.waitForLoadState('networkidle')
+}
+
+/** The account e-mail of the dashboard is shown whole: not clipped, not cut. */
+async function expectWholeEmail(page: Page, email: string, state: string) {
+ const value = page.locator('main dd', { hasText: email })
+ await expect(value).toHaveText(email)
+ const clipped = await value.evaluate((dd) => dd.scrollWidth > dd.clientWidth)
+ expect(clipped, `e-mail clipped on ${state}`).toBe(false)
+}
+
+/** A confirmation opened with Enter keeps the focus, fits, and Escape gives it back. */
+async function checkConfirmation(
+ page: Page,
+ action: string,
+ title: string,
+ state: string,
+) {
+ const button = page.getByRole('button', { name: action, exact: true })
+ await button.focus()
+ await page.keyboard.press('Enter')
+ const dialog = page.getByRole('dialog', { name: title })
+ await expect(dialog).toBeVisible()
+ expect(await focusOwner(page)).toBe('dialog')
+ await expectNoHorizontalOverflow(page, state)
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ await expect(button).toBeFocused()
+}
+
+async function checkDrawer(page: Page, dict: Dict, state: string) {
+ const menu = page.getByRole('button', { name: dict['shell.open_menu'] })
+ await menu.focus()
+ await page.keyboard.press('Enter')
+ const drawer = page.getByRole('dialog', { name: dict['shell.nav_label'] })
+ await expect(drawer).toBeVisible()
+ await expectNoHorizontalOverflow(page, state)
+ await page.keyboard.press('Escape')
+ await expect(drawer).toBeHidden()
+ await expect(menu).toBeFocused()
+}
+
+for (const [locale, dict] of LANGUAGES) {
+ test.describe(`responsive (${locale})`, () => {
+ test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
+ test.beforeEach(async ({ context }) => {
+ await routeToSandbox(context)
+ })
+ test.afterEach(async ({ context }) => {
+ await dropLateReplays(context)
+ })
+
+ test('no sideways scroll on the shell pages, dialogs and drawer, long values', async ({
+ page,
+ requests,
+ }, info) => {
+ test.setTimeout(240_000)
+ const account = await createAccount(locale, true, LONG.localPart)
+ requests.forbid(account.email, account.password, account.displayName)
+ const client = await seedClient(account, LONG.client, {
+ email: LONG.clientEmail,
+ addressLine1: LONG.address,
+ city: LONG.city,
+ phone: '+33639980001',
+ })
+ const structure = await seedClient(account, LONG.structure, {
+ kind: 'organization',
+ city: LONG.city,
+ })
+ const animal = await seedAnimal(account, LONG.animal)
+ await seedRelation(account, animal, client, 'owner', '2024-01-01')
+ await seedRelation(account, animal, structure, 'keeper', '2024-02-01')
+ await signIn(page, account, dict)
+
+ const pages = [
+ '/app',
+ '/app/clients',
+ '/app/clients/new',
+ `/app/clients/${client}`,
+ `/app/clients/${client}/edit`,
+ '/app/animals',
+ '/app/animals/new',
+ `/app/animals/${animal}`,
+ `/app/animals/${animal}/edit`,
+ ]
+ const widths = isPhone(info) ? PHONE_WIDTHS : [page.viewportSize()!.width]
+ for (const width of widths) {
+ await page.setViewportSize({ width, height: 667 })
+ for (const path of pages) {
+ await open(page, path)
+ const state = `${path.replace(/[0-9a-f-]{36}/, ':id')} at ${width} px`
+ await expectNoHorizontalOverflow(page, state)
+ if (path === '/app') await expectWholeEmail(page, account.email, state)
+ if (path === `/app/clients/${client}`)
+ await checkConfirmation(
+ page,
+ dict['clients.detail.archive'],
+ dict['clients.archive.title'],
+ `the client archive confirmation at ${width} px`,
+ )
+ if (path === `/app/animals/${animal}`)
+ await checkConfirmation(
+ page,
+ dict['animals.detail.archive'],
+ dict['animals.archive.title'],
+ `the animal archive confirmation at ${width} px`,
+ )
+ }
+ if (isPhone(info)) {
+ await open(page, '/app/clients')
+ await checkDrawer(page, dict, `the open drawer at ${width} px`)
+ }
+ }
+ })
+ })
+}
diff --git a/apps/app/e2e/shell/shell.spec.ts b/apps/app/e2e/shell/shell.spec.ts
new file mode 100644
index 00000000..497919b2
--- /dev/null
+++ b/apps/app/e2e/shell/shell.spec.ts
@@ -0,0 +1,172 @@
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import type { Page } from '@playwright/test'
+import {
+ expect,
+ expectAccessible,
+ expectNoHorizontalOverflow,
+ focusOwner,
+ focusedName,
+ test,
+} from '../support/browser'
+import {
+ createAccount,
+ dropLateReplays,
+ routeToSandbox,
+} from '../support/sandbox'
+import { signIn } from '../support/shell'
+
+// The authenticated shell on the isolated stack: sign-in, dashboard, the
+// account photo confirmation and the mobile drawer, through the shared modal.
+
+const LANGUAGES = [
+ ['fr', fr],
+ ['en', en],
+] as const
+
+/** Focus steps of `count` Tab presses, the browser's interface written « browser ». */
+async function tabWalk(page: Page, count: number): Promise {
+ const steps: string[] = []
+ for (let i = 0; i < count; i++) {
+ await page.keyboard.press('Tab')
+ const owner = await focusOwner(page)
+ steps.push(owner === 'dialog' ? await focusedName(page) : owner)
+ }
+ return steps
+}
+
+for (const [locale, dict] of LANGUAGES) {
+ test.describe(`shell (${locale})`, () => {
+ test.use({ locale: locale === 'fr' ? 'fr-FR' : 'en-GB' })
+ test.beforeEach(async ({ context }) => {
+ await routeToSandbox(context)
+ })
+ test.afterEach(async ({ context }) => {
+ await dropLateReplays(context)
+ })
+
+ test('sign-in, dashboard, then the photo confirmation of the account', async ({
+ page,
+ requests,
+ }) => {
+ const account = await createAccount(locale, true)
+ requests.forbid(account.email, account.password, account.displayName)
+ await signIn(page, account, dict)
+ await expectAccessible(page, 'dashboard')
+ await expectNoHorizontalOverflow(page, 'dashboard')
+
+ await page.getByTestId('topbar-account').click()
+ await expect(page).toHaveURL(/\/app\/account$/)
+ const remove = page.getByRole('button', {
+ name: dict['account.avatar.remove'],
+ })
+ await expect(remove).toBeVisible()
+ await expect(
+ page
+ .getByTestId('avatar-section')
+ .getByRole('img', { name: dict['account.avatar.alt'] }),
+ ).toBeVisible()
+ await expectAccessible(page, 'account')
+ await expectNoHorizontalOverflow(page, 'account')
+
+ await remove.focus()
+ await page.keyboard.press('Enter')
+ const dialog = page.getByRole('dialog', {
+ name: dict['account.avatar.remove_title'],
+ })
+ await expect(dialog).toBeVisible()
+ await expect(dialog).toHaveAccessibleDescription(
+ dict['account.avatar.remove_body'],
+ )
+ expect(await focusedName(page)).toBe(dict['common.close'])
+ expect(await tabWalk(page, 4)).toEqual([
+ dict['common.cancel'],
+ dict['account.avatar.remove_confirm'],
+ 'browser',
+ dict['common.close'],
+ ])
+ await expectAccessible(page, 'the photo confirmation')
+ await expectNoHorizontalOverflow(page, 'the photo confirmation')
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ await expect(remove).toBeFocused()
+
+ // A slow removal: the confirmation must stay open until it settles, or the
+ // focus would return to a button about to vanish.
+ let settled = false
+ await page.route('**/rest/v1/rpc/remove_avatar', async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 800))
+ settled = true
+ await route.fallback()
+ })
+ await page.keyboard.press('Enter')
+ await expect(dialog).toBeVisible()
+ await dialog
+ .getByRole('button', {
+ name: dict['account.avatar.remove_confirm'],
+ exact: true,
+ })
+ .focus()
+ await page.keyboard.press('Enter')
+ await page.waitForTimeout(400)
+ expect(settled).toBe(false)
+ await expect(dialog).toBeVisible()
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeVisible()
+ await expect(dialog).toBeHidden()
+ expect(settled).toBe(true)
+ await expect(page.getByText(dict['account.avatar.removed'])).toBeVisible()
+ await expect(remove).toHaveCount(0)
+ // The visible button, not the file input it opens (out of the tab order).
+ const change = page
+ .getByTestId('avatar-section')
+ .locator('button', { hasText: dict['account.avatar.change'] })
+ await expect(change).toBeFocused()
+ })
+
+ test('mobile drawer: contained focus, Escape, return to the menu button @phone', async ({
+ page,
+ requests,
+ }) => {
+ const account = await createAccount(locale, false)
+ requests.forbid(account.email, account.password, account.displayName)
+ await signIn(page, account, dict)
+
+ const menu = page.getByRole('button', { name: dict['shell.open_menu'] })
+ await menu.focus()
+ await page.keyboard.press('Enter')
+ const drawer = page.getByRole('dialog', { name: dict['shell.nav_label'] })
+ await expect(drawer).toBeVisible()
+ expect(await focusOwner(page)).toBe('dialog')
+ const steps = await tabWalk(page, 12)
+ expect(
+ steps.filter((step) => step.startsWith('outside') || step === 'body'),
+ ).toEqual([])
+ expect(steps).toContain(dict['shell.sign_out'])
+ expect(steps).toContain('browser')
+ await expectAccessible(page, 'the open drawer')
+ await expectNoHorizontalOverflow(page, 'the open drawer')
+ await page.keyboard.press('Escape')
+ await expect(drawer).toBeHidden()
+ await expect(menu).toBeFocused()
+
+ await page.keyboard.press('Enter')
+ await drawer
+ .getByRole('link', { name: dict['shell.nav.account'] })
+ .click()
+ await expect(drawer).toBeHidden()
+ await expect(page).toHaveURL(/\/app\/account$/)
+
+ // Widening past the sidebar breakpoint closes the drawer and frees the page.
+ await menu.click()
+ await expect(drawer).toBeVisible()
+ await page.setViewportSize({ width: 1280, height: 800 })
+ await expect(drawer).toBeHidden()
+ await page
+ .getByRole('link', { name: dict['shell.nav.dashboard'] })
+ .first()
+ .click()
+ await expect(page).toHaveURL(/\/app\/?$/)
+ })
+ })
+}
diff --git a/apps/app/e2e/support/browser.ts b/apps/app/e2e/support/browser.ts
new file mode 100644
index 00000000..674c4182
--- /dev/null
+++ b/apps/app/e2e/support/browser.ts
@@ -0,0 +1,220 @@
+/**
+ * Shared pieces of the Playwright suites (docs/development/BROWSER_TESTS.md):
+ * the two Chromium projects, the request guard every test runs under, the axe
+ * gate, and the focus and layout probes.
+ */
+import AxeBuilder from '@axe-core/playwright'
+import {
+ devices,
+ expect,
+ test as base,
+ type Page,
+ type Project,
+} from '@playwright/test'
+
+/**
+ * Desktop and the 375 × 667 phone of the V1-1 contract (§12.5); Chromium only
+ * until V1-5. A test tagged `@phone` covers what exists on small screens only.
+ */
+export const PROJECTS: Project[] = [
+ {
+ name: 'chromium-desktop',
+ grepInvert: /@phone/,
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 1280, height: 800 },
+ },
+ },
+ {
+ name: 'chromium-375',
+ use: {
+ ...devices['Desktop Chrome'],
+ viewport: { width: 375, height: 667 },
+ deviceScaleFactor: 2,
+ isMobile: true,
+ hasTouch: true,
+ },
+ },
+]
+
+export interface GuardOptions {
+ /** Origins the page may reach; every other request is aborted and fails the test. */
+ allowedOrigins: string[]
+ /** Strings no request URL may carry (fixture names, emails, search terms). */
+ forbiddenInUrls: string[]
+}
+
+export interface RequestGuard {
+ /** Adds values made during the test (a fictitious account) to `forbiddenInUrls`. */
+ forbid: (...values: string[]) => void
+}
+
+/**
+ * Every test runs under a request guard: a request to an origin outside the
+ * allowlist (the DEV stack, a CDN, anything) is aborted, and the test fails
+ * listing it, as it fails on a URL holding a fixture value (masked in the
+ * report, which never shows the value itself).
+ */
+export const test = base.extend({
+ allowedOrigins: [[], { option: true }],
+ forbiddenInUrls: [[], { option: true }],
+ requests: [
+ async ({ context, allowedOrigins, forbiddenInUrls }, use) => {
+ const forbidden = forbiddenInUrls.filter((value) => value !== '')
+ const refused: string[] = []
+ const leaking: string[] = []
+ const mask = (url: string) =>
+ forbidden.reduce(
+ (masked, value) => masked.replaceAll(value, ''),
+ url,
+ )
+ await context.route(
+ (url) => !allowedOrigins.includes(url.origin),
+ (route) => {
+ refused.push(mask(decodeURIComponent(route.request().url())))
+ return route.abort('blockedbyclient')
+ },
+ )
+ context.on('request', (request) => {
+ const url = decodeURIComponent(request.url())
+ if (forbidden.some((value) => url.includes(value)))
+ leaking.push(mask(url))
+ })
+ await use({
+ forbid: (...values) =>
+ forbidden.push(...values.filter((v) => v !== '')),
+ })
+ expect(refused, 'requests outside the allowed origins').toEqual([])
+ expect(leaking, 'request URLs carrying a fixture value').toEqual([])
+ },
+ { auto: true },
+ ],
+})
+
+export { expect }
+
+/**
+ * Serious violations found before V1-1.3, outside its code, listed in TODO RR-7
+ * until their own fix: the scan lets through only the node that matches the
+ * rule, the selector, the opening markup and the route of each entry, and fails
+ * on any other, so a new screen or a new element never inherits an exception
+ * (WCAG 2.5.3 label in name, 1.3.1 info and relationships).
+ */
+const KNOWN_VIOLATIONS: {
+ id: string
+ target: RegExp
+ html: RegExp
+ path: RegExp
+ note: string
+}[] = [
+ {
+ id: 'label-content-name-mismatch',
+ target: /^button\[aria-label="(Passer en français|Switch to English)"\]$/,
+ html: /^]*aria-label="(Passer en français|Switch to English)"/,
+ path: /^\//,
+ note: 'LanguageSwitcher (every page): shows « FR » / « EN », named « Passer en français » / « Switch to English »',
+ },
+ {
+ id: 'label-content-name-mismatch',
+ target: /^\.pr-1$/,
+ html: /^]*href="\/app\/account"/,
+ path: /^\/app(\/|$)/,
+ note: 'AppLayout top bar account link: shows the display name, named « Mon compte » / « My account »',
+ },
+ {
+ id: 'definition-list',
+ target: /^dl$/,
+ html: /^/,
+ path: /^\/app\/?$/,
+ note: 'DashboardRoute account card: the verified-status row is a div without dt/dd inside the dl',
+ },
+]
+
+const isKnown = (id: string, target: string, html: string, path: string) =>
+ KNOWN_VIOLATIONS.some(
+ (known) =>
+ known.id === id &&
+ known.target.test(target) &&
+ known.html.test(html) &&
+ known.path.test(path),
+ )
+
+/**
+ * Zero serious or critical axe violation on the page as it stands (WCAG 2.0 to
+ * 2.2 A and AA rules plus axe best practices), known ones aside; the failure
+ * message lists them.
+ */
+export async function expectAccessible(
+ page: Page,
+ state: string,
+): Promise {
+ // Colours are measured at rest: an entrance animation still running would blend them.
+ await page.waitForFunction(() =>
+ document
+ .getAnimations()
+ .every((animation) => animation.playState !== 'running'),
+ )
+ const { violations } = await new AxeBuilder({ page })
+ .withTags([
+ 'wcag2a',
+ 'wcag2aa',
+ 'wcag21a',
+ 'wcag21aa',
+ 'wcag22aa',
+ 'best-practice',
+ ])
+ .analyze()
+ const path = new URL(page.url()).pathname
+ const blocking = violations
+ .filter((v) => v.impact === 'serious' || v.impact === 'critical')
+ .flatMap((v) =>
+ v.nodes
+ .filter(
+ (node) => !isKnown(v.id, node.target.join(' '), node.html, path),
+ )
+ .map(
+ (node) =>
+ `${v.impact} ${v.id}: ${v.help} → ${node.target.join(' ')} on ${path}`,
+ ),
+ )
+ expect(blocking, `axe on ${state}`).toEqual([])
+}
+
+/**
+ * Where the focus is: in the open modal dialog, in the browser's own interface
+ * (the document lost focus, as Tab past a modal dialog's last control does), or
+ * on something else of the page.
+ */
+export function focusOwner(page: Page): Promise {
+ return page.evaluate(() => {
+ const active = document.activeElement
+ if (!document.hasFocus()) return 'browser'
+ if (!active || active === document.body) return 'body'
+ if (active.closest('dialog:modal')) return 'dialog'
+ return `outside:${active.tagName.toLowerCase()}:${active.textContent?.trim().slice(0, 40)}`
+ })
+}
+
+/** Accessible name of the focused element (aria-label, else its text). */
+export function focusedName(page: Page): Promise {
+ return page.evaluate(() => {
+ const active = document.activeElement as HTMLElement | null
+ return (
+ active?.getAttribute('aria-label') ?? active?.textContent?.trim() ?? ''
+ )
+ })
+}
+
+/** No horizontal page scroll: the document is no wider than the viewport. */
+export async function expectNoHorizontalOverflow(
+ page: Page,
+ state: string,
+): Promise {
+ const { scrollWidth, clientWidth } = await page.evaluate(() => ({
+ scrollWidth: document.documentElement.scrollWidth,
+ clientWidth: document.documentElement.clientWidth,
+ }))
+ expect(scrollWidth, `horizontal overflow on ${state}`).toBeLessThanOrEqual(
+ clientWidth,
+ )
+}
diff --git a/apps/app/e2e/support/records.ts b/apps/app/e2e/support/records.ts
new file mode 100644
index 00000000..4770b0e1
--- /dev/null
+++ b/apps/app/e2e/support/records.ts
@@ -0,0 +1,58 @@
+/**
+ * Setup rows of the shell suites, written as postgres in an account's
+ * workspace of the isolated stack: the subject of a test goes through the
+ * page, its surroundings through here. Values are fictitious literals; each
+ * one is quoted as an SQL literal, never pasted raw.
+ */
+import { sql } from '../../../../packages/supabase/tests/sandbox/stack'
+import { workspaceOf, type SandboxAccount } from './sandbox'
+
+/** A text as an SQL literal ('' doubles a quote), or null. */
+export const literal = (value: string | null) =>
+ value === null ? 'null' : `'${value.replaceAll("'", "''")}'`
+
+export interface ClientSeed {
+ kind?: 'person' | 'organization'
+ city?: string | null
+ phone?: string | null
+ email?: string | null
+ addressLine1?: string | null
+}
+
+export async function seedClient(
+ account: SandboxAccount,
+ displayName: string,
+ seed: ClientSeed = {},
+): Promise {
+ const ws = await workspaceOf(account)
+ return sql(`insert into public.clients (workspace_id, kind, display_name, city, phone, email, address_line1,
+ create_request_id, create_request_digest)
+ values (${literal(ws)}, ${literal(seed.kind ?? 'person')}, ${literal(displayName)}, ${literal(seed.city ?? null)},
+ ${literal(seed.phone ?? null)}, ${literal(seed.email ?? null)}, ${literal(seed.addressLine1 ?? null)},
+ gen_random_uuid(), '\\x00') returning id`)
+}
+
+export async function seedAnimal(
+ account: SandboxAccount,
+ name: string,
+ speciesId = 'equine',
+ sex: 'male' | 'female' | 'unknown' = 'female',
+): Promise {
+ const ws = await workspaceOf(account)
+ return sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+ values (${literal(ws)}, ${literal(name)}, ${literal(speciesId)}, ${literal(sex)}, gen_random_uuid(), '\\x00') returning id`)
+}
+
+export async function seedRelation(
+ account: SandboxAccount,
+ animalId: string,
+ clientId: string,
+ role: 'owner' | 'keeper' | 'contact',
+ startedOn: string | null = null,
+): Promise {
+ const ws = await workspaceOf(account)
+ return sql(`insert into public.animal_client_relations
+ (workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest)
+ values (${literal(ws)}, ${literal(animalId)}, ${literal(clientId)}, ${literal(role)}, ${literal(startedOn)},
+ gen_random_uuid(), '\\x00') returning id`)
+}
diff --git a/apps/app/e2e/support/sandbox.ts b/apps/app/e2e/support/sandbox.ts
new file mode 100644
index 00000000..4f34dda7
--- /dev/null
+++ b/apps/app/e2e/support/sandbox.ts
@@ -0,0 +1,133 @@
+/**
+ * The shell suite's backend: the throwaway stack of `pnpm db:sandbox`, never
+ * DEV. The app is built against a fake origin that resolves nowhere; every
+ * request to it is replayed on the sandbox's loopback services, the way Kong
+ * maps them on the CLI stack. Accounts are fictitious and made per test.
+ */
+import { createHash, randomBytes, randomUUID } from 'node:crypto'
+import type { BrowserContext } from '@playwright/test'
+import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
+
+/** The Supabase URL the e2e:shell dev server is built with (RFC 6761 `.invalid`). */
+export const FAKE_SUPABASE_ORIGIN = 'http://sandbox.faunosteo.invalid'
+
+const storageUrl = process.env.SANDBOX_STORAGE_URL
+if (!storageUrl)
+ throw new Error('SANDBOX_STORAGE_URL missing: run pnpm e2e:shell')
+
+const ROUTES: [prefix: string, target: string][] = [
+ ['/auth/v1/', `${stack.authUrl}/`],
+ ['/rest/v1/', `${stack.restUrl}/`],
+ ['/storage/v1/', `${storageUrl}/`],
+]
+
+/** The sandbox URL a request to the fake Supabase origin maps to, or null when unmapped. */
+export function sandboxUrl(url: string): string | null {
+ const { pathname, search } = new URL(url)
+ const path = pathname + search
+ const mapped = ROUTES.find(([prefix]) => path.startsWith(prefix))
+ return mapped ? mapped[1] + path.slice(mapped[0].length) : null
+}
+
+/** Replays the page's Supabase calls on the sandbox; an unmapped path is refused. */
+export async function routeToSandbox(context: BrowserContext): Promise {
+ await context.route(`${FAKE_SUPABASE_ORIGIN}/**`, async (route) => {
+ const target = sandboxUrl(route.request().url())
+ if (!target) return route.abort('blockedbyclient')
+ const response = await route.fetch({ url: target })
+ await route.fulfill({ response })
+ })
+}
+
+/**
+ * After a test: removes the replay without waiting for it. A page may still be
+ * reading (a list, a section reloaded after a change) when the last check
+ * passed; that answer is dropped with the context instead of failing the test.
+ */
+export async function dropLateReplays(context: BrowserContext): Promise {
+ await context.unrouteAll({ behavior: 'ignoreErrors' })
+}
+
+/** 1 × 1 lossless WebP: a real image for the clean avatar the account starts with. */
+const AVATAR_WEBP = Buffer.from(
+ 'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==',
+ 'base64',
+)
+
+export interface SandboxAccount {
+ id: string
+ email: string
+ password: string
+ displayName: string
+}
+
+async function admin(path: string, init: RequestInit): Promise {
+ const response = await fetch(`${stack.authUrl}${path}`, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${stack.serviceKey}`,
+ apikey: stack.serviceKey,
+ 'Content-Type': 'application/json',
+ },
+ })
+ if (!response.ok)
+ throw new Error(`sandbox admin ${path}: HTTP ${response.status}`)
+ return response
+}
+
+/** The clean avatar the worker would have produced: row as postgres, object with the service key. */
+async function seedAvatar(ownerId: string): Promise {
+ const assetId = randomUUID()
+ const key = `profiles/${ownerId}/${assetId}/avatar.webp`
+ const sha256 = createHash('sha256').update(AVATAR_WEBP).digest('hex')
+ const upload = await fetch(`${storageUrl}/object/avatars/${key}`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${stack.serviceKey}`,
+ 'Content-Type': 'image/webp',
+ },
+ body: AVATAR_WEBP,
+ })
+ if (!upload.ok)
+ throw new Error(`sandbox avatar upload: HTTP ${upload.status}`)
+ await sql(`insert into public.assets
+ (id, owner_id, kind, bucket_id, object_key, status, declared_mime, declared_size, byte_size, sha256)
+ values ('${assetId}', '${ownerId}', 'profile_avatar', 'avatars', '${key}', 'clean',
+ 'image/webp', ${AVATAR_WEBP.length}, ${AVATAR_WEBP.length}, '${sha256}')`)
+}
+
+/**
+ * A confirmed fictitious account, its profile in `locale`, with or without a
+ * photo; `localPart` starts the address (a long one tests narrow screens).
+ */
+export async function createAccount(
+ locale: 'fr' | 'en',
+ withAvatar: boolean,
+ localPart = 'e2e-shell',
+): Promise {
+ const tag = randomUUID().slice(0, 8)
+ const account = {
+ email: `${localPart}-${tag}@sandbox.local`,
+ password: randomBytes(18).toString('base64url'),
+ displayName: `Praticienne Fictive ${tag}`,
+ }
+ const response = await admin('/admin/users', {
+ method: 'POST',
+ body: JSON.stringify({
+ email: account.email,
+ password: account.password,
+ email_confirm: true,
+ user_metadata: { display_name: account.displayName, locale },
+ }),
+ })
+ const { id } = (await response.json()) as { id: string }
+ if (withAvatar) await seedAvatar(id)
+ return { ...account, id }
+}
+
+/** The personal workspace of a sandbox account (created by the server at sign-up). */
+export function workspaceOf(account: SandboxAccount): Promise {
+ return sql(
+ `select id from public.workspaces where personal_user_id = '${account.id}'`,
+ )
+}
diff --git a/apps/app/e2e/support/shell.ts b/apps/app/e2e/support/shell.ts
new file mode 100644
index 00000000..95c9d9c7
--- /dev/null
+++ b/apps/app/e2e/support/shell.ts
@@ -0,0 +1,17 @@
+import type { Dict } from '@/i18n/types'
+import type { Page } from '@playwright/test'
+import { expect } from './browser'
+import type { SandboxAccount } from './sandbox'
+
+/** Signs in through the login form; resolves on the dashboard once the profile answered. */
+export async function signIn(page: Page, account: SandboxAccount, dict: Dict) {
+ await page.goto('/login')
+ await page.getByLabel(dict['auth.email']).fill(account.email)
+ await page
+ .getByLabel(dict['auth.password'], { exact: true })
+ .fill(account.password)
+ await page.getByRole('button', { name: dict['auth.login.submit'] }).click()
+ await expect(page).toHaveURL(/\/app\/?$/)
+ // The greeting needs the profile: the session and the first REST call went through.
+ await expect(page.locator('main h1')).toContainText(account.displayName)
+}
diff --git a/apps/app/e2e/tsconfig.json b/apps/app/e2e/tsconfig.json
new file mode 100644
index 00000000..ea6716e8
--- /dev/null
+++ b/apps/app/e2e/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "types": ["node", "vite/client"],
+ "baseUrl": "..",
+ "paths": {
+ "@/*": ["src/*"]
+ }
+ },
+ "include": ["."]
+}
diff --git a/apps/app/e2e/ui/dialog.spec.ts b/apps/app/e2e/ui/dialog.spec.ts
new file mode 100644
index 00000000..833b6bb0
--- /dev/null
+++ b/apps/app/e2e/ui/dialog.spec.ts
@@ -0,0 +1,216 @@
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import {
+ expect,
+ expectAccessible,
+ expectNoHorizontalOverflow,
+ focusOwner,
+ focusedName,
+ test,
+} from '../support/browser'
+import type { Page } from '@playwright/test'
+
+// The D13 contract of components/ui/Dialog on its test page (e2e/harness/dialog.tsx).
+
+async function openScenario(page: Page, opener: string, title: string) {
+ await page.getByRole('button', { name: opener }).focus()
+ await page.keyboard.press('Enter')
+ const dialog = page.getByRole('dialog', { name: title })
+ await expect(dialog).toBeVisible()
+ return dialog
+}
+
+/** Names of the elements the focus visits over `count` presses of `key`. */
+async function focusWalk(page: Page, key: 'Tab' | 'Shift+Tab', count: number) {
+ const visited: { owner: string; name: string }[] = []
+ for (let i = 0; i < count; i++) {
+ await page.keyboard.press(key)
+ visited.push({
+ owner: await focusOwner(page),
+ name: await focusedName(page),
+ })
+ }
+ return visited
+}
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/e2e/harness/dialog.html')
+ await expect(
+ page.getByRole('heading', { name: 'Dialog harness' }),
+ ).toBeVisible()
+})
+
+test('is a named, described modal dialog and moves focus into it', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
+ await expect(dialog).toHaveAccessibleDescription('Three controls follow.')
+ expect(
+ await dialog.evaluate((d) => d.tagName === 'DIALOG' && d.matches(':modal')),
+ ).toBe(true)
+ expect(await focusOwner(page)).toBe('dialog')
+ expect(await focusedName(page)).toBe(fr['common.close'])
+})
+
+// Past either end the focus visits the browser's interface (one step, the page
+// holds no focus) and comes back into the dialog; it never reaches the page.
+test('Tab and Shift+Tab cycle through the dialog, never the page', async ({
+ page,
+}) => {
+ await openScenario(page, 'Open basic', 'Basic dialog')
+ const step = (f: { owner: string; name: string }) =>
+ f.owner === 'dialog' ? f.name : f.owner
+ const forward = await focusWalk(page, 'Tab', 10)
+ expect(forward.map(step)).toEqual([
+ 'First',
+ 'Second',
+ 'Done',
+ 'browser',
+ fr['common.close'],
+ 'First',
+ 'Second',
+ 'Done',
+ 'browser',
+ fr['common.close'],
+ ])
+ const backward = await focusWalk(page, 'Shift+Tab', 10)
+ expect(backward.map(step)).toEqual([
+ 'browser',
+ 'Done',
+ 'Second',
+ 'First',
+ fr['common.close'],
+ 'browser',
+ 'Done',
+ 'Second',
+ 'First',
+ fr['common.close'],
+ ])
+})
+
+test('the page behind is inert: no focus, no click, no scroll', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog')
+ const background = page.getByRole('button', {
+ name: 'Background action',
+ includeHidden: true,
+ })
+ const box = await background.boundingBox()
+ if (!box) throw new Error('background button not laid out')
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
+ await background.evaluate((b) => (b as HTMLElement).focus())
+ expect(await focusOwner(page)).toBe('dialog')
+ await page.mouse.move(box.x + 5, box.y + 5)
+ await page.mouse.wheel(0, 800)
+ await page.waitForTimeout(200)
+ expect(await page.evaluate(() => window.scrollY)).toBe(0)
+ await expect(dialog).toBeVisible()
+ await expect(page.getByTestId('background-clicks')).toHaveText('0')
+})
+
+test('Escape closes when allowed and focus returns to the opener', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ expect(await focusedName(page)).toBe('Open basic')
+ await expect(
+ page.getByRole('button', { name: 'Background action' }),
+ ).toBeEnabled()
+})
+
+test('Escape is only a request: refused twice, the dialog stays open', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog')
+ await page.keyboard.press('Escape')
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeVisible()
+ expect(await dialog.evaluate((d) => (d as HTMLDialogElement).open)).toBe(true)
+ expect(await focusOwner(page)).toBe('dialog')
+ await page.getByRole('checkbox', { name: 'Busy' }).uncheck()
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ expect(await focusedName(page)).toBe('Open guarded')
+})
+
+test('the close button closes from the keyboard and restores focus', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
+ expect(await focusedName(page)).toBe(fr['common.close'])
+ await page.keyboard.press('Enter')
+ await expect(dialog).toBeHidden()
+ expect(await focusedName(page)).toBe('Open basic')
+})
+
+test('an opener gone on close hands focus to its container’s first control', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Remove item', 'Remove the item?')
+ await page.getByRole('button', { name: 'Confirm removal' }).click()
+ await expect(dialog).toBeHidden()
+ await expect(page.getByRole('button', { name: 'Remove item' })).toHaveCount(0)
+ expect(await focusedName(page)).toBe('Add item')
+})
+
+test('long content scrolls inside the panel, the page stays put', async ({
+ page,
+}) => {
+ const dialog = await openScenario(page, 'Open long', 'Long dialog')
+ const panel = dialog.locator('header').locator('..')
+ const { scrollHeight, clientHeight } = await panel.evaluate((p) => ({
+ scrollHeight: p.scrollHeight,
+ clientHeight: p.clientHeight,
+ }))
+ expect(scrollHeight).toBeGreaterThan(clientHeight)
+ expect(await focusedName(page)).toBe(fr['common.close'])
+ await page.keyboard.press('Tab')
+ const end = page.getByRole('button', { name: 'End of content' })
+ await expect(end).toBeFocused()
+ await expect(end).toBeInViewport()
+ expect(await page.evaluate(() => window.scrollY)).toBe(0)
+ const box = await panel.boundingBox()
+ const viewport = page.viewportSize()
+ expect(
+ box && viewport && box.y >= 0 && box.y + box.height <= viewport.height,
+ ).toBe(true)
+})
+
+test('fits the viewport without horizontal page scroll', async ({ page }) => {
+ await expectNoHorizontalOverflow(page, 'the page')
+ for (const [opener, title] of [
+ ['Open basic', 'Basic dialog'],
+ ['Open long', 'Long dialog'],
+ ]) {
+ const dialog = await openScenario(page, opener, title)
+ const box = await dialog.locator('header').locator('..').boundingBox()
+ const width = page.viewportSize()?.width ?? 0
+ expect(
+ box && box.x >= 0 && box.x + box.width <= width,
+ `${title} inside the viewport`,
+ ).toBe(true)
+ await expectNoHorizontalOverflow(page, title)
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ }
+})
+
+for (const [lang, dict] of [
+ ['fr', fr],
+ ['en', en],
+] as const) {
+ test(`axe finds no serious violation, close control named in ${lang}`, async ({
+ page,
+ }) => {
+ await page.goto(`/e2e/harness/dialog.html?lang=${lang}`)
+ await expectAccessible(page, `the harness (${lang})`)
+ await openScenario(page, 'Open basic', 'Basic dialog')
+ await expect(
+ page.getByRole('button', { name: dict['common.close'] }),
+ ).toBeFocused()
+ await expectAccessible(page, `the open dialog (${lang})`)
+ })
+}
diff --git a/apps/app/e2e/ui/local-tool.spec.ts b/apps/app/e2e/ui/local-tool.spec.ts
new file mode 100644
index 00000000..547613cf
--- /dev/null
+++ b/apps/app/e2e/ui/local-tool.spec.ts
@@ -0,0 +1,104 @@
+import { en } from '@/i18n/en'
+import { fr } from '@/i18n/fr'
+import {
+ expect,
+ expectAccessible,
+ expectNoHorizontalOverflow,
+ focusOwner,
+ focusedName,
+ test,
+} from '../support/browser'
+import type { Page } from '@playwright/test'
+import type { Dict } from '@/i18n/types'
+
+// The shared Dialog where the local tool uses it, on the real routes with no
+// backend: the sheet disclaimer, the edit dialog and the replace confirmation.
+// Fictitious names only.
+
+const ANIMAL = 'Fictif Alezan'
+
+/** Required label text without the trailing « * » marker. */
+const label = (dict: Dict, key: string) => dict[key].replace(/\s*\*$/, '')
+
+async function startReport(page: Page, dict: Dict) {
+ await page
+ .getByLabel(label(dict, 'form.practitioner.name'))
+ .fill('Praticien Fictif')
+ await page.getByLabel(label(dict, 'form.animal.name')).fill(ANIMAL)
+ await page
+ .getByLabel(label(dict, 'form.owner.name'))
+ .fill('Propriétaire Fictif')
+ await page.getByRole('button', { name: dict['new_report.submit'] }).click()
+}
+
+for (const [locale, dict] of [
+ ['fr-FR', fr],
+ ['en-GB', en],
+] as const) {
+ test.describe(`local tool (${locale})`, () => {
+ test.use({ locale, forbiddenInUrls: [ANIMAL, 'Fictif'] })
+
+ test('editor dialogs: disclaimer, edit, replace confirmation', async ({
+ page,
+ }) => {
+ await page.goto('/')
+ // Scanned once the sheet is loaded: the import button fades in from disabled.
+ await expect(
+ page.getByRole('button', { name: dict['home.import.cta'] }),
+ ).toBeEnabled()
+ await expectAccessible(page, 'home')
+ await page
+ .getByRole('button', { name: dict['home.new_report.cta'] })
+ .click()
+ await expect(page).toHaveURL(/\/new$/)
+ await expectNoHorizontalOverflow(page, 'new report')
+ await startReport(page, dict)
+
+ await expect(page).toHaveURL(/\/editor$/)
+ const disclaimer = page.getByRole('dialog', {
+ name: dict['editor.disclaimer_title'],
+ })
+ await expect(disclaimer).toBeVisible()
+ expect(await disclaimer.getAttribute('aria-describedby')).toBeTruthy()
+ expect(await focusOwner(page)).toBe('dialog')
+ expect(await focusedName(page)).toBe(dict['common.close'])
+ await page.keyboard.press('Tab')
+ expect(await focusedName(page)).toBe(dict['common.understood'])
+ await expectAccessible(page, 'editor with the disclaimer')
+ await expectNoHorizontalOverflow(page, 'editor with the disclaimer')
+ await page.keyboard.press('Escape')
+ await expect(disclaimer).toBeHidden()
+
+ const edit = page.getByRole('button', { name: dict['editor.edit_infos'] })
+ await edit.focus()
+ await page.keyboard.press('Enter')
+ const editDialog = page.getByRole('dialog', {
+ name: dict['editor.edit_dialog_title'],
+ })
+ await expect(editDialog).toBeVisible()
+ expect(await focusOwner(page)).toBe('dialog')
+ await expectNoHorizontalOverflow(page, 'edit dialog')
+ await page.keyboard.press('Escape')
+ await expect(editDialog).toBeHidden()
+ await expect(edit).toBeFocused()
+
+ // A reload: the bilan stays in the tab, not yet in the store (the « unloaded » message).
+ await page.goto('/new')
+ await startReport(page, dict)
+ const replace = page.getByRole('dialog', {
+ name: dict['session.replace.title'],
+ })
+ await expect(replace).toBeVisible()
+ await expect(replace).toHaveAccessibleDescription(
+ dict['session.replace.body_unloaded'],
+ )
+ await expectAccessible(page, 'replace confirmation')
+ await page.keyboard.press('Escape')
+ await expect(replace).toBeHidden()
+ await expect(page).toHaveURL(/\/new$/)
+ await expect(
+ page.getByRole('button', { name: dict['new_report.submit'] }),
+ ).toBeFocused()
+ })
+ })
+}
diff --git a/apps/app/package.json b/apps/app/package.json
index 121dad4f..efe9a954 100644
--- a/apps/app/package.json
+++ b/apps/app/package.json
@@ -8,10 +8,12 @@
"dev": "vite",
"build": "tsc -p tsconfig.json --noEmit && vite build",
"preview": "vite preview",
- "typecheck": "tsc -p tsconfig.json --noEmit",
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p e2e/tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
- "lint": "eslint . --max-warnings 0"
+ "lint": "eslint . --max-warnings 0",
+ "e2e:ui": "playwright test -c e2e/playwright.ui.config.ts",
+ "e2e:shell": "playwright test -c e2e/playwright.shell.config.ts"
},
"dependencies": {
"@faunosteo/core-wasm": "workspace:*",
@@ -24,6 +26,8 @@
"zustand": "^5.0.2"
},
"devDependencies": {
+ "@axe-core/playwright": "4.14.0",
+ "@playwright/test": "1.64.1",
"@tailwindcss/vite": "^4.3.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
diff --git a/apps/app/src/animals/age.ts b/apps/app/src/animals/age.ts
new file mode 100644
index 00000000..6e0ca5c6
--- /dev/null
+++ b/apps/app/src/animals/age.ts
@@ -0,0 +1,29 @@
+/**
+ * The age shown on an animal's page, for display only (contract §5.2): from
+ * the full date when known, else « environ N ans » from the year. Nothing is
+ * stored or sent.
+ */
+export interface AnimalAge {
+ unit: 'year' | 'month'
+ count: number
+ /** From the year alone: the day is unknown. */
+ about: boolean
+}
+
+export function animalAge(
+ birthYear: number | null,
+ birthDate: string | null,
+ today: string,
+): AnimalAge | null {
+ const [ty, tm, td] = today.split('-').map(Number)
+ if (birthDate) {
+ const [by, bm, bd] = birthDate.split('-').map(Number)
+ const months = (ty - by) * 12 + (tm - bm) - (td < bd ? 1 : 0)
+ if (months < 0) return null
+ return months >= 12
+ ? { unit: 'year', count: Math.floor(months / 12), about: false }
+ : { unit: 'month', count: months, about: false }
+ }
+ if (birthYear === null || birthYear > ty) return null
+ return { unit: 'year', count: ty - birthYear, about: true }
+}
diff --git a/apps/app/src/animals/species.tsx b/apps/app/src/animals/species.tsx
new file mode 100644
index 00000000..0c445b4c
--- /dev/null
+++ b/apps/app/src/animals/species.tsx
@@ -0,0 +1,100 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useState,
+ type ReactNode,
+} from 'react'
+import {
+ classifyRecordError,
+ fetchSpeciesLabels,
+ type RecordFailureKind,
+ type SpeciesLabel,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
+import type { Locale } from '@/i18n/types'
+
+export type SpeciesState =
+ | { status: 'idle' }
+ | { status: 'loading' }
+ | { status: 'ready'; labels: SpeciesLabel[] }
+ | { status: 'error'; failure: RecordFailureKind }
+
+interface SpeciesContextValue {
+ state: SpeciesState
+ /** Starts the read once; later calls change nothing. */
+ request: () => void
+ retry: () => void
+}
+
+const SpeciesContext = createContext(null)
+
+/**
+ * The active species (reference rows of contract §5.4), read once per
+ * workspace and only when a page needs them: the list filter, the form and
+ * the record pages share one answer. Mounted under RequireWorkspace, it
+ * leaves with the workspace on a change of account.
+ */
+export function SpeciesProvider({ children }: { children: ReactNode }) {
+ const [state, setState] = useState({ status: 'idle' })
+ // 0 until a page asks; each retry bumps it.
+ const [attempt, setAttempt] = useState(0)
+
+ useEffect(() => {
+ if (attempt === 0) return
+ let live = true
+ const client = getSupabaseClient()
+ setState({ status: 'loading' })
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ fetchSpeciesLabels(client)
+ .then((labels) => {
+ if (live) setState({ status: 'ready', labels })
+ })
+ .catch((error: unknown) => {
+ if (live)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ return () => {
+ live = false
+ }
+ }, [attempt])
+
+ const request = useCallback(() => setAttempt((n) => (n === 0 ? 1 : n)), [])
+ const retry = useCallback(() => setAttempt((n) => n + 1), [])
+ const value = useMemo(
+ () => ({ state, request, retry }),
+ [state, request, retry],
+ )
+ return (
+ {children}
+ )
+}
+
+/** The species labels of the workspace; the first page that asks starts the read. */
+export function useSpecies(): Omit {
+ const context = useContext(SpeciesContext)
+ if (!context) throw new Error('useSpecies needs a SpeciesProvider')
+ const { request } = context
+ useEffect(() => request(), [request])
+ return { state: context.state, retry: context.retry }
+}
+
+/** The species name in the locale, followed by the « Autre » detail when there is one. */
+export function speciesName(
+ labels: readonly SpeciesLabel[],
+ speciesId: string,
+ detail: string | null,
+ locale: Locale,
+): string {
+ const label = labels.find((s) => s.id === speciesId)
+ const name = label
+ ? pickLocaleLabel(label.name_fr, label.name_en, locale, speciesId)
+ : speciesId
+ return detail ? `${name} (${detail})` : name
+}
diff --git a/apps/app/src/animals/useAnimalForm.ts b/apps/app/src/animals/useAnimalForm.ts
new file mode 100644
index 00000000..958a029c
--- /dev/null
+++ b/apps/app/src/animals/useAnimalForm.ts
@@ -0,0 +1,232 @@
+import { useRef, useState, type FormEvent } from 'react'
+import {
+ classifyRecordError,
+ createAnimalRecord,
+ fetchAnimalRecord,
+ updateAnimalRecord,
+ type AnimalRecord,
+ type AnimalRelationRole,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { generateUuid } from '@/lib/id'
+import { localDateIso } from '@/lib/dates'
+import {
+ EMPTY_ANIMAL_VALUES,
+ EMPTY_RELATION_VALUES,
+ animalFieldErrors,
+ animalFormValues,
+ animalSchema,
+ relationIssues,
+ withBirthDate,
+ type AnimalFieldErrors,
+ type AnimalFormValues,
+ type RelationFieldErrors,
+ type RelationFormValues,
+} from './validation'
+
+export interface PickedClient {
+ id: string
+ display_name: string
+}
+
+export type AnimalFormTarget =
+ | {
+ mode: 'create'
+ workspaceId: string
+ /** The client the form opened from, pre-associated; the practitioner may remove it. */
+ initialClient: PickedClient | null
+ }
+ | { mode: 'edit'; record: AnimalRecord }
+
+export type AnimalFormPhase =
+ | { kind: 'idle' }
+ | { kind: 'saving' }
+ | { kind: 'failed'; failure: RecordFailureKind }
+
+export interface AnimalSaved {
+ animalId: string
+ /** The client the new animal was linked to, if any. */
+ linkedClientId: string | null
+}
+
+const FIELDS = Object.keys(EMPTY_ANIMAL_VALUES) as (keyof AnimalFormValues)[]
+
+function sameValues(a: AnimalFormValues, b: AnimalFormValues): boolean {
+ return FIELDS.every((key) => a[key] === b[key])
+}
+
+function sameRelation(a: RelationFormValues, b: RelationFormValues): boolean {
+ return (
+ a.client?.id === b.client?.id &&
+ a.relation_role === b.relation_role &&
+ a.started_on === b.started_on
+ )
+}
+
+/**
+ * The animal form: typed values, the D-R7 schema, one save. A create keeps
+ * one request id for the life of the form, and sends the animal with its
+ * optional first client in one create_animal call, so a retry after a lost
+ * answer returns the animal (and relation) already made. An update sends the
+ * revision it was read at; on `conflict` the stored animal is shown beside
+ * the typed values, which stay.
+ */
+export function useAnimalForm(
+ target: AnimalFormTarget,
+ activeSpeciesIds: readonly string[],
+ onSaved: (saved: AnimalSaved) => void,
+) {
+ const initial =
+ target.mode === 'edit'
+ ? animalFormValues(target.record)
+ : EMPTY_ANIMAL_VALUES
+ const initialRelation: RelationFormValues =
+ target.mode === 'create'
+ ? { ...EMPTY_RELATION_VALUES, client: target.initialClient }
+ : EMPTY_RELATION_VALUES
+ const [values, setValues] = useState(initial)
+ const [baseline, setBaseline] = useState(initial)
+ const [relation, setRelation] = useState(initialRelation)
+ const [relationBaseline, setRelationBaseline] = useState(initialRelation)
+ const [errors, setErrors] = useState({})
+ const [relationErrors, setRelationErrors] = 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 AnimalFormValues) => (value: string) =>
+ setValues((v) => ({ ...v, [key]: value }))
+ const setBirthDate = (value: string) =>
+ setValues((v) => withBirthDate(v, value))
+ const chooseClient = (client: PickedClient | null) =>
+ setRelation((r) => ({ ...r, client }))
+ const setRelationRole = (role: AnimalRelationRole) =>
+ setRelation((r) => ({ ...r, relation_role: role }))
+ const setStartedOn = (value: string) =>
+ setRelation((r) => ({ ...r, started_on: value }))
+
+ /** The species the form may send: on an edit, the stored one even if it left the active list. */
+ const speciesIds =
+ target.mode === 'edit' &&
+ !activeSpeciesIds.includes(target.record.species_id)
+ ? [...activeSpeciesIds, target.record.species_id]
+ : activeSpeciesIds
+
+ async function readStored(animalId: string) {
+ const client = getSupabaseClient()
+ const record = client
+ ? await fetchAnimalRecord(client, animalId).catch(() => null)
+ : null
+ if (record) {
+ revision.current = record.revision
+ setStored(record)
+ }
+ }
+
+ function validate() {
+ const today = localDateIso()
+ const parsed = animalSchema({ speciesIds, today }).safeParse(values)
+ const linkIssues =
+ target.mode === 'create' ? relationIssues(relation, today, false) : {}
+ const fieldIssues = parsed.success ? {} : animalFieldErrors(parsed.error)
+ setErrors(fieldIssues)
+ setRelationErrors(linkIssues)
+ if (!parsed.success || Object.keys(linkIssues).length > 0) {
+ setErrorRound((n) => n + 1)
+ return null
+ }
+ return parsed.data
+ }
+
+ async function save(fields: NonNullable>) {
+ const client = getSupabaseClient()
+ if (!client) throw new TypeError('no backend')
+ if (target.mode === 'edit') {
+ revision.current = (
+ await updateAnimalRecord(client, {
+ animalId: target.record.id,
+ expectedRevision: revision.current,
+ fields,
+ })
+ ).revision
+ return { animalId: target.record.id, linkedClientId: null }
+ }
+ const linked = relation.client
+ const created = await createAnimalRecord(client, {
+ workspaceId: target.workspaceId,
+ requestId,
+ fields,
+ relation: linked
+ ? {
+ clientId: linked.id,
+ relationRole: relation.relation_role as AnimalRelationRole,
+ startedOn: relation.started_on || null,
+ }
+ : null,
+ })
+ return { animalId: created.id, linkedClientId: linked?.id ?? null }
+ }
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ if (inFlight.current) return
+ const fields = validate()
+ if (!fields) return
+ inFlight.current = true
+ setPhase({ kind: 'saving' })
+ try {
+ const saved = await save(fields)
+ setBaseline(values)
+ setRelationBaseline(relation)
+ setPhase({ kind: 'idle' })
+ onSaved(saved)
+ } catch (error) {
+ const failure = classifyRecordError(error)
+ if (failure === 'conflict' && target.mode === 'edit')
+ await readStored(target.record.id)
+ setPhase({ kind: 'failed', failure })
+ } finally {
+ inFlight.current = false
+ }
+ }
+
+ /** Drops the typed values for the stored ones after a conflict. */
+ function takeStored() {
+ if (!stored) return
+ const next = animalFormValues(stored)
+ setValues(next)
+ setBaseline(next)
+ setStored(null)
+ setErrors({})
+ setPhase({ kind: 'idle' })
+ }
+
+ return {
+ mode: target.mode,
+ values,
+ setField,
+ setBirthDate,
+ relation,
+ chooseClient,
+ setRelationRole,
+ setStartedOn,
+ errors,
+ relationErrors,
+ /** Changes after each refused submit, so the form can focus the first error. */
+ errorRound,
+ phase,
+ /** The stored animal after a conflict, shown beside the typed values. */
+ stored,
+ takeStored,
+ dirty:
+ !sameValues(values, baseline) ||
+ !sameRelation(relation, relationBaseline),
+ submit,
+ }
+}
+
+export type AnimalForm = ReturnType
diff --git a/apps/app/src/animals/useAnimalList.ts b/apps/app/src/animals/useAnimalList.ts
new file mode 100644
index 00000000..bcefddab
--- /dev/null
+++ b/apps/app/src/animals/useAnimalList.ts
@@ -0,0 +1,110 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ searchAnimals,
+ type AnimalListItem,
+ type NameCursor,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+import { SEARCH_DELAY_MS } from '@/clients/useClientList'
+
+export type AnimalListState =
+ | { status: 'loading' }
+ | {
+ status: 'ready'
+ rows: AnimalListItem[]
+ next: NameCursor | null
+ moreFailure: RecordFailureKind | null
+ }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/**
+ * The animals of the workspace for a term, a species and the archived
+ * toggle: the server searches (search_animals, POST), pages of 25 in name
+ * order, « Afficher plus » appends the next page. An answer to an older
+ * search is dropped.
+ */
+export function useAnimalList(workspaceId: string) {
+ const [query, setQuery] = useState('')
+ const [term, setTerm] = useState('')
+ const [speciesId, setSpeciesId] = useState(null)
+ 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
+ }
+ searchAnimals(client, { workspaceId, query: term, speciesId, archived })
+ .then((page) => {
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: page.rows,
+ next: page.next,
+ moreFailure: null,
+ })
+ })
+ .catch((error: unknown) => {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ }, [workspaceId, term, speciesId, archived, reload])
+
+ const loadMore = useCallback(async () => {
+ const client = getSupabaseClient()
+ if (state.status !== 'ready' || !state.next || !client || loadingMore)
+ return
+ const current = generation.current
+ setLoadingMore(true)
+ try {
+ const page = await searchAnimals(client, {
+ workspaceId,
+ query: term,
+ speciesId,
+ archived,
+ after: state.next,
+ })
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: [...state.rows, ...page.rows],
+ next: page.next,
+ moreFailure: null,
+ })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ ...state, moreFailure: classifyRecordError(error) })
+ } finally {
+ setLoadingMore(false)
+ }
+ }, [state, loadingMore, workspaceId, term, speciesId, archived])
+
+ return {
+ query,
+ setQuery,
+ /** The term the shown rows answer (the typed one after the pause). */
+ term,
+ speciesId,
+ setSpeciesId,
+ archived,
+ setArchived,
+ state,
+ loadingMore,
+ loadMore,
+ retry: () => setReload((n) => n + 1),
+ }
+}
diff --git a/apps/app/src/animals/useAnimalRecord.ts b/apps/app/src/animals/useAnimalRecord.ts
new file mode 100644
index 00000000..fd920920
--- /dev/null
+++ b/apps/app/src/animals/useAnimalRecord.ts
@@ -0,0 +1,50 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ fetchAnimalRecord,
+ type AnimalRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+export type AnimalRecordState =
+ | { status: 'loading' }
+ | { status: 'ready'; record: AnimalRecord }
+ | { status: 'not_found' }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/** One animal by id; an unknown id and an id of another workspace are both not_found. */
+export function useAnimalRecord(animalId: string) {
+ const [state, setState] = useState({ status: 'loading' })
+ const [reload, setReload] = useState(0)
+ const shownId = useRef(null)
+
+ useEffect(() => {
+ let live = true
+ const client = getSupabaseClient()
+ // A refresh of the same animal keeps it on screen until the new answer.
+ if (shownId.current !== animalId) setState({ status: 'loading' })
+ shownId.current = animalId
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ fetchAnimalRecord(client, animalId)
+ .then((record) => {
+ if (live)
+ setState(
+ record ? { status: 'ready', record } : { status: 'not_found' },
+ )
+ })
+ .catch((error: unknown) => {
+ if (live)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ })
+ return () => {
+ live = false
+ }
+ }, [animalId, reload])
+
+ const refresh = useCallback(() => setReload((n) => n + 1), [])
+ return { state, refresh }
+}
diff --git a/apps/app/src/animals/validation.ts b/apps/app/src/animals/validation.ts
new file mode 100644
index 00000000..15b6be94
--- /dev/null
+++ b/apps/app/src/animals/validation.ts
@@ -0,0 +1,253 @@
+import { z } from 'zod'
+import {
+ ANIMAL_FIELD_LIMITS,
+ BIRTH_YEAR_MIN,
+ CONTROL_CHARACTERS,
+ RECORD_DATE_MIN,
+ codePointLength,
+ type AnimalFields,
+ type AnimalRecord,
+ type AnimalRelationRole,
+ type AnimalSex,
+} from '@faunosteo/supabase'
+
+/**
+ * The animal form (contract §5.2, §11.3; D-R7): bounds from field-limits,
+ * proven equal to the SQL CHECKs, so the form never sends what the database
+ * refuses. The birth keeps the precision given (D6b): a year alone stays a
+ * year, a full date carries its year again. « Not in the future » is the
+ * device's local date (`today`); the RPCs allow up to tomorrow UTC. Messages
+ * are i18n keys; `|n` carries the {max} placeholder.
+ */
+
+export const ANIMAL_SEXES: readonly AnimalSex[] = ['male', 'female', 'unknown']
+export const RELATION_ROLES: readonly AnimalRelationRole[] = [
+ 'owner',
+ 'keeper',
+ 'contact',
+]
+
+/** The species that asks for a detail (« Autre »). */
+export const OTHER_SPECIES = 'other'
+
+export interface AnimalFormValues {
+ name: string
+ species_id: string
+ species_detail: string
+ /** '' until the practitioner picks one: no default (N8). */
+ sex: AnimalSex | ''
+ breed: string
+ birth_year: string
+ birth_date: string
+}
+
+export const EMPTY_ANIMAL_VALUES: AnimalFormValues = {
+ name: '',
+ species_id: '',
+ species_detail: '',
+ sex: '',
+ breed: '',
+ birth_year: '',
+ birth_date: '',
+}
+
+/** The form's view of a stored animal: null fields become empty inputs. */
+export function animalFormValues(record: AnimalRecord): AnimalFormValues {
+ return {
+ name: record.name,
+ species_id: record.species_id,
+ species_detail: record.species_detail ?? '',
+ sex: record.sex,
+ breed: record.breed ?? '',
+ birth_year: record.birth_year === null ? '' : String(record.birth_year),
+ birth_date: record.birth_date ?? '',
+ }
+}
+
+/**
+ * U3: a complete date fills the year (which the form then locks); clearing
+ * the date leaves the year as it was, editable again.
+ */
+export function withBirthDate(
+ values: AnimalFormValues,
+ birthDate: string,
+): AnimalFormValues {
+ const year = /^\d{4}-\d{2}-\d{2}$/.test(birthDate)
+ ? birthDate.slice(0, 4)
+ : values.birth_year
+ return { ...values, birth_date: birthDate, birth_year: year }
+}
+
+function isCalendarDate(value: string): boolean {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
+ if (!match) return false
+ const [y, m, d] = match.slice(1).map(Number)
+ const date = new Date(Date.UTC(y, m - 1, d))
+ return (
+ date.getUTCFullYear() === y &&
+ date.getUTCMonth() === m - 1 &&
+ date.getUTCDate() === d
+ )
+}
+
+/**
+ * The issue of an optional record date (birth, relation start or end), or
+ * null when it is fine: a real calendar date from 1900 to `today` (ISO text
+ * compares in date order).
+ */
+export function recordDateIssue(value: string, today: string): string | null {
+ if (value === '') return null
+ if (!isCalendarDate(value)) return 'animals.error.date_format'
+ if (value < RECORD_DATE_MIN || value > today)
+ return 'animals.error.date_range'
+ return null
+}
+
+/** Trimmed text of at most `max` code points without control characters. */
+function textIssue(value: string, max: number): string | null {
+ if (codePointLength(value) > max) return `animals.error.too_long|${max}`
+ if (CONTROL_CHARACTERS.test(value)) return 'animals.error.characters'
+ return null
+}
+
+export interface AnimalSchemaContext {
+ /** The species the form may send: the active ones, plus the stored one on an edit. */
+ speciesIds: readonly string[]
+ /** The device's local date, YYYY-MM-DD. */
+ today: string
+}
+
+type Issue = { path: keyof AnimalFormValues; message: string }
+
+function identityIssues(v: AnimalFormValues, ctx: AnimalSchemaContext) {
+ const issues: Issue[] = []
+ const name = v.name.trim()
+ const nameIssue =
+ name === ''
+ ? 'animals.error.required'
+ : textIssue(name, ANIMAL_FIELD_LIMITS.name)
+ if (nameIssue) issues.push({ path: 'name', message: nameIssue })
+ if (!ctx.speciesIds.includes(v.species_id))
+ issues.push({ path: 'species_id', message: 'animals.error.species' })
+ if (v.species_id === OTHER_SPECIES) {
+ const detail = v.species_detail.trim()
+ const detailIssue =
+ detail === ''
+ ? 'animals.error.species_detail'
+ : textIssue(detail, ANIMAL_FIELD_LIMITS.speciesDetail)
+ if (detailIssue)
+ issues.push({ path: 'species_detail', message: detailIssue })
+ }
+ if (!ANIMAL_SEXES.includes(v.sex as AnimalSex))
+ issues.push({ path: 'sex', message: 'animals.error.sex' })
+ const breedIssue = textIssue(v.breed.trim(), ANIMAL_FIELD_LIMITS.breed)
+ if (breedIssue) issues.push({ path: 'breed', message: breedIssue })
+ return issues
+}
+
+function birthIssues(v: AnimalFormValues, today: string) {
+ const issues: Issue[] = []
+ if (v.birth_year !== '') {
+ if (!/^\d{4}$/.test(v.birth_year))
+ issues.push({ path: 'birth_year', message: 'animals.error.year_format' })
+ else if (
+ Number(v.birth_year) < BIRTH_YEAR_MIN ||
+ Number(v.birth_year) > Number(today.slice(0, 4))
+ )
+ issues.push({ path: 'birth_year', message: 'animals.error.year_range' })
+ }
+ const dateIssue = recordDateIssue(v.birth_date, today)
+ if (dateIssue) issues.push({ path: 'birth_date', message: dateIssue })
+ else if (v.birth_date !== '' && v.birth_date.slice(0, 4) !== v.birth_year)
+ issues.push({ path: 'birth_year', message: 'animals.error.date_year' })
+ return issues
+}
+
+const nullIfEmpty = (value: string) => (value === '' ? null : value)
+
+/** Parses the typed values into the seven fields the RPCs take. */
+export function animalSchema(ctx: AnimalSchemaContext) {
+ return z
+ .object({
+ name: z.string(),
+ species_id: z.string(),
+ species_detail: z.string(),
+ sex: z.string(),
+ breed: z.string(),
+ birth_year: z.string(),
+ birth_date: z.string(),
+ })
+ .superRefine((raw, zctx) => {
+ const v = raw as AnimalFormValues
+ for (const issue of [
+ ...identityIssues(v, ctx),
+ ...birthIssues(v, ctx.today),
+ ])
+ zctx.addIssue({
+ code: 'custom',
+ path: [issue.path],
+ message: issue.message,
+ })
+ })
+ .transform(
+ (v): AnimalFields => ({
+ name: v.name.trim(),
+ species_id: v.species_id,
+ // Any other species refuses a detail: a hidden leftover is dropped, never sent.
+ species_detail:
+ v.species_id === OTHER_SPECIES ? v.species_detail.trim() : null,
+ sex: v.sex as AnimalSex,
+ breed: nullIfEmpty(v.breed.trim()),
+ birth_year: v.birth_year === '' ? null : Number(v.birth_year),
+ birth_date: nullIfEmpty(v.birth_date),
+ }),
+ )
+}
+
+/** The optional client of a new animal, or of a relation added from a page. */
+export interface RelationFormValues {
+ client: { id: string; display_name: string } | null
+ /** '' until chosen: no role is preselected (owner decision 2026-10-26). */
+ relation_role: AnimalRelationRole | ''
+ started_on: string
+}
+
+export const EMPTY_RELATION_VALUES: RelationFormValues = {
+ client: null,
+ relation_role: '',
+ started_on: '',
+}
+
+export type RelationFieldErrors = Partial<
+ Record<'client' | 'relation_role' | 'started_on', string>
+>
+
+/** Errors of a relation choice; `requireClient` when the client is the point of the form. */
+export function relationIssues(
+ values: RelationFormValues,
+ today: string,
+ requireClient: boolean,
+): RelationFieldErrors {
+ const errors: RelationFieldErrors = {}
+ if (!values.client) {
+ if (requireClient) errors.client = 'animals.error.client'
+ return errors
+ }
+ if (!RELATION_ROLES.includes(values.relation_role as AnimalRelationRole))
+ errors.relation_role = 'animals.error.role'
+ const dateIssue = recordDateIssue(values.started_on, today)
+ if (dateIssue) errors.started_on = dateIssue
+ return errors
+}
+
+export type AnimalFieldErrors = Partial>
+
+/** The first message of each field, in form order. */
+export function animalFieldErrors(error: z.ZodError): AnimalFieldErrors {
+ const errors: AnimalFieldErrors = {}
+ for (const issue of error.issues) {
+ const key = issue.path[0] as keyof AnimalFormValues
+ errors[key] ??= issue.message
+ }
+ return errors
+}
diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx
index 4ceb897b..b952bc8d 100644
--- a/apps/app/src/app/App.tsx
+++ b/apps/app/src/app/App.tsx
@@ -16,6 +16,15 @@ 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 AnimalsListRoute from './routes/app/animals/AnimalsListRoute'
+import AnimalCreateRoute from './routes/app/animals/AnimalCreateRoute'
+import AnimalDetailRoute from './routes/app/animals/AnimalDetailRoute'
+import AnimalEditRoute from './routes/app/animals/AnimalEditRoute'
import { useUnsavedGuard } from './useUnsavedGuard'
/** The local tool: unchanged routes, no account needed, shared footer. */
@@ -50,6 +59,21 @@ export function AppRoutes() {
}>
} />
} />
+ {/* One workspace gate for the records: moving between clients and animals keeps it. */}
+ }>
+
+ } />
+ } />
+ } />
+ } />
+
+
+ } />
+ } />
+ } />
+ } />
+
+
} />
diff --git a/apps/app/src/app/guards/RequireWorkspace.tsx b/apps/app/src/app/guards/RequireWorkspace.tsx
new file mode 100644
index 00000000..f320c770
--- /dev/null
+++ b/apps/app/src/app/guards/RequireWorkspace.tsx
@@ -0,0 +1,66 @@
+import { Fragment } from 'react'
+import { Outlet, useOutletContext } from 'react-router-dom'
+import Button from '@/components/ui/Button'
+import Notice from '@/components/ui/Notice'
+import { SpeciesProvider } from '@/animals/species'
+import { useAuthStore } from '@/state/authStore'
+import { useT } from '@/i18n/useT'
+
+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 (clients and animals): they render only once the
+ * personal workspace is read, and remount when it changes, so no list, form
+ * or species answer of another account survives a change of account. Every
+ * other state is said, never guessed.
+ */
+export default function RequireWorkspace() {
+ const t = useT()
+ 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/DashboardRoute.tsx b/apps/app/src/app/routes/app/DashboardRoute.tsx
index 45e3ca63..b1a94665 100644
--- a/apps/app/src/app/routes/app/DashboardRoute.tsx
+++ b/apps/app/src/app/routes/app/DashboardRoute.tsx
@@ -87,8 +87,9 @@ function AccountCard() {
{t('dashboard.account.title')}
-
{t('dashboard.account.email')}
- {user?.email}
+ {t('dashboard.account.email')}
+ {/* An address longer than the card wraps: never cut, never wider than the screen. */}
+ {user?.email}
@@ -126,7 +127,8 @@ export default function DashboardRoute() {
{t('dashboard.intro')}
-
+ {/* One explicit column below md: an implicit track would grow to the cards' content. */}
+
diff --git a/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx
new file mode 100644
index 00000000..aca11539
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx
@@ -0,0 +1,108 @@
+import { useLocation, useNavigate } from 'react-router-dom'
+import { UUID_PATTERN } from '@faunosteo/supabase'
+import AnimalForm from '@/components/animals/AnimalForm'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useSpecies } from '@/animals/species'
+import { useAnimalForm, type PickedClient } from '@/animals/useAnimalForm'
+import { useClientRecord } from '@/clients/useClientRecord'
+import { useT } from '@/i18n/useT'
+import type { ClientFlash } from '../clients/ClientDetailRoute'
+import type { AnimalFlash } from './AnimalDetailRoute'
+
+/**
+ * What a client page hands to this page: the client to pre-associate, in
+ * the navigation state, never in the URL (brief V1-1.6 §6).
+ */
+export interface AnimalCreateState {
+ clientId: string
+}
+
+type Origin =
+ | { status: 'none' }
+ | { status: 'loading' }
+ | { status: 'ready'; client: PickedClient }
+ | { status: 'unavailable' }
+
+/** The client the form opened from, read again: only an active client of this workspace is pre-associated. */
+function useOrigin(clientId: string | null): Origin {
+ const { state } = useClientRecord(clientId ?? '')
+ if (!clientId) return { status: 'none' }
+ if (state.status === 'loading') return { status: 'loading' }
+ if (state.status === 'ready' && state.record.archived_at === null)
+ return {
+ status: 'ready',
+ client: { id: state.record.id, display_name: state.record.display_name },
+ }
+ return { status: 'unavailable' }
+}
+
+function CreateForm({ origin }: { origin: PickedClient | null }) {
+ const t = useT()
+ const navigate = useNavigate()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const activeIds =
+ species.status === 'ready' ? species.labels.map((s) => s.id) : []
+ const form = useAnimalForm(
+ { mode: 'create', workspaceId, initialClient: origin },
+ activeIds,
+ (saved) => {
+ if (origin && saved.linkedClientId === origin.id)
+ navigate(`/app/clients/${origin.id}`, {
+ replace: true,
+ state: { flash: 'animal_added' satisfies ClientFlash },
+ })
+ else
+ navigate(`/app/animals/${saved.animalId}`, {
+ replace: true,
+ state: { flash: 'created' satisfies AnimalFlash },
+ })
+ },
+ )
+ useLeaveGuard(form.dirty)
+ return (
+
+ )
+}
+
+/** /app/animals/new: one creation intent, one request id kept for retries, an optional first client. */
+export default function AnimalCreateRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const location = useLocation()
+ const passed = (location.state as Partial
| null)?.clientId
+ const origin = useOrigin(
+ typeof passed === 'string' && UUID_PATTERN.test(passed) ? passed : null,
+ )
+
+ return (
+
+
+ {t('animals.form.create_title')}
+
+ {origin.status === 'loading' && (
+
+ {t('animals.form.origin_loading')}
+
+ )}
+ {origin.status === 'unavailable' && (
+
{t('animals.form.origin_unavailable')}
+ )}
+ {origin.status !== 'loading' && (
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx
new file mode 100644
index 00000000..8d2874f3
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx
@@ -0,0 +1,248 @@
+import { useEffect, useState, type ReactNode } from 'react'
+import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
+import {
+ classifyRecordError,
+ setAnimalArchived,
+ type AnimalRecord,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import AnimalNotFound from '@/components/animals/AnimalNotFound'
+import ArchiveAnimalDialog from '@/components/animals/ArchiveAnimalDialog'
+import AnimalRelations from '@/components/relations/AnimalRelations'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { usePageHeading } from '@/app/usePageHeading'
+import { animalAge, type AnimalAge } from '@/animals/age'
+import { speciesName, useSpecies } from '@/animals/species'
+import { useAnimalRecord } from '@/animals/useAnimalRecord'
+import { formatDate, localDateIso } from '@/lib/dates'
+import { getSupabaseClient } from '@/lib/supabase'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+/** What a page that saved the animal asks this page to announce (no value in it). */
+export type AnimalFlash = 'created' | 'updated'
+
+type Translate = ReturnType
+
+const linkClass =
+ 'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
+
+function ageText(age: AnimalAge | null, t: Translate): string | null {
+ if (!age) return null
+ if (age.about && age.count === 0) return t('animals.age.under_one')
+ const unit = age.unit === 'year' ? 'years' : 'months'
+ const base = t(
+ `animals.age.${unit}_${age.count === 1 ? 'one' : 'other'}`,
+ ).replace('{count}', String(age.count))
+ return age.about ? t('animals.age.about').replace('{age}', base) : base
+}
+
+/** The birth with the precision known (D6b): a date, a year, or « inconnue »; never a made-up day. */
+function birthText(record: AnimalRecord, t: Translate, locale: 'fr' | 'en') {
+ const age = ageText(
+ animalAge(record.birth_year, record.birth_date, localDateIso()),
+ t,
+ )
+ const when = record.birth_date
+ ? t('animals.detail.birth_on').replace(
+ '{date}',
+ formatDate(record.birth_date, locale),
+ )
+ : record.birth_year !== null
+ ? t('animals.detail.birth_in').replace(
+ '{year}',
+ String(record.birth_year),
+ )
+ : null
+ if (!when) return t('animals.detail.birth_unknown')
+ return age ? `${when} (${age})` : when
+}
+
+function IdentityCard({ record }: { record: AnimalRecord }) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const rows: [string, ReactNode][] = [
+ [
+ t('animals.detail.species'),
+ speciesName(labels, record.species_id, record.species_detail, locale),
+ ],
+ [t('animals.detail.sex'), t(`animals.sex.${record.sex}`)],
+ [t('animals.detail.breed'), record.breed ?? t('animals.detail.breed_none')],
+ [t('animals.detail.birth'), birthText(record, t, locale)],
+ [
+ t('animals.detail.status'),
+ record.archived_at
+ ? t('animals.detail.status_archived')
+ : t('animals.detail.status_active'),
+ ],
+ ]
+ return (
+
+
+ {t('animals.detail.identity')}
+
+
+ {rows.map(([label, value]) => (
+
+
{label}
+ {value}
+
+ ))}
+
+
+ )
+}
+
+/** /app/animals/:animalId: identity, clients current and former, edit, archive or restore. */
+export default function AnimalDetailRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const navigate = useNavigate()
+ const location = useLocation()
+ const workspaceId = useWorkspaceId()
+ const { animalId = '' } = useParams()
+ const { state, refresh } = useAnimalRecord(animalId)
+ const flash = (location.state as { flash?: AnimalFlash } | null)?.flash
+ const [status, setStatus] = useState(
+ flash ? t(`animals.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 setAnimalArchived(client, animalId, false)
+ setStatus(t('animals.detail.restored'))
+ refresh()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setRestoring(false)
+ }
+ }
+
+ if (state.status === 'not_found') return
+ if (state.status === 'loading')
+ return (
+
+ {t('animals.detail.loading')}
+
+ )
+ if (state.status === 'error')
+ return (
+
+ {t(`animals.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )
+
+ const record = state.record
+ const archived = record.archived_at !== null
+
+ return (
+
+
+ {t('animals.detail.back')}
+
+
+
+
+ {record.name}
+
+ {archived && {t('animals.archived_badge')} }
+
+
+ {archived ? (
+ void restore()}
+ aria-disabled={restoring}
+ >
+ {restoring
+ ? t('animals.detail.restoring')
+ : t('animals.detail.restore')}
+
+ ) : (
+ <>
+
+ {t('animals.detail.edit')}
+
+ setArchiveOpen(true)}
+ >
+ {t('animals.detail.archive')}
+
+ >
+ )}
+
+
+
+ {status &&
{status} }
+ {failure && (
+
{t(`animals.failure.${failure}`)}
+ )}
+ {archived && (
+
{t('animals.detail.archived_notice')}
+ )}
+
+
+
+
+
setArchiveOpen(false)}
+ onArchived={() => {
+ setArchiveOpen(false)
+ setStatus(t('animals.detail.archived'))
+ refresh()
+ }}
+ />
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx
new file mode 100644
index 00000000..b2df7811
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx
@@ -0,0 +1,85 @@
+import { Link, useNavigate, useParams } from 'react-router-dom'
+import type { AnimalRecord } from '@faunosteo/supabase'
+import AnimalForm from '@/components/animals/AnimalForm'
+import AnimalNotFound from '@/components/animals/AnimalNotFound'
+import Button from '@/components/ui/Button'
+import Notice from '@/components/ui/Notice'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { useLeaveGuard } from '@/app/useLeaveGuard'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useSpecies } from '@/animals/species'
+import { useAnimalForm } from '@/animals/useAnimalForm'
+import { useAnimalRecord } from '@/animals/useAnimalRecord'
+import { useT } from '@/i18n/useT'
+import type { AnimalFlash } from './AnimalDetailRoute'
+
+function EditForm({ record }: { record: AnimalRecord }) {
+ const t = useT()
+ const navigate = useNavigate()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const activeIds =
+ species.status === 'ready' ? species.labels.map((s) => s.id) : []
+ const form = useAnimalForm({ mode: 'edit', record }, activeIds, (saved) =>
+ navigate(`/app/animals/${saved.animalId}`, {
+ state: { flash: 'updated' satisfies AnimalFlash },
+ }),
+ )
+ useLeaveGuard(form.dirty)
+ return (
+
+ )
+}
+
+/** /app/animals/:animalId/edit: the stored values at their revision; an archived animal is read-only. */
+export default function AnimalEditRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const { animalId = '' } = useParams()
+ const { state, refresh } = useAnimalRecord(animalId)
+
+ if (state.status === 'not_found') return
+ return (
+
+
+ {t('animals.form.edit_title')}
+
+ {state.status === 'loading' && (
+
+ {t('animals.detail.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`animals.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )}
+ {state.status === 'ready' && state.record.archived_at && (
+
+ {t('animals.detail.archived_notice')}
+
+ {t('animals.form.back_to_animal')}
+
+
+ )}
+ {state.status === 'ready' && !state.record.archived_at && (
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx
new file mode 100644
index 00000000..7d218841
--- /dev/null
+++ b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx
@@ -0,0 +1,240 @@
+import { Link } from 'react-router-dom'
+import type { AnimalListItem, SpeciesLabel } from '@faunosteo/supabase'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
+import FormField from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import Notice from '@/components/ui/Notice'
+import Select from '@/components/ui/Select'
+import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+import { usePageHeading } from '@/app/usePageHeading'
+import { speciesName, useSpecies } from '@/animals/species'
+import { useAnimalList } from '@/animals/useAnimalList'
+import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
+import type { Locale } from '@/i18n/types'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+type Translate = ReturnType
+
+/** « Propriétaires : A, B, C +2 », or « Propriétaire non renseigné » (no placeholder client). */
+function ownersText(animal: AnimalListItem, t: Translate): string {
+ if (animal.current_owner_count === 0) return t('animals.no_owner')
+ const names = animal.current_owners
+ .map((o) =>
+ o.archived
+ ? t('animals.owner_archived').replace('{name}', o.display_name)
+ : o.display_name,
+ )
+ .join(', ')
+ const more = animal.current_owner_count - animal.current_owners.length
+ const list =
+ more > 0
+ ? `${names} ${t('animals.list.owners_more').replace('{count}', String(more))}`
+ : names
+ return t(
+ animal.current_owner_count === 1
+ ? 'animals.list.owner'
+ : 'animals.list.owners',
+ ).replace('{names}', list)
+}
+
+function AnimalRow(props: {
+ animal: AnimalListItem
+ labels: readonly SpeciesLabel[]
+ locale: Locale
+ t: Translate
+}) {
+ const { animal, t } = props
+ const details = [
+ speciesName(
+ props.labels,
+ animal.species_id,
+ animal.species_detail,
+ props.locale,
+ ),
+ animal.breed,
+ t(`animals.sex.${animal.sex}`),
+ ].filter(Boolean)
+ return (
+
+
+
+
+ {animal.name}
+
+ {animal.archived_at && (
+ {t('animals.archived_badge')}
+ )}
+
+
+ {details.join(' · ')}
+
+
+ {ownersText(animal, t)}
+
+
+
+ )
+}
+
+/** /app/animals: search, species filter, the archived toggle (U2) and « Afficher plus » pages (U1). */
+export default function AnimalsListRoute() {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const heading = usePageHeading()
+ const workspaceId = useWorkspaceId()
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const list = useAnimalList(workspaceId)
+ const { state } = list
+
+ const emptyMessage =
+ list.term || list.speciesId
+ ? t('animals.list.no_results')
+ : list.archived
+ ? t('animals.list.archived_empty')
+ : t('animals.list.empty')
+
+ return (
+
+
+
+ {t('animals.list.title')}
+
+
+ {t('animals.list.new')}
+
+
+
+
+
+ list.setQuery(e.target.value)}
+ maxLength={100}
+ autoComplete="off"
+ aria-describedby="animal-search-hint"
+ />
+
+
+ list.setSpeciesId(e.target.value || null)}
+ >
+ {t('animals.list.species_all')}
+ {labels.map((s) => (
+
+ {pickLocaleLabel(s.name_fr, s.name_en, locale, s.id)}
+
+ ))}
+
+
+
+ list.setArchived(e.target.checked)}
+ className="h-5 w-5 accent-[var(--color-accent)]"
+ />
+ {t('animals.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
+ ? 'animals.list.count_one'
+ : 'animals.list.count_other',
+ ).replace('{count}', String(state.rows.length))}
+
+
+ {state.status === 'loading' && (
+
+ {t('animals.list.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`animals.failure.${state.failure}`)}
+
+ {t('common.retry')}
+
+
+ )}
+ {state.status === 'ready' && state.rows.length === 0 && (
+
+
{emptyMessage}
+ {!list.term && !list.speciesId && !list.archived && (
+
+ {t('animals.list.empty_hint')}
+
+ )}
+
+ )}
+ {state.status === 'ready' && state.rows.length > 0 && (
+ <>
+
+ {state.rows.map((animal) => (
+
+ ))}
+
+ {state.moreFailure && (
+
+ {t(`animals.failure.${state.moreFailure}`)}
+
+ )}
+ {state.next && (
+
+ void list.loadMore()}
+ aria-disabled={list.loadingMore}
+ >
+ {list.loadingMore
+ ? t('animals.list.loading_more')
+ : t('animals.list.more')}
+
+
+ )}
+ >
+ )}
+
+ )
+}
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..b9956224
--- /dev/null
+++ b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx
@@ -0,0 +1,250 @@
+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 { useWorkspaceId } from '@/app/guards/RequireWorkspace'
+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, or an animal of it, asks this page to announce (no value in it). */
+export type ClientFlash = 'created' | 'updated' | 'animal_added'
+
+const linkClass =
+ 'text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded-sm'
+
+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 (add, link, open), edit, archive or restore. */
+export default function ClientDetailRoute() {
+ const t = useT()
+ const heading = usePageHeading()
+ const navigate = useNavigate()
+ const location = useLocation()
+ const workspaceId = useWorkspaceId()
+ const { clientId = '' } = useParams()
+ const { state, refresh } = useClientRecord(clientId)
+ const flash = (location.state as { flash?: ClientFlash } | null)?.flash
+ 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/account/AvatarSection.tsx b/apps/app/src/components/account/AvatarSection.tsx
index e50041fe..d93923d0 100644
--- a/apps/app/src/components/account/AvatarSection.tsx
+++ b/apps/app/src/components/account/AvatarSection.tsx
@@ -90,6 +90,7 @@ export default function AvatarSection() {
avatar?.inFlight ? { kind: 'processing', long: false } : { kind: 'idle' },
)
const [confirmOpen, setConfirmOpen] = useState(false)
+ const [removing, setRemoving] = useState(false)
const inputRef = useRef(null)
const pollRef = useRef(null)
@@ -171,16 +172,27 @@ export default function AvatarSection() {
}
}
+ const closeConfirm = () => !removing && setConfirmOpen(false)
+
+ // The confirmation stays open until the removal settles: it closes with the
+ // photo gone, so focus moves past the vanished button (ModalDialog fallback).
async function onRemove() {
const client = getSupabaseClient()
- setConfirmOpen(false)
- if (!client) return
+ if (removing) return
+ if (!client) {
+ setConfirmOpen(false)
+ return
+ }
+ setRemoving(true)
try {
await removeAvatar(client)
clearAvatar()
setPhase({ kind: 'removed' })
} catch (error) {
setPhase({ kind: 'failed', failure: classifyAssetError(error) })
+ } finally {
+ setRemoving(false)
+ setConfirmOpen(false)
}
}
@@ -211,6 +223,8 @@ export default function AvatarSection() {
accept={ACCEPT}
onChange={onPick}
className="sr-only"
+ // Opened by the visible button: an invisible tab stop would hide the focus.
+ tabIndex={-1}
aria-label={t('account.avatar.change')}
disabled={busy}
/>
@@ -256,10 +270,15 @@ export default function AvatarSection() {
{t(`account.avatar.error.${phase.failure}`)}
)}
{rejected && {t(`account.avatar.rejected.${rejected}`)} }
- setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm">
- {t('account.avatar.remove_body')}
+ {t('account.avatar.remove_body')}}
+ size="sm"
+ >
-
setConfirmOpen(false)}>
+
{t('common.cancel')}
diff --git a/apps/app/src/components/animals/AnimalForm.tsx b/apps/app/src/components/animals/AnimalForm.tsx
new file mode 100644
index 00000000..00f1a017
--- /dev/null
+++ b/apps/app/src/components/animals/AnimalForm.tsx
@@ -0,0 +1,439 @@
+import { useEffect, useRef } from 'react'
+import { Link } from 'react-router-dom'
+import { ANIMAL_FIELD_LIMITS } from '@faunosteo/supabase'
+import Button, { buttonClassName } from '@/components/ui/Button'
+import Card from '@/components/ui/Card'
+import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios'
+import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
+import Input from '@/components/ui/Input'
+import Notice from '@/components/ui/Notice'
+import Select from '@/components/ui/Select'
+import { ClientPicker } from '@/components/relations/Pickers'
+import { speciesName, useSpecies } from '@/animals/species'
+import type { AnimalForm as AnimalFormState } from '@/animals/useAnimalForm'
+import {
+ ANIMAL_SEXES,
+ OTHER_SPECIES,
+ RELATION_ROLES,
+ animalFormValues,
+ type AnimalFormValues,
+ type RelationFieldErrors,
+} from '@/animals/validation'
+import { translateFieldError } from '@/account/validation'
+import { formatDate, localDateIso } from '@/lib/dates'
+import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+/** Ids of the controls that take focus on an error, in form order. */
+const FIELD_IDS: Record<
+ keyof AnimalFormValues | keyof RelationFieldErrors,
+ string
+> = {
+ name: 'animal-name',
+ species_id: 'animal-species',
+ species_detail: 'animal-species-detail',
+ sex: firstChoiceId('animal-sex', 'male'),
+ breed: 'animal-breed',
+ birth_year: 'animal-birth-year',
+ birth_date: 'animal-birth-date',
+ client: 'animal-client-search',
+ relation_role: firstChoiceId('animal-role', 'owner'),
+ started_on: 'animal-started-on',
+}
+
+export interface AnimalFormProps {
+ form: AnimalFormState
+ workspaceId: string
+ submitLabel: string
+ /** Where « Annuler » leads; the shell asks first while the form holds changes. */
+ cancelTo: string
+}
+
+/**
+ * The animal form, one page on every screen (contract §11.3): identity
+ * (name, species with its detail for « Autre », sex with no default, breed),
+ * birth (a year, or a full date that fills and locks the year: U3), and on
+ * a creation the optional first client with an explicit role. Every field
+ * is labelled, errors sit under their field and the first one takes focus.
+ */
+export default function AnimalForm({
+ form,
+ workspaceId,
+ submitLabel,
+ cancelTo,
+}: AnimalFormProps) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species, retry: retrySpecies } = useSpecies()
+ const { values, errors, relation, relationErrors, phase, stored } = form
+ const labels = species.status === 'ready' ? species.labels : []
+ const today = localDateIso()
+ const chosenText = useRef(null)
+ const shownClient = useRef(relation.client?.id ?? null)
+
+ // Choosing a client focuses the choice; removing it focuses the search that replaces it.
+ useEffect(() => {
+ const id = relation.client?.id ?? null
+ if (id === shownClient.current) return
+ shownClient.current = id
+ if (id) chosenText.current?.focus()
+ else document.getElementById(FIELD_IDS.client)?.focus()
+ }, [relation.client])
+
+ useEffect(() => {
+ if (form.errorRound === 0) return
+ const all = { ...errors, ...relationErrors } as Record
+ const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find(
+ (key) => all[key],
+ )
+ if (first) document.getElementById(FIELD_IDS[first])?.focus()
+ }, [form.errorRound, errors, relationErrors])
+
+ const err = (key: keyof AnimalFormValues) =>
+ translateFieldError(t, errors[key])
+ const relErr = (key: keyof RelationFieldErrors) =>
+ translateFieldError(t, relationErrors[key])
+
+ /** After a conflict: the stored value under each field that differs from the typed one. */
+ const storedHint = (key: keyof AnimalFormValues): string | undefined => {
+ if (!stored) return undefined
+ const value = animalFormValues(stored)[key]
+ if (value === values[key]) return undefined
+ const shown =
+ value === ''
+ ? ''
+ : key === 'species_id'
+ ? speciesName(labels, value, null, locale)
+ : key === 'sex'
+ ? t(`animals.sex.${value}`)
+ : key === 'birth_date'
+ ? formatDate(value, locale)
+ : value
+ return shown
+ ? t('animals.form.stored_value').replace('{value}', shown)
+ : t('animals.form.stored_empty')
+ }
+ const describedBy = (key: keyof AnimalFormValues, hint?: string) =>
+ fieldDescribedBy(FIELD_IDS[key], hint, errors[key])
+
+ function textField(
+ key: 'name' | 'breed' | 'species_detail',
+ label: string,
+ max: number,
+ isRequired: boolean,
+ hint?: string,
+ ) {
+ const shownHint = storedHint(key) ?? hint
+ return (
+
+ form.setField(key)(e.target.value)}
+ maxLength={max}
+ autoComplete="off"
+ aria-invalid={Boolean(errors[key])}
+ aria-describedby={describedBy(key, shownHint)}
+ required={isRequired}
+ />
+
+ )
+ }
+
+ const required = t('animals.form.required')
+ const optional = t('animals.form.optional')
+ const saving = phase.kind === 'saving'
+ const yearLocked = /^\d{4}-\d{2}-\d{2}$/.test(values.birth_date)
+ const yearHint =
+ storedHint('birth_year') ??
+ t(
+ yearLocked
+ ? 'animals.form.birth_year_locked'
+ : 'animals.form.birth_year_hint',
+ )
+ const speciesHint = storedHint('species_id')
+
+ return (
+
+ )
+}
diff --git a/apps/app/src/components/animals/AnimalNotFound.tsx b/apps/app/src/components/animals/AnimalNotFound.tsx
new file mode 100644
index 00000000..e10ebfbc
--- /dev/null
+++ b/apps/app/src/components/animals/AnimalNotFound.tsx
@@ -0,0 +1,27 @@
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import { usePageHeading } from '@/app/usePageHeading'
+import { useT } from '@/i18n/useT'
+
+/** The same screen for an unknown id, a malformed one and an id of another workspace (contract §11.1). */
+export default function AnimalNotFound() {
+ const t = useT()
+ const heading = usePageHeading()
+ return (
+
+
+ {t('animals.not_found.title')}
+
+
+ {t('animals.not_found.body')}
+
+
+ {t('animals.not_found.back')}
+
+
+ )
+}
diff --git a/apps/app/src/components/animals/ArchiveAnimalDialog.tsx b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx
new file mode 100644
index 00000000..2f434ebc
--- /dev/null
+++ b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx
@@ -0,0 +1,98 @@
+import { useState } from 'react'
+import {
+ classifyRecordError,
+ setAnimalArchived,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import Button from '@/components/ui/Button'
+import Dialog from '@/components/ui/Dialog'
+import Notice from '@/components/ui/Notice'
+import { getSupabaseClient } from '@/lib/supabase'
+import { useT } from '@/i18n/useT'
+
+export interface ArchiveAnimalDialogProps {
+ open: boolean
+ animalId: string
+ onClose: () => void
+ /** Called once the server archived the animal; the page then closes the dialog. */
+ onArchived: () => void
+}
+
+/**
+ * Confirmation before archiving an animal (contract §7.1): its relations are
+ * kept and frozen, no client is archived. Closing it is never a
+ * confirmation, and while the request runs it refuses to close.
+ */
+export default function ArchiveAnimalDialog({
+ open,
+ animalId,
+ onClose,
+ onArchived,
+}: ArchiveAnimalDialogProps) {
+ const t = useT()
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(null)
+
+ const close = () => {
+ if (pending) return
+ setFailure(null)
+ onClose()
+ }
+
+ async function confirm() {
+ const client = getSupabaseClient()
+ if (pending) return
+ if (!client) return setFailure('unavailable')
+ setPending(true)
+ setFailure(null)
+ try {
+ await setAnimalArchived(client, animalId, true)
+ onArchived()
+ } catch (error) {
+ setFailure(classifyRecordError(error))
+ } finally {
+ setPending(false)
+ }
+ }
+
+ return (
+
+ {t('animals.archive.body')}
+
+ }
+ size="sm"
+ >
+ {failure && (
+
+ {t(`animals.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('animals.archive.archiving')
+ : t('animals.archive.confirm')}
+
+
+
+ )
+}
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..44ced86b
--- /dev/null
+++ b/apps/app/src/components/clients/ClientAnimals.tsx
@@ -0,0 +1,290 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Link } from 'react-router-dom'
+import {
+ classifyRecordError,
+ listClientAnimals,
+ type ClientAnimalItem,
+ type RecordFailureKind,
+ type RelationCursor,
+} from '@faunosteo/supabase'
+import Badge from '@/components/ui/Badge'
+import Button from '@/components/ui/Button'
+import ButtonLink from '@/components/ui/ButtonLink'
+import Card from '@/components/ui/Card'
+import Notice from '@/components/ui/Notice'
+import RelationPanel from '@/components/relations/RelationPanel'
+import { speciesName, useSpecies } from '@/animals/species'
+import type { AnimalCreateState } from '@/app/routes/app/animals/AnimalCreateRoute'
+import { getSupabaseClient } from '@/lib/supabase'
+import { formatDate } from '@/lib/dates'
+import { useLocaleStore } from '@/state/localeStore'
+import { useT } from '@/i18n/useT'
+
+type State =
+ | { status: 'loading' }
+ | { status: 'ready'; rows: ClientAnimalItem[]; next: RelationCursor | null }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/** One animal of the client with every relation of one group (current or former). */
+interface AnimalGroup {
+ animalId: string
+ rows: ClientAnimalItem[]
+}
+
+/**
+ * The relations come one per role (list_client_animals); the page shows each
+ * animal once per group with its roles, so an owner who also keeps the
+ * horse sees it once. Rows already arrive current first, by animal name.
+ */
+function byAnimal(rows: ClientAnimalItem[], current: boolean): AnimalGroup[] {
+ const groups = new Map()
+ for (const row of rows.filter((r) => r.is_current === current)) {
+ const group = groups.get(row.animal_id)
+ if (group) group.rows.push(row)
+ else groups.set(row.animal_id, { animalId: row.animal_id, rows: [row] })
+ }
+ return [...groups.values()]
+}
+
+const linkClass =
+ 'rounded-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
+
+export interface ClientAnimalsProps {
+ clientId: string
+ workspaceId: string
+ /** An archived client takes no new relation (contract §7.1): no add, no link. */
+ archived: boolean
+ /** A change made here, announced by the page. */
+ onStatus: (message: string) => void
+}
+
+/**
+ * The client's animals from list_client_animals, current then former, each
+ * with the client's roles and their dates when known, linked to the animal's
+ * page. On an active client: « Ajouter un animal » opens the animal form
+ * with this client pre-associated, « Associer un animal existant » links an
+ * animal already recorded.
+ */
+export default function ClientAnimals({
+ clientId,
+ workspaceId,
+ archived,
+ onStatus,
+}: ClientAnimalsProps) {
+ const t = useT()
+ const locale = useLocaleStore((s) => s.locale)
+ const { state: species } = useSpecies()
+ const labels = species.status === 'ready' ? species.labels : []
+ const [state, setState] = useState({ status: 'loading' })
+ const [loadingMore, setLoadingMore] = useState(false)
+ const [panelOpen, setPanelOpen] = useState(false)
+ const linkButton = useRef(null)
+ const panelWasOpen = useRef(false)
+ const generation = useRef(0)
+
+ const load = useCallback(async () => {
+ const current = ++generation.current
+ const client = getSupabaseClient()
+ try {
+ if (!client) throw new TypeError('no backend')
+ const page = await listClientAnimals(client, clientId)
+ if (current === generation.current)
+ setState({ status: 'ready', rows: page.rows, next: page.next })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ }
+ }, [clientId])
+
+ useEffect(() => {
+ // The ref object is stable: bumping it on unmount drops the answer in flight.
+ const requests = generation
+ void load()
+ return () => {
+ requests.current++
+ }
+ }, [load])
+
+ // The panel gave focus to its own heading; when it closes, focus goes back to « Associer ».
+ useEffect(() => {
+ if (panelWasOpen.current && !panelOpen) linkButton.current?.focus()
+ panelWasOpen.current = panelOpen
+ }, [panelOpen])
+
+ async function more() {
+ const client = getSupabaseClient()
+ if (state.status !== 'ready' || !state.next || !client || loadingMore)
+ return
+ const current = generation.current
+ setLoadingMore(true)
+ try {
+ const page = await listClientAnimals(client, clientId, {
+ after: state.next,
+ })
+ if (current === generation.current)
+ setState({
+ status: 'ready',
+ rows: [...state.rows, ...page.rows],
+ next: page.next,
+ })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ } finally {
+ setLoadingMore(false)
+ }
+ }
+
+ const roleText = (row: ClientAnimalItem) => {
+ const role = t(
+ `clients.role.${row.is_current ? '' : 'former_'}${row.relation_role}`,
+ )
+ const dates = [
+ row.started_on &&
+ t('clients.animals.since').replace(
+ '{date}',
+ formatDate(row.started_on, locale),
+ ),
+ row.ended_on &&
+ t('clients.animals.until').replace(
+ '{date}',
+ formatDate(row.ended_on, locale),
+ ),
+ ].filter(Boolean)
+ return [role, ...dates].join(' · ')
+ }
+
+ function section(groups: AnimalGroup[], current: boolean) {
+ if (!groups.length) return null
+ const id = current ? 'client-animals-current' : 'client-animals-former'
+ return (
+
+
+ {t(current ? 'clients.animals.current' : 'clients.animals.former')}
+
+
+ {groups.map(({ animalId, rows }) => {
+ const first = rows[0]
+ return (
+
+
+
+ {first.animal_name}
+
+
+ {speciesName(
+ labels,
+ first.species_id,
+ first.species_detail,
+ locale,
+ )}
+
+ {first.animal_archived_at && (
+ {t('animals.archived_badge')}
+ )}
+
+
+ {rows.map((row) => (
+ {roleText(row)}
+ ))}
+
+
+ )
+ })}
+
+
+ )
+ }
+
+ const empty = state.status === 'ready' && state.rows.length === 0
+
+ return (
+
+
+
+ {t('clients.animals.title')}
+
+ {!archived && !panelOpen && (
+
+
+ {t(empty ? 'clients.animals.add_first' : 'clients.animals.add')}
+
+ setPanelOpen(true)}
+ >
+ {t('clients.animals.link_existing')}
+
+
+ )}
+
+ {state.status === 'loading' && (
+
+ {t('clients.animals.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+ {t(`clients.failure.${state.failure}`)}
+ void load()}>
+ {t('common.retry')}
+
+
+ )}
+ {empty && (
+
+ {t('clients.animals.none')}
+
+ )}
+ {state.status === 'ready' && (
+ <>
+ {section(byAnimal(state.rows, true), true)}
+ {section(byAnimal(state.rows, false), false)}
+ {state.next && (
+ void more()}
+ aria-disabled={loadingMore}
+ >
+ {loadingMore
+ ? t('clients.list.loading_more')
+ : t('clients.list.more')}
+
+ )}
+ >
+ )}
+ {panelOpen && (
+ setPanelOpen(false)}
+ onSaved={async () => {
+ await load()
+ onStatus(t('relations.added_animal'))
+ setPanelOpen(false)
+ }}
+ />
+ )}
+
+ )
+}
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..02a015ac
--- /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 { usePageHeading } from '@/app/usePageHeading'
+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()
+ const heading = usePageHeading()
+ return (
+
+
+ {t('clients.not_found.title')}
+
+ {t('clients.not_found.body')}
+
+ {t('clients.not_found.back')}
+
+
+ )
+}
diff --git a/apps/app/src/components/relations/AnimalRelations.tsx b/apps/app/src/components/relations/AnimalRelations.tsx
new file mode 100644
index 00000000..7ed2ab51
--- /dev/null
+++ b/apps/app/src/components/relations/AnimalRelations.tsx
@@ -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(null)
+ const [stale, setStale] = useState(null)
+ const addButton = useRef(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) => (
+ setTarget({ action: kind, relation: r })}
+ >
+ {t(key)}
+
+ )
+ return (
+
+
+
+
+ {r.client.display_name}
+
+ {r.client.archived_at && (
+ {t('clients.archived_badge')}
+ )}
+
+
+ {roleLabel(r)}
+ {period(r) && ` · ${period(r)}`}
+
+
+ {r.client.phone && (
+
+ {r.client.phone}
+
+ )}
+ {editable && (
+
+ {r.ended_at === null && action('end', 'relations.end.action')}
+ {action('dates', 'relations.dates.action')}
+ {action('void', 'relations.void.action')}
+
+ )}
+
+ )
+ }
+
+ function group(rows: AnimalRelationItem[], key: string, id: string) {
+ if (!rows.length) return null
+ return (
+
+ )
+ }
+
+ const groups =
+ state.status === 'ready' ? groupRelations(state.relations) : null
+
+ return (
+
+
+
+ {t('relations.title')}
+
+ {editable && !panelOpen && (
+ setPanelOpen(true)}
+ >
+ {t('relations.add_client')}
+
+ )}
+
+ {state.status === 'loading' && (
+
+ {t('relations.loading')}
+
+ )}
+ {state.status === 'error' && (
+
+
+ {t(`relations.failure.${state.failure}`)}
+
+ void reload()}
+ >
+ {t('common.retry')}
+
+
+ )}
+ {stale && {t(`relations.failure.${stale}`)} }
+ {groups && !groups.hasOwner && (
+
+ {t('animals.no_owner')}
+
+ )}
+ {groups && groups.current.length + groups.former.length === 0 && (
+
+ {t('relations.none')}
+
+ )}
+ {groups &&
+ group(groups.current, 'relations.current', 'animal-relations-current')}
+ {groups &&
+ group(groups.former, 'relations.former', 'animal-relations-former')}
+ {panelOpen && (
+ setPanelOpen(false)}
+ onSaved={async () => {
+ await reload()
+ setStale(null)
+ onStatus(t('relations.added_client'))
+ setPanelOpen(false)
+ }}
+ />
+ )}
+ {target?.action === 'end' && (
+ handlers.onDone(t('relations.end.done'))}
+ />
+ )}
+ {target?.action === 'dates' && (
+ handlers.onDone(t('relations.dates.done'))}
+ />
+ )}
+ {target?.action === 'void' && (
+ handlers.onDone(t('relations.void.done'))}
+ />
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/relations/Pickers.tsx b/apps/app/src/components/relations/Pickers.tsx
new file mode 100644
index 00000000..030d66c7
--- /dev/null
+++ b/apps/app/src/components/relations/Pickers.tsx
@@ -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 (
+
+ 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 (
+
+ 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}
+ />
+ )
+}
diff --git a/apps/app/src/components/relations/RecordPicker.tsx b/apps/app/src/components/relations/RecordPicker.tsx
new file mode 100644
index 00000000..e189339e
--- /dev/null
+++ b/apps/app/src/components/relations/RecordPicker.tsx
@@ -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 {
+ 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
+ /** 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 =
+ | { 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({
+ id,
+ label,
+ hint,
+ resultsLabel,
+ emptyLabel,
+ search,
+ toItem,
+ onChoose,
+ error,
+}: RecordPickerProps) {
+ const t = useT()
+ const [query, setQuery] = useState('')
+ const [term, setTerm] = useState('')
+ const [results, setResults] = useState>({ 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 (
+
+
+ setQuery(e.target.value)}
+ maxLength={100}
+ autoComplete="off"
+ aria-invalid={Boolean(error)}
+ aria-describedby={describedBy}
+ />
+
+ {results.status === 'loading' && (
+
+ {t('relations.picker.loading')}
+
+ )}
+ {results.status === 'error' && (
+
+
+ {t(`relations.failure.${results.failure}`)}
+
+ setAttempt((n) => n + 1)}
+ >
+ {t('common.retry')}
+
+
+ )}
+ {results.status === 'ready' && results.items.length === 0 && (
+
+ {emptyLabel}
+
+ )}
+ {results.status === 'ready' && results.items.length > 0 && (
+
+ {results.items.map((row) => {
+ const item = toItem(row)
+ return (
+
+ 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)]"
+ >
+
+ {item.name}
+
+ {item.detail && (
+
+ {item.detail}
+
+ )}
+
+
+ )
+ })}
+
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/relations/RelationActionDialog.tsx b/apps/app/src/components/relations/RelationActionDialog.tsx
new file mode 100644
index 00000000..ce7e569b
--- /dev/null
+++ b/apps/app/src/components/relations/RelationActionDialog.tsx
@@ -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
+ /**
+ * 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
+}
+
+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
+}
+
+/**
+ * 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(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 (
+
+ {relationLabel}
+ {body}
+
+ }
+ size="sm"
+ >
+
+ {children}
+ {failure && (
+ {t(`relations.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 ? pendingLabel : confirmLabel}
+
+
+
+ )
+}
diff --git a/apps/app/src/components/relations/RelationDialogs.tsx b/apps/app/src/components/relations/RelationDialogs.tsx
new file mode 100644
index 00000000..d4684f94
--- /dev/null
+++ b/apps/app/src/components/relations/RelationDialogs.tsx
@@ -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 (
+
+ props.onChange(e.target.value)}
+ aria-invalid={Boolean(props.error)}
+ aria-describedby={
+ props.error ? `${props.id}-error` : `${props.id}-hint`
+ }
+ />
+
+ )
+}
+
+/** 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(null)
+ return (
+ {
+ 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,
+ })
+ }
+ >
+
+
+ )
+}
+
+/** 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 (
+ {
+ 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,
+ })
+ }
+ >
+
+ {ended && (
+
+ )}
+
+ )
+}
+
+/**
+ * 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 (
+
+ voidAnimalClientRelation(backend(), {
+ relationId: relation.id,
+ expectedRevision: relation.revision,
+ })
+ }
+ />
+ )
+}
diff --git a/apps/app/src/components/relations/RelationPanel.tsx b/apps/app/src/components/relations/RelationPanel.tsx
new file mode 100644
index 00000000..cef60fc7
--- /dev/null
+++ b/apps/app/src/components/relations/RelationPanel.tsx
@@ -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
+ 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(null)
+ const chosenText = useRef(null)
+ const [chosen, setChosen] = useState(null)
+ const [role, setRole] = useState('')
+ const [startedOn, setStartedOn] = useState('')
+ const [errors, setErrors] = useState({})
+ const [errorRound, setErrorRound] = useState(0)
+ const [pending, setPending] = useState(false)
+ const [failure, setFailure] = useState(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 (
+
+ )
+}
diff --git a/apps/app/src/components/report/DisclaimerDialog.tsx b/apps/app/src/components/report/DisclaimerDialog.tsx
index 55299e09..b79f4f2a 100644
--- a/apps/app/src/components/report/DisclaimerDialog.tsx
+++ b/apps/app/src/components/report/DisclaimerDialog.tsx
@@ -18,13 +18,11 @@ export default function DisclaimerDialog({
open
onClose={onAcknowledge}
title={t('editor.disclaimer_title')}
+ description={{text}
}
size="md"
>
-
-
{text}
-
- {t('common.understood')}
-
+
+ {t('common.understood')}
)
diff --git a/apps/app/src/components/report/HeldSessionPanel.tsx b/apps/app/src/components/report/HeldSessionPanel.tsx
index 226fceb9..3ea0af19 100644
--- a/apps/app/src/components/report/HeldSessionPanel.tsx
+++ b/apps/app/src/components/report/HeldSessionPanel.tsx
@@ -114,15 +114,17 @@ export default function HeldSessionPanel({
? 'session.held.open_title'
: `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`,
)}
+ description={
+
+ {t(
+ pending?.action === 'open'
+ ? 'session.held.open_body'
+ : 'session.held.discard_body',
+ )}
+
+ }
size="sm"
>
-
- {t(
- pending?.action === 'open'
- ? 'session.held.open_body'
- : 'session.held.discard_body',
- )}
-
setPending(null)}>
{t('common.cancel')}
diff --git a/apps/app/src/components/report/ReplaceSessionDialog.tsx b/apps/app/src/components/report/ReplaceSessionDialog.tsx
index 4a9b9188..47d95e56 100644
--- a/apps/app/src/components/report/ReplaceSessionDialog.tsx
+++ b/apps/app/src/components/report/ReplaceSessionDialog.tsx
@@ -30,8 +30,13 @@ export default function ReplaceSessionDialog({
? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name)
: t('session.replace.body_unloaded')
return (
-
- {body}
+ {body}}
+ size="sm"
+ >
{unsaved && (
{t('session.replace.unsaved')}
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/MobileDrawer.tsx b/apps/app/src/components/shell/MobileDrawer.tsx
index 648598cf..94cafbe8 100644
--- a/apps/app/src/components/shell/MobileDrawer.tsx
+++ b/apps/app/src/components/shell/MobileDrawer.tsx
@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom'
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import Brand from '@/components/brand/Brand'
import Icon from '@/components/ui/Icon'
+import ModalDialog from '@/components/ui/ModalDialog'
import SidebarNav from './SidebarNav'
import SignOutButton from './SignOutButton'
import UserBadge from './UserBadge'
@@ -13,64 +14,65 @@ export interface MobileDrawerProps {
onClose: () => void
}
+/** The sidebar's breakpoint (Tailwind `lg`): from there the drawer has no reason to stay open. */
+const LARGE_SCREEN = '(min-width: 64rem)'
+
/** Left-side navigation drawer for small screens (transform + opacity only). */
export default function MobileDrawer({ open, onClose }: MobileDrawerProps) {
+ return
{open && }
+}
+
+function DrawerSurface({ onClose }: Pick
) {
const t = useT()
const reduced = useReducedMotion()
const slide = reduced ? { x: 0 } : { x: '-100%' }
+ // A modal drawer left open while the window widens would keep the page inert.
useEffect(() => {
- if (!open) return
- const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [open, onClose])
+ const query = window.matchMedia(LARGE_SCREEN)
+ const onChange = (event: MediaQueryListEvent) => event.matches && onClose()
+ query.addEventListener('change', onChange)
+ return () => query.removeEventListener('change', onChange)
+ }, [onClose])
return (
-
- {open && (
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
- )}
-
+
+
+
+
+
+
+
+
+
)
}
diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx
index 98f9830e..ac0eebc2 100644
--- a/apps/app/src/components/shell/SidebarNav.tsx
+++ b/apps/app/src/components/shell/SidebarNav.tsx
@@ -12,6 +12,8 @@ interface NavItem {
export const NAV_ITEMS: readonly NavItem[] = [
{ to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true },
+ { to: '/app/clients', icon: 'users', labelKey: 'shell.nav.clients' },
+ { to: '/app/animals', icon: 'paw', labelKey: 'shell.nav.animals' },
{ to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' },
{
to: '/',
@@ -31,7 +33,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/Button.tsx b/apps/app/src/components/ui/Button.tsx
index a5c1a3da..c7cdb8ef 100644
--- a/apps/app/src/components/ui/Button.tsx
+++ b/apps/app/src/components/ui/Button.tsx
@@ -1,9 +1,11 @@
-import type { ButtonHTMLAttributes, ReactNode } from 'react'
+import type { ButtonHTMLAttributes, ReactNode, Ref } from 'react'
export interface ButtonProps extends ButtonHTMLAttributes {
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
size?: 'sm' | 'md' | 'lg'
children?: ReactNode
+ /** React 19 passes it as a prop; it reaches the with the rest. */
+ ref?: Ref
}
const VARIANTS: Record, string> = {
diff --git a/apps/app/src/components/ui/Card.tsx b/apps/app/src/components/ui/Card.tsx
index 35dfa819..1e885b2c 100644
--- a/apps/app/src/components/ui/Card.tsx
+++ b/apps/app/src/components/ui/Card.tsx
@@ -4,15 +4,19 @@ export interface CardProps {
children: ReactNode
className?: string
as?: 'div' | 'section' | 'article'
+ /** Names a section card by its heading, so it reads as a named region. */
+ 'aria-labelledby'?: string
}
export default function Card({
children,
className = '',
as: Tag = 'div',
+ 'aria-labelledby': labelledBy,
}: CardProps) {
return (
{
+ /** Prefix of the radio ids: the first one is `${id}-${options[0].value}`. */
+ id: string
+ legend: string
+ /** « obligatoire » or « facultatif », shown beside the legend like FormField. */
+ marker?: string
+ options: readonly { value: V; label: string }[]
+ /** '' when nothing is chosen: no option is preselected. */
+ value: V | ''
+ onChange: (value: V) => void
+ hint?: string
+ error?: string
+}
+
+/** The id of the radio that takes focus when the group is in error. */
+export const firstChoiceId = (id: string, first: string) => `${id}-${first}`
+
+/**
+ * A required choice among a few explicit options, as large touch targets
+ * (the client kind's look): a fieldset named by its legend, the error under
+ * it and linked from every radio, nothing checked until the user picks.
+ */
+export default function ChoiceRadios({
+ id,
+ legend,
+ marker,
+ options,
+ value,
+ onChange,
+ hint,
+ error,
+}: ChoiceRadiosProps) {
+ const describedBy = error ? `${id}-error` : hint ? `${id}-hint` : undefined
+ return (
+
+ {/* The look of Label (FormField), on the element that names the group. */}
+
+ {legend}
+ {marker && (
+
+ {marker}
+
+ )}
+
+
+ {options.map((option) => (
+
+ onChange(option.value)}
+ aria-invalid={Boolean(error)}
+ aria-describedby={describedBy}
+ className="h-4 w-4 accent-[var(--color-accent)]"
+ />
+ {option.label}
+
+ ))}
+
+ {error ? (
+
+ {error}
+
+ ) : (
+ hint && (
+
+ {hint}
+
+ )
+ )}
+
+ )
+}
diff --git a/apps/app/src/components/ui/Dialog.tsx b/apps/app/src/components/ui/Dialog.tsx
index 8d9211ac..5b85a9c4 100644
--- a/apps/app/src/components/ui/Dialog.tsx
+++ b/apps/app/src/components/ui/Dialog.tsx
@@ -1,11 +1,15 @@
-import { useEffect, type ReactNode } from 'react'
+import { useId, type ReactNode } from 'react'
import { AnimatePresence, motion } from 'motion/react'
+import ModalDialog from './ModalDialog'
import { useT } from '@/i18n/useT'
export interface DialogProps {
open: boolean
+ /** Asked on Escape, the close button and a backdrop click; the dialog leaves when `open` turns false. */
onClose: () => void
title: string
+ /** The dialog's message, announced with its name (aria-describedby). */
+ description?: ReactNode
children: ReactNode
size?: 'sm' | 'md' | 'lg' | 'xl'
}
@@ -17,61 +21,66 @@ const SIZE: Record, string> = {
xl: 'max-w-4xl',
}
-export default function Dialog({
- open,
- onClose,
- title,
- children,
- size = 'md',
-}: DialogProps) {
- const t = useT()
- useEffect(() => {
- if (!open) return
- const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [open, onClose])
-
+export default function Dialog({ open, ...surface }: DialogProps) {
return (
-
- {open && (
-
-
{open && }
+ )
+}
+
+function DialogSurface({
+ onClose,
+ title,
+ description,
+ children,
+ size = 'md',
+}: Omit) {
+ const t = useT()
+ const titleId = useId()
+ const descriptionId = useId()
+ return (
+
+
+
+
+
+ {title}
+
+
-
-
- {children}
-
+ ✕
+
+
+
+ {description &&
{description}
}
+ {children}
- )}
-
+
+
)
}
diff --git a/apps/app/src/components/ui/Icon.tsx b/apps/app/src/components/ui/Icon.tsx
index 0123c7bd..b44da71a 100644
--- a/apps/app/src/components/ui/Icon.tsx
+++ b/apps/app/src/components/ui/Icon.tsx
@@ -5,6 +5,8 @@ export type IconName =
| 'close'
| 'dashboard'
| 'user'
+ | 'users'
+ | 'paw'
| 'tool'
| 'logout'
| 'eye'
@@ -20,6 +22,8 @@ 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',
+ paw: 'M3.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M7.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M13.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M16.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M12 12.5c-2.5 0-5 3.2-5 5.3 0 1.6 1.3 2.4 2.8 2.4 1 0 1.5-.5 2.2-.5s1.2.5 2.2.5c1.5 0 2.8-.8 2.8-2.4 0-2.1-2.5-5.3-5-5.3z',
tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3',
logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9',
eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
diff --git a/apps/app/src/components/ui/ModalDialog.tsx b/apps/app/src/components/ui/ModalDialog.tsx
new file mode 100644
index 00000000..5e5cf3bd
--- /dev/null
+++ b/apps/app/src/components/ui/ModalDialog.tsx
@@ -0,0 +1,142 @@
+import {
+ useLayoutEffect,
+ useRef,
+ type KeyboardEvent,
+ type ReactNode,
+ type SyntheticEvent,
+} from 'react'
+
+export interface ModalDialogProps {
+ /** Asked on Escape and on the platform's close requests; the consumer decides. */
+ onClose: () => void
+ /** Id of the visible title; `label` names a dialog that shows none. */
+ labelledBy?: string
+ label?: string
+ describedBy?: string
+ className?: string
+ children: ReactNode
+}
+
+/**
+ * Controls in the tab order: the first one takes focus on open, and serves as a
+ * fallback when the opener is gone.
+ */
+const FOCUSABLE = [
+ 'a[href]',
+ 'button:not([disabled])',
+ 'input:not([disabled]):not([type="hidden"])',
+ 'select:not([disabled])',
+ 'textarea:not([disabled])',
+ '[tabindex]',
+]
+ .map((selector) => `${selector}:not([tabindex="-1"])`)
+ .join(', ')
+
+/** Full-viewport transparent container: the consumer draws its own backdrop and panel. */
+const SURFACE =
+ 'm-0 h-full max-h-none w-full max-w-none overflow-hidden border-0 bg-transparent p-0 ' +
+ 'text-inherit backdrop:bg-transparent'
+
+/** False when the browser refused the focus (element gone, disabled, hidden or inert). */
+function tryFocus(element: HTMLElement): boolean {
+ element.focus()
+ return document.activeElement === element
+}
+
+function ancestorsOf(element: HTMLElement | null): HTMLElement[] {
+ const chain: HTMLElement[] = []
+ for (let node = element?.parentElement; node; node = node.parentElement)
+ chain.push(node)
+ return chain
+}
+
+/**
+ * The opener when it still takes focus, else the first control of its nearest
+ * container still on the page.
+ */
+function restoreFocus(
+ opener: HTMLElement | null,
+ ancestors: HTMLElement[],
+): void {
+ if (!opener || tryFocus(opener)) return
+ for (const container of ancestors) {
+ if (!container.isConnected) continue
+ const controls = Array.from(
+ container.querySelectorAll(FOCUSABLE),
+ )
+ if (controls.some(tryFocus)) return
+ }
+}
+
+/**
+ * Native modal `` shown while mounted (D13): `showModal()` makes the
+ * rest of the page inert and keeps focus in the top layer. The dialog never
+ * closes itself: Escape and close requests call `onClose`, and it leaves the
+ * screen when the consumer unmounts it. Focus starts on the first control and
+ * then returns to the opener. Tab past the last control reaches the browser's
+ * own interface, never the page, as the platform intends.
+ */
+export default function ModalDialog({
+ onClose,
+ labelledBy,
+ label,
+ describedBy,
+ className = '',
+ children,
+}: ModalDialogProps) {
+ const ref = useRef(null)
+
+ useLayoutEffect(() => {
+ const dialog = ref.current
+ if (!dialog) return
+ const active = document.activeElement
+ const opener =
+ active instanceof HTMLElement && active !== document.body ? active : null
+ const ancestors = ancestorsOf(opener)
+ dialog.showModal()
+ // The first control, not the platform's pick: Chromium focuses a scrollable
+ // panel when the content is long, the close button otherwise.
+ dialog.querySelector(FOCUSABLE)?.focus()
+ return () => {
+ if (dialog.open) dialog.close()
+ // After the commit: the render that closes the dialog may remove the opener
+ // too. A dialog still on screen was only remounted (React StrictMode).
+ queueMicrotask(() => {
+ if (!dialog.isConnected) restoreFocus(opener, ancestors)
+ })
+ }
+ }, [])
+
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape' || event.nativeEvent.isComposing) return
+ // A cancelled keydown is no close request: Chromium would otherwise close the
+ // dialog on a second Escape without asking (close watcher anti-abuse rule).
+ event.preventDefault()
+ event.stopPropagation()
+ onClose()
+ }
+ const onCancel = (event: SyntheticEvent) => {
+ event.preventDefault()
+ onClose()
+ }
+ // Closed by the platform anyway: keep the consumer's state in step. The check
+ // ignores the `close` event queued by a cleanup the dialog has since reopened from.
+ const onClosed = () => {
+ if (ref.current && !ref.current.open) onClose()
+ }
+
+ return (
+
+ {children}
+
+ )
+}
diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts
index 8846d23c..e444ef4c 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,371 @@ 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',
+
+ // V1-1.6 animals and relations
+ 'shell.nav.animals': 'Animals',
+ 'clients.failure.duplicate_relation':
+ 'This client already holds this role, currently, for this animal.',
+ 'clients.failure.already_ended': 'This relation has already ended.',
+ 'clients.detail.animal_added': 'Animal created and linked to this client.',
+ 'clients.animals.add': 'Add an animal',
+ 'clients.animals.add_first': 'Add a first animal',
+ 'clients.animals.link_existing': 'Link an existing animal',
+ 'animals.failure.not_found':
+ 'This animal, or the chosen client, cannot be found.',
+ 'animals.failure.archived':
+ 'This animal, or the chosen client, is archived: restore it to continue.',
+ 'animals.failure.conflict': 'This animal was changed in the meantime.',
+ 'animals.failure.request_conflict':
+ 'An earlier attempt of this creation carried other values and may already have created the animal. Check the animal list before trying again.',
+ 'animals.failure.limit_reached':
+ 'Your workspace has reached its maximum number of animals or relations.',
+ 'animals.failure.rate_limited':
+ 'Too many changes in a short time. Try again in a few minutes.',
+ 'animals.failure.invalid_input':
+ 'A value was not accepted. Check the fields.',
+ 'animals.failure.duplicate_relation':
+ 'This client already holds this role, currently, for this animal.',
+ 'animals.failure.already_ended': 'This relation has already ended.',
+ 'animals.failure.session_expired': 'Your session has expired. Sign in again.',
+ 'animals.failure.network': 'No connection. Check your network, then retry.',
+ 'animals.failure.unavailable':
+ 'The service is not answering right now. Retry.',
+ 'animals.sex.male': 'Male',
+ 'animals.sex.female': 'Female',
+ 'animals.sex.unknown': 'Unknown',
+ 'animals.archived_badge': 'Archived',
+ 'animals.no_owner': 'Owner not entered',
+ 'animals.owner_archived': '{name} (archived)',
+ 'animals.list.title': 'Animals',
+ 'animals.list.new': 'New animal',
+ 'animals.list.search_label': 'Search an animal',
+ 'animals.list.search_hint': 'Name, breed or species detail',
+ 'animals.list.species_filter': 'Species',
+ 'animals.list.species_all': 'All species',
+ 'animals.list.archived_toggle': 'Show archived',
+ 'animals.list.loading': 'Loading animals…',
+ 'animals.list.results_label': 'Animals found',
+ 'animals.list.count_one': '1 animal shown',
+ 'animals.list.count_other': '{count} animals shown',
+ 'animals.list.empty': 'No animal yet.',
+ 'animals.list.empty_hint':
+ 'Create an animal with “New animal”, or from a client’s page.',
+ 'animals.list.no_results': 'No animal matches this search.',
+ 'animals.list.archived_empty': 'No archived animal.',
+ 'animals.list.more': 'Show more',
+ 'animals.list.loading_more': 'Loading…',
+ 'animals.list.owner': 'Owner: {names}',
+ 'animals.list.owners': 'Owners: {names}',
+ 'animals.list.owners_more': 'and {count} more',
+ 'animals.form.create_title': 'New animal',
+ 'animals.form.edit_title': 'Edit the animal',
+ 'animals.form.identity_title': 'Identity',
+ 'animals.form.name': 'Name',
+ 'animals.form.species': 'Species',
+ 'animals.form.species_choose': 'Choose a species',
+ 'animals.form.species_loading': 'Loading species…',
+ 'animals.form.species_failed': 'The species list could not be loaded.',
+ 'animals.form.species_detail': 'Species detail',
+ 'animals.form.species_detail_hint': 'For “Other”: “Ferret”, “Llama”.',
+ 'animals.form.sex': 'Sex',
+ 'animals.form.sex_hint': 'Choose “Unknown” if you do not know.',
+ 'animals.form.breed': 'Breed',
+ 'animals.form.birth_title': 'Birth',
+ 'animals.form.birth_year': 'Year of birth',
+ 'animals.form.birth_year_hint': 'If you know it: 2015.',
+ 'animals.form.birth_year_locked':
+ 'Taken from the full date. Clear the date to change the year.',
+ 'animals.form.birth_date': 'Full date of birth',
+ 'animals.form.birth_date_hint':
+ 'Only if you know the day. The year fills itself in.',
+ 'animals.form.client_title': 'Client',
+ 'animals.form.client_hint':
+ 'Optional: the animal can be created without a client and linked later.',
+ 'animals.form.client_remove': 'Remove this client',
+ 'animals.form.origin_loading': 'Loading the client…',
+ 'animals.form.origin_unavailable':
+ 'The client you came from is no longer available: the animal will be created without a client unless you choose one.',
+ 'animals.form.required': 'required',
+ 'animals.form.optional': 'optional',
+ 'animals.form.submit_create': 'Create the animal',
+ 'animals.form.submit_update': 'Save',
+ 'animals.form.saving': 'Saving…',
+ 'animals.form.back_to_animal': 'Back to the record',
+ 'animals.form.conflict_title': 'This animal was changed elsewhere.',
+ 'animals.form.conflict_body':
+ 'Your entries are kept and the saved value is shown under each field that differs. “Save” will replace the saved values with yours.',
+ 'animals.form.conflict_take_stored': 'Take the saved values',
+ 'animals.form.stored_value': 'Saved value: {value}',
+ 'animals.form.stored_empty': 'Saved value: empty',
+ 'animals.error.required': 'This field is required.',
+ 'animals.error.too_long': '{max} characters at most.',
+ 'animals.error.characters': 'Character not accepted (tab, line break…).',
+ 'animals.error.species': 'Choose a species.',
+ 'animals.error.species_detail': 'Give the species.',
+ 'animals.error.sex': 'Choose the sex, “Unknown” included.',
+ 'animals.error.year_format': 'Four-digit year: 2015.',
+ 'animals.error.year_range': 'The year runs from 1900 to the current year.',
+ 'animals.error.date_format': 'Invalid date.',
+ 'animals.error.date_range':
+ 'The date cannot be in the future, nor before 1900.',
+ 'animals.error.date_year': 'The year does not match the full date.',
+ 'animals.error.client': 'Pick one from the list.',
+ 'animals.error.role': 'Choose the role.',
+ 'animals.age.years_one': '1 year',
+ 'animals.age.years_other': '{count} years',
+ 'animals.age.months_one': '1 month',
+ 'animals.age.months_other': '{count} months',
+ 'animals.age.about': 'about {age}',
+ 'animals.age.under_one': 'under a year',
+ 'animals.detail.loading': 'Loading the animal…',
+ 'animals.detail.back': '← Animals',
+ 'animals.detail.identity': 'Identity',
+ 'animals.detail.species': 'Species',
+ 'animals.detail.sex': 'Sex',
+ 'animals.detail.breed': 'Breed',
+ 'animals.detail.breed_none': 'Not entered',
+ 'animals.detail.birth': 'Birth',
+ 'animals.detail.birth_on': 'On {date}',
+ 'animals.detail.birth_in': 'In {year}',
+ 'animals.detail.birth_unknown': 'Unknown',
+ 'animals.detail.status': 'Status',
+ 'animals.detail.status_active': 'Active',
+ 'animals.detail.status_archived': 'Archived',
+ 'animals.detail.edit': 'Edit',
+ 'animals.detail.archive': 'Archive',
+ 'animals.detail.restore': 'Restore',
+ 'animals.detail.restoring': 'Restoring…',
+ 'animals.detail.archived_notice':
+ 'This animal is archived: its record and its relations are read-only. Restore it to edit them.',
+ 'animals.detail.created': 'Animal created.',
+ 'animals.detail.updated': 'Changes saved.',
+ 'animals.detail.archived': 'Animal archived.',
+ 'animals.detail.restored': 'Animal restored.',
+ 'animals.archive.title': 'Archive this animal?',
+ 'animals.archive.body':
+ 'The animal will be hidden from the lists and its record, relations included, becomes read-only. Its relations are kept and no client is archived. You can restore it at any time.',
+ 'animals.archive.confirm': 'Archive',
+ 'animals.archive.archiving': 'Archiving…',
+ 'animals.not_found.title': 'Animal not found',
+ 'animals.not_found.body':
+ 'This animal does not exist or cannot be reached from your account.',
+ 'animals.not_found.back': 'Back to animals',
+ 'relations.failure.not_found':
+ 'This client, animal or relation cannot be found: it may have been removed in the meantime.',
+ 'relations.failure.archived':
+ 'The animal or the client is archived: restore it to change its relations.',
+ 'relations.failure.conflict':
+ 'This relation was changed or removed in the meantime. The record is up to date: check it before trying again.',
+ 'relations.failure.request_conflict':
+ 'An earlier attempt of this link carried other values and may already have created the relation. Check the record before trying again.',
+ 'relations.failure.limit_reached':
+ 'The maximum number of relations is reached (20 current or 200 in total for an animal).',
+ 'relations.failure.rate_limited':
+ 'Too many changes in a short time. Try again in a few minutes.',
+ 'relations.failure.invalid_input':
+ 'The change was not accepted. Check the dates: not in the future, and the end after the start.',
+ 'relations.failure.duplicate_relation':
+ 'This client already holds this role, currently, for this animal.',
+ 'relations.failure.already_ended': 'This relation has already ended.',
+ 'relations.failure.session_expired':
+ 'Your session has expired. Sign in again.',
+ 'relations.failure.network':
+ 'No connection. Check your network, then retry.',
+ 'relations.failure.unavailable':
+ 'The service is not answering right now. Retry.',
+ 'relations.title': 'Linked clients',
+ 'relations.loading': 'Loading linked clients…',
+ 'relations.none': 'No client linked to this animal.',
+ 'relations.current': 'Current',
+ 'relations.former': 'History',
+ 'relations.since': 'since {date}',
+ 'relations.until': 'until {date}',
+ 'relations.add_client': 'Add a client',
+ 'relations.added_client': 'Client linked to this animal.',
+ 'relations.added_animal': 'Animal linked to this client.',
+ 'relations.saving': 'Saving…',
+ 'relations.date_hint': 'Optional: leave it empty if you do not know it.',
+ 'relations.action_named': '{action}: {name}, {role}',
+ 'relations.panel.title_client': 'Link a client to this animal',
+ 'relations.panel.title_animal': 'Link an animal to this client',
+ 'relations.panel.client_chosen': 'Chosen client:',
+ 'relations.panel.animal_chosen': 'Chosen animal:',
+ 'relations.panel.change': 'Change',
+ 'relations.panel.role': 'Role',
+ 'relations.panel.started_on': 'Start of the relation',
+ 'relations.panel.save_client': 'Link this client',
+ 'relations.panel.save_animal': 'Link this animal',
+ 'relations.panel.saving': 'Saving…',
+ 'relations.picker.client_label': 'Search a client',
+ 'relations.picker.client_hint':
+ 'Active clients: name, city, email or phone',
+ 'relations.picker.client_results': 'Suggested clients',
+ 'relations.picker.client_none': 'No active client matches.',
+ 'relations.picker.animal_label': 'Search an animal',
+ 'relations.picker.animal_hint': 'Active animals: name, breed or species detail',
+ 'relations.picker.animal_results': 'Suggested animals',
+ 'relations.picker.animal_none': 'No active animal matches.',
+ 'relations.picker.loading': 'Searching…',
+ 'relations.end.action': 'End',
+ 'relations.end.title': 'End this relation?',
+ 'relations.end.body':
+ 'It moves to the history, with its end date if you know it. Nothing is deleted.',
+ 'relations.end.ended_on': 'End date',
+ 'relations.end.confirm': 'End the relation',
+ 'relations.end.done': 'Relation ended.',
+ 'relations.dates.action': 'Correct the dates',
+ 'relations.dates.title': 'Correct the dates',
+ 'relations.dates.body':
+ 'The client and the role do not change. An empty date means “unknown”.',
+ 'relations.dates.started_on': 'Start date',
+ 'relations.dates.ended_on': 'End date',
+ 'relations.dates.confirm': 'Save the dates',
+ 'relations.dates.done': 'Dates saved.',
+ 'relations.void.action': 'Entered by mistake',
+ 'relations.void.title': 'Remove a relation entered by mistake?',
+ 'relations.void.body':
+ 'Only if this relation never existed: wrong client, wrong animal or wrong role. It will disappear from the records, the lists and the history without being deleted, and cannot be brought back. For a relation that really ended, use “End”.',
+ 'relations.void.confirm': 'Remove the relation',
+ 'relations.void.done': 'Relation removed (entered by mistake).',
+ 'relations.error.end_before_start': 'The end cannot come before the start.',
}
diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts
index 319712a9..90e4d7c0 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,384 @@ 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',
+
+ // V1-1.6 animals and relations
+ 'shell.nav.animals': 'Animaux',
+ 'clients.failure.duplicate_relation':
+ 'Ce client a déjà ce rôle, en cours, pour cet animal.',
+ 'clients.failure.already_ended': 'Cette relation est déjà terminée.',
+ 'clients.detail.animal_added': 'Animal créé et lié à ce client.',
+ 'clients.animals.add': 'Ajouter un animal',
+ 'clients.animals.add_first': 'Ajouter un premier animal',
+ 'clients.animals.link_existing': 'Associer un animal existant',
+ 'animals.failure.not_found':
+ 'Cet animal, ou le client choisi, est introuvable.',
+ 'animals.failure.archived':
+ 'Cet animal, ou le client choisi, est archivé : restaurez-le pour continuer.',
+ 'animals.failure.conflict': 'Cet animal a été modifié entre-temps.',
+ 'animals.failure.request_conflict':
+ "Une tentative précédente de cette création portait d'autres valeurs et a peut-être déjà créé l'animal. Vérifiez la liste des animaux avant de recommencer.",
+ 'animals.failure.limit_reached':
+ "Le nombre maximal d'animaux ou de relations de votre espace est atteint.",
+ 'animals.failure.rate_limited':
+ "Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.",
+ 'animals.failure.invalid_input':
+ "Une valeur n'a pas été acceptée. Vérifiez les champs.",
+ 'animals.failure.duplicate_relation':
+ 'Ce client a déjà ce rôle, en cours, pour cet animal.',
+ 'animals.failure.already_ended': 'Cette relation est déjà terminée.',
+ 'animals.failure.session_expired':
+ 'Votre session a expiré. Reconnectez-vous.',
+ 'animals.failure.network':
+ 'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
+ 'animals.failure.unavailable':
+ 'Le service ne répond pas pour le moment. Réessayez.',
+ 'animals.sex.male': 'Mâle',
+ 'animals.sex.female': 'Femelle',
+ 'animals.sex.unknown': 'Inconnu',
+ 'animals.archived_badge': 'Archivé',
+ 'animals.no_owner': 'Propriétaire non renseigné',
+ 'animals.owner_archived': '{name} (archivé)',
+ 'animals.list.title': 'Animaux',
+ 'animals.list.new': 'Nouvel animal',
+ 'animals.list.search_label': 'Rechercher un animal',
+ 'animals.list.search_hint': "Nom, race ou précision d'espèce",
+ 'animals.list.species_filter': 'Espèce',
+ 'animals.list.species_all': 'Toutes les espèces',
+ 'animals.list.archived_toggle': 'Afficher les archivés',
+ 'animals.list.loading': 'Chargement des animaux…',
+ 'animals.list.results_label': 'Animaux trouvés',
+ 'animals.list.count_one': '1 animal affiché',
+ 'animals.list.count_other': '{count} animaux affichés',
+ 'animals.list.empty': "Aucun animal pour l'instant.",
+ 'animals.list.empty_hint':
+ "Créez un animal avec « Nouvel animal », ou depuis la fiche d'un client.",
+ 'animals.list.no_results': 'Aucun animal ne correspond à cette recherche.',
+ 'animals.list.archived_empty': 'Aucun animal archivé.',
+ 'animals.list.more': 'Afficher plus',
+ 'animals.list.loading_more': 'Chargement…',
+ 'animals.list.owner': 'Propriétaire : {names}',
+ 'animals.list.owners': 'Propriétaires : {names}',
+ 'animals.list.owners_more': 'et {count} de plus',
+ 'animals.form.create_title': 'Nouvel animal',
+ 'animals.form.edit_title': "Modifier l'animal",
+ 'animals.form.identity_title': 'Identité',
+ 'animals.form.name': 'Nom',
+ 'animals.form.species': 'Espèce',
+ 'animals.form.species_choose': 'Choisir une espèce',
+ 'animals.form.species_loading': 'Chargement des espèces…',
+ 'animals.form.species_failed':
+ "La liste des espèces n'a pas pu être chargée.",
+ 'animals.form.species_detail': "Précision de l'espèce",
+ 'animals.form.species_detail_hint': 'Pour « Autre » : « Furet », « Lama ».',
+ 'animals.form.sex': 'Sexe',
+ 'animals.form.sex_hint': 'Choisissez « Inconnu » si vous ne savez pas.',
+ 'animals.form.breed': 'Race',
+ 'animals.form.birth_title': 'Naissance',
+ 'animals.form.birth_year': 'Année de naissance',
+ 'animals.form.birth_year_hint': 'Si vous la connaissez : 2015.',
+ 'animals.form.birth_year_locked':
+ "Reprise de la date complète. Effacez la date pour modifier l'année.",
+ 'animals.form.birth_date': 'Date de naissance complète',
+ 'animals.form.birth_date_hint':
+ "Seulement si vous connaissez le jour. L'année se remplit d'elle-même.",
+ 'animals.form.client_title': 'Client',
+ 'animals.form.client_hint':
+ "Facultatif : l'animal peut être créé sans client et lié plus tard.",
+ 'animals.form.client_remove': 'Retirer ce client',
+ 'animals.form.origin_loading': 'Chargement du client…',
+ 'animals.form.origin_unavailable':
+ "Le client d'origine n'est plus disponible : l'animal sera créé sans client, sauf si vous en choisissez un.",
+ 'animals.form.required': 'obligatoire',
+ 'animals.form.optional': 'facultatif',
+ 'animals.form.submit_create': "Créer l'animal",
+ 'animals.form.submit_update': 'Enregistrer',
+ 'animals.form.saving': 'Enregistrement…',
+ 'animals.form.back_to_animal': 'Retour à la fiche',
+ 'animals.form.conflict_title': 'Cet animal a été modifié ailleurs.',
+ 'animals.form.conflict_body':
+ 'Vos saisies sont conservées et la valeur enregistrée est indiquée sous chaque champ qui diffère. « Enregistrer » remplacera les valeurs enregistrées par les vôtres.',
+ 'animals.form.conflict_take_stored': 'Reprendre les valeurs enregistrées',
+ 'animals.form.stored_value': 'Valeur enregistrée : {value}',
+ 'animals.form.stored_empty': 'Valeur enregistrée : vide',
+ 'animals.error.required': 'Ce champ est obligatoire.',
+ 'animals.error.too_long': '{max} caractères au maximum.',
+ 'animals.error.characters':
+ 'Caractère non accepté (tabulation, saut de ligne…).',
+ 'animals.error.species': 'Choisissez une espèce.',
+ 'animals.error.species_detail': "Précisez l'espèce.",
+ 'animals.error.sex': 'Choisissez le sexe, « Inconnu » compris.',
+ 'animals.error.year_format': 'Année sur quatre chiffres : 2015.',
+ 'animals.error.year_range': "L'année va de 1900 à l'année en cours.",
+ 'animals.error.date_format': 'Date invalide.',
+ 'animals.error.date_range':
+ 'La date ne peut pas être dans le futur, ni avant 1900.',
+ 'animals.error.date_year': "L'année ne correspond pas à la date complète.",
+ 'animals.error.client': 'Faites un choix dans la liste.',
+ 'animals.error.role': 'Choisissez le rôle.',
+ 'animals.age.years_one': '1 an',
+ 'animals.age.years_other': '{count} ans',
+ 'animals.age.months_one': '1 mois',
+ 'animals.age.months_other': '{count} mois',
+ 'animals.age.about': 'environ {age}',
+ 'animals.age.under_one': "moins d'un an",
+ 'animals.detail.loading': "Chargement de l'animal…",
+ 'animals.detail.back': '← Animaux',
+ 'animals.detail.identity': 'Identité',
+ 'animals.detail.species': 'Espèce',
+ 'animals.detail.sex': 'Sexe',
+ 'animals.detail.breed': 'Race',
+ 'animals.detail.breed_none': 'Non renseignée',
+ 'animals.detail.birth': 'Naissance',
+ 'animals.detail.birth_on': 'Le {date}',
+ 'animals.detail.birth_in': 'En {year}',
+ 'animals.detail.birth_unknown': 'Inconnue',
+ 'animals.detail.status': 'Statut',
+ 'animals.detail.status_active': 'Actif',
+ 'animals.detail.status_archived': 'Archivé',
+ 'animals.detail.edit': 'Modifier',
+ 'animals.detail.archive': 'Archiver',
+ 'animals.detail.restore': 'Restaurer',
+ 'animals.detail.restoring': 'Restauration…',
+ 'animals.detail.archived_notice':
+ 'Cet animal est archivé : sa fiche et ses relations sont en lecture seule. Restaurez-le pour les modifier.',
+ 'animals.detail.created': 'Animal créé.',
+ 'animals.detail.updated': 'Modifications enregistrées.',
+ 'animals.detail.archived': 'Animal archivé.',
+ 'animals.detail.restored': 'Animal restauré.',
+ 'animals.archive.title': 'Archiver cet animal ?',
+ 'animals.archive.body':
+ "L'animal sera masqué des listes et sa fiche passera en lecture seule, relations comprises. Ses relations sont conservées et aucun client n'est archivé. Vous pourrez le restaurer à tout moment.",
+ 'animals.archive.confirm': 'Archiver',
+ 'animals.archive.archiving': 'Archivage…',
+ 'animals.not_found.title': 'Animal introuvable',
+ 'animals.not_found.body':
+ "Cet animal n'existe pas ou n'est pas accessible depuis votre compte.",
+ 'animals.not_found.back': 'Retour aux animaux',
+ 'relations.failure.not_found':
+ 'Ce client, cet animal ou cette relation est introuvable : il a peut-être été retiré entre-temps.',
+ 'relations.failure.archived':
+ "L'animal ou le client est archivé : restaurez-le pour modifier ses relations.",
+ 'relations.failure.conflict':
+ 'Cette relation a été modifiée ou retirée entre-temps. La fiche est à jour : vérifiez-la avant de recommencer.',
+ 'relations.failure.request_conflict':
+ "Une tentative précédente de cet ajout portait d'autres valeurs et a peut-être déjà créé la relation. Vérifiez la fiche avant de recommencer.",
+ 'relations.failure.limit_reached':
+ 'Le nombre maximal de relations est atteint (20 en cours ou 200 au total pour un animal).',
+ 'relations.failure.rate_limited':
+ "Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.",
+ 'relations.failure.invalid_input':
+ "La modification n'a pas été acceptée. Vérifiez les dates : pas dans le futur, et la fin après le début.",
+ 'relations.failure.duplicate_relation':
+ 'Ce client a déjà ce rôle, en cours, pour cet animal.',
+ 'relations.failure.already_ended': 'Cette relation est déjà terminée.',
+ 'relations.failure.session_expired':
+ 'Votre session a expiré. Reconnectez-vous.',
+ 'relations.failure.network':
+ 'Connexion impossible. Vérifiez votre réseau, puis réessayez.',
+ 'relations.failure.unavailable':
+ 'Le service ne répond pas pour le moment. Réessayez.',
+ 'relations.title': 'Clients liés',
+ 'relations.loading': 'Chargement des clients liés…',
+ 'relations.none': 'Aucun client lié à cet animal.',
+ 'relations.current': 'Actuels',
+ 'relations.former': 'Historique',
+ 'relations.since': 'depuis le {date}',
+ 'relations.until': "jusqu'au {date}",
+ 'relations.add_client': 'Ajouter un client',
+ 'relations.added_client': 'Client lié à cet animal.',
+ 'relations.added_animal': 'Animal associé à ce client.',
+ 'relations.saving': 'Enregistrement…',
+ 'relations.date_hint':
+ 'Facultative : laissez vide si vous ne la connaissez pas.',
+ 'relations.action_named': '{action} : {name}, {role}',
+ 'relations.panel.title_client': 'Lier un client à cet animal',
+ 'relations.panel.title_animal': 'Associer un animal à ce client',
+ 'relations.panel.client_chosen': 'Client choisi :',
+ 'relations.panel.animal_chosen': 'Animal choisi :',
+ 'relations.panel.change': 'Changer',
+ 'relations.panel.role': 'Rôle',
+ 'relations.panel.started_on': 'Début de la relation',
+ 'relations.panel.save_client': 'Lier ce client',
+ 'relations.panel.save_animal': 'Associer cet animal',
+ 'relations.panel.saving': 'Enregistrement…',
+ 'relations.picker.client_label': 'Rechercher un client',
+ 'relations.picker.client_hint':
+ 'Clients actifs : nom, ville, e-mail ou téléphone',
+ 'relations.picker.client_results': 'Clients proposés',
+ 'relations.picker.client_none': 'Aucun client actif ne correspond.',
+ 'relations.picker.animal_label': 'Rechercher un animal',
+ 'relations.picker.animal_hint':
+ "Animaux actifs : nom, race ou précision d'espèce",
+ 'relations.picker.animal_results': 'Animaux proposés',
+ 'relations.picker.animal_none': 'Aucun animal actif ne correspond.',
+ 'relations.picker.loading': 'Recherche…',
+ 'relations.end.action': 'Terminer',
+ 'relations.end.title': 'Terminer cette relation ?',
+ 'relations.end.body':
+ "Elle passera dans l'historique, avec sa date de fin si vous la connaissez. Rien n'est supprimé.",
+ 'relations.end.ended_on': 'Date de fin',
+ 'relations.end.confirm': 'Terminer la relation',
+ 'relations.end.done': 'Relation terminée.',
+ 'relations.dates.action': 'Corriger les dates',
+ 'relations.dates.title': 'Corriger les dates',
+ 'relations.dates.body':
+ 'Le client et le rôle ne changent pas. Une date vide veut dire « inconnue ».',
+ 'relations.dates.started_on': 'Date de début',
+ 'relations.dates.ended_on': 'Date de fin',
+ 'relations.dates.confirm': 'Enregistrer les dates',
+ 'relations.dates.done': 'Dates enregistrées.',
+ 'relations.void.action': 'Erreur de saisie',
+ 'relations.void.title': 'Retirer une relation saisie par erreur ?',
+ 'relations.void.body':
+ "Seulement si cette relation n'a jamais existé : mauvais client, mauvais animal ou mauvais rôle. Elle disparaîtra des fiches, des listes et de l'historique sans être supprimée, et ne pourra pas être rétablie. Pour une relation qui a réellement pris fin, utilisez « Terminer ».",
+ 'relations.void.confirm': 'Retirer la relation',
+ 'relations.void.done': 'Relation retirée (erreur de saisie).',
+ 'relations.error.end_before_start': 'La fin ne peut pas précéder le début.',
}
diff --git a/apps/app/src/lib/dates.ts b/apps/app/src/lib/dates.ts
index f25497f2..38680bb4 100644
--- a/apps/app/src/lib/dates.ts
+++ b/apps/app/src/lib/dates.ts
@@ -4,6 +4,13 @@ export function todayIso(): string {
return new Date().toISOString().slice(0, 10)
}
+/** The device's local date as YYYY-MM-DD: what « not in the future » means in a form (contract §9.3). */
+export function localDateIso(date: Date = new Date()): string {
+ const month = String(date.getMonth() + 1).padStart(2, '0')
+ const day = String(date.getDate()).padStart(2, '0')
+ return `${date.getFullYear()}-${month}-${day}`
+}
+
export function nowIso(): string {
return new Date().toISOString()
}
diff --git a/apps/app/src/lib/id.ts b/apps/app/src/lib/id.ts
index e66860e0..16e48667 100644
--- a/apps/app/src/lib/id.ts
+++ b/apps/app/src/lib/id.ts
@@ -11,3 +11,18 @@ export function generateId(): string {
}
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
}
+
+/**
+ * A random version 4 uuid, also on an origin that is not a secure context
+ * (the DEV origin is plain HTTP on the LAN, where crypto.randomUUID is
+ * missing but crypto.getRandomValues is not). Used for request ids the
+ * database stores as uuid.
+ */
+export function generateUuid(): string {
+ if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
+ const bytes = crypto.getRandomValues(new Uint8Array(16))
+ bytes[6] = (bytes[6] & 0x0f) | 0x40
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
+}
diff --git a/apps/app/src/relations/choices.ts b/apps/app/src/relations/choices.ts
new file mode 100644
index 00000000..61d6afac
--- /dev/null
+++ b/apps/app/src/relations/choices.ts
@@ -0,0 +1,50 @@
+import { useCallback } from 'react'
+import {
+ searchAnimals,
+ searchClients,
+ type AnimalListItem,
+ type ClientListItem,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+/** Matches shown at once: enough to pick from, the term narrows the rest. */
+const CHOICES = 8
+
+function backend() {
+ const client = getSupabaseClient()
+ if (!client) throw new TypeError('no backend')
+ return client
+}
+
+/** Active clients of the workspace for a term; only an active client can be linked (§7.1). */
+export function useClientChoices(workspaceId: string) {
+ return useCallback(
+ async (term: string): Promise =>
+ (
+ await searchClients(backend(), {
+ workspaceId,
+ query: term,
+ archived: false,
+ pageSize: CHOICES,
+ })
+ ).rows,
+ [workspaceId],
+ )
+}
+
+/** Active animals of the workspace for a term, every species. */
+export function useAnimalChoices(workspaceId: string) {
+ return useCallback(
+ async (term: string): Promise =>
+ (
+ await searchAnimals(backend(), {
+ workspaceId,
+ query: term,
+ speciesId: null,
+ archived: false,
+ pageSize: CHOICES,
+ })
+ ).rows,
+ [workspaceId],
+ )
+}
diff --git a/apps/app/src/relations/groups.ts b/apps/app/src/relations/groups.ts
new file mode 100644
index 00000000..eb088ba0
--- /dev/null
+++ b/apps/app/src/relations/groups.ts
@@ -0,0 +1,34 @@
+import type { AnimalRelationItem } from '@faunosteo/supabase'
+
+const ROLE_ORDER = { owner: 0, keeper: 1, contact: 2 } as const
+
+const byName = (a: AnimalRelationItem, b: AnimalRelationItem) =>
+ a.client.display_name.localeCompare(b.client.display_name) ||
+ a.id.localeCompare(b.id)
+
+/**
+ * An animal's relations for its page: the current ones by role (owners
+ * first) then client name; the former ones, most recently ended first.
+ * `ended_at` orders the history only; the end date shown is `ended_on`.
+ */
+export function groupRelations(relations: readonly AnimalRelationItem[]) {
+ const current = relations
+ .filter((r) => r.ended_at === null)
+ .sort(
+ (a, b) =>
+ ROLE_ORDER[a.relation_role] - ROLE_ORDER[b.relation_role] ||
+ byName(a, b),
+ )
+ const former = relations
+ .filter((r) => r.ended_at !== null)
+ .sort(
+ (a, b) =>
+ (b.ended_at ?? '').localeCompare(a.ended_at ?? '') || byName(a, b),
+ )
+ return {
+ current,
+ former,
+ /** No current owner: the page says « Propriétaire non renseigné », never a placeholder client. */
+ hasOwner: current.some((r) => r.relation_role === 'owner'),
+ }
+}
diff --git a/apps/app/src/relations/useAnimalRelations.ts b/apps/app/src/relations/useAnimalRelations.ts
new file mode 100644
index 00000000..e855275a
--- /dev/null
+++ b/apps/app/src/relations/useAnimalRelations.ts
@@ -0,0 +1,54 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import {
+ classifyRecordError,
+ fetchAnimalRelations,
+ type AnimalRelationItem,
+ type RecordFailureKind,
+} from '@faunosteo/supabase'
+import { getSupabaseClient } from '@/lib/supabase'
+
+export type AnimalRelationsState =
+ | { status: 'loading' }
+ | { status: 'ready'; relations: AnimalRelationItem[] }
+ | { status: 'error'; failure: RecordFailureKind }
+
+/**
+ * The relations of one animal (voided ones never come back). `reload`
+ * resolves once the new answer is on screen, so a confirmation can stay open
+ * until the change it made is shown; the rows stay visible meanwhile. An
+ * answer older than the last request, or arriving after unmount, is dropped.
+ */
+export function useAnimalRelations(animalId: string) {
+ const [state, setState] = useState({
+ status: 'loading',
+ })
+ const generation = useRef(0)
+
+ const reload = useCallback(async () => {
+ const current = ++generation.current
+ const client = getSupabaseClient()
+ if (!client) {
+ setState({ status: 'error', failure: 'unavailable' })
+ return
+ }
+ try {
+ const relations = await fetchAnimalRelations(client, animalId)
+ if (current === generation.current)
+ setState({ status: 'ready', relations })
+ } catch (error) {
+ if (current === generation.current)
+ setState({ status: 'error', failure: classifyRecordError(error) })
+ }
+ }, [animalId])
+
+ useEffect(() => {
+ // The ref object is stable: bumping it on unmount drops the answer in flight.
+ const requests = generation
+ void reload()
+ return () => {
+ requests.current++
+ }
+ }, [reload])
+
+ return { state, reload }
+}
diff --git a/apps/app/src/state/authStore.ts b/apps/app/src/state/authStore.ts
index f688ff30..99a155ab 100644
--- a/apps/app/src/state/authStore.ts
+++ b/apps/app/src/state/authStore.ts
@@ -13,7 +13,10 @@ import {
type AvatarState,
downloadAvatar,
fetchOwnAvatarState,
+ fetchPersonalWorkspaceId,
+ classifyRecordError,
type FaunosteoClient,
+ type RecordFailureKind,
type OwnProfilePatch,
type PlatformRole,
type Profile,
@@ -26,6 +29,21 @@ import { getSupabaseClient } from '@/lib/supabase'
*/
export type AuthStatus = 'loading' | 'unavailable' | 'signed_out' | 'signed_in'
+/**
+ * The account's personal workspace (contract §4): created by the server at
+ * sign-up, read once with the account, never created here. RLS hides it from
+ * a deactivated profile and an unconfirmed email, told apart before reading;
+ * `missing` is an active, confirmed account whose workspace does not answer.
+ */
+export type WorkspaceState =
+ | { status: 'idle' }
+ | { status: 'loading' }
+ | { status: 'ready'; id: string }
+ | { status: 'inactive' }
+ | { status: 'unconfirmed' }
+ | { status: 'missing' }
+ | { status: 'error'; failure: RecordFailureKind }
+
export interface AuthState {
status: AuthStatus
session: Session | null
@@ -41,9 +59,12 @@ export interface AuthState {
avatar: AvatarState | null
/** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */
avatarUrl: string | null
+ workspace: WorkspaceState
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void
refreshAccount: () => Promise
+ /** Reads the personal workspace again (after a failure). */
+ refreshWorkspace: () => Promise
updateProfile: (patch: OwnProfilePatch) => Promise
/** Re-reads the own rows; downloads the clean photo when it changed. */
refreshAvatar: () => Promise
@@ -83,13 +104,56 @@ async function syncAvatar(client: FaunosteoClient, user: User, set: Set, get: Ge
return avatar
}
+/** A setter that drops the patch once another account has signed in: no late response leaks across accounts. */
+function setForUser(user: User, set: Set, get: Get): Set {
+ return (patch) => {
+ if (get().user?.id === user.id) set(patch)
+ }
+}
+
+async function loadWorkspace(
+ client: FaunosteoClient,
+ user: User,
+ profile: Profile | null,
+ set: Set,
+ get: Get,
+) {
+ if (!user.email_confirmed_at) return set({ workspace: { status: 'unconfirmed' } })
+ if (profile && !profile.active) return set({ workspace: { status: 'inactive' } })
+ // A re-read (USER_UPDATED, retry) keeps a ready workspace on screen until the
+ // answer, so the routes under it, an open form included, stay mounted.
+ if (get().workspace.status !== 'ready') set({ workspace: { status: 'loading' } })
+ try {
+ const id = await fetchPersonalWorkspaceId(client, user.id)
+ set({ workspace: id ? { status: 'ready', id } : { status: 'missing' } })
+ } catch (error) {
+ set({ workspace: { status: 'error', failure: classifyRecordError(error) } })
+ }
+}
+
async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: Get) {
+ const setOwn = setForUser(user, set, get)
const [profile, roles] = await Promise.all([
fetchOwnProfile(client, user.id),
fetchOwnPlatformRoles(client, user.id),
])
- set({ profile, roles })
- await syncAvatar(client, user, set, get).catch(() => set({ avatar: null }))
+ setOwn({ profile, roles })
+ await Promise.all([
+ loadWorkspace(client, user, profile, setOwn, get),
+ syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })),
+ ])
+}
+
+/** Everything the store holds about one account: dropped together on sign-out and on a change of account. */
+function accountReset(get: Get): Partial {
+ revokeUrl(get().avatarUrl)
+ return {
+ profile: null,
+ roles: [],
+ avatar: null,
+ avatarUrl: null,
+ workspace: { status: 'idle' },
+ }
}
/**
@@ -105,30 +169,33 @@ function applyAuthEvent(
) {
const previousUserId = get().user?.id
if (event === 'SIGNED_OUT' || session === null) {
- revokeUrl(get().avatarUrl)
set({
+ ...accountReset(get),
status: 'signed_out',
session: null,
user: null,
- profile: null,
- roles: [],
recovery: false,
- avatar: null,
- avatarUrl: null,
})
return
}
+ const changedAccount = session.user.id !== previousUserId
const patch: Partial = {
+ // Another account: nothing of the previous one stays on screen while the new one loads.
+ ...(changedAccount ? { ...accountReset(get), workspace: { status: 'loading' } } : {}),
status: 'signed_in',
session,
user: session.user,
}
if (event === 'PASSWORD_RECOVERY') patch.recovery = true
set(patch)
- if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
+ if (changedAccount || event === 'USER_UPDATED') {
setTimeout(() => {
- void loadAccount(client, session.user, set, get).catch(() => {
- set({ profile: null, roles: [] })
+ void loadAccount(client, session.user, set, get).catch((error: unknown) => {
+ setForUser(session.user, set, get)({
+ profile: null,
+ roles: [],
+ workspace: { status: 'error', failure: classifyRecordError(error) },
+ })
})
}, 0)
}
@@ -155,6 +222,7 @@ export const useAuthStore = create((set, get) => ({
urlFailure: null,
avatar: null,
avatarUrl: null,
+ workspace: { status: 'idle' },
start: () => {
const client = getSupabaseClient()
@@ -175,6 +243,11 @@ export const useAuthStore = create((set, get) => ({
await loadAccount(requireClient(), requireUser(get().user), set, get)
},
+ refreshWorkspace: async () => {
+ const user = requireUser(get().user)
+ await loadWorkspace(requireClient(), user, get().profile, setForUser(user, set, get), get)
+ },
+
refreshAvatar: async () => {
return syncAvatar(requireClient(), requireUser(get().user), set, get)
},
@@ -197,16 +270,12 @@ export const useAuthStore = create((set, get) => ({
signOut: async () => {
const clear = () => {
- revokeUrl(get().avatarUrl)
set({
+ ...accountReset(get),
status: 'signed_out',
session: null,
user: null,
- profile: null,
- roles: [],
recovery: false,
- avatar: null,
- avatarUrl: null,
})
}
try {
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/src/styles/index.css b/apps/app/src/styles/index.css
index e7d281d3..e3013938 100644
--- a/apps/app/src/styles/index.css
+++ b/apps/app/src/styles/index.css
@@ -2,6 +2,8 @@
@import './tokens.css';
html, body, #root { height: 100%; }
+/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */
+html:has(dialog:modal) { overflow: hidden; }
body {
background: var(--color-bg);
color: var(--color-ink);
diff --git a/apps/app/tests/unit/animals.validation.test.ts b/apps/app/tests/unit/animals.validation.test.ts
new file mode 100644
index 00000000..c5a2036b
--- /dev/null
+++ b/apps/app/tests/unit/animals.validation.test.ts
@@ -0,0 +1,349 @@
+import { describe, expect, it } from 'vitest'
+import type { AnimalRelationItem } from '@faunosteo/supabase'
+import { animalAge } from '@/animals/age'
+import {
+ EMPTY_ANIMAL_VALUES,
+ animalFieldErrors,
+ animalSchema,
+ recordDateIssue,
+ relationIssues,
+ withBirthDate,
+ type AnimalFormValues,
+} from '@/animals/validation'
+import { groupRelations } from '@/relations/groups'
+
+const TODAY = '2026-10-26'
+const SPECIES = ['equine', 'canine', 'other']
+const BASE: AnimalFormValues = {
+ ...EMPTY_ANIMAL_VALUES,
+ name: 'Tornado',
+ species_id: 'equine',
+ sex: 'female',
+}
+
+const parse = (patch: Partial, today = TODAY) =>
+ animalSchema({ speciesIds: SPECIES, today }).safeParse({ ...BASE, ...patch })
+const errorsOf = (patch: Partial, today = TODAY) => {
+ const result = parse(patch, today)
+ return result.success ? {} : animalFieldErrors(result.error)
+}
+
+describe('animal form schema (D-R7 on field-limits)', () => {
+ it('needs name, species and sex; empty optionals become null; name trimmed', () => {
+ const result = parse({ name: ' Tornado ' })
+ expect(result.success && result.data).toEqual({
+ name: 'Tornado',
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: null,
+ birth_year: null,
+ birth_date: null,
+ })
+ })
+
+ it('refuses an empty form field by field, sex included (no default)', () => {
+ expect(
+ animalSchema({ speciesIds: SPECIES, today: TODAY }).safeParse(
+ EMPTY_ANIMAL_VALUES,
+ ).success,
+ ).toBe(false)
+ const result = animalSchema({
+ speciesIds: SPECIES,
+ today: TODAY,
+ }).safeParse(EMPTY_ANIMAL_VALUES)
+ expect(result.success ? {} : animalFieldErrors(result.error)).toEqual({
+ name: 'animals.error.required',
+ species_id: 'animals.error.species',
+ sex: 'animals.error.sex',
+ })
+ })
+
+ it('counts name code points: 80 accepted, 81 refused, astral counts once', () => {
+ expect(errorsOf({ name: 'é'.repeat(80) })).toEqual({})
+ expect(errorsOf({ name: '𝄞'.repeat(80) })).toEqual({})
+ expect(errorsOf({ name: 'é'.repeat(81) })).toEqual({
+ name: 'animals.error.too_long|80',
+ })
+ })
+
+ it('refuses control characters in the name and the breed', () => {
+ expect(errorsOf({ name: 'Tor\tnado' })).toEqual({
+ name: 'animals.error.characters',
+ })
+ expect(errorsOf({ breed: 'Pur\nsang' })).toEqual({
+ breed: 'animals.error.characters',
+ })
+ })
+
+ it('bounds the breed to 80', () => {
+ expect(errorsOf({ breed: 'a'.repeat(80) })).toEqual({})
+ expect(errorsOf({ breed: 'a'.repeat(81) })).toEqual({
+ breed: 'animals.error.too_long|80',
+ })
+ })
+
+ it('accepts only the allowed species', () => {
+ expect(errorsOf({ species_id: 'dragon' })).toEqual({
+ species_id: 'animals.error.species',
+ })
+ })
+
+ it('« other » needs a detail; any other species drops a leftover detail', () => {
+ expect(errorsOf({ species_id: 'other' })).toEqual({
+ species_detail: 'animals.error.species_detail',
+ })
+ expect(
+ errorsOf({ species_id: 'other', species_detail: 'f'.repeat(81) }),
+ ).toEqual({
+ species_detail: 'animals.error.too_long|80',
+ })
+ const ferret = parse({ species_id: 'other', species_detail: ' Furet ' })
+ expect(ferret.success && ferret.data.species_detail).toBe('Furet')
+ const horse = parse({ species_id: 'equine', species_detail: 'Furet' })
+ expect(horse.success && horse.data.species_detail).toBeNull()
+ })
+
+ it('takes the three sexes, « inconnu » included', () => {
+ for (const sex of ['male', 'female', 'unknown'] as const)
+ expect(errorsOf({ sex })).toEqual({})
+ expect(errorsOf({ sex: 'x' as never })).toEqual({
+ sex: 'animals.error.sex',
+ })
+ })
+
+ it('keeps the five birth states of D6b', () => {
+ const none = parse({})
+ expect(
+ none.success && [none.data.birth_year, none.data.birth_date],
+ ).toEqual([null, null])
+ const year = parse({ birth_year: '2015' })
+ expect(
+ year.success && [year.data.birth_year, year.data.birth_date],
+ ).toEqual([2015, null])
+ const full = parse({ birth_year: '2015', birth_date: '2015-04-12' })
+ expect(
+ full.success && [full.data.birth_year, full.data.birth_date],
+ ).toEqual([2015, '2015-04-12'])
+ expect(errorsOf({ birth_year: '2016', birth_date: '2015-04-12' })).toEqual({
+ birth_year: 'animals.error.date_year',
+ })
+ expect(errorsOf({ birth_date: '2015-04-12' })).toEqual({
+ birth_year: 'animals.error.date_year',
+ })
+ })
+
+ it('refuses malformed years and dates', () => {
+ expect(errorsOf({ birth_year: '15' })).toEqual({
+ birth_year: 'animals.error.year_format',
+ })
+ expect(errorsOf({ birth_year: '20a5' })).toEqual({
+ birth_year: 'animals.error.year_format',
+ })
+ expect(errorsOf({ birth_year: '2015', birth_date: '2015-02-30' })).toEqual({
+ birth_date: 'animals.error.date_format',
+ })
+ expect(errorsOf({ birth_year: '2015', birth_date: '12/04/2015' })).toEqual({
+ birth_date: 'animals.error.date_format',
+ })
+ })
+
+ it('bounds the year from 1900 to the current local year', () => {
+ expect(errorsOf({ birth_year: '1900' })).toEqual({})
+ expect(errorsOf({ birth_year: '1899' })).toEqual({
+ birth_year: 'animals.error.year_range',
+ })
+ expect(errorsOf({ birth_year: '2026' })).toEqual({})
+ expect(errorsOf({ birth_year: '2027' })).toEqual({
+ birth_year: 'animals.error.year_range',
+ })
+ })
+
+ it('refuses a date in the future or before 1900', () => {
+ expect(errorsOf({ birth_year: '2026', birth_date: TODAY })).toEqual({})
+ expect(errorsOf({ birth_year: '2026', birth_date: '2026-10-27' })).toEqual({
+ birth_date: 'animals.error.date_range',
+ })
+ expect(
+ errorsOf({ birth_year: '1899', birth_date: '1899-12-31' }),
+ ).toMatchObject({
+ birth_date: 'animals.error.date_range',
+ })
+ })
+})
+
+describe('withBirthDate (U3)', () => {
+ it('fills the year from a complete date', () => {
+ expect(
+ withBirthDate({ ...BASE, birth_year: '2010' }, '2015-04-12'),
+ ).toMatchObject({
+ birth_year: '2015',
+ birth_date: '2015-04-12',
+ })
+ })
+ it('keeps the year when the date is cleared or incomplete', () => {
+ const filled = withBirthDate(BASE, '2015-04-12')
+ expect(withBirthDate(filled, '')).toMatchObject({
+ birth_year: '2015',
+ birth_date: '',
+ })
+ expect(
+ withBirthDate({ ...BASE, birth_year: '2012' }, '2015-04'),
+ ).toMatchObject({ birth_year: '2012' })
+ })
+})
+
+describe('recordDateIssue', () => {
+ it('accepts empty, a real date up to today; refuses the rest', () => {
+ expect(recordDateIssue('', TODAY)).toBeNull()
+ expect(recordDateIssue('1900-01-01', TODAY)).toBeNull()
+ expect(recordDateIssue(TODAY, TODAY)).toBeNull()
+ expect(recordDateIssue('1899-12-31', TODAY)).toBe(
+ 'animals.error.date_range',
+ )
+ expect(recordDateIssue('2026-10-27', TODAY)).toBe(
+ 'animals.error.date_range',
+ )
+ expect(recordDateIssue('2024-02-30', TODAY)).toBe(
+ 'animals.error.date_format',
+ )
+ expect(recordDateIssue('2024-02-29', TODAY)).toBeNull()
+ expect(recordDateIssue('soon', TODAY)).toBe('animals.error.date_format')
+ })
+})
+
+describe('relationIssues', () => {
+ const client = { id: 'c1', display_name: 'Marie' }
+ it('no client: nothing to check, unless the client is the point of the form', () => {
+ expect(
+ relationIssues(
+ { client: null, relation_role: '', started_on: '' },
+ TODAY,
+ false,
+ ),
+ ).toEqual({})
+ expect(
+ relationIssues(
+ { client: null, relation_role: '', started_on: '' },
+ TODAY,
+ true,
+ ),
+ ).toEqual({
+ client: 'animals.error.client',
+ })
+ })
+ it('a chosen client needs a role; the start date follows the record date rules', () => {
+ expect(
+ relationIssues(
+ { client, relation_role: '', started_on: '' },
+ TODAY,
+ false,
+ ),
+ ).toEqual({
+ relation_role: 'animals.error.role',
+ })
+ expect(
+ relationIssues(
+ { client, relation_role: 'owner', started_on: '' },
+ TODAY,
+ true,
+ ),
+ ).toEqual({})
+ expect(
+ relationIssues(
+ { client, relation_role: 'keeper', started_on: '2026-10-27' },
+ TODAY,
+ true,
+ ),
+ ).toEqual({
+ started_on: 'animals.error.date_range',
+ })
+ })
+})
+
+describe('animalAge (display only)', () => {
+ it('from a full date: months under a year, whole years after', () => {
+ expect(animalAge(2026, '2026-04-27', TODAY)).toEqual({
+ unit: 'month',
+ count: 5,
+ about: false,
+ })
+ expect(animalAge(2025, '2025-10-26', TODAY)).toEqual({
+ unit: 'year',
+ count: 1,
+ about: false,
+ })
+ expect(animalAge(2015, '2015-10-27', TODAY)).toEqual({
+ unit: 'year',
+ count: 10,
+ about: false,
+ })
+ })
+ it('from a year only: about N years, 0 for this year', () => {
+ expect(animalAge(2015, null, TODAY)).toEqual({
+ unit: 'year',
+ count: 11,
+ about: true,
+ })
+ expect(animalAge(2026, null, TODAY)).toEqual({
+ unit: 'year',
+ count: 0,
+ about: true,
+ })
+ })
+ it('nothing for unknown or future births', () => {
+ expect(animalAge(null, null, TODAY)).toBeNull()
+ expect(animalAge(2027, null, TODAY)).toBeNull()
+ expect(animalAge(2026, '2026-11-01', TODAY)).toBeNull()
+ })
+})
+
+function relation(
+ id: string,
+ patch: Partial & { name?: string },
+): AnimalRelationItem {
+ const { name = 'Client', ...rest } = patch
+ return {
+ id,
+ relation_role: 'owner',
+ started_on: null,
+ ended_on: null,
+ ended_at: null,
+ revision: 1,
+ client: {
+ id: `c-${id}`,
+ kind: 'person',
+ display_name: name,
+ phone: null,
+ email: null,
+ archived_at: null,
+ },
+ ...rest,
+ }
+}
+
+describe('groupRelations', () => {
+ it('current by role then name, former most recently ended first', () => {
+ const groups = groupRelations([
+ relation('1', { relation_role: 'contact', name: 'Alice' }),
+ relation('2', { relation_role: 'owner', name: 'Zoé' }),
+ relation('3', { relation_role: 'keeper', name: 'Bob' }),
+ relation('4', { relation_role: 'owner', name: 'Anne' }),
+ relation('5', { name: 'Old', ended_at: '2020-01-01T00:00:00Z' }),
+ relation('6', { name: 'Recent', ended_at: '2024-01-01T00:00:00Z' }),
+ ])
+ expect(groups.current.map((r) => r.id)).toEqual(['4', '2', '3', '1'])
+ expect(groups.former.map((r) => r.id)).toEqual(['6', '5'])
+ expect(groups.hasOwner).toBe(true)
+ })
+ it('no current owner with only keepers or former owners', () => {
+ expect(
+ groupRelations([relation('1', { relation_role: 'keeper' })]).hasOwner,
+ ).toBe(false)
+ expect(
+ groupRelations([relation('1', { ended_at: '2024-01-01T00:00:00Z' })])
+ .hasOwner,
+ ).toBe(false)
+ expect(groupRelations([]).hasOwner).toBe(false)
+ })
+})
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/components.AvatarSection.test.tsx b/apps/app/tests/unit/components.AvatarSection.test.tsx
index 4c0f8db6..bf37edbb 100644
--- a/apps/app/tests/unit/components.AvatarSection.test.tsx
+++ b/apps/app/tests/unit/components.AvatarSection.test.tsx
@@ -157,6 +157,25 @@ describe('AvatarSection', () => {
expect(screen.queryByRole('img')).toBeNull()
})
+ it('keeps the confirmation open until the removal settles, then focuses the photo control', async () => {
+ useAuthStore.setState({ avatarUrl: 'blob:current', avatar: { clean: fakeAssetRow(), inFlight: null, lastRejected: null } })
+ let settle: (value: { data: number; error: null }) => void = () => {}
+ vi.spyOn(fake.client, 'rpc').mockImplementationOnce(
+ () => new Promise((resolve) => (settle = resolve)) as unknown as ReturnType,
+ )
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove'] }))
+ const dialog = await screen.findByRole('dialog', { name: fr['account.avatar.remove_title'] })
+ await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove_confirm'] }))
+ fireEvent.keyDown(dialog, { key: 'Escape' })
+ await userEvent.click(screen.getByRole('button', { name: fr['common.cancel'] }))
+ expect(dialog).toBeInTheDocument()
+ await act(async () => settle({ data: 1, error: null }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(screen.queryByRole('button', { name: fr['account.avatar.remove'] })).toBeNull()
+ await waitFor(() => expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toHaveFocus())
+ })
+
it('resumes the processing state for a row in flight at mount', async () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: fakeAssetRow({ status: 'uploaded' }), lastRejected: null } })
render( )
diff --git a/apps/app/tests/unit/lib.id.test.ts b/apps/app/tests/unit/lib.id.test.ts
index 1dfd464d..840c6178 100644
--- a/apps/app/tests/unit/lib.id.test.ts
+++ b/apps/app/tests/unit/lib.id.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { generateId } from '@/lib/id'
+import { generateId, generateUuid } from '@/lib/id'
describe('generateId', () => {
it('returns a non-empty string', () => {
@@ -12,3 +12,23 @@ describe('generateId', () => {
expect(a).not.toBe(b)
})
})
+
+describe('generateUuid', () => {
+ const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
+
+ it('returns a version 4 uuid', () => {
+ expect(generateUuid()).toMatch(V4)
+ })
+
+ it('still returns one where crypto.randomUUID is missing (plain HTTP on the LAN)', () => {
+ const original = crypto.randomUUID
+ Object.defineProperty(crypto, 'randomUUID', { value: undefined, configurable: true })
+ try {
+ const ids = new Set(Array.from({ length: 50 }, () => generateUuid()))
+ expect([...ids].every((id) => V4.test(id))).toBe(true)
+ expect(ids.size).toBe(50)
+ } finally {
+ Object.defineProperty(crypto, 'randomUUID', { value: original, configurable: true })
+ }
+ })
+})
diff --git a/apps/app/tests/unit/routes.animals.test.tsx b/apps/app/tests/unit/routes.animals.test.tsx
new file mode 100644
index 00000000..fcc5c30f
--- /dev/null
+++ b/apps/app/tests/unit/routes.animals.test.tsx
@@ -0,0 +1,1198 @@
+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,
+ type InitialEntry,
+} 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 ClientDetailRoute from '@/app/routes/app/clients/ClientDetailRoute'
+import AnimalsListRoute from '@/app/routes/app/animals/AnimalsListRoute'
+import AnimalCreateRoute from '@/app/routes/app/animals/AnimalCreateRoute'
+import AnimalDetailRoute from '@/app/routes/app/animals/AnimalDetailRoute'
+import AnimalEditRoute from '@/app/routes/app/animals/AnimalEditRoute'
+import { SEARCH_DELAY_MS } from '@/clients/useClientList'
+import { useAuthStore } from '@/state/authStore'
+import { useLocaleStore } from '@/state/localeStore'
+import { fr } from '@/i18n/fr'
+
+/**
+ * The animal screens and the client page's animals on a fake client: states,
+ * the calls they make and what they keep. The RPC shapes are proven in
+ * packages/supabase (unit and real PostgREST); the journeys run in Chromium.
+ */
+const WS = '11111111-1111-4111-8111-111111111111'
+const AID = '22222222-2222-4222-8222-222222222222'
+const CID = '33333333-3333-4333-8333-333333333333'
+const R1 = '44444444-4444-4444-8444-444444444441'
+const R2 = '44444444-4444-4444-8444-444444444442'
+const R3 = '44444444-4444-4444-8444-444444444443'
+const R4 = '44444444-4444-4444-8444-444444444444'
+
+let fake: FakeSupabase
+
+const SPECIES = [
+ {
+ id: 'equine',
+ name_fr: 'Cheval',
+ name_en: 'Horse',
+ sort_order: 10,
+ active: true,
+ },
+ {
+ id: 'canine',
+ name_fr: 'Chien',
+ name_en: 'Dog',
+ sort_order: 30,
+ active: true,
+ },
+ {
+ id: 'other',
+ name_fr: 'Autre',
+ name_en: 'Other',
+ sort_order: 1000,
+ active: true,
+ },
+]
+
+function listRow(i: number, patch: Record = {}) {
+ return {
+ id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
+ name: `Animal ${String(i).padStart(2, '0')}`,
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: null,
+ birth_year: null,
+ archived_at: null,
+ name_key: `animal ${String(i).padStart(2, '0')}`,
+ current_owners: [],
+ current_owner_count: 0,
+ ...patch,
+ }
+}
+
+function animalRow(patch: Record = {}) {
+ return {
+ id: AID,
+ name: 'Tornado',
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: 'Pur-sang',
+ birth_year: 2015,
+ birth_date: '2015-04-12',
+ revision: 1,
+ archived_at: null,
+ created_at: '2026-10-26T10:00:00Z',
+ updated_at: '2026-10-26T10:00:00Z',
+ ...patch,
+ }
+}
+
+function clientRow(patch: Record = {}) {
+ return {
+ id: CID,
+ 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,
+ }
+}
+
+function relationRow(
+ id: string,
+ name: string,
+ patch: Record = {},
+) {
+ return {
+ id,
+ animal_id: AID,
+ relation_role: 'owner',
+ started_on: null,
+ ended_on: null,
+ ended_at: null,
+ voided_at: null,
+ revision: 1,
+ created_at: '2026-10-26T10:00:00Z',
+ client: {
+ id: `55555555-5555-4555-8555-55555555555${id.slice(-1)}`,
+ kind: 'person',
+ display_name: name,
+ phone: null,
+ email: null,
+ archived_at: null,
+ },
+ ...patch,
+ }
+}
+
+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(entry: InitialEntry) {
+ useAuthStore.setState({
+ status: 'signed_in',
+ user: fakeUser(),
+ profile: fakeProfile(),
+ workspace: { status: 'ready', id: WS },
+ })
+ return render(
+
+
+ }>
+ dashboard} />
+ }>
+
+ clients} />
+ } />
+
+
+ } />
+ } />
+ } />
+ } />
+
+
+
+
+
+ ,
+ )
+}
+
+/** Holds the next call of `name` until released (the fake answers `result`). */
+function holdRpc(name: string, result: { data?: unknown; error?: unknown }) {
+ 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 (n, args) => {
+ if (n !== name) return rpc(n, args)
+ fake.rpcCalls.push([n, args])
+ await pending
+ return { data: result.data ?? null, error: result.error ?? null }
+ }
+ return () => act(async () => release())
+}
+
+const label = (key: string) =>
+ new RegExp(fr[key].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
+
+async function fillIdentity(name = 'Tornado') {
+ await userEvent.type(screen.getByLabelText(label('animals.form.name')), name)
+ await userEvent.selectOptions(
+ screen.getByRole('combobox', { name: label('animals.form.species') }),
+ 'equine',
+ )
+ await userEvent.click(
+ screen.getByRole('radio', { name: fr['animals.sex.female'] }),
+ )
+}
+
+beforeEach(() => {
+ useLocaleStore.setState({ locale: 'fr' })
+ fake = createFakeSupabase()
+ fake.tables.species = SPECIES.map((s) => ({ ...s }))
+ fake.tables.animals = []
+ fake.tables.clients = []
+ fake.tables.animal_client_relations = []
+ fake.rpcResults.search_animals = { data: [] }
+ fake.rpcResults.search_clients = { data: [] }
+ fake.rpcResults.list_client_animals = { data: [] }
+ mocks.fake = fake
+})
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+})
+
+describe('animal list', () => {
+ it('lists the first page with owners or « Propriétaire non renseigné », then « Afficher plus »', async () => {
+ fake.rpcResults.search_animals = {
+ data: [
+ listRow(1, {
+ current_owners: [
+ { client_id: CID, display_name: 'Marie Dupont', archived: false },
+ ],
+ current_owner_count: 1,
+ }),
+ ...Array.from({ length: 25 }, (_, i) => listRow(i + 2)),
+ ],
+ }
+ mount('/app/animals')
+ expect(page().getByRole('status')).toHaveTextContent(
+ fr['animals.list.loading'],
+ )
+ expect(await screen.findByText('Animal 01')).toBeInTheDocument()
+ expect(
+ page().getByRole('heading', { level: 1, name: fr['animals.list.title'] }),
+ ).toHaveFocus()
+ expect(screen.getByText('Propriétaire : Marie Dupont')).toBeInTheDocument()
+ expect(screen.getAllByText(fr['animals.no_owner']).length).toBeGreaterThan(
+ 0,
+ )
+ const results = screen.getByRole('list', {
+ name: fr['animals.list.results_label'],
+ })
+ expect(within(results).getAllByRole('listitem')).toHaveLength(25)
+ expect(rpcArgs('search_animals')[0]).toMatchObject({
+ workspace_id: WS,
+ query: '',
+ archived: false,
+ page_size: 26,
+ species_filter: undefined,
+ })
+ fake.rpcResults.search_animals = { data: [listRow(26), listRow(27)] }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.list.more'] }),
+ )
+ expect(await screen.findByText('Animal 27')).toBeInTheDocument()
+ expect(rpcArgs('search_animals').at(-1)).toMatchObject({
+ after_name_key: 'animal 25',
+ after_id: listRow(25).id,
+ })
+ expect(
+ screen.queryByRole('button', { name: fr['animals.list.more'] }),
+ ).toBeNull()
+ })
+
+ it('says it is empty', async () => {
+ mount('/app/animals')
+ expect(
+ await screen.findByText(fr['animals.list.empty']),
+ ).toBeInTheDocument()
+ expect(screen.getByText(fr['animals.list.empty_hint'])).toBeInTheDocument()
+ })
+
+ it('filters by species and by archive, in the RPC body', async () => {
+ mount('/app/animals')
+ await screen.findByText(fr['animals.list.empty'])
+ const filter = screen.getByRole('combobox', {
+ name: fr['animals.list.species_filter'],
+ })
+ await waitFor(() =>
+ expect(
+ within(filter).getByRole('option', { name: 'Chien' }),
+ ).toBeInTheDocument(),
+ )
+ await userEvent.selectOptions(filter, 'canine')
+ await waitFor(() =>
+ expect(rpcArgs('search_animals').at(-1)?.species_filter).toBe('canine'),
+ )
+ expect(
+ await screen.findByText(fr['animals.list.no_results']),
+ ).toBeInTheDocument()
+ fake.rpcResults.search_animals = {
+ data: [listRow(1, { archived_at: '2026-10-26T10:00:00Z' })],
+ }
+ await userEvent.click(
+ screen.getByRole('switch', { name: fr['animals.list.archived_toggle'] }),
+ )
+ expect(
+ await screen.findByText(fr['animals.archived_badge']),
+ ).toBeInTheDocument()
+ expect(rpcArgs('search_animals').at(-1)).toMatchObject({
+ archived: true,
+ species_filter: 'canine',
+ })
+ })
+
+ it('waits for a pause in typing, then sends the term in the body once', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ mount('/app/animals')
+ await screen.findByText(fr['animals.list.empty'])
+ const before = rpcArgs('search_animals').length
+ const box = screen.getByRole('searchbox', {
+ name: label('animals.list.search_label'),
+ })
+ for (const value of ['t', 'to', 'tor'])
+ fireEvent.change(box, { target: { value } })
+ await act(() => vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS + 10))
+ await waitFor(() =>
+ expect(rpcArgs('search_animals').length).toBe(before + 1),
+ )
+ expect(rpcArgs('search_animals').at(-1)?.query).toBe('tor')
+ })
+
+ it('names a failure and retries', async () => {
+ fake.rpcResults.search_animals = {
+ error: { code: 'P0001', message: 'rate_limited' },
+ }
+ mount('/app/animals')
+ expect(
+ await screen.findByText(fr['animals.failure.rate_limited']),
+ ).toBeInTheDocument()
+ fake.rpcResults.search_animals = { data: [listRow(1)] }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['common.retry'] }),
+ )
+ expect(await screen.findByText('Animal 01')).toBeInTheDocument()
+ })
+})
+
+describe('animal creation', () => {
+ it('refuses an empty form, focuses the name; no sex is preselected', async () => {
+ mount('/app/animals/new')
+ for (const sex of ['male', 'female', 'unknown'])
+ expect(
+ screen.getByRole('radio', { name: fr[`animals.sex.${sex}`] }),
+ ).not.toBeChecked()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ expect(screen.getByLabelText(label('animals.form.name'))).toHaveFocus()
+ expect(screen.getByText(fr['animals.error.required'])).toBeInTheDocument()
+ expect(screen.getByText(fr['animals.error.species'])).toBeInTheDocument()
+ expect(screen.getByText(fr['animals.error.sex'])).toBeInTheDocument()
+ expect(rpcArgs('create_animal')).toEqual([])
+ })
+
+ it('« Autre » asks for its detail', async () => {
+ mount('/app/animals/new')
+ expect(
+ screen.queryByLabelText(label('animals.form.species_detail')),
+ ).toBeNull()
+ const species = screen.getByRole('combobox', {
+ name: label('animals.form.species'),
+ })
+ await waitFor(() =>
+ expect(
+ within(species).getByRole('option', { name: 'Autre' }),
+ ).toBeInTheDocument(),
+ )
+ await userEvent.selectOptions(species, 'other')
+ expect(
+ screen.getByLabelText(label('animals.form.species_detail')),
+ ).toBeInTheDocument()
+ })
+
+ it('a full birth date fills and locks the year; clearing it unlocks', async () => {
+ mount('/app/animals/new')
+ const year = screen.getByLabelText(label('animals.form.birth_year'))
+ const date = screen.getByLabelText(label('animals.form.birth_date'))
+ fireEvent.change(date, { target: { value: '2015-04-12' } })
+ expect(year).toHaveValue('2015')
+ expect(year).toHaveAttribute('readonly')
+ fireEvent.change(date, { target: { value: '' } })
+ expect(year).toHaveValue('2015')
+ expect(year).not.toHaveAttribute('readonly')
+ })
+
+ it('sends the same request id after a lost answer, then opens the animal', async () => {
+ fake.rpcResults.create_animal = {
+ error: { code: '', message: 'TypeError: fetch failed' },
+ }
+ mount('/app/animals/new')
+ await screen.findByRole('option', { name: 'Cheval' })
+ await fillIdentity()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ expect(
+ await screen.findByText(fr['animals.failure.unavailable']),
+ ).toBeInTheDocument()
+ fake.rpcResults.create_animal = {
+ data: { id: AID, revision: 1, relation_id: null },
+ }
+ fake.tables.animals = [animalRow()]
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('where')).toHaveTextContent(
+ `/app/animals/${AID}`,
+ ),
+ )
+ const [first, second] = rpcArgs('create_animal')
+ expect(first.create_request_id).toBe(second.create_request_id)
+ expect(first).toMatchObject({
+ workspace_id: WS,
+ name: 'Tornado',
+ species_id: 'equine',
+ sex: 'female',
+ })
+ expect(first.client_id).toBeUndefined()
+ expect(
+ await screen.findByText(fr['animals.detail.created']),
+ ).toBeInTheDocument()
+ })
+
+ it('a new form is a new intent: another request id', async () => {
+ fake.rpcResults.create_animal = {
+ error: { code: 'P0001', message: 'rate_limited' },
+ }
+ const first = mount('/app/animals/new')
+ await screen.findByRole('option', { name: 'Cheval' })
+ await fillIdentity()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ await screen.findByText(fr['animals.failure.rate_limited'])
+ first.unmount()
+ mount('/app/animals/new')
+ await screen.findByRole('option', { name: 'Cheval' })
+ await fillIdentity()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ await screen.findByText(fr['animals.failure.rate_limited'])
+ const ids = rpcArgs('create_animal').map((a) => a.create_request_id)
+ expect(ids[0]).not.toBe(ids[1])
+ })
+})
+
+describe('animal creation from a client page', () => {
+ const fromClient = (clientId: unknown = CID) => ({
+ pathname: '/app/animals/new',
+ state: { clientId },
+ })
+
+ it('pre-associates the client with no role; refuses a save without a role; one create_animal with the relation', async () => {
+ fake.tables.clients = [clientRow()]
+ mount(fromClient())
+ expect(await screen.findByText('Marie Dupont')).toBeInTheDocument()
+ expect(
+ screen.getByText(fr['relations.panel.client_chosen'], { exact: false }),
+ ).toBeInTheDocument()
+ for (const role of ['owner', 'keeper', 'contact'])
+ expect(
+ screen.getByRole('radio', { name: fr[`clients.role.${role}`] }),
+ ).not.toBeChecked()
+ await screen.findByRole('option', { name: 'Cheval' })
+ await fillIdentity()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ expect(screen.getByText(fr['animals.error.role'])).toBeInTheDocument()
+ expect(rpcArgs('create_animal')).toEqual([])
+ await userEvent.click(
+ screen.getByRole('radio', { name: fr['clients.role.owner'] }),
+ )
+ fake.rpcResults.create_animal = {
+ data: { id: AID, revision: 1, relation_id: R1 },
+ }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('where')).toHaveTextContent(
+ `/app/clients/${CID}`,
+ ),
+ )
+ expect(rpcArgs('create_animal')).toHaveLength(1)
+ expect(rpcArgs('create_animal')[0]).toMatchObject({
+ client_id: CID,
+ relation_role: 'owner',
+ })
+ expect(rpcArgs('create_animal')[0].started_on).toBeUndefined()
+ expect(rpcArgs('create_animal_client_relation')).toEqual([])
+ expect(
+ await screen.findByText(fr['clients.detail.animal_added']),
+ ).toBeInTheDocument()
+ })
+
+ it('removing the client sends none and opens the animal', async () => {
+ fake.tables.clients = [clientRow()]
+ mount(fromClient())
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: fr['animals.form.client_remove'],
+ }),
+ )
+ expect(
+ screen.getByRole('searchbox', {
+ name: label('relations.picker.client_label'),
+ }),
+ ).toHaveFocus()
+ await screen.findByRole('option', { name: 'Cheval' })
+ await fillIdentity()
+ fake.rpcResults.create_animal = {
+ data: { id: AID, revision: 1, relation_id: null },
+ }
+ fake.tables.animals = [animalRow()]
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_create'] }),
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('where')).toHaveTextContent(
+ `/app/animals/${AID}`,
+ ),
+ )
+ expect(rpcArgs('create_animal')[0].client_id).toBeUndefined()
+ expect(rpcArgs('create_animal')[0].relation_role).toBeUndefined()
+ })
+
+ it.each([
+ ['archived', [clientRow({ archived_at: '2026-10-26T11:00:00Z' })]],
+ ['unknown', []],
+ ])(
+ 'an %s origin client is not pre-associated, and the page says so',
+ async (_, rows) => {
+ fake.tables.clients = rows
+ mount(fromClient())
+ expect(
+ await screen.findByText(fr['animals.form.origin_unavailable']),
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByText(fr['relations.panel.client_chosen'], {
+ exact: false,
+ }),
+ ).toBeNull()
+ },
+ )
+
+ it('a malformed state value reads nothing', async () => {
+ const from = vi.spyOn(
+ fake.client as unknown as { from: (t: string) => unknown },
+ 'from',
+ )
+ mount(fromClient('not-an-id'))
+ await screen.findByRole('option', { name: 'Cheval' })
+ expect(from.mock.calls.map(([t]) => t)).not.toContain('clients')
+ expect(screen.queryByText(fr['animals.form.origin_unavailable'])).toBeNull()
+ })
+})
+
+describe('animal edit', () => {
+ it('on conflict shows the stored value beside the typed one and keeps it', async () => {
+ fake.tables.animals = [animalRow()]
+ mount(`/app/animals/${AID}/edit`)
+ const name = await screen.findByLabelText(label('animals.form.name'))
+ expect(name).toHaveValue('Tornado')
+ await userEvent.clear(name)
+ await userEvent.type(name, 'Typhon')
+ fake.tables.animals = [animalRow({ name: 'Ouragan', revision: 2 })]
+ fake.rpcResults.update_animal = {
+ error: { code: 'P0001', message: 'conflict' },
+ }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_update'] }),
+ )
+ expect(
+ await screen.findByText(fr['animals.form.conflict_title']),
+ ).toBeInTheDocument()
+ expect(name).toHaveValue('Typhon')
+ expect(
+ screen.getByText(
+ fr['animals.form.stored_value'].replace('{value}', 'Ouragan'),
+ ),
+ ).toBeInTheDocument()
+ fake.rpcResults.update_animal = { data: { revision: 3 } }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.form.submit_update'] }),
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('where')).toHaveTextContent(
+ `/app/animals/${AID}`,
+ ),
+ )
+ expect(rpcArgs('update_animal').map((a) => a.expected_revision)).toEqual([
+ 1, 2,
+ ])
+ expect(rpcArgs('update_animal')[1]).toMatchObject({
+ name: 'Typhon',
+ birth_year: '2015',
+ birth_date: '2015-04-12',
+ species_detail: null,
+ })
+ })
+
+ it('an archived animal has no form', async () => {
+ fake.tables.animals = [animalRow({ archived_at: '2026-10-26T11:00:00Z' })]
+ mount(`/app/animals/${AID}/edit`)
+ expect(
+ await screen.findByText(fr['animals.detail.archived_notice']),
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: fr['animals.form.submit_update'] }),
+ ).toBeNull()
+ })
+})
+
+describe('animal page', () => {
+ it('shows the identity with the birth precision', async () => {
+ fake.tables.animals = [animalRow()]
+ mount(`/app/animals/${AID}`)
+ expect(
+ await page().findByRole('heading', { level: 1, name: 'Tornado' }),
+ ).toHaveFocus()
+ expect(await screen.findByText('Cheval')).toBeInTheDocument()
+ expect(screen.getByText('Femelle')).toBeInTheDocument()
+ expect(screen.getByText('Pur-sang')).toBeInTheDocument()
+ expect(
+ screen.getByText(/^Le 12 avril 2015 \(\d+ ans\)$/),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText(fr['animals.detail.status_active']),
+ ).toBeInTheDocument()
+ })
+
+ it.each([
+ [{ birth_date: null, birth_year: 2015 }, /^En 2015 \(environ \d+ ans\)$/],
+ [
+ { birth_date: null, birth_year: null },
+ new RegExp(`^${fr['animals.detail.birth_unknown']}$`),
+ ],
+ ])('birth %o', async (patch, text) => {
+ fake.tables.animals = [animalRow(patch)]
+ mount(`/app/animals/${AID}`)
+ expect(await screen.findByText(text)).toBeInTheDocument()
+ })
+
+ it('shows the same « introuvable » for an unknown id and a malformed one', async () => {
+ mount(`/app/animals/${AID}`)
+ expect(
+ await screen.findByRole('heading', {
+ name: fr['animals.not_found.title'],
+ }),
+ ).toHaveFocus()
+ cleanup()
+ mount('/app/animals/not-an-id')
+ expect(
+ await screen.findByRole('heading', {
+ name: fr['animals.not_found.title'],
+ }),
+ ).toHaveFocus()
+ })
+
+ it('archives after a confirmation that refuses to close while the request runs', async () => {
+ fake.tables.animals = [animalRow()]
+ const release = holdRpc('set_animal_archived', { data: { revision: 2 } })
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', { name: fr['animals.detail.archive'] }),
+ )
+ const dialog = await screen.findByRole('dialog', {
+ name: fr['animals.archive.title'],
+ })
+ await userEvent.click(
+ within(dialog).getByRole('button', {
+ name: fr['animals.archive.confirm'],
+ }),
+ )
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['common.cancel'] }),
+ )
+ expect(dialog).toBeInTheDocument()
+ fake.tables.animals = [
+ animalRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 }),
+ ]
+ await release()
+ expect(
+ await screen.findByText(fr['animals.detail.archived']),
+ ).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(rpcArgs('set_animal_archived')).toEqual([
+ { animal_id: AID, archived: true },
+ ])
+ })
+
+ it('an archived animal is read-only, relations included, and can be restored', async () => {
+ fake.tables.animals = [
+ animalRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 }),
+ ]
+ fake.tables.animal_client_relations = [relationRow(R1, 'Marie Dupont')]
+ mount(`/app/animals/${AID}`)
+ expect(
+ await screen.findByText(fr['animals.detail.archived_notice']),
+ ).toBeInTheDocument()
+ expect(
+ await screen.findByRole('link', { name: 'Marie Dupont' }),
+ ).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /Terminer/ })).toBeNull()
+ expect(
+ screen.queryByRole('button', { name: fr['relations.add_client'] }),
+ ).toBeNull()
+ expect(
+ screen.queryByRole('link', { name: fr['animals.detail.edit'] }),
+ ).toBeNull()
+ fake.rpcResults.set_animal_archived = { data: { revision: 3 } }
+ fake.tables.animals = [animalRow({ revision: 3 })]
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['animals.detail.restore'] }),
+ )
+ expect(
+ await screen.findByText(fr['animals.detail.restored']),
+ ).toBeInTheDocument()
+ expect(rpcArgs('set_animal_archived')).toEqual([
+ { animal_id: AID, archived: false },
+ ])
+ expect(
+ await screen.findByRole('button', { name: fr['relations.add_client'] }),
+ ).toBeInTheDocument()
+ })
+})
+
+describe('animal relations', () => {
+ function seed() {
+ fake.tables.animals = [animalRow()]
+ fake.tables.animal_client_relations = [
+ relationRow(R1, 'Marie Dupont', { started_on: '2020-03-01' }),
+ relationRow(R2, 'Écurie du Lac', { relation_role: 'keeper' }),
+ relationRow(R3, 'Jean Martin', {
+ ended_at: '2024-01-01T00:00:00Z',
+ ended_on: '2023-12-31',
+ }),
+ relationRow(R4, 'Fantôme Erroné', { voided_at: '2026-01-01T00:00:00Z' }),
+ ]
+ }
+
+ it('groups current and former relations; a voided one is never shown', async () => {
+ seed()
+ mount(`/app/animals/${AID}`)
+ expect(
+ await screen.findByRole('link', { name: 'Marie Dupont' }),
+ ).toHaveAttribute(
+ 'href',
+ `/app/clients/55555555-5555-4555-8555-555555555551`,
+ )
+ expect(
+ screen.getByRole('heading', { name: fr['relations.current'] }),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('heading', { name: fr['relations.former'] }),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByText(/Ancien propriétaire · jusqu'au 31 décembre 2023/),
+ ).toBeInTheDocument()
+ expect(screen.queryByText('Fantôme Erroné')).toBeNull()
+ expect(screen.queryByText(fr['animals.no_owner'])).toBeNull()
+ })
+
+ it('says « Propriétaire non renseigné » without a current owner', async () => {
+ fake.tables.animals = [animalRow()]
+ fake.tables.animal_client_relations = [
+ relationRow(R2, 'Écurie du Lac', { relation_role: 'keeper' }),
+ ]
+ mount(`/app/animals/${AID}`)
+ expect(await screen.findByText(fr['animals.no_owner'])).toBeInTheDocument()
+ })
+
+ it('ends a relation without a date, then with one', async () => {
+ seed()
+ fake.rpcResults.end_animal_client_relation = { data: { revision: 2 } }
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'Terminer : Marie Dupont, propriétaire',
+ }),
+ )
+ let dialog = await screen.findByRole('dialog', {
+ name: fr['relations.end.title'],
+ })
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }),
+ )
+ expect(
+ await screen.findByText(fr['relations.end.done']),
+ ).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(rpcArgs('end_animal_client_relation')[0]).toEqual({
+ relation_id: R1,
+ expected_revision: 1,
+ })
+ await userEvent.click(
+ screen.getByRole('button', {
+ name: 'Terminer : Écurie du Lac, détenteur',
+ }),
+ )
+ dialog = await screen.findByRole('dialog', {
+ name: fr['relations.end.title'],
+ })
+ fireEvent.change(
+ within(dialog).getByLabelText(label('relations.end.ended_on')),
+ {
+ target: { value: '2026-01-15' },
+ },
+ )
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }),
+ )
+ await waitFor(() =>
+ expect(rpcArgs('end_animal_client_relation')).toHaveLength(2),
+ )
+ expect(rpcArgs('end_animal_client_relation')[1]).toMatchObject({
+ relation_id: R2,
+ ended_on: '2026-01-15',
+ })
+ })
+
+ it('refuses an end before the start, in the dialog', async () => {
+ seed()
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'Terminer : Marie Dupont, propriétaire',
+ }),
+ )
+ const dialog = await screen.findByRole('dialog', {
+ name: fr['relations.end.title'],
+ })
+ const field = within(dialog).getByLabelText(label('relations.end.ended_on'))
+ fireEvent.change(field, { target: { value: '2019-01-01' } })
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }),
+ )
+ expect(
+ within(dialog).getByText(fr['relations.error.end_before_start']),
+ ).toBeInTheDocument()
+ expect(field).toHaveFocus()
+ expect(rpcArgs('end_animal_client_relation')).toEqual([])
+ })
+
+ it('a conflict reloads and says the relation changed; a network failure stays in the dialog', async () => {
+ seed()
+ fake.rpcResults.end_animal_client_relation = {
+ error: { code: '', message: 'TypeError: fetch failed' },
+ }
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'Terminer : Marie Dupont, propriétaire',
+ }),
+ )
+ const dialog = await screen.findByRole('dialog', {
+ name: fr['relations.end.title'],
+ })
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }),
+ )
+ expect(
+ await within(dialog).findByText(fr['relations.failure.unavailable']),
+ ).toBeInTheDocument()
+ expect(dialog).toBeInTheDocument()
+ fake.rpcResults.end_animal_client_relation = {
+ error: { code: 'P0001', message: 'conflict' },
+ }
+ fake.tables.animal_client_relations = [
+ relationRow(R1, 'Marie Dupont', {
+ revision: 2,
+ ended_at: '2026-10-26T12:00:00Z',
+ }),
+ ]
+ await userEvent.click(
+ within(dialog).getByRole('button', { name: fr['relations.end.confirm'] }),
+ )
+ expect(
+ await screen.findByText(fr['relations.failure.conflict']),
+ ).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(screen.queryByRole('link', { name: 'Écurie du Lac' })).toBeNull()
+ })
+
+ it('corrects the dates of a former relation', async () => {
+ seed()
+ fake.rpcResults.update_animal_client_relation = { data: { revision: 2 } }
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'Corriger les dates : Jean Martin, ancien propriétaire',
+ }),
+ )
+ const dialog = await screen.findByRole('dialog', {
+ name: fr['relations.dates.title'],
+ })
+ fireEvent.change(
+ within(dialog).getByLabelText(label('relations.dates.started_on')),
+ {
+ target: { value: '2018-05-01' },
+ },
+ )
+ await userEvent.click(
+ within(dialog).getByRole('button', {
+ name: fr['relations.dates.confirm'],
+ }),
+ )
+ expect(
+ await screen.findByText(fr['relations.dates.done']),
+ ).toBeInTheDocument()
+ expect(rpcArgs('update_animal_client_relation')).toEqual([
+ {
+ relation_id: R3,
+ expected_revision: 1,
+ started_on: '2018-05-01',
+ ended_on: '2023-12-31',
+ },
+ ])
+ })
+
+ it('voids a relation entered by mistake after a danger confirmation', async () => {
+ seed()
+ fake.rpcResults.void_animal_client_relation = { data: { revision: 2 } }
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: 'Erreur de saisie : Écurie du Lac, détenteur',
+ }),
+ )
+ const dialog = await screen.findByRole('dialog', {
+ name: fr['relations.void.title'],
+ })
+ expect(dialog).toHaveAccessibleDescription(
+ expect.stringContaining(fr['relations.void.body']),
+ )
+ fake.tables.animal_client_relations =
+ fake.tables.animal_client_relations.filter((r) => r.id !== R2)
+ await userEvent.click(
+ within(dialog).getByRole('button', {
+ name: fr['relations.void.confirm'],
+ }),
+ )
+ expect(
+ await screen.findByText(fr['relations.void.done']),
+ ).toBeInTheDocument()
+ expect(rpcArgs('void_animal_client_relation')).toEqual([
+ { relation_id: R2, expected_revision: 1 },
+ ])
+ await waitFor(() =>
+ expect(screen.queryByRole('link', { name: 'Écurie du Lac' })).toBeNull(),
+ )
+ })
+
+ it('the add-client panel needs a choice and a role, phrases a duplicate, reuses its request id', async () => {
+ fake.tables.animals = [animalRow()]
+ fake.rpcResults.search_clients = {
+ data: [
+ {
+ id: CID,
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ city: 'Lyon',
+ phone: null,
+ email: null,
+ archived_at: null,
+ name_key: 'marie dupont',
+ current_animal_count: 0,
+ },
+ ],
+ }
+ mount(`/app/animals/${AID}`)
+ await userEvent.click(
+ await screen.findByRole('button', { name: fr['relations.add_client'] }),
+ )
+ expect(
+ screen.getByRole('heading', { name: fr['relations.panel.title_client'] }),
+ ).toHaveFocus()
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['relations.panel.save_client'] }),
+ )
+ expect(screen.getByText(fr['animals.error.client'])).toBeInTheDocument()
+ await userEvent.click(
+ await screen.findByRole('button', { name: /Marie Dupont/ }),
+ )
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['relations.panel.save_client'] }),
+ )
+ expect(screen.getByText(fr['animals.error.role'])).toBeInTheDocument()
+ expect(rpcArgs('create_animal_client_relation')).toEqual([])
+ await userEvent.click(
+ screen.getByRole('radio', { name: fr['clients.role.keeper'] }),
+ )
+ fake.rpcResults.create_animal_client_relation = {
+ error: { code: 'P0001', message: 'duplicate_relation' },
+ }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['relations.panel.save_client'] }),
+ )
+ expect(
+ await screen.findByText(fr['relations.failure.duplicate_relation']),
+ ).toBeInTheDocument()
+ fake.rpcResults.create_animal_client_relation = {
+ data: { id: R1, revision: 1 },
+ }
+ fake.tables.animal_client_relations = [
+ relationRow(R1, 'Marie Dupont', { relation_role: 'keeper' }),
+ ]
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['relations.panel.save_client'] }),
+ )
+ expect(
+ await screen.findByText(fr['relations.added_client']),
+ ).toBeInTheDocument()
+ const calls = rpcArgs('create_animal_client_relation')
+ expect(calls[0]).toMatchObject({
+ animal_id: AID,
+ client_id: CID,
+ relation_role: 'keeper',
+ })
+ expect(calls[0].create_request_id).toBe(calls[1].create_request_id)
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', { name: fr['relations.add_client'] }),
+ ).toHaveFocus(),
+ )
+ })
+})
+
+describe('client page animals', () => {
+ const ANIMAL2 = '66666666-6666-4666-8666-666666666666'
+ function item(relationId: string, patch: Record = {}) {
+ return {
+ relation_id: relationId,
+ relation_role: 'owner',
+ started_on: null,
+ ended_on: null,
+ is_current: true,
+ relation_revision: 1,
+ animal_id: AID,
+ animal_name: 'Tornado',
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: null,
+ birth_year: null,
+ animal_archived_at: null,
+ sort_key: '0tornado',
+ ...patch,
+ }
+ }
+
+ it('shows each animal once with all its roles, linked to its page', async () => {
+ fake.tables.clients = [clientRow()]
+ fake.rpcResults.list_client_animals = {
+ data: [
+ item(R1),
+ item(R2, { relation_role: 'keeper' }),
+ item(R3, {
+ animal_id: ANIMAL2,
+ animal_name: 'Éclair',
+ is_current: false,
+ sort_key: '1eclair',
+ }),
+ ],
+ }
+ mount(`/app/clients/${CID}`)
+ const links = await screen.findAllByRole('link', { name: 'Tornado' })
+ expect(links).toHaveLength(1)
+ expect(links[0]).toHaveAttribute('href', `/app/animals/${AID}`)
+ expect(screen.getByText(fr['clients.role.owner'])).toBeInTheDocument()
+ expect(screen.getByText(fr['clients.role.keeper'])).toBeInTheDocument()
+ expect(
+ screen.getByText(fr['clients.role.former_owner']),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('link', { name: fr['clients.animals.add'] }),
+ ).toBeInTheDocument()
+ })
+
+ it('offers « Ajouter un premier animal » when there is none, with the client in the navigation state', async () => {
+ fake.tables.clients = [clientRow()]
+ mount(`/app/clients/${CID}`)
+ await userEvent.click(
+ await screen.findByRole('link', {
+ name: fr['clients.animals.add_first'],
+ }),
+ )
+ await waitFor(() =>
+ expect(screen.getByTestId('where')).toHaveTextContent('/app/animals/new'),
+ )
+ expect(
+ await screen.findByText(fr['relations.panel.client_chosen'], {
+ exact: false,
+ }),
+ ).toBeInTheDocument()
+ expect(screen.getByText('Marie Dupont')).toBeInTheDocument()
+ })
+
+ it('links an existing animal with the client id', async () => {
+ fake.tables.clients = [clientRow()]
+ fake.rpcResults.search_animals = {
+ data: [listRow(1, { id: AID, name: 'Tornado' })],
+ }
+ mount(`/app/clients/${CID}`)
+ await userEvent.click(
+ await screen.findByRole('button', {
+ name: fr['clients.animals.link_existing'],
+ }),
+ )
+ await userEvent.click(
+ await screen.findByRole('button', { name: /Tornado/ }),
+ )
+ await userEvent.click(
+ screen.getByRole('radio', { name: fr['clients.role.contact'] }),
+ )
+ fake.rpcResults.create_animal_client_relation = {
+ data: { id: R1, revision: 1 },
+ }
+ fake.rpcResults.list_client_animals = {
+ data: [item(R1, { relation_role: 'contact' })],
+ }
+ await userEvent.click(
+ screen.getByRole('button', { name: fr['relations.panel.save_animal'] }),
+ )
+ expect(
+ await screen.findByText(fr['relations.added_animal']),
+ ).toBeInTheDocument()
+ expect(rpcArgs('create_animal_client_relation')[0]).toMatchObject({
+ animal_id: AID,
+ client_id: CID,
+ relation_role: 'contact',
+ })
+ expect(rpcArgs('search_animals')[0]).toMatchObject({
+ archived: false,
+ workspace_id: WS,
+ })
+ })
+
+ it('an archived client offers no add and no link', async () => {
+ fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z' })]
+ fake.rpcResults.list_client_animals = { data: [item(R1)] }
+ mount(`/app/clients/${CID}`)
+ expect(
+ await screen.findByRole('link', { name: 'Tornado' }),
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('link', { name: fr['clients.animals.add'] }),
+ ).toBeNull()
+ expect(
+ screen.queryByRole('button', {
+ name: fr['clients.animals.link_existing'],
+ }),
+ ).toBeNull()
+ })
+})
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..9e4c6d42
--- /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'] })).toHaveFocus()
+ 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()
+ })
+})
diff --git a/apps/app/tests/unit/state.authStore.test.ts b/apps/app/tests/unit/state.authStore.test.ts
index 7a499b16..7a9bec6e 100644
--- a/apps/app/tests/unit/state.authStore.test.ts
+++ b/apps/app/tests/unit/state.authStore.test.ts
@@ -2,7 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeAssetRow,
+ fakeProfile,
fakeSession,
+ fakeUser,
flush,
type FakeSupabase,
} from '../helpers/fakeSupabase'
@@ -25,6 +27,7 @@ const INITIAL = {
urlFailure: null,
avatar: null,
avatarUrl: null,
+ workspace: { status: 'idle' as const },
}
let fake: FakeSupabase
@@ -112,10 +115,18 @@ describe('authStore', () => {
expect(fake.storage.download).toHaveBeenCalledTimes(1)
await useAuthStore.getState().refreshAvatar()
expect(fake.storage.download).toHaveBeenCalledTimes(1)
- fake.tables.assets.push(fakeAssetRow({ id: 'asset-2', object_key: 'profiles/user-1/asset-2/avatar.webp', created_at: '2026-10-13T12:00:00Z' }))
+ fake.tables.assets.push(
+ fakeAssetRow({
+ id: 'asset-2',
+ object_key: 'profiles/user-1/asset-2/avatar.webp',
+ created_at: '2026-10-13T12:00:00Z',
+ }),
+ )
fake.tables.assets[0].status = 'deleted'
await useAuthStore.getState().refreshAvatar()
- expect(fake.storage.download).toHaveBeenLastCalledWith('profiles/user-1/asset-2/avatar.webp')
+ expect(fake.storage.download).toHaveBeenLastCalledWith(
+ 'profiles/user-1/asset-2/avatar.webp',
+ )
})
it('clearAvatar drops the URL and the clean row; sign-out clears it too', async () => {
@@ -129,7 +140,10 @@ describe('authStore', () => {
expect(useAuthStore.getState().avatar?.clean).toBeNull()
await useAuthStore.getState().refreshAvatar()
fake.emit('SIGNED_OUT', null)
- expect(useAuthStore.getState()).toMatchObject({ avatar: null, avatarUrl: null })
+ expect(useAuthStore.getState()).toMatchObject({
+ avatar: null,
+ avatarUrl: null,
+ })
})
it('signOut calls the client and resets the state', async () => {
@@ -139,4 +153,175 @@ describe('authStore', () => {
expect(fake.auth.signOut).toHaveBeenCalled()
expect(useAuthStore.getState().status).toBe('signed_out')
})
+
+ describe('personal workspace', () => {
+ it('is read with the account and ready by its id', async () => {
+ fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ expect(useAuthStore.getState().workspace).toEqual({ status: 'loading' })
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'ready',
+ id: 'ws-1',
+ })
+ })
+
+ it('is missing when RLS returns no row for an active, confirmed account', async () => {
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({ status: 'missing' })
+ })
+
+ it('tells a deactivated profile and an unconfirmed email apart, without asking for the workspace', async () => {
+ fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
+ fake.tables.profiles = [fakeProfile({ active: false })]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({ status: 'inactive' })
+ fake.tables.profiles = [fakeProfile()]
+ fake.emit(
+ 'SIGNED_IN',
+ fakeSession(fakeUser({ id: 'user-1', email_confirmed_at: undefined })),
+ )
+ fake.emit(
+ 'USER_UPDATED',
+ fakeSession(fakeUser({ email_confirmed_at: undefined })),
+ )
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'unconfirmed',
+ })
+ })
+
+ it('reports a failed read as an error kind and reads again on refresh', async () => {
+ const from = fake.client.from.bind(fake.client)
+ let failing = true
+ ;(fake.client as unknown as { from: (t: string) => unknown }).from = (
+ table: string,
+ ) =>
+ table === 'workspaces' && failing
+ ? {
+ select: () => ({
+ eq: () => ({
+ maybeSingle: async () => ({
+ data: null,
+ error: { code: '', message: 'FetchError' },
+ status: 0,
+ }),
+ }),
+ }),
+ }
+ : from(table as never)
+ fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'error',
+ failure: 'network',
+ })
+ failing = false
+ await useAuthStore.getState().refreshWorkspace()
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'ready',
+ id: 'ws-1',
+ })
+ })
+
+ it('drops the previous account at once on a change of account, and ignores its late answers', async () => {
+ fake.tables.workspaces = [
+ { id: 'ws-1', personal_user_id: 'user-1' },
+ { id: 'ws-2', personal_user_id: 'user-2' },
+ ]
+ fake.tables.profiles = [
+ fakeProfile(),
+ fakeProfile({ id: 'user-2', display_name: 'Bob Local' }),
+ ]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'ready',
+ id: 'ws-1',
+ })
+
+ // Account 1's next load is held back, then answers after account 2 signed in.
+ let release: () => void = () => undefined
+ const held = new Promise((resolve) => (release = resolve))
+ const from = fake.client.from.bind(fake.client)
+ ;(fake.client as unknown as { from: (t: string) => unknown }).from = (
+ table: string,
+ ) => {
+ const query = from(table as never) as unknown as {
+ maybeSingle: () => Promise
+ }
+ const original = query.maybeSingle
+ query.maybeSingle = async () => {
+ const answer = (await original()) as { data: { id?: string } | null }
+ if (table === 'profiles' && answer.data?.id === 'user-1') await held
+ return answer
+ }
+ return query
+ }
+ fake.emit('USER_UPDATED', fakeSession())
+ await flush()
+ fake.emit(
+ 'SIGNED_IN',
+ fakeSession(fakeUser({ id: 'user-2', email: 'bob@example.test' })),
+ )
+ const switched = useAuthStore.getState()
+ expect(switched.profile).toBeNull()
+ expect(switched.workspace).toEqual({ status: 'loading' })
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().profile?.display_name).toBe('Bob Local')
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'ready',
+ id: 'ws-2',
+ })
+ release()
+ await flush()
+ await flush()
+ expect(useAuthStore.getState().profile?.display_name).toBe('Bob Local')
+ expect(useAuthStore.getState().workspace).toEqual({
+ status: 'ready',
+ id: 'ws-2',
+ })
+ })
+
+ it('keeps a ready workspace on screen while the same account is read again', async () => {
+ fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ const seen: string[] = []
+ const unsubscribe = useAuthStore.subscribe((s) => seen.push(s.workspace.status))
+ fake.emit('USER_UPDATED', fakeSession())
+ await flush()
+ await flush()
+ unsubscribe()
+ expect(seen).not.toContain('loading')
+ expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1' })
+ })
+
+ it('forgets the workspace on sign-out', async () => {
+ fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
+ stop = useAuthStore.getState().start()
+ fake.emit('SIGNED_IN', fakeSession())
+ await flush()
+ await flush()
+ fake.emit('SIGNED_OUT', null)
+ expect(useAuthStore.getState().workspace).toEqual({ status: 'idle' })
+ })
+ })
})
diff --git a/apps/app/tests/unit/ui.Dialog.test.tsx b/apps/app/tests/unit/ui.Dialog.test.tsx
index 32ea6659..7bd73f67 100644
--- a/apps/app/tests/unit/ui.Dialog.test.tsx
+++ b/apps/app/tests/unit/ui.Dialog.test.tsx
@@ -1,7 +1,14 @@
import { describe, it, expect, vi } from 'vitest'
-import { render, screen } from '@testing-library/react'
+import { useState } from 'react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Dialog from '@/components/ui/Dialog'
+import ModalDialog from '@/components/ui/ModalDialog'
+import { useLocaleStore } from '@/state/localeStore'
+
+// happy-dom implements neither the top layer nor inertness nor the dialog's focus
+// steps: these tests cover the React wiring, the browser behaviour is proven by
+// the Playwright suites (apps/app/e2e).
describe('Dialog', () => {
it('renders nothing when open=false', () => {
@@ -32,4 +39,173 @@ describe('Dialog', () => {
await userEvent.click(screen.getByTestId('dialog-backdrop'))
expect(onClose).toHaveBeenCalled()
})
+
+ it('is a native dialog named by its title and described by its message', () => {
+ render(
+ {}}
+ title="Remove the photo?"
+ description={It goes for good.
}
+ >
+ Remove
+ ,
+ )
+ const dialog = screen.getByRole('dialog', { name: 'Remove the photo?' })
+ expect(dialog.tagName).toBe('DIALOG')
+ expect(dialog).toHaveAccessibleDescription('It goes for good.')
+ })
+
+ it('has no description when none is given', () => {
+ render(
+ {}} title="X">
+ body
+ ,
+ )
+ expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-describedby')
+ })
+
+ it.each([
+ ['fr', 'Fermer'],
+ ['en', 'Close'],
+ ] as const)(
+ 'asks to close from the close button, named in %s',
+ async (locale, name) => {
+ useLocaleStore.setState({ locale })
+ const onClose = vi.fn()
+ render(
+
+ body
+ ,
+ )
+ await userEvent.click(screen.getByRole('button', { name }))
+ expect(onClose).toHaveBeenCalledTimes(1)
+ },
+ )
+})
+
+describe('ModalDialog', () => {
+ it('opens as a modal while mounted and closes on unmount', () => {
+ const showModal = vi.spyOn(HTMLDialogElement.prototype, 'showModal')
+ const close = vi.spyOn(HTMLDialogElement.prototype, 'close')
+ const { unmount } = render(
+ {}} label="Menu">
+ Inside
+ ,
+ )
+ expect(showModal).toHaveBeenCalledTimes(1)
+ unmount()
+ expect(close).toHaveBeenCalledTimes(1)
+ showModal.mockRestore()
+ close.mockRestore()
+ })
+
+ it('turns Escape into a request: the consumer decides, the dialog stays open', () => {
+ const onClose = vi.fn()
+ render(
+
+ Inside
+ ,
+ )
+ const dialog = screen.getByRole('dialog', {
+ name: 'Menu',
+ }) as HTMLDialogElement
+ const escape = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ })
+ screen.getByRole('button', { name: 'Inside' }).dispatchEvent(escape)
+ fireEvent.keyDown(dialog, { key: 'Escape' })
+ expect(escape.defaultPrevented).toBe(true)
+ expect(onClose).toHaveBeenCalledTimes(2)
+ expect(dialog.open).toBe(true)
+ })
+
+ it('ignores Escape while a composition is in progress', () => {
+ const onClose = vi.fn()
+ render(
+
+
+ ,
+ )
+ fireEvent.keyDown(screen.getByLabelText('Name'), {
+ key: 'Escape',
+ isComposing: true,
+ })
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ it('cancels the platform close request and asks the consumer instead', () => {
+ const onClose = vi.fn()
+ render(
+
+ Inside
+ ,
+ )
+ const cancel = new Event('cancel', { cancelable: true })
+ screen.getByRole('dialog').dispatchEvent(cancel)
+ expect(cancel.defaultPrevented).toBe(true)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('follows a close the platform forced, and ignores a close event while still open', () => {
+ const onClose = vi.fn()
+ render(
+
+ Inside
+ ,
+ )
+ const dialog = screen.getByRole('dialog') as HTMLDialogElement
+ dialog.dispatchEvent(new Event('close'))
+ expect(onClose).not.toHaveBeenCalled()
+ dialog.close()
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+})
+
+/** An opener that can disappear while its dialog is open, beside a sibling control. */
+function Harness({ removeOpener = false }: { removeOpener?: boolean }) {
+ const [open, setOpen] = useState(false)
+ const [openerShown, setOpenerShown] = useState(true)
+ const confirm = () => {
+ if (removeOpener) setOpenerShown(false)
+ setOpen(false)
+ }
+ return (
+
+
+ Sibling
+ {openerShown && (
+ setOpen(true)}>
+ Open
+
+ )}
+
+ setOpen(false)} title="Confirm">
+
+ Confirm
+
+
+
+ )
+}
+
+describe('Dialog focus return', () => {
+ it('returns focus to the opener', async () => {
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Open' }))
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(screen.getByRole('button', { name: 'Open' })).toHaveFocus()
+ })
+
+ it('falls back to the first control of the opener’s container when the opener is gone', async () => {
+ render( )
+ await userEvent.click(screen.getByRole('button', { name: 'Open' }))
+ await userEvent.click(screen.getByRole('button', { name: 'Confirm' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(screen.queryByRole('button', { name: 'Open' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Sibling' })).toHaveFocus()
+ })
})
diff --git a/docs/design/README.md b/docs/design/README.md
index 1cce98d6..e6bc8bf3 100644
--- a/docs/design/README.md
+++ b/docs/design/README.md
@@ -30,14 +30,14 @@ step has built yet, with the step that owns them:
| Element | Owner |
|---|---|
-| Clients and Animaux entries and screens | roadmap V1-1 (plan Step 12 reduced, `docs/development/V1-1_OWNERS_ANIMALS.md`) |
+| Clients and Animaux entries and screens | roadmap V1-1 (plan Step 12 reduced, `docs/development/V1-1_OWNERS_ANIMALS.md`). Clients built in V1-1.5 (2026-10-26): the entry in the sidebar and the drawer after Tableau de bord, the screens on the existing cards, fields, badges and buttons (the mockup draws no client screen); Animaux built in V1-1.6 (2026-10-26): the entry after Clients, the list, form and page on the same components (the mockup draws no animal screen either), relation actions as bordered buttons and in-page panel |
| Fiches anatomiques entry and screen | roadmap V1-2 (plan Step 13 reduced) |
| Bilans entry and screens | roadmap V1-3 (plan Step 14) |
| Agenda entry and screens | plan Step 20 |
| Stat tiles (bilans créés, clients, animaux, rendez-vous) and "Derniers bilans" | once the reports and agenda tables exist; never invented numbers |
| Notification bell | notifications step |
| Avatar photo and "Modifier la photo" | built in Step 8 (2026-10-13): circle + "Modifier la photo" in Informations personnelles, photo in the sidebar / drawer badge and in the top bar with the name on desktop (link to Mon compte, no dropdown) |
-| Bottom tab bar on mobile | with the first list screens (today only two destinations) |
+| Bottom tab bar on mobile | not reproduced in V1-1: owner decision D11 of 2026-10-26, the drawer stays the mobile navigation for V1-1 (Clients and Animaux in it). The mockup's bar (Accueil, Bilans, Agenda, Profil) stays the direction, a later UX subject, at the earliest with Bilans (V1-3); no custom V1-1 bar, the mockup unchanged |
| Tabs in Mon compte | optional restructuring when "Cabinet et activité" gains fields (activity type, website) |
| Password rule checklist | the mockup says 8 characters; the server policy is 12 with lower, upper and digit (config.toml); the hint text follows the server |
diff --git a/docs/development/BACKEND_ARCHITECTURE.md b/docs/development/BACKEND_ARCHITECTURE.md
index 8f581756..5a95f488 100644
--- a/docs/development/BACKEND_ARCHITECTURE.md
+++ b/docs/development/BACKEND_ARCHITECTURE.md
@@ -83,14 +83,27 @@ private.has_active_entitlement(uid, capability text)
Each helper ships with pgTAP tests in the same migration step: positive case,
negative case, expired grant, revoked grant, wrong organization.
+As built from V1-1 (contract `V1-1_OWNERS_ANIMALS.md` §9, BDR-073/074): the
+perimeter is a workspace, not an organization. `private.caller_workspace_ids()`
+(member, active profile, confirmed email; no parameter, `auth.uid()` only;
+EXECUTE for `authenticated`) and `private.writable_workspace_ids()` (the same,
+restricted to a write role; EXECUTE for nobody, called inside definer RPCs)
+replace `is_org_*` and `can_view_client/animal` for V1-1 records. They avoid
+RLS recursion by running as the table owner (`security definer`, owner
+`postgres`, `search_path = ''`) rather than with `row_security = off`. No
+helper or policy has a platform-role branch (D16). Every V1-1 table revokes
+all privileges from `anon` and `service_role` (N7); `postgres` keeps
+`BYPASSRLS` on the Supabase image and the service key stays a GoTrue admin
+credential, residual paths named in the contract §6.3.
+
### 4.2 Policy rules per domain (summary of §17.3)
| Table family | SELECT | INSERT/UPDATE/DELETE |
|---|---|---|
| `profiles` | own row; admins via view | own row; roles only through RPC |
-| `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place |
-| `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
-| `animals` | `can_view_animal` | practitioner with an active relationship or grant |
+| `workspaces`, `workspace_members` (V1-1; cabinets extend them instead of `organizations`) | members, through `caller_workspace_ids()` | none through the API: personal workspace created by trigger; cabinet membership RPCs come with Step 10 |
+| `clients`, `animals`, `animal_client_relations` (V1-1, built: M2 and M3) | members of the workspace, through `caller_workspace_ids()` | none through the API: definer RPCs check the write role of the workspace (`writable_workspace_ids()`); relations only between an animal and a client of one workspace (composite keys), voided instead of deleted (`V1-1_OWNERS_ANIMALS.md` §8.2, §8.3) |
+| `client_contacts`, `client_consents` (later steps) | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) |
| `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC |
| `report_revisions` | same as parent report | insert via RPC/trigger only |
| `anatomical_sheets` | public metadata through a view; full row for creator, grantee, or follower of a public sheet | creator only; publish via RPC |
diff --git a/docs/development/BROWSER_TESTS.md b/docs/development/BROWSER_TESTS.md
new file mode 100644
index 00000000..2b1c9621
--- /dev/null
+++ b/docs/development/BROWSER_TESTS.md
@@ -0,0 +1,137 @@
+# Browser tests (Playwright and axe)
+
+Status: V1-1.3, 2026-10-25 (decision D14, `V1-1_OWNERS_ANIMALS.md` §12.5).
+Chromium only until V1-5. The suites live in `apps/app/e2e`.
+
+## 1. Suites
+
+| Command | Backend | Dev server | Content |
+|---|---|---|---|
+| `pnpm e2e:ui` | none | Vite on `127.0.0.1:5191` | `e2e/ui/dialog.spec.ts`: the D13 contract of the shared Dialog on a test page; `e2e/ui/local-tool.spec.ts`: the disclaimer, edit and replace dialogs on the real local-tool routes |
+| `pnpm e2e:shell` | the isolated stack of `pnpm db:sandbox` | Vite on `127.0.0.1:5192` | `e2e/shell/shell.spec.ts`: sign-in, dashboard, the account photo confirmation, the phone drawer; `e2e/shell/clients.spec.ts`: the client journeys (V1-1.5); `e2e/shell/animals.spec.ts`: the animal and relation journeys (V1-1.6, contract §11.8); `e2e/shell/responsive.spec.ts`: no sideways scroll on nine shell pages, the archive confirmations and the drawer at 320, 360, 375, 390 and 430 px (phone project) and 1280 px, long values, the dashboard e-mail shown whole (RESP-01) |
+
+Each suite runs on two Chromium projects: `chromium-desktop` (1280 × 800) and
+`chromium-375` (375 × 667, mobile viewport, touch). A test tagged `@phone`
+runs on the phone project only (the drawer has no desktop counterpart). Both
+languages run: the local tool and the shell through the browser locale and
+the account's locale, the test page through `?lang=en`.
+
+The test page `e2e/harness/dialog.html` is served by the dev server only
+(`/e2e/harness/dialog.html`); the build has one entry, `index.html`, so it
+never ships. It holds the D13 cases (basic, long content, refused close,
+vanishing opener) and no product journey.
+
+The shell suite never reaches DEV. Its dev server is built with the Supabase
+URL `http://sandbox.faunosteo.invalid` (a name that resolves nowhere,
+RFC 6761); `e2e/support/sandbox.ts` replays `/auth/v1`, `/rest/v1` and
+`/storage/v1` on the sandbox's loopback ports, the way Kong maps them on the
+CLI stack. Each test creates its own confirmed account through the sandbox's
+GoTrue admin API (random address under `sandbox.local`, random password, a
+fictitious display name, the profile locale of the test), and seeds the clean
+avatar the worker would have produced (the `assets` row as postgres, the
+object with the service key). Rows around the subject of a test (clients,
+animals, relations) are written as postgres by `e2e/support/records.ts`,
+every value quoted as an SQL literal. `pnpm db:sandbox down` removes all of it.
+`pnpm db:sandbox e2e-shell ` passes its arguments to Playwright: one
+spec file, `--project`, `--grep`. Every shell suite removes its routes after
+each test without waiting for them (`dropLateReplays`), so an answer still in
+flight when the last check passed is dropped with the context instead of
+failing the test (the V1-1.6 verifier saw the client journey fail that way once
+the client page reloads its animals after a restore).
+
+## 2. Prerequisites
+
+- The repository's Node and pnpm, `pnpm install`.
+- The Chromium build of the pinned Playwright (1.64.1, Chromium 1248):
+ `pnpm --filter @faunosteo/app exec playwright install chromium`. It
+ downloads into `~/.cache/ms-playwright` and needs no `sudo`. Never pass
+ `--with-deps`: it installs system packages with `sudo`, an owner action. On
+ the Ubuntu development machine the headless shell runs with the libraries
+ already present.
+- `pnpm wasm:build`: the local tool runs the core, and the UI suite stops on a
+ missing or stale module (`packages/core-wasm/tests/global-setup.ts`).
+- For `pnpm e2e:shell`: Docker (rootless works) and the sandbox up,
+ `pnpm db:sandbox up fresh` (or `up upgrade `).
+- Ports 5191 and 5192 free: each server uses `--strictPort` and is never
+ reused, so the owner's `pnpm dev` on 5173 is never picked up by mistake.
+
+## 3. Guarantees
+
+- Request guard (`e2e/support/browser.ts`, automatic in every test): an
+ allowlist of origins per suite (the dev server, plus the fake Supabase
+ origin for the shell). Any other request, DEV's API on the LAN address
+ included, is aborted and fails the test with its URL.
+- No fixture value in a URL: the local tool's names and the shell account's
+ email, password and display name are checked against every request URL;
+ a match fails the test and the report masks the value.
+- axe (`@axe-core/playwright` 4.14.0, rules tagged WCAG 2.0 to 2.2 A and AA
+ plus best practices): zero serious or critical violation on each scanned
+ state, colours measured once animations have settled. Three pre-existing
+ findings, outside the V1-1.3 code, are listed with their reason in
+ `KNOWN_VIOLATIONS` and in TODO RR-7: the language switcher's names (« FR »
+ shown, « Passer en français » announced), the top bar account link (display
+ name shown, « Mon compte » announced), the dashboard's `dl` holding a status
+ row without `dt`/`dd`. Each entry names the axe rule, the selector, the
+ opening markup of the element and the route where it lives; a node is let
+ through only when all four match, so a new screen or a new element never
+ inherits an exception (owner brief 2026-10-26).
+- Reports: `apps/app/e2e/test-results/` and `apps/app/e2e/playwright-report/`,
+ git-ignored. The UI suite keeps a trace and a screenshot of a failed test
+ (no backend, no secret). The shell suite keeps the terminal output and a
+ screenshot of a failed test only: a trace would hold the session tokens, and
+ an HTML report the typed values, the fictitious accounts' passwords included
+ (found in the V1-1.5 report check, 2026-10-26; the HTML reporter was removed
+ from the shell config). Screenshots and the failure's page snapshot show
+ fictitious names and addresses only.
+
+## 4. Reading a failure
+
+The terminal shows each step and the failing assertion. The HTML report of
+the UI suite: `pnpm --filter @faunosteo/app exec playwright show-report
+e2e/playwright-report/ui` (the shell suite has none); a UI trace: `pnpm --filter @faunosteo/app exec playwright
+show-trace `. Setup failures are named: a missing
+Chromium (Playwright prints the install command), a stale core module
+(`run pnpm wasm:build`), the shell suite outside its wrapper
+(`SANDBOX_ANON_KEY missing: run pnpm e2e:shell`), the sandbox down
+(`db-sandbox: not running`).
+
+## 5. In `pnpm check:all` and a future CI
+
+`pnpm check:all` runs `pnpm e2e:ui` when the pinned Chromium is installed;
+otherwise it prints `SKIPPED` with the reason and the install command, and
+goes on. `pnpm e2e:shell` needs the sandbox and stays a separate run, like
+`pnpm e2e:avatar`. The last lines of a green run state each browser suite:
+`PASSED`, `SKIPPED` (environment missing, with the reason) or `NOT RUN`
+(`e2e:shell`). A suite that runs and fails stops `check:all` with
+`== FAILED: ` and a non-zero exit, never a warning. Both suites keep
+their own commands and run alone. A CI runner installs the same Chromium
+(`playwright install chromium` in its image) and runs `pnpm e2e:ui`; the shell
+suite needs Docker in the runner for the sandbox.
+
+## 6. Limits
+
+- Chromium only. Firefox, WebKit and the 412 × 915 viewport join at V1-5
+ (contract §12.5). WebKit's system libraries may need `sudo` (owner action).
+ Desktop WebKit is not iOS Safari: the owner's manual check on a real iPhone
+ and on a computer over the LAN stays a validation criterion of every mobile
+ step.
+- Tab past a modal dialog's last control reaches the browser's own interface
+ for one step, then the first control (the platform's behaviour, D13); the
+ page behind is never reached. The tests assert exactly that walk.
+- Safari does not focus a button on a pointer click, so a dialog opened by a
+ click has no opener to return to there; a keyboard opening always has one.
+- The vitest suites (happy-dom) cover the React wiring of the dialogs only:
+ happy-dom has no top layer, no inertness and no dialog focusing steps.
+- axe's target-size rule measures a control partly under the sticky top bar
+ as cut. Two phone states of the animal suite are reached at the bottom of a
+ long page (the client page after linking an animal, a refused duplicate);
+ they are scanned from the top of the page (`expectAccessibleFromTop`), where
+ nothing sits under the bar. The controls are 44 px high either way.
+
+## 7. Adding a test
+
+Import `test` and `expect` from `e2e/support/browser.ts` (the request guard
+comes with them), read every visible string from `@/i18n/{fr,en}`, use
+fictitious values only, and pass the values a test creates to
+`requests.forbid(...)`. A new backend origin goes into the suite's
+`allowedOrigins`, never into a wildcard.
diff --git a/docs/development/DOMAIN_MAP.md b/docs/development/DOMAIN_MAP.md
index 63b830cc..52e7028b 100644
--- a/docs/development/DOMAIN_MAP.md
+++ b/docs/development/DOMAIN_MAP.md
@@ -11,7 +11,8 @@ the code of 2026-10-08: the TypeScript modules they name have since moved into
`crates/core` or been deleted (Steps 5 to 8, R2 to R5); `CLAUDE.md` holds the
current map. Clients and Animals (§4, §5) are being reframed by the V1-1
contract (`V1-1_OWNERS_ANIMALS.md`): workspaces, no global client record,
-client-animal links with roles; owner orientations awaiting ratification.
+client-animal links with roles; business decisions ratified by the owner on
+2026-10-25 (BDR-073); where this map differs, the contract governs V1-1.
Conventions used below:
diff --git a/docs/development/FRONTEND_ARCHITECTURE.md b/docs/development/FRONTEND_ARCHITECTURE.md
index c39723b7..3def0f7f 100644
--- a/docs/development/FRONTEND_ARCHITECTURE.md
+++ b/docs/development/FRONTEND_ARCHITECTURE.md
@@ -9,7 +9,22 @@ Edge Functions are retired (D-R9), the packages `domain`, `anatomy`, `pdf` and
pdf-lib were replaced by `crates/core` and deleted (R4.8, R5.7), the legacy
editors and `public/species` were deleted at Step 5, no TanStack Query
(BDR-041), the public site framework is Astro (D-R8). `CLAUDE.md` (folder map,
-architecture) is the current description.
+architecture) is the current description. V1-1.3 (2026-10-25): every modal
+(`Dialog`, the mobile drawer) is built on `components/ui/ModalDialog.tsx`, the
+native `` in modal mode (behaviour in `V1-1_OWNERS_ANIMALS.md` §11.6),
+and the real-browser suites live in `apps/app/e2e` (`BROWSER_TESTS.md`).
+V1-1.5 (2026-10-26): the first record screens, the clients
+(`V1-1_OWNERS_ANIMALS.md` §11.7): data access only through
+`packages/supabase` (closed `RecordFailure` kinds), page-local state in hooks
+under `apps/app/src/clients/`, the personal workspace in `authStore`, the
+routes behind `RequireWorkspace`, unsaved changes guarded by `useLeaveGuard`
+and `AppLayout`. No data cache library: each page reads what it shows.
+V1-1.6 (2026-10-26): the animal screens and the relations (§11.8): hooks
+under `apps/app/src/animals/` and `apps/app/src/relations/`, components
+under `components/{animals,relations}/`; one `RequireWorkspace` above the
+client and animal routes, which also holds the species labels (read once per
+workspace, dropped with it); no new business rule in TypeScript (the M3 RPCs
+decide, the schemas are D-R7 form checks, age and grouping are display).
## 1. Starting point
diff --git a/docs/development/IMPLEMENTATION_PLAN.md b/docs/development/IMPLEMENTATION_PLAN.md
index f212f60e..385e5d87 100644
--- a/docs/development/IMPLEMENTATION_PLAN.md
+++ b/docs/development/IMPLEMENTATION_PLAN.md
@@ -314,6 +314,13 @@ Definition of Done: architecture Sprint 2 minus seats billing.
Risks: context leakage into later queries (every report/client query must take the context explicitly; enforce by a service-layer signature, not a global).
```
+Step 10 note (2026-10-25): with C4 ratified (BDR-073), cabinets are built as
+workspaces of kind `cabinet` on the `workspaces` / `workspace_members` tables
+that V1-1 creates, not as separate `organizations` / `organization_members`
+tables; cabinet roles extend `workspace_member_role` and plug into the V1-1
+workspace helpers (`V1-1_OWNERS_ANIMALS.md` §3, §4, §9.1). The rest of the
+step (member management, context switcher, seats) is unchanged.
+
```text
Step 11
Name: Entitlement engine skeleton (no Stripe)
@@ -342,13 +349,17 @@ Definition of Done: architecture Sprint 3; rule 1 (animal ≠ sheet) visible in
Risks: the global-client design (C4) if confirmed as plain shared rows; GDPR consent texts not final (version column from day one).
```
-Step 12 note (2026-10-25): roadmap item V1-1 proposes a reduced Step 12 under
-the owner's orientation C4 (records attached to a workspace, one personal
-workspace per practitioner, cabinets later, no global client record shared
-between practitioners), without consents, grants, sharing, files or candidate
-matching: `V1-1_OWNERS_ANIMALS.md`. The text above stands until the owner
-ratifies the contract's orientations (§9.1) and answers its sub-choices
-(§9.2).
+Step 12 note (2026-10-25): roadmap item V1-1 is a reduced Step 12 under C4,
+ratified by the owner on 2026-10-25 (BDR-073): records attached to a
+workspace, one personal workspace per practitioner, cabinets later, no global
+client record shared between practitioners, no consents, grants, sharing,
+files or candidate matching. Contract and technical design:
+`V1-1_OWNERS_ANIMALS.md` (business decisions approved; architecture and N1-N9
+validated 2026-10-25, BDR-074; the workspaces, clients and animals and
+relations migrations (V1-1.1, V1-1.2, V1-1.4) written and tested in
+isolation, not applied to DEV). Where the
+text above differs (global clients, consents, grants, photo, files, deceased
+flow), the contract governs V1-1.
```text
Step 13 (∥ Steps 9–12)
diff --git a/docs/development/OPEN_QUESTIONS.md b/docs/development/OPEN_QUESTIONS.md
index b147c7e8..90004d6a 100644
--- a/docs/development/OPEN_QUESTIONS.md
+++ b/docs/development/OPEN_QUESTIONS.md
@@ -6,7 +6,7 @@ ambiguities or technically risky points found when confronting
questions for the developer that change architecture or development order.
Items that are merely interesting are left out.
-## Status (revised 2026-10-25, P0)
+## Status (revised 2026-10-25, P0 and V1-1 ratification)
The analysis below is the 2026-10-08 text, kept as written; this table says
what has been settled since and by which record (BDR = `.claude/memory/decisions.md`,
@@ -19,9 +19,9 @@ Step 5).
| C1 vertebral formula | settled | ordered `vertebral_config.regions`, free codes (BDR-031) |
| C2 report-only points | open | `localAnnotations` reserved empty in Report v3 (BDR-038); promotion semantics undecided (Q6a); defining it later is a report version bump |
| C3 worker on day one | settled | Rust worker built at Step 8 / R1 (BDR-044, BDR-048) |
-| C4 global client record | owner orientation, awaiting ratification | records belong to a workspace (one personal workspace per practitioner in V1-1, cabinets later); no global directory shared between practitioners (owner, 2026-10-25); contract `V1-1_OWNERS_ANIMALS.md` §3, D2 |
-| C5 animal update rights | owner orientation, awaiting ratification | writes reserved to workspace members with a write right, in V1-1 the practitioner in their personal workspace; no retroactive silent change of a finished bilan (owner, 2026-10-25); V1-1 contract §5.1, §5.3 |
-| C6 unverified accounts | owner orientation, awaiting ratification | email confirmation ≠ professional verification; private use for confirmed-email accounts, verification (Step 9) required for public features presenting a verified professional; statuses are not platform roles (BDR-026) (owner, 2026-10-25); V1-1 contract §5.2. Replaces the 2026-10-08 assumption below (no clients or reports before verification) once ratified |
+| C4 global client record | settled (owner ratification 2026-10-25, BDR-073) | records belong to a workspace (`workspaces`, `workspace_members`; one personal workspace per practitioner in V1-1, cabinet workspaces later without destructive transfer); no global directory shared between practitioners, no data visible between them; contract `V1-1_OWNERS_ANIMALS.md` §4, D2 |
+| C5 animal update rights | settled (owner ratification 2026-10-25, BDR-073) | writes reserved to workspace members with a write right, in V1-1 the practitioner in their personal workspace; no retroactive silent change of a finished bilan; V1-1 contract §6.1, §6.4 |
+| C6 unverified accounts | settled (owner ratification 2026-10-25, BDR-073) | email confirmed, professional status verified and platform role are three distinct notions; a confirmed email gives private use of the workspace; verification (Step 9) required later for public features presenting a verified professional; no verified status by default; statuses are not platform roles (BDR-026); V1-1 contract §6.2. Replaces the 2026-10-08 assumption below (no clients or reports before verification) |
| C7 « Observation » vocabulary | settled | finding category kind `observation` renamed `consultation_reason` (BDR-033 point 5); *Observation* stays the report block |
| C8 drafts per sheet | settled | one draft per sheet, partial unique index (BDR-032) |
| C9 detail view asset | settled | nullable `svg_asset_id`, crop by `view_box`; the equine head is a crop of one cleaned drawing (BDR-031, BDR-036, BDR-037) |
@@ -35,7 +35,7 @@ Step 5).
| Q3 non-mammal layouts | settled | free region codes (BDR-031) |
| Q4 external use of the pathology editor | moot | the tool was deleted at Step 5 (BDR-038); content changes go through `curation/changes.json` until the Step 17 editor (owner confirmed 2026-10-25) |
| Q5 one or two equine assets | settled | one cleaned drawing, head as crop (BDR-036, BDR-037) |
-| Q6 manual points, shared client records | open (a); (b) reframed by C4 | (a) as C2; (b) no shared record if C4 is confirmed, so the edit-rights question moves inside a data space (V1-1 contract §5) |
+| Q6 manual points, shared client records | open (a); (b) settled by C4 | (a) as C2; (b) no shared record (C4 ratified), so edit rights live inside a workspace (V1-1 contract §6) |
| Q7 phone and email providers | open | Step 7 shipped email only; needed before production SMTP and phone verification |
| Q8 public site framework | settled | Astro (D-R8, validated with BDR-045), Rust exception recorded |
| Q9 catalog anomalies | settled, against the 2026-10-08 recommendation | no medical correction at import, anomalies reported, degraded slugs normalised (BDR-034); later corrections through curation changes (BDR-036, BDR-037) |
diff --git a/docs/development/STORAGE.md b/docs/development/STORAGE.md
index d32b061f..8dd34dc8 100644
--- a/docs/development/STORAGE.md
+++ b/docs/development/STORAGE.md
@@ -260,7 +260,15 @@ token, no user content.
4. Poll the own row every 1 s, 30 s at most: `clean` → download
`object_key` (`storage.from('avatars').download`), keep a blob URL in the
auth store; `rejected` → message per code; still `uploaded` after 30 s →
- "processing, come back later" (the next mount polls again).
+ "processing, come back later" (the next mount polls again). Only a row
+ the section knows at mount resumes: after a full page reload the section
+ mounts before the auth store has read the rows, so it shows the clean
+ photo with « Modifier » and « Supprimer » enabled, and a new save
+ supersedes the waiting row (`deleted`, keys enqueued). An in-app return to
+ Mon compte resumes the polling. Without a running worker (a DEV stack where
+ `docker compose --profile worker up worker` was not started, §3.2 of
+ SUPABASE.md) every new photo stays `uploaded` and ends on that message;
+ the clean photo is kept (AVATAR-01, 2026-10-27, isolated reproduction).
5. "Supprimer la photo": confirmation dialog → `remove_avatar()` → monogram.
Closed failure kinds the UI phrases (`AssetFailure.kind`): `too_large`,
diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md
index 1d9bb47e..28424e29 100644
--- a/docs/development/SUPABASE.md
+++ b/docs/development/SUPABASE.md
@@ -18,7 +18,10 @@ supabase/
│ ├─ 20261009100000_sheet_asset_storage.sql bucket anatomical-sheet-assets + read policy through the sheet
│ ├─ 20261010100000_sheet_document_schema_v2.sql document schema 2: references, review_status, count_range checks
│ ├─ 20261011100000_profiles_professional.sql practice_name, professional_title, siret
-│ └─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md)
+│ ├─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md)
+│ ├─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3)
+│ ├─ 20261025110000_clients.sql V1-1.2 (M2): clients, unaccent, client RPCs and search, write budget per workspace, N9 audit filter (§3.4)
+│ └─ 20261026100000_animals_relations.sql V1-1.4 (M3): species rows, animals, relations with history and voiding, their RPCs and reads (§3.5)
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
├─ seed/anatomical-sheets/equine/ official equine sheet as a DRAFT, generated by `pnpm import:equine`
│ ├─ legacy-sources/ the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input)
@@ -181,11 +184,562 @@ Seed accounts (local only, password `LocalDev-only-password-1`):
| `alice@faunosteo.local` | plain user |
| `bob@faunosteo.local` | plain user |
+### 3.3 Workspaces (V1-1.1, migration M1)
+
+Contract: `docs/development/V1-1_OWNERS_ANIMALS.md` §4, §8.1, §9. Every
+account has exactly one personal workspace, created by the trigger
+`profiles_create_personal_workspace` in the sign-up transaction (GoTrue →
+`handle_new_auth_user` → profile → workspace + `holder` membership), through
+the single write path `private.ensure_personal_workspace(uuid)` (one
+statement, idempotent, race-safe). A deferred constraint trigger refuses at
+commit a personal workspace without its holder or with any other member.
+Reads: RLS through `private.caller_workspace_ids()` (member, active profile,
+confirmed email, `auth.uid()` only). No API role writes either table; `anon`
+and `service_role` hold no privilege on them. From M2 on, record tables use
+the same helpers; the app passes its workspace id explicitly.
+
+M1, M2 and M3 are written and tested on PGlite and on the isolated stack
+(§5.1), none is applied to the DEV stack. Applying them there is an owner
+action, never run by Claude, never with `db reset`, `db push`, `migration
+repair`, a volume removal or any other destructive command. The procedure
+below takes DEV from its current state (every migration up to
+`20261013100000` applied, fictitious accounts present) to M3 in one run; the
+upgrade path was rehearsed on the isolated stack (`pnpm db:sandbox up upgrade
+20261025100000`). Steps 0 to 3 only read DEV (the SQL helpers force a
+read-only session); step 3b writes on the sandbox only; step 4 is the one
+write on DEV. Nothing below prints a key: the database password stays in the
+containers' environment, and `supabase status` is read with `-o env`
+filtered to the API URL, because its default output prints the service key
+and the JWT secret.
+
+Read-only preflight of 2026-10-26 (Claude; CLI 2.120.0, PostgreSQL 17.11,
+branch at `9f585e9`): history 9 applied, M1 to M3 pending, nothing
+remote-only, no linked project; none of the tables, types, functions,
+trigger, constraint or extension M1 to M3 create exists; types drift =
+exactly the 24 names of step 1, nothing removed; 6 accounts = 6 profiles (4
+confirmed), 1 platform role, 9 asset rows (1 clean), 2 storage objects (11
+files in the storage volume, leftovers of earlier resets), 13 due rows in the
+purge queue, 35 audit rows, species `equine` only, vault empty; `unaccent`
+and `pgtap` available, not installed. Run steps 0 to 2 again on the day: DEV
+changes as it is used.
+
+```bash
+# Same shell for every step: helpers, backup folder, private file mode.
+devsql() { docker exec -i supabase_db_faunosteo sh -c 'PGOPTIONS="-c default_transaction_read_only=on" \
+ PGPASSWORD="$POSTGRES_PASSWORD" psql -X -q -A -t -v ON_ERROR_STOP=1 -h 127.0.0.1 -U postgres -d "$1"' sh "$1"; }
+boxsql() { docker exec -i faunosteo_dbsandbox_db sh -c 'PGOPTIONS="-c default_transaction_read_only=on" \
+ PGPASSWORD="$POSTGRES_PASSWORD" psql -X -q -A -t -v ON_ERROR_STOP=1 -h 127.0.0.1 -U postgres -d "$1"' sh "$1"; }
+B=~/faunosteo-backups
+umask 077
+
+# 0. Target: the local CLI stack of this project, nothing remote.
+git status -sb # the V1-1 branch, clean, equal to origin
+test ! -f supabase/.temp/project-ref && echo "no linked project"
+pnpm -s supabase status -o env | grep '^API_URL=' # http://:54321
+docker port supabase_db_faunosteo 5432 # 0.0.0.0:54322: the DEV database
+docker inspect -f '{{.Name}} {{.Config.Image}}' supabase_db_faunosteo faunosteo_dbsandbox_db
+ # the same postgres:17.11.0.004 image twice; no sandbox
+ # container → `pnpm db:sandbox up fresh` first (§5.1)
+mkdir -p "$B" && chmod 700 "$B" # outside Git, never synced, never attached to a report
+
+# 1. History and drift: only the V1-1 migrations may be pending.
+pnpm supabase migration list --local # local = remote on every row up to 20261013100000, remote empty on
+ # 20261025100000 (M1), 20261025110000 (M2), 20261026100000 (M3), nothing else
+pnpm -s db:types:check > "$B/types-before.diff"
+grep -c '^<' "$B/types-before.diff" # 0: nothing removed
+grep -oE '^> [a-z_]+:' "$B/types-before.diff" | sort -u | wc -l
+# 24 names, only these: workspaces, workspace_members, workspace_kind, workspace_member_role (M1);
+# clients, client_kind, create_client, update_client, set_client_archived, search_clients (M2);
+# animals, animal_client_relations, animal_sex, animal_relation_role, create_animal, update_animal,
+# set_animal_archived, create_/end_/update_/void_animal_client_relation, search_animals,
+# list_client_animals, client_archive_preview (M3); any other name = drift, STOP
+
+# 2. State before: counts, row fingerprints (md5 only, no row printed) and structure.
+cat > "$B/counts.sql" <<'SQL'
+set timezone = 'UTC';
+select 'users ' || count(*) from auth.users;
+select 'identities ' || count(*) from auth.identities;
+select 'profiles ' || count(*) from public.profiles;
+select 'profile_roles ' || count(*) from public.profile_roles;
+select 'species ' || count(*) from public.species;
+select 'sheets ' || count(*) from public.anatomical_sheets;
+select 'sheet_versions ' || count(*) from public.anatomical_sheet_versions;
+select 'assets ' || count(*) from public.assets;
+select 'purge_queue ' || count(*) from private.object_purge_queue;
+select 'buckets ' || count(*) from storage.buckets;
+select 'objects ' || count(*) from storage.objects;
+select 'audit_logs ' || count(*) from audit.audit_logs;
+select 'migrations ' || string_agg(version, ',' order by version) from supabase_migrations.schema_migrations;
+select 'md5 users ' || md5(coalesce(string_agg(t::text, '|' order by t::text), '')) from auth.users t;
+select 'md5 profiles ' || md5(coalesce(string_agg(t::text, '|' order by t::text), '')) from public.profiles t;
+select 'md5 profile_roles ' || md5(coalesce(string_agg(t::text, '|' order by t::text), '')) from public.profile_roles t;
+select 'md5 assets ' || md5(coalesce(string_agg(t::text, '|' order by t::text), '')) from public.assets t;
+select 'md5 sheet_versions ' || md5(coalesce(string_agg(t::text, '|' order by t::text), '')) from public.anatomical_sheet_versions t;
+select 'md5 species equine ' || md5(t::text) from public.species t where t.id = 'equine';
+select 'tables ' || n.nspname || ' ' || count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where c.relkind in ('r', 'p') and n.nspname in ('public', 'private', 'audit', 'auth', 'storage') group by n.nspname order by n.nspname;
+select 'functions ' || n.nspname || ' ' || count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ where n.nspname in ('public', 'private') group by n.nspname order by n.nspname;
+select 'policies ' || count(*) from pg_policies where schemaname in ('public', 'storage', 'audit');
+select 'rls tables public ' || count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = 'public' and c.relkind = 'r' and c.relrowsecurity;
+SQL
+devsql postgres < "$B/counts.sql" > "$B/counts-before.txt" && cat "$B/counts-before.txt"
+# users = profiles = N (6 on 2026-10-26); the other lines are the reference of steps 3b and 5
+# Privileges (read only), the reference of step 3b: effective ACLs of the application schemas, grants
+# of auth and storage to the API roles, policies, triggers, constraints, extensions, postgres defaults.
+cat > "$B/privs.sql" <<'SQL'
+select 'acl relations ' || n.nspname || ' ' || md5(string_agg(c.relname || ':' || coalesce(c.relacl, acldefault(case c.relkind when 'S' then 's'::"char" else 'r'::"char" end, c.relowner))::text || ':' || c.relrowsecurity || c.relforcerowsecurity, '|' order by c.relname))
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where n.nspname in ('public', 'private', 'audit', 'supabase_migrations') and c.relkind in ('r', 'v', 'S', 'p') group by n.nspname order by n.nspname;
+select 'acl functions ' || n.nspname || ' ' || md5(string_agg(p.oid::regprocedure::text || ':' || coalesce(p.proacl::text, '-') || ':' || p.prosecdef || ':' || coalesce(array_to_string(p.proconfig, ','), '-'), '|' order by p.oid::regprocedure::text))
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname in ('public', 'private', 'audit') group by n.nspname order by n.nspname;
+select 'acl schemas ' || md5(string_agg(nspname || ':' || coalesce(nspacl::text, '-'), '|' order by nspname))
+ from pg_namespace where nspname in ('public', 'private', 'audit');
+select 'grants ' || n.nspname || ' ' || md5(string_agg(c.relname || ':' || pg_get_userbyid(a.grantee) || ':' || a.privilege_type || ':' || a.is_grantable, '|'
+ order by c.relname, pg_get_userbyid(a.grantee), a.privilege_type))
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace cross join lateral aclexplode(c.relacl) a
+ where n.nspname in ('auth', 'storage') and a.grantee not in (c.relowner, 'postgres'::regrole) group by n.nspname order by n.nspname;
+select 'policies ' || md5(string_agg(schemaname || '.' || tablename || '.' || policyname || ':' || cmd || ':' || roles::text || ':' || coalesce(qual, '-') || ':' || coalesce(with_check, '-'), '|'
+ order by schemaname, tablename, policyname)) from pg_policies where schemaname in ('public', 'storage', 'audit');
+select 'triggers ' || count(*) || ' ' || md5(string_agg(tgrelid::regclass::text || '.' || tgname || ':' || tgenabled::text || ':' || tgfoid::regprocedure::text, '|' order by tgrelid::regclass::text, tgname))
+ from pg_trigger t join pg_class c on c.oid = t.tgrelid join pg_namespace n on n.oid = c.relnamespace
+ where not tgisinternal and n.nspname in ('public', 'private', 'audit', 'auth', 'storage');
+select 'constraints ' || count(*) || ' ' || md5(string_agg(conrelid::regclass::text || '.' || conname || ':' || pg_get_constraintdef(oid), '|' order by conrelid::regclass::text, conname))
+ from pg_constraint where connamespace::regnamespace::text in ('public', 'private', 'audit');
+select 'extensions ' || string_agg(extname || '@' || extversion, ',' order by extname) from pg_extension;
+select 'default acl postgres ' || count(*) || ' ' || md5(string_agg(defaclnamespace::regnamespace::text || ':' || defaclobjtype::text || ':' || defaclacl::text, '|' order by defaclnamespace::regnamespace::text, defaclobjtype::text))
+ from pg_default_acl where defaclrole = 'postgres'::regrole;
+SQL
+devsql postgres < "$B/privs.sql" > "$B/privs-before.txt" && wc -l < "$B/privs-before.txt" # 15
+cat > "$B/managed.sql" <<'SQL'
+select 'vault secrets ' || count(*) from vault.secrets;
+select 'managed default acl ' || count(*) from pg_default_acl
+ where defaclrole in ('supabase_admin'::regrole, 'supabase_auth_admin'::regrole);
+SQL
+devsql postgres < "$B/managed.sql"
+# vault secrets 0, else STOP: no backup, no M1 to M3; vault rows need a procedure of their own (keys)
+# managed default acl D (21 on 2026-10-26): step 3b leaves out exactly D + 8 entries
+
+# 3. Backup outside Git: the whole `postgres` database (auth, storage metadata, public, private, audit,
+# migration history, grants) and the bytes of the Storage files (the storage container's volume).
+docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -h 127.0.0.1 -U postgres -d postgres -Fc' \
+ > "$B/dev-before-v1-1.dump" && chmod 600 "$B/dev-before-v1-1.dump"
+docker cp supabase_storage_faunosteo:/mnt - > "$B/dev-before-v1-1-storage.tar" && chmod 600 "$B/dev-before-v1-1-storage.tar"
+ls -l "$B" # both files non-empty, -rw-------
+docker exec -i supabase_db_faunosteo pg_restore --list < "$B/dev-before-v1-1.dump" \
+ | grep -cE "TABLE DATA (auth users|public profiles|storage objects|supabase_migrations schema_migrations)" # 4
+tar -tvf "$B/dev-before-v1-1-storage.tar" | grep -c '^-' # the volume's file count (11 on 2026-10-26)
+
+# 3b. The dump restores, on the isolated stack (never on the DEV server), with exit status 0: a scratch
+# database of the sandbox, restored in one transaction that stops at the first error, compared with
+# step 2, then dropped. `restore_check_v1_1` is the only database created or dropped here.
+# Prerequisite, sandbox only: DEV owns the cluster role `supabase_functions_admin` (schema
+# `supabase_functions`), a fresh sandbox does not, and the dump's ACL entries name it. Create
+# it once there, NOLOGIN with no global privilege (what a no-owner replay needs); never on DEV:
+docker exec -i faunosteo_dbsandbox_db sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -X -q -v ON_ERROR_STOP=1 -h 127.0.0.1 -U postgres -d postgres' <<'SQL'
+do $$ begin
+ if not exists (select 1 from pg_roles where rolname = 'supabase_functions_admin') then
+ create role supabase_functions_admin nologin nosuperuser nocreaterole nocreatedb noreplication nobypassrls noinherit;
+ end if;
+end $$;
+SQL
+# The restore leaves out the D + 8 TOC entries `postgres` may not replay; the dump file itself stays
+# complete and unchanged (the list is a copy of its table of contents):
+# - D « DEFAULT ACL … supabase_admin | supabase_auth_admin »: default privileges for objects those
+# roles create (platform defaults; `postgres` may not change another role's defaults; no data,
+# no application privilege; the sandbox image holds its own);
+# - 5 « ACL vault »: secrets, decrypted_secrets, create_secret, update_secret,
+# _crypto_aead_det_decrypt; with --no-owner their extension makes them postgres's own, and
+# postgres cannot grant itself a grant option; the service_role grants of these entries come
+# out identical from the extension (rehearsal of 2026-10-26);
+# - 1 « ACL pg_catalog » pg_reload_conf, 1 « ACL extensions » pg_stat_statements_reset: owned by
+# supabase_admin, postgres may not grant on them;
+# - 1 « TABLE DATA vault secrets »: postgres may not write vault.secrets; nothing is lost only
+# because step 2 read 0 rows. With rows there, this procedure does not apply.
+docker exec -i faunosteo_dbsandbox_db pg_restore --list < "$B/dev-before-v1-1.dump" > "$B/full.list"; echo "list exit $?" # 0
+grep -E '^[0-9]+; [0-9]+ [0-9]+ (DEFAULT ACL [a-z_]+ DEFAULT PRIVILEGES FOR (SEQUENCES|FUNCTIONS|TABLES) (supabase_admin|supabase_auth_admin)|ACL pg_catalog FUNCTION pg_reload_conf\(\) supabase_admin|ACL extensions FUNCTION pg_stat_statements_reset\(.*\) supabase_admin|ACL vault (FUNCTION|TABLE) .* supabase_admin|TABLE DATA vault secrets supabase_admin)$' \
+ "$B/full.list" > "$B/excluded.list"
+cut -d' ' -f4-5 "$B/excluded.list" | sort | uniq -c
+# exactly: D « DEFAULT ACL », 1 « ACL extensions », 1 « ACL pg_catalog », 5 « ACL vault », 1 « TABLE DATA »;
+# any other count = STOP (never widen the pattern to make it fit)
+grep -vxFf "$B/excluded.list" "$B/full.list" > "$B/restore.list"
+wc -l < "$B/full.list"; wc -l < "$B/restore.list" # the second = the first minus D + 8
+docker cp "$B/restore.list" faunosteo_dbsandbox_db:/tmp/restore.list # names only, no data; gone with the sandbox
+docker exec faunosteo_dbsandbox_db sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" createdb -h 127.0.0.1 -U postgres restore_check_v1_1'
+docker exec -i faunosteo_dbsandbox_db sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_restore -h 127.0.0.1 -U postgres \
+ -d restore_check_v1_1 --no-owner --use-list=/tmp/restore.list --single-transaction --exit-on-error' \
+ < "$B/dev-before-v1-1.dump" 2> "$B/restore-check.log"; echo "pg_restore exit $?"
+wc -c < "$B/restore-check.log" # 0: the log, rewritten by this run, holds no message
+# exit 0 and an empty log, else STOP: the single transaction rolled back, the scratch database is
+# empty; keep the log (a COPY error can quote a row: report only its ERROR and Command was lines),
+# drop the database (last line), report
+boxsql restore_check_v1_1 < "$B/counts.sql" > "$B/counts-restored.txt"
+diff "$B/counts-before.txt" "$B/counts-restored.txt" && echo "rows identical" # the 28 lines
+boxsql restore_check_v1_1 < "$B/privs.sql" > "$B/privs-restored.txt"
+diff "$B/privs-before.txt" "$B/privs-restored.txt" && echo "privileges identical" # the 15 lines
+docker exec faunosteo_dbsandbox_db sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" dropdb -h 127.0.0.1 -U postgres restore_check_v1_1'
+
+# 4. Apply without reset (M1's backfill runs inside the migration); no app session open on DEV meanwhile.
+# `migration up` applies every pending migration of the checkout, in order.
+pnpm supabase migration up --local; echo "migration up exit $?"
+# "Applying migration 20261025100000_workspaces.sql...", then ..._clients.sql, then
+# 20261026100000_animals_relations.sql; exit 0. Keep the whole output for the report.
+```
+
+Step 3b was rehearsed on the sandbox with fictitious data, never with DEV
+data (2026-10-26, a 156 MB dump of the sandbox's `postgres` database at M3,
+2 144 accounts, vault empty; D = 18 there, the sandbox has no
+`supabase_functions` schema). Four variants, exit status read from the shell:
+
+- `--no-owner` alone (the earlier procedure): exit 1, 26 errors, the 26
+ entries above (18 default privileges, 5 vault ACL, 2 ACL on supabase_admin
+ functions, the vault.secrets COPY); rows identical;
+- `--no-acl`: exit 1 (the vault.secrets COPY), and every grant of the
+ application schemas lost: rejected, it removes what the check must prove;
+- `--exit-on-error` on the whole list: exit 1 at the vault.secrets COPY,
+ before the policies: rejected;
+- the filtered list with `--single-transaction --exit-on-error`: exit 0, empty
+ log, the 28 lines and the 15 privilege lines identical. Retained.
+
+First run on the real DEV dump (2026-10-27): the 29 expected entries were
+left out (D = 21), and the restore stopped with exit 1 on
+`GRANT USAGE ON SCHEMA supabase_functions TO postgres`: role
+`supabase_functions_admin` missing from the sandbox (DEV: LOGIN, CREATEROLE,
+`search_path=supabase_functions`, owns the `supabase_functions` objects).
+With the NOLOGIN role above and nothing else changed: exit 0, empty log, the
+28 and 15 lines identical, schema `supabase_functions` restored with its 2
+tables. The DEV role's login, CREATEROLE and password are not copied: no
+privilege is exercised by a `--no-owner` replay.
+
+A table whose stored ACL is the explicit owner-only one comes back with no
+ACL, the same privileges (pg_dump leaves out an ACL equal to the default):
+`privs.sql` therefore compares effective ACLs (`acldefault`). DEV differs
+from the sandbox (read-only check, 2026-10-26): D = 21, the three more rows
+being the defaults of its `supabase_functions` schema, so 29 entries left
+out; its other own objects (`supabase_functions`, `_realtime`) grant
+`postgres` no grant option. An entry that would still fail on the DEV dump
+stops the single transaction: exit status not 0, nothing kept, STOP. This
+backup is no full cluster backup. What it covers and what it does not:
+
+- the dump holds the whole `postgres` database: auth (accounts, identities,
+ sessions, password hashes: the files are as sensitive as DEV itself),
+ profiles, roles, assets, storage metadata, audit, the migration history and
+ the grants. It does not hold the cluster roles (created by the image), the
+ `_supabase` database (services' internal metadata), nor the Storage file
+ bytes. It holds the vault rows, but a restore as `postgres` cannot reload
+ them (left out of step 3b; it only proves anything because DEV has none,
+ step 2, and says nothing of a restore with vault rows);
+- the tar holds the Storage file bytes; restoring it is not rehearsed, and M1
+ to M3 touch neither Storage nor `assets`;
+- a restore of this dump into the DEV stack is not rehearsed: step 3b proves
+ the dump is complete and readable, not that DEV can be rolled back with it
+ (see below).
+
+After applying (read only, before anyone signs in):
+
+```bash
+pnpm supabase migration list --local # M1, M2, M3 now have their remote column; nothing pending
+cat > "$B/post.sql" <<'SQL'
+select 'workspaces ' || count(*) from public.workspaces;
+select 'members ' || count(*) from public.workspace_members;
+select 'profiles without exactly one personal workspace ' || count(*) from public.profiles p
+ where (select count(*) from public.workspaces w where w.personal_user_id = p.id) <> 1;
+select 'personal workspaces without their sole holder ' || count(*) from public.workspaces w
+ where w.kind = 'personal'
+ and ((select count(*) from public.workspace_members m where m.workspace_id = w.id) <> 1
+ or not exists (select 1 from public.workspace_members m
+ where m.workspace_id = w.id and m.user_id = w.personal_user_id and m.member_role = 'holder'));
+select 'duplicate memberships ' || count(*) from (
+ select workspace_id, user_id from public.workspace_members group by 1, 2 having count(*) > 1) d;
+select 'active species ' || count(*) from public.species where active;
+select 'species ' || string_agg(id, ',' order by sort_order) from public.species;
+select 'clients ' || count(*) from public.clients;
+select 'animals ' || count(*) from public.animals;
+select 'relations ' || count(*) from public.animal_client_relations;
+select 'rls off on V1-1 tables ' || count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = 'public' and not c.relrowsecurity
+ and c.relname in ('workspaces', 'workspace_members', 'clients', 'animals', 'animal_client_relations');
+select 'anon, service_role or PUBLIC grants on V1-1 tables ' || count(*) from information_schema.role_table_grants
+ where table_schema = 'public' and grantee in ('anon', 'service_role', 'PUBLIC')
+ and table_name in ('workspaces', 'workspace_members', 'clients', 'animals', 'animal_client_relations');
+select 'anon EXECUTE on V1-1 RPCs ' || count(*) from information_schema.role_routine_grants
+ where routine_schema = 'public' and grantee in ('anon', 'PUBLIC')
+ and routine_name in ('create_client', 'update_client', 'set_client_archived', 'search_clients',
+ 'create_animal', 'update_animal', 'set_animal_archived', 'search_animals', 'list_client_animals',
+ 'client_archive_preview', 'create_animal_client_relation', 'end_animal_client_relation',
+ 'update_animal_client_relation', 'void_animal_client_relation');
+select 'unaccent ' || count(*) from pg_extension where extname = 'unaccent';
+select 'pgtap ' || count(*) from pg_extension where extname = 'pgtap';
+SQL
+devsql postgres < "$B/post.sql"
+# workspaces N, members N, then 0, 0, 0; active species 10;
+# species equine,asinine,canine,feline,bovine,caprine,ovine,porcine,leporine,other;
+# clients 0, animals 0, relations 0; then 0, 0, 0; unaccent 1; pgtap 0
+devsql postgres < "$B/counts.sql" > "$B/counts-after.txt"; diff "$B/counts-before.txt" "$B/counts-after.txt"
+# only these lines differ (2026-10-26 values): species 1 → 10; migrations + the three V1-1 versions;
+# tables private 1 → 2, public 7 → 12; functions private 41 → 54, public 26 → 40; policies 15 → 20;
+# rls tables public 7 → 12. Every count and md5 of the existing rows is unchanged.
+pnpm db:types:check # no diff
+pnpm db:test; echo "db:test exit $?" # pgTAP 001-014, 921 assertions, exit 0 (see its effects and the 2026-10-27 run below)
+echo "select 'pgtap ' || count(*) from pg_extension where extname = 'pgtap';" | devsql postgres
+# 0, as before the run; 1 = left installed (interrupted run): report it, do not drop it by hand
+devsql postgres < "$B/counts.sql" | diff "$B/counts-after.txt" - # no diff: the tests left no row
+```
+
+Effects of the test commands on DEV, read from the installed CLI 2.120.0 and
+the scripts:
+
+- `pnpm db:test` (`supabase test db`): runs pg_prove as `postgres`; every file
+ of `supabase/tests` is one `begin … rollback`, so no row stays. It creates
+ the `pgtap` extension before the run and drops it after when it was absent
+ (DEV: absent), a transient schema change; an interrupted run can leave
+ `pgtap` installed (`post.sql` shows it). Run it before the browser
+ acceptance, with no app session open and the worker stopped (010 leases
+ the queue rows it finds until its rollback). The files share the stack with the
+ data it already holds: 007 and 010 count only their own keys, and 010
+ first leases the base's own queued work (due purge entries, avatar jobs,
+ uploads begun more than 24 h ago) inside its transaction. Assumptions that
+ stay: the avatars bucket far below its 10 GiB ceiling; fewer than about 90
+ quarantine leftovers of the base (the sweep returns at most 100, oldest
+ first); the official equine sheet still at its seeded single draft (007
+ checks the seed as delivered).
+- First run on DEV after M1 to M3 (2026-10-27, suites at `6c36e2f`): exit 1,
+ 919 assertions planned, 915 run, 914 passed. 007 stopped at its storage
+ insert (the drawing was already uploaded and confirmed on DEV: duplicate
+ key, 4 assertions never run); 010 failed « nothing is due before its grace
+ elapsed » (13 due purge entries of DEV counted). 012 to 014 (V1-1) passed;
+ data, privileges and `pgtap` (absent) identical before and after. Both
+ files were fixed on the branch (007: 20 assertions, 010: 141) and validated
+ on the sandbox, clean and with those conditions reproduced (scenarios and
+ mutations in the journal of 2026-10-27). DEV is not validated by `db:test`
+ until a run there passes.
+- `pnpm e2e:avatar`: not part of this procedure; optional, the owner's call.
+ It writes on DEV beyond its own fixture: it creates a temporary confirmed
+ account `e2e-avatar-@faunosteo.local` (and, after M1, its workspace),
+ deletes it at the end (a failed run leaves it), signs in as
+ `bob@faunosteo.local` (sessions and `last_sign_in_at` of an existing
+ account), and its worker drains every due purge-queue row and quarantine
+ leftover of the stack (13 rows on 2026-10-26). M1 to M3 touch neither
+ Storage nor `assets`; the avatar stays covered by the browser acceptance
+ below.
+
+Stop and report instead of continuing when: `migration list` shows another
+pending migration or a remote-only one; `db:types:check` before step 4 shows a
+removed line or another name than the 24 of step 1; the dump check misses a
+line; `vault.secrets` is not empty; the excluded entries differ from D + 8;
+the restore check exits other than 0, logs anything or shows a differing
+line; `migration up` applies anything else than the three V1-1 migrations
+or fails; any check after it differs from the expectation.
+
+When something fails:
+
+- backup or restore check fails: nothing was applied; fix the cause (space,
+ container, sandbox) and start again from step 2. Never apply without a
+ restore check that passed;
+- history diverges (another pending version, a remote-only version, an object
+ present without its history): stop; no `migration repair`, no hand-made
+ insert into the history. The divergence is analysed first, then resolved by
+ its own owner-validated procedure;
+- `migration up` fails: run nothing else. Read its message, then
+ `pnpm supabase migration list --local` (which of the three versions are
+ recorded) and the object query below (which objects exist; before M1: 0
+ everywhere and species 1; after M3: tables 6, types 5, functions 27,
+ trigger 1, constraint 1, unaccent 1, species 10).
+ The CLI applies the files one after the other and stops at the first
+ failure: M1 can be recorded with M2 not. Whether a failed file leaves part
+ of its statements behind was not verified on this CLI version: check the
+ objects, not only the history. Do not assume a full rollback, and do not
+ run `migration up` again before the state is understood;
+- profiles not caught up (a profile without exactly one workspace): stop;
+ `private.backfill_personal_workspaces()` is idempotent, but running it by
+ hand is a write on DEV, decided after the cause is known;
+- an RLS policy refuses a legitimate access in the browser: note the account
+ (fictitious), the screen and the time; read `pnpm db:test` and `post.sql`;
+ the fix is a new migration on the branch, tested on the sandbox first,
+ never a grant typed on DEV;
+- the generated types differ: compare with the committed file; a difference
+ means the applied schema is not the branch's: stop;
+- the browser acceptance finds a regression: record it per line, device and
+ language; the fix goes through the branch, its gates and a fresh verifier.
+
+Object query (read only), for a failed or doubtful step 4:
+
+```bash
+cat > "$B/objects.sql" <<'SQL'
+select 'tables ' || count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where (n.nspname, c.relname) in (('public', 'workspaces'), ('public', 'workspace_members'), ('public', 'clients'),
+ ('public', 'animals'), ('public', 'animal_client_relations'), ('private', 'workspace_write_budgets'));
+select 'types ' || count(*) from pg_type t join pg_namespace n on n.oid = t.typnamespace where n.nspname = 'public'
+ and t.typname in ('workspace_kind', 'workspace_member_role', 'client_kind', 'animal_sex', 'animal_relation_role');
+select 'functions ' || count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ where (n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids',
+ 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids',
+ 'consume_write_budget', 'fold_text', 'is_clean_text', 'lock_relation_for_write', 'parse_birth_year',
+ 'parse_record_date', 'utc_tomorrow'))
+ or (n.nspname = 'public' and p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients',
+ 'client_archive_preview', 'create_animal', 'update_animal', 'set_animal_archived', 'search_animals',
+ 'list_client_animals', 'create_animal_client_relation', 'end_animal_client_relation',
+ 'update_animal_client_relation', 'void_animal_client_relation'));
+select 'trigger ' || count(*) from pg_trigger where tgname = 'profiles_create_personal_workspace';
+select 'constraint ' || count(*) from pg_constraint where conname = 'audit_logs_correlation_id_format';
+select 'unaccent ' || count(*) from pg_extension where extname = 'unaccent';
+select 'species ' || count(*) from public.species;
+SQL
+devsql postgres < "$B/objects.sql"
+```
+
+Going back is a decision of its own, never a reflex. No down migration
+exists. The preferred way is forward: a new migration that corrects. A
+restore of the step 3 dump into DEV is not rehearsed: it would replace the
+`postgres` database the services use, and it loses every write made after
+the backup (accounts created or confirmed, password and profile changes,
+sessions, which would end on every device, audit rows, clients, animals and
+relations created during the acceptance, assets and purge-queue changes);
+a Storage file uploaded after the backup would remain without its row, and a
+file deleted after it would come back as a row without bytes. Rehearse it on
+the sandbox before relying on it.
+
+### 3.4 Clients (V1-1.2, migration M2)
+
+Contract: `V1-1_OWNERS_ANIMALS.md` §5.1, §8.2, §9, §10. `public.clients`
+holds the clients of a workspace; the browser reads them through RLS (members
+of the workspace, active profile, confirmed email) and writes them only
+through `create_client`, `update_client` and `set_client_archived` (security
+definer); `search_clients` (invoker, POST) searches one workspace. Refusals
+are closed codes: 42501 `not_found` (also for a foreign id), P0001
+`invalid_input`, `archived`, `conflict`, `request_conflict`, `limit_reached`,
+`rate_limited`. Writes are counted per workspace in
+`private.workspace_write_budgets` (UTC hour and day). M2 creates the
+extension `unaccent` in `extensions` (available on the CLI image and in
+PGlite 0.3.16, loaded by the harness). An account whose workspace holds a
+client can no longer be deleted (D9a); in DEV, delete its clients first from
+a privileged SQL session, or reset.
+
+### 3.5 Animals and relations (V1-1.4, migration M3)
+
+Contract: `V1-1_OWNERS_ANIMALS.md` §5.2 to §5.4, §8.3, §9, §10. M3 adds the
+species rows (`asinine` to `leporine` and `other`; `equine` unchanged; a row
+never means a sheet exists), `public.animals` and
+`public.animal_client_relations`. The browser reads them through RLS and
+writes them only through `create_animal` (with an optional first relation),
+`update_animal`, `set_animal_archived`, `create_animal_client_relation`,
+`end_animal_client_relation`, `update_animal_client_relation` and
+`void_animal_client_relation` (security definer); `search_animals`,
+`list_client_animals` and `client_archive_preview` read (invoker, POST), and
+`search_clients` now returns `current_animal_count`. A relation joins an
+animal and a client of one workspace (composite keys); it is current, ended
+(`ended_at`, `ended_on` when known) or voided (entered by mistake, kept,
+frozen, shown nowhere); it is never deleted. New refusal codes:
+`duplicate_relation`, `already_ended`. Writes share the workspace budget of
+M2. An account whose workspace holds an animal can no longer be deleted
+either (D9a): in DEV, delete its relations, animals and clients first from a
+privileged SQL session, in that order.
+
+The browser reaches these tables through `packages/supabase/src/{workspaces,clients,species,records}.ts`
+since V1-1.5 (contract §11.7) and `{animals,relations}.ts` since V1-1.6
+(§11.8). The client and animal screens run against DEV only once the owner has
+applied M1 to M3 with §3.3; until then they are developed and tested on the
+isolated stack, and no DEV acceptance is recorded.
+
+#### Browser acceptance on DEV (owner, after §3.3)
+
+A checkpoint of its own: the Playwright suites never run against DEV, so this
+is the owner's check, on `pnpm dev` (DEV origin), from a computer and a phone
+of the private network, with fictitious accounts only: `alice@faunosteo.local`
+(account A) and `bob@faunosteo.local` (account B), password of §3.2. No real
+profile is changed for a test and nothing is created outside these two
+workspaces; records carry names that say they are tests (« Recette Client
+1 »). Each journey is done in French and in English, on a computer and at
+375 px (a phone, or the browser's responsive mode); the main actions once more
+with the keyboard only (Tab, Enter, Escape in the dialogs). Results are
+recorded per line, device and language; a line not done is reported as not
+done.
+
+Sign-in and workspace:
+
+1. A signs in; the dashboard opens; Clients and Animaux open from the sidebar
+ (computer) and from the drawer (phone);
+2. A signs out and signs in again: the records of the lines below are still
+ there, after a reload too;
+3. signed out, `/app/clients` and a copied record URL lead to the sign-in
+ page, then back to that page after sign-in.
+
+Clients:
+
+4. create a client; find it by name, by city, then by phone digits; open its
+ page;
+5. edit its details (address, phone), save, reload: the values are kept;
+6. archive it (the confirmation lists its sole-owned animals), find it under
+ « Afficher les archivés », restore it.
+
+Animals and relations:
+
+7. create an animal with no client: « Propriétaire non renseigné »;
+8. from a client's page, « Ajouter un animal »: owner role chosen, back on the
+ client page with the animal;
+9. link an existing animal to a second client (co-ownership), then a
+ structure as keeper and a third client as contact: each role shows on both
+ pages; linking a client already linked in the same role is refused (no
+ second current relation);
+10. end a relation with a date: « Ancien propriétaire » on that client's page,
+ the relation under the former ones on the animal's page;
+11. correct the dates of a relation;
+12. remove a relation entered by mistake (« Erreur de saisie »): gone from
+ both pages;
+13. « Autre » with « Furet »; a birth year alone, then a full date;
+14. archive the animal, find it with the archived toggle, restore it;
+15. from the phone: find an animal, open it, the owner's `tel:` link opens the
+ dialer;
+16. Mon compte: A's photo still shows (no V1-1 change; checks the Storage path
+ after the migrations).
+
+Isolation:
+
+17. A signs out and B signs in on the same browser: no client and no animal
+ of A in the lists or the searches, not even for an instant, nor with the
+ back button;
+18. B opens a copied URL of A's client and of A's animal, then the same URL
+ with one character changed: the same « introuvable » screen each time;
+19. optional: `owner@faunosteo.local` (platform owner) sees none of A's
+ records either (no staff access in V1-1).
+
+Not covered: Safari iOS and Firefox unless such a device is used (the browser
+suites are Chromium only until V1-5); the refusal of an unconfirmed account
+(only with a fictitious unconfirmed account whose password is known, which
+means a sign-up on DEV, the owner's choice); the back and forward guard
+(accepted debt). This acceptance is no production security certification:
+RR-1 to RR-10 stay open.
+
+Run of 2026-10-27 (the owner's results; the detailed records stay outside
+Git): the 19 lines validated in French one by one; English validated as a
+whole, four lines at 375 px recorded one by one; isolation A, B and owner
+checked. Two anomalies:
+
+- RESP-01, sideways scroll at 375 px: the global scroll first seen came from
+ the browser zoom (the owner's measures without zoom: `/app` and
+ `/app/clients` at 375 and 320 px, no overflow; no other page is declared
+ conform by them). A real defect found apart, on the isolated stack: an
+ account e-mail longer than the card (from about 31 characters at 320 px)
+ widened the dashboard cards past a phone screen (implicit grid track); fixed, covered by
+ `e2e/shell/responsive.spec.ts`. Owner counter-check on the fixed code: 375 px
+ FR and EN, card readability, client list at 375 px, dashboard at 320 px,
+ console measure at 320 px (0 px overflow): six PASS. Closed, fixed.
+- AVATAR-01, a new photo ends on « Le traitement prend plus de temps que
+ prévu »: expected on DEV without a running worker (STORAGE.md §4 step 4);
+ the pipeline completes once a worker runs (reproduced on the isolated
+ stack, never on DEV). Owner decision: class A, an operating constraint
+ that does not block V1-1; the DEV worker stays stopped on purpose, Alice's
+ waiting upload is kept as is and may be processed whenever a worker is
+ started later. No V1-1 regression shown. The reload gap found on the way
+ (STORAGE.md §4 step 4) is ticket AVATAR-02, out of V1-1.
+
## 4. Writing a migration
1. `pnpm supabase migration new ` creates `supabase/migrations/_.sql`.
2. A migration that adds a table adds, in the same file: RLS enable, explicit
- `revoke all ... from public, anon, authenticated` then the exact grants,
+ `revoke all ... from public, anon, authenticated` (and `service_role` for
+ V1-1 record tables, contract N7) then the exact grants,
separate SELECT / INSERT / UPDATE / DELETE policies, indexes, comments.
3. Add or extend a pgTAP file under `supabase/tests/`: the allowed path and
every denied path (other user, anon, direct write bypassing an RPC). Scope
@@ -218,6 +772,42 @@ Two parity traps met so far: counts must be scoped to fixture ids (the real
stack carries `seed.sql` rows), and `order by` on text must pin
`collate "C"` (the real image sorts with a locale collation, PGlite with C).
+### 5.1 Isolated stack (`pnpm db:sandbox`)
+
+A throwaway Supabase stack for migration steps, so the DEV stack is never
+reset or migrated by a test (owner rule since V1-1.1). `scripts/db-sandbox.sh`
+starts the images the CLI stack uses (PostgreSQL 17.11.0.004, GoTrue v2.197.0,
+Storage v1.79.36, PostgREST v16.4, Mailpit v1.31.3, pinned in the script) on
+the network `faunosteo_dbsandbox_net`, containers `faunosteo_dbsandbox_*`,
+ports on 127.0.0.1 only and distinct from DEV (db 57432, auth 57999, rest
+57300, storage 57500, mail 57025). Nothing is mounted and the images declare
+no volume, so `down` removes the containers and the network by their literal
+names and can never reach a `supabase_*_faunosteo` volume. The password, JWT
+secret and keys are generated at each `up` into a 600 file under
+`~/.cache/faunosteo-db-sandbox` (`FAUNOSTEO_SANDBOX_DIR`, refused inside the
+repository), with 600 env files that hand them to the containers; deleted by
+`down`, never printed, never on a command line (the CLI and psql read
+`PGPASSWORD` from the environment). An incomplete secrets file stops the
+script before any CLI call, and a wrong `up` mode or version (fourteen
+digits) is refused before any container or secret exists. Works with rootless
+Docker.
+
+| Command | What it does |
+|---|---|
+| `pnpm db:sandbox up fresh` | every migration through `supabase migration up --db-url`, then the seeds of `config.toml` (as `db reset`) |
+| `pnpm db:sandbox up upgrade []` | the migrations before ``, the seeds, two GoTrue accounts (confirmed, unconfirmed), then `migration up`: the path a DEV database takes; with ``, the migrations before `` first (the workspaces count is printed), then the rest |
+| `pnpm db:sandbox test-db` | `supabase test db --db-url`: the pgTAP files on the real image (rows unchanged afterwards) |
+| `pnpm db:sandbox types [--check]` | `supabase gen types --db-url ... --schema public` through Prettier, written or diffed with the committed file |
+| `pnpm db:sandbox test` | `packages/supabase/tests/sandbox/*.sandbox.ts`: real GoTrue and PostgREST sessions, concurrent SQL sessions |
+| `pnpm db:sandbox e2e-shell` (= `pnpm e2e:shell`) | the authenticated `/app` shell in Chromium (`apps/app/e2e/shell`, `docs/development/BROWSER_TESTS.md`): a loopback dev server whose Supabase calls are replayed on the sandbox, fictitious accounts per test |
+| `pnpm db:sandbox sql` / `down` | psql as postgres on stdin / remove the stack |
+
+Every CLI call passes `--db-url` with `sslmode=disable` (the sandbox has no
+TLS); none can fall back to the local DEV database. Differences from the CLI
+stack: no Kong (GoTrue and PostgREST are called directly), no Studio, no
+realtime or edge runtime, and the database init keeps only the role
+passwords the services use.
+
How a test impersonates a user (same technique in both runners):
```sql
diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md
index 087d7cc9..0546f614 100644
--- a/docs/development/TEST_STRATEGY.md
+++ b/docs/development/TEST_STRATEGY.md
@@ -9,9 +9,43 @@ Docker sandbox; 11 pgTAP files under the flat `supabase/tests/`. The locations
`apps/app/tests/components`, `apps/app/tests/integration`, `apps/app/e2e`,
`supabase/tests/{db,rls}` and `supabase/seed/test/` in §1 and §3 are planned,
not created; the real-stack e2e lives in `packages/supabase/tests/e2e`. No
-real-browser suite exists yet (TODO RR-8; V1-1 contract §8.4 proposes the
-first one). No CI has ever run (BDR-047): "CI" in the tables means the
+real-browser suite exists yet (TODO RR-8; V1-1 contract §12.5 proposes the
+first one, decision D14). No CI has ever run (BDR-047): "CI" in the tables means the
prepared workflow.
+V1-1.1 (2026-10-25): supabase vitest 44 (config test added), 12 pgTAP files
+(`012_workspaces.sql`, 85 checks; 531 checks in all), also run on an isolated
+real stack because the DEV stack stays untouched until the owner applies M1
+(`V1-1_OWNERS_ANIMALS.md` §8.1).
+V1-1.2 (2026-10-25): supabase vitest 53 (field-limits parity test added), 13
+pgTAP files (`013_clients.sql`, 130 checks; 661 in all); the isolated stack is
+a project tool (`pnpm db:sandbox`, SUPABASE.md §5.1) with its own suite under
+`packages/supabase/tests/sandbox` (28 real-stack checks: HTTP per role,
+concurrency, budget races, 20 000-client search timing).
+V1-1.3 (2026-10-25): the first real-browser suites (D14,
+`docs/development/BROWSER_TESTS.md`): Playwright 1.64.1 with axe 4.14.0 on
+Chromium, desktop and 375 × 667, under `apps/app/e2e`. `pnpm e2e:ui` (no
+backend) 26 cases, `pnpm e2e:shell` (isolated stack) 6 cases; vitest app 458
+(Dialog and avatar confirmation wiring added).
+V1-1.4 (2026-10-26): supabase vitest 59 (animal and relation parity cases
+added), 14 pgTAP files (`014_animals_relations.sql`, 258 checks; 919 in all),
+the sandbox suites 46 real-stack checks (`animals.sandbox.ts` 18: HTTP per
+role, no lock outside the workspace, replays, relation races, caps and the
+shared budget under concurrency, D9a through GoTrue admin, read timings on
+20 000 animals), run in four migration states; 14 deliberate faults of M3
+caught (`V1-1_OWNERS_ANIMALS.md` §8.3). The axe exceptions match rule,
+selector, markup and route.
+V1-1.5 (2026-10-26): supabase vitest 92 (access layer 33); sandbox suites 54
+(`clients-access.sandbox.ts` 8: the access layer through supabase-js against
+real GoTrue and PostgREST); app vitest 509 (client screens 22, form schema 20,
+workspace and account change 7); `e2e:shell` 42 (client journeys 36, FR/EN,
+desktop and 375 px, axe). The shell suite keeps no HTML report.
+V1-1.6 (2026-10-26): supabase vitest 127 (animal and relation access 35);
+sandbox suites 61 (`animals-access.sandbox.ts` 7: the same functions against
+real GoTrue and PostgREST, replays, duplicates, end, void, archived, foreign
+ids); app vitest 566 (animal screens 35, animal form schema and display rules
+22); `e2e:shell` 82 (animal and relation journeys 40: ten journeys, FR/EN,
+desktop and 375 px, axe). Counter-checks: 12 deliberate faults caught by the
+unit suites, 2 by the browser journeys.
## 1. Layers
@@ -22,7 +56,7 @@ prepared workflow.
| Integration (app ↔ local Supabase) | vitest with `supabase start`, test users created via the admin API in a fixture | `apps/app/tests/integration` | CI job with the Supabase stack |
| Database (schema, functions, triggers) | pgTAP via `supabase test db` | `supabase/tests/db` | CI, before app tests |
| RLS | pgTAP, per table, per role | `supabase/tests/rls` | CI, release gate |
-| End-to-end | Playwright against `pnpm preview` + local Supabase | `apps/app/e2e` | CI nightly + release gate |
+| End-to-end | Playwright and axe on Chromium (desktop, 375 px) against a loopback Vite dev server: no backend (`pnpm e2e:ui`) or the isolated stack (`pnpm e2e:shell`), never DEV; request allowlist, fixture values kept out of URLs | `apps/app/e2e` (`docs/development/BROWSER_TESTS.md`) | `e2e:ui` in `pnpm check:all` when the pinned Chromium is installed (SKIPPED line otherwise); `e2e:shell` by hand with `pnpm db:sandbox up`; CI nightly + release gate planned |
| Migration | `supabase db reset` from zero + seed + regression fixtures | CI | every PR touching `supabase/` |
| PDF regression | cargo: the R4 oracles (O1 draw logs, O2 PDFs, O4 to O10) and the R4 digests of the writer's own bytes; vitest: the Step 6 goldens read back from the app export's file (`tests/helpers/pdfFile.ts`, no pdf-lib), the attachment roundtrip through the module's reader, the N-1 readers | `crates/core/tests/pdf_*.rs`, `apps/app/tests/unit/pdf.*.test.ts`, `packages/core-wasm/tests/pdf-*.test.ts` | CI |
| SQL/TS contract | generated types diff check | CI | every PR touching `supabase/` |
diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md
index 817d7d0f..b908134f 100644
--- a/docs/development/V1-1_OWNERS_ANIMALS.md
+++ b/docs/development/V1-1_OWNERS_ANIMALS.md
@@ -1,35 +1,52 @@
-# V1-1 Clients and animals: functional contract
+# V1-1 Clients and animals: contract
-Status: proposal, 2026-10-25, revised the same day with the owner's
-orientations (brief « P0 : arbitrages documentaires et finalisation du contrat
-V1-1 »). Nothing is implemented and nothing is authorised: no migration,
-table, RPC, RLS policy, component or route exists or may be created for this
-step until the owner ratifies the orientations of §9.1 and answers §9.2. The
-orientations are recorded as proposed, not ratified. Roadmap position:
-`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also
-lays the permission frame of Step 10. The file name keeps "OWNERS" so the
-documents that cite it keep working.
+Status: business decisions approved by the owner on 2026-10-25 (brief « V1-1 :
+ratification des décisions métier et préparation de l'implémentation »,
+BDR-073). The architecture of Parts 4 to 9 and the technical choices N1 to N9
+were validated by the owner the same day (brief « Validation du contrat V1-1
+et autorisation de V1-1.1 Workspaces », BDR-074, §13.2), with the precisions
+written into §5.3, §9 and §10. The interface choices of §13.3 stay proposals
+until their UI steps. V1-1.1 was validated by the owner on 2026-10-25 (brief
+« Validation V1-1.1 et autorisation V1-1.2 Données clients », BDR-075), which
+authorised V1-1.2. V1-1.2 and V1-1.3 were validated on 2026-10-25 and
+2026-10-26 (BDR-076; brief « Validation V1-1.3 et autorisation V1-1.4
+Animaux et relations », BDR-077), which authorised V1-1.4. Migrations M1
+(§8.1), M2 (§8.2) and M3 (§8.3) are written and tested on the isolated stack
+(`pnpm db:sandbox`, SUPABASE.md §5.1); none is applied to Supabase DEV (owner
+procedure: SUPABASE.md §3.3). V1-1.4 was validated on 2026-10-26 (brief
+« Validation V1-1.4 et autorisation V1-1.5 Interface Clients »), which
+authorised the client screens of V1-1.5 (§11.7), built and tested on the
+isolated stack. V1-1.5 was validated on 2026-10-26 (brief « Validation V1-1.5
+et autorisation V1-1.6 Interface Animaux et clôture »), which authorised the
+animal screens and the relations of V1-1.6 (§11.8), built and tested on the
+isolated stack, and the closure inventory (§15).
+Branch: `feature/v1-1-clients-animals`. Roadmap position:
+`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays
+the permission frame of Step 10. The file name keeps "OWNERS" so the documents
+that cite it keep working.
-Part 1 states the facts. Parts 2 to 7 are the proposed contract. Part 8 lists
-the tests and the Definition of Done. Part 9 lists the orientations, the
-sub-choices they leave, and the decisions still open.
+Parts: 1 facts, 2 scope, 3 nomenclature, 4 workspaces, 5 entities,
+6 permissions, 7 archive, deletion and data protection, 8 SQL schema,
+9 policies, helpers and RPCs, 10 technical limits, 11 screens and journeys,
+12 tests and Definition of Done, 13 decisions, 14 implementation steps and
+risks, 15 closure inventory.
---
## 1. Facts the contract rests on
-| Area | State on `develop` (0c54e4b) |
+| Area | State on `develop` (5502617) |
|---|---|
| Client and animal data | Text inside a bilan only: report v3 `owner = { name }`, `animal = { speciesId, name, breed?, age? }` (`crates/core/src/domain/report/identity.rs`). No table. |
-| Species | `public.species` (`id` slug, `name_fr`, `name_en`, `sort_order`, `active`), one row `equine` / Cheval / Horse; SELECT for `authenticated` on active rows; no API write path. |
-| Anatomical sheets | Only the equine DRAFT exists, unpublished until business review (BDR-034, BDR-037). Its content changes only through `curation/changes.json` and the Rust pipeline until plan Step 17 (owner, 2026-10-25). |
-| Accounts | Email/password sign-up, `enable_confirmations = true` (no session before the email is confirmed), `profiles.active` switched by staff only, `private.require_actor()` refuses a missing or deactivated actor. |
+| Species | `public.species` (`id` slug, `name_fr`, `name_en`, `sort_order`, `active`), one row `equine` / Cheval / Horse; SELECT for `authenticated` on active rows; no API write path. The application never reads this table (the editor uses the bundled sheet). |
+| Anatomical sheets | Only the equine DRAFT exists, unpublished until business review (BDR-034, BDR-037). Its content changes only through `curation/changes.json` and the Rust pipeline until plan Step 17. |
+| Accounts | Email/password sign-up, `enable_confirmations = true` (no session before the email is confirmed, `auth.users.email_confirmed_at`), anonymous sign-in disabled, `profiles.active` switched by staff only, `private.require_actor()` refuses a missing or deactivated actor. |
| Roles | `platform_role` = owner, admin, moderator, support (BDR-026). No professional status and no cabinet table exist. |
-| Audit | `audit.audit_logs` append-only, written by `private.log_event()`, action format `domain.verb`. |
-| Files | `client-files` and `animal-files` buckets exist, closed (row only, no policy). |
+| Audit | `audit.audit_logs` append-only, written by `private.log_event()`, action format `domain.verb`; platform owners and admins read every row (`audit_logs_select_admin`). |
+| Files | `client-files` and `animal-files` buckets exist, closed (row only, no policy). `assets.owner_id` is the account that owns a file (Step 8). |
| UI | `/app` shell (sidebar, drawer, top bar), `Dashboard`, `Account`. The validated mockup (`docs/design/`) shows Clients and Animaux sidebar entries and a mobile tab bar Accueil / Bilans / Agenda / Profil. The shared `Dialog` has no focus trap or focus restore (RR-7). |
-| Form validation | D-R7: form constraints stay TypeScript (Zod schemas returning i18n keys); a constants module is checked against `pg_constraint` by a PGlite test. The SQL CHECK is the server boundary. The 2026-10-25 inventory put V1-1 validation in `crates/core`: that contradicted D-R7 and is withdrawn here (EVAL-034). |
-| Tests | pgTAP on PGlite and on the real stack; real-stack e2e pattern in `packages/supabase/tests/e2e`; no real-browser test runner in the repository (RR-8). |
+| Form validation | D-R7: form constraints stay TypeScript (Zod schemas returning i18n keys); the SQL CHECK is the server boundary; a constants module checked against `pg_constraint` by a PGlite test is planned (TODO chore D-R7), none exists yet. |
+| Tests | pgTAP on PGlite (0.3.16, which ships `unaccent` and `pg_trgm` as contrib; the harness loads only pgTAP today) and on the real stack; real-stack e2e pattern in `packages/supabase/tests/e2e`; no real-browser test runner (RR-8). |
---
@@ -37,460 +54,1571 @@ sub-choices they leave, and the decisions still open.
In V1-1, a signed-in practitioner with a confirmed email:
-1. creates, edits, lists, searches, archives and restores clients, persons
- and organisations;
-2. creates, edits, lists, searches, archives and restores animals, each
- linked to zero, one or several clients with a role per link;
-3. sees a client's animals and an animal's clients, current and former;
+1. creates, edits, lists, searches, archives and restores clients, persons and
+ structures;
+2. creates, edits, lists, searches, archives and restores animals, each linked
+ to zero, one or several clients with a role per link;
+3. sees a client's animals and an animal's clients, current and former, and
+ records a change of owner or keeper without losing the history;
4. does all of it on a phone (375 px wide) and on a computer, in French and
English, with the keyboard alone and with a screen reader.
-Out of scope, each named so nobody builds it early: cabinet creation and
-membership management, sharing between practitioners, client portal and
-client accounts, any directory or matching across practitioners, consent
-records, photos, weight and files, imports (CSV, PDF), notifications, any
-link with bilans (V1-3), account closure, deletion, anonymisation and export
-(D9), quotas and billing, the professional verification process (plan Step
-9), any staff access to the records (D16), any editing of the anatomical
-reference. The local tool and the bilan format do not change; annotating a
-bilan never changes `curation/changes.json`.
+Out of scope, each named so nobody builds it early: cabinet creation,
+membership management and invitations, sharing between practitioners, client
+portal and client accounts, any directory or matching across practitioners,
+consent records, animal weight, photo, detailed identification, coat colour,
+neutering status, date of death and notes (D6, deferred), client notes
+(§13.2 N3), files, imports (CSV, PDF), notifications, any link with bilans
+(V1-3), account closure, deletion, anonymisation and export (D9), quotas and
+billing, the professional verification process (plan Step 9), any staff
+access to the records (D16), any editing of the anatomical reference. The local
+tool and the bilan format do not change; annotating a bilan never changes
+`curation/changes.json`.
---
-## 3. Workspaces and the future cabinets (D2, C4)
+## 3. Nomenclature
-Orientation D2 / C4: records belong to a workspace. In V1-1 each practitioner
-has one personal workspace. There is no global directory of clients shared
-between practitioners. Multi-practitioner cabinets come later and are not
-built in V1-1.
+Owner requirement: one explicit name per concept, the same in SQL, in the
+generated TypeScript types and in the documents. The generated types carry the
+SQL names unchanged; TypeScript variables follow them (`relationRole`,
+`memberRole`, `platformRole`, never a bare `role` or `owner`).
-| Table | V1-1 content | Later |
+| Concept | SQL | UI (FR / EN) |
|---|---|---|
-| `workspaces` | `id`, `kind` (`personal` only), `created_at`; one personal workspace per profile, created with the profile (trigger + backfill of existing profiles) | `kind = cabinet`, name, logo: the plan's Step 10 builds cabinets as workspaces instead of a separate `organizations` table |
-| `workspace_members` | `workspace_id`, `user_id`, `role` (`owner` only) | roles `manager`, `practitioner`, `secretary` added with the cabinet step |
+| Perimeter that owns and isolates records | table `workspaces`; column `workspace_id` on every record table | not shown in V1-1 |
+| Kind of workspace | `workspaces.kind`, enum `workspace_kind`: `personal` (`cabinet` added by the cabinet step) | espace personnel / personal workspace |
+| Account whose personal workspace it is | `workspaces.personal_user_id` (unique, null for a future cabinet) | not shown |
+| Membership and rights of a member | table `workspace_members` (`workspace_id`, `user_id`, `member_role`), enum `workspace_member_role`: `holder` in V1-1 | titulaire / holder |
+| Responsible of a workspace | personal workspace: the account of `personal_user_id`, its only member, with `member_role = holder`; cabinet: defined by the cabinet step (Step 10) | not shown |
+| Technical platform role | enum `platform_role` (`owner`, `admin`, `moderator`, `support`), table `profile_roles` (existing, BDR-026) | not shown |
+| Client | table `clients`, `client_id`; enum `client_kind`: `person`, `organization` | client: personne, structure / client: person, organization |
+| Animal | table `animals`, `animal_id`; enum `animal_sex`: `male`, `female`, `unknown` | animal: mâle, femelle, inconnu / animal: male, female, unknown |
+| Relation between a client and an animal | table `animal_client_relations`; column `relation_role`, enum `animal_relation_role`: `owner`, `keeper`, `contact` | propriétaire, détenteur, contact / owner, keeper, contact |
+| File owner (existing, Step 8) | `assets.owner_id` | not reused by V1-1 |
-One helper answers every access question: the caller's role in a workspace,
-null when the caller is not a member or the profile is inactive. Policies and
-RPCs never test `user_id = auth.uid()` on the record itself, so the cabinet step
-adds members, not new policies on every table.
+Rules:
-Why not a plain `owner_user_id` column: it is simpler today, but every policy
-and helper of clients, animals and later bilans would need a second branch for
-cabinets, and moving a practitioner's records into a cabinet would rewrite
-ownership columns. The workspace costs two small tables now.
-
-Record placement is explicit: the browser sends the target workspace on
-create and the server checks the caller's role in it. In V1-1 the app always
-sends the personal workspace.
+- `owner` exists as `platform_role.owner` (the Faunosteo platform owner) and as
+ `animal_relation_role.owner` (the owner of an animal). It is never a
+ workspace member role: the person responsible for a personal workspace is its
+ `holder`.
+- No record table (`clients`, `animals`, `animal_client_relations`) has an
+ `owner_id`, `user_id` or `created_by` column. Placement is `workspace_id`;
+ authorship lives in the audit log.
+- Future client or animal files are placed by workspace, never by
+ `assets.owner_id`.
+- The schema↔types test pins every name of this table.
---
-## 4. Entities and fields
+## 4. Workspaces (D2 / C4, approved)
-Vocabulary (orientation D1): the interface says « Clients » (English
-"Clients") and the code entity is `clients`. A client is the person or the
-structure the practitioner deals with. Its relation to an animal carries a
-role: `owner` (Propriétaire), `keeper` (Détenteur, for example the stable that
-boards the horse) or `contact` (Contact). The entity and the role are never
-merged: the same client can own one horse and keep another.
+Clients and animals belong to a workspace. In V1-1 each account has exactly one
+personal workspace, created automatically. There is no global directory of
+clients shared between practitioners, no data visible from one practitioner to
+another, and no sharing between practitioners of a cabinet. Invitations and
+cabinet permissions are not built.
-### 4.1 Client
+- Creation: a controlled server initialisation, never a client call. A
+ trigger after insert on `profiles` creates the personal workspace and its
+ `holder` membership in the transaction that creates the account (GoTrue
+ inserts `auth.users`, `private.handle_new_auth_user` inserts the profile,
+ the trigger creates the workspace): a failure anywhere rolls back the whole
+ sign-up, so no account exists without its workspace and no workspace
+ without its account. The workspace exists before the email is confirmed and
+ stays unreadable until then (§9.1). The migration backfills existing
+ profiles through the same write path.
+- Uniqueness: `personal_user_id` is unique, so an account never has two
+ personal workspaces. The single write path inserts with `on conflict do
+ nothing` on that key: a retry, a replay or two concurrent calls create one
+ workspace and one membership, never two (§8.1).
+- Consistency: a personal workspace has exactly one member, its account, as
+ `holder`. A deferred constraint trigger checks it at commit, whatever role
+ writes, so neither row survives alone and no other account can be added.
+- Deletion: no archive state for a workspace. A personal workspace follows its
+ account: deleting an empty account deletes it; from M2 on, records refuse
+ the deletion (D9a, §7.2).
+- Context: every read and write names its workspace (RPC parameter or filter).
+ The app reads its personal workspace once after sign-in and passes its id
+ explicitly to the access layer; nothing reads a global "current workspace"
+ (plan Step 10 risk: context leakage).
+- Policies and RPCs never compare `auth.uid()` with a column of the record:
+ they ask the workspace helpers (§9.1). The cabinet step adds members and
+ roles, not new policies on every table.
+- Evolution without destructive transfer: a cabinet is a workspace of kind
+ `cabinet`. Either a practitioner's workspace gains members and changes kind
+ (no record moves), or a later step moves the records of one workspace to
+ another in one transaction (the composite keys of §8 can then be made
+ deferrable with `ALTER CONSTRAINT`). Records never belong to a user column,
+ so neither path rewrites ownership. The first path leaves the practitioner
+ without a personal workspace (`personal_user_id` is null on a cabinet), so
+ it must also create a new one for them; the cabinet step chooses.
+
+Why not an `owner_user_id` column: every policy of clients, animals and later
+bilans would need a second branch for cabinets, and attaching a practitioner's
+records to a cabinet would rewrite ownership columns. The workspace costs two
+small tables now.
+
+---
+
+## 5. Entities and fields
+
+Text rule for every text column: no leading or trailing space, no control
+character, never an empty string (an absent value is `null`). The control set
+is written as explicit ranges, the same literal in SQL and in TypeScript
+(U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029), because `[[:cntrl:]]`
+differs between the C libraries of PGlite and of the real stack. SQL checks
+U+0020 at both ends (`btrim`); the form trims all Unicode whitespace before
+sending, which only ever sends values SQL accepts. Lengths count characters
+as PostgreSQL's `char_length` does (code points); §12.2 states how TypeScript
+counts the same. Email pattern, shared by SQL and TypeScript:
+`^[^@\s]+@[^@\s]+\.[^@\s]+$` on the lower-cased value. Country codes come from
+a committed ISO 3166-1 alpha-2 list; their FR and EN labels from
+`Intl.DisplayNames` (no dependency).
+
+### 5.1 Client (D3, D4, D4a, approved)
| Field | Rule | Required |
|---|---|---|
-| `kind` | `person` (personne physique) or `organisation` (structure: écurie, haras, association, entreprise or another legal entity); defaults to `person` | column always set, nothing to type (D3) |
-| `display_name` | person: the name as the practitioner writes it (« Marie Dupont »); organisation: its name (« Écurie du Lac »); 1 to 120 characters | yes, the only required input (D4) |
-| `email` | practical address format, at most 254 characters, stored lower-case | no |
-| `phone` | E.164 like `profiles.phone`; French national input (`06 12 34 56 78`) normalised to `+33…` on submit | no |
-| `address_line1`, `address_line2`, `postal_code`, `city` | at most 120 / 120 / 16 / 80 characters, no postal format check (Belgium, Switzerland) | no |
-| `country` | ISO 3166-1 alpha-2; no SQL default, the form proposes France | no |
-| `notes` | private to the workspace, at most 4 000 characters | no |
-| `archived_at`, `archived_by` | set by the archive RPC only | n/a |
+| `kind` | `person` (personne physique) or `organization` (structure: écurie, haras, association, entreprise, other legal entity); the form shows both with « Personne » visibly selected | yes |
+| `display_name` | person: the name as the practitioner writes it (« Marie Dupont », « Mme Dupont »); organization: its name (« Écurie du Lac »); the label follows the kind: « Nom affiché » or « Dénomination »; 1 to 120 characters | yes, the only required text |
+| `email` | practical format, at most 254 characters, stored lower-case, not unique | no |
+| `phone` | E.164 like `profiles.phone`; entry rule §11.3 | no |
+| `address_line1`, `address_line2` | at most 120 characters each | no |
+| `postal_code` | at most 16 characters, no format check (Belgium, Switzerland) | no |
+| `city` | at most 80 characters | no |
+| `country` | ISO 3166-1 alpha-2, upper-case; no default in SQL or in the form: empty until the practitioner picks one | no |
+| `revision`, `archived_at`, `created_at`, `updated_at` | server-maintained | n/a |
-Every text field is trimmed, refuses control characters and is never empty
-when present. No uniqueness on email or phone: two clients may share a
-household address or phone. Contact details are optional at creation (D4):
-what a booking, an invoice or a regulated document requires is set by the
-step that introduces it, never by a NOT NULL here.
+No uniqueness on email or phone: two clients may share a household address or
+phone. Contact details are optional at creation; what a booking, an invoice or
+a regulated document requires is set by the step that introduces it, never by
+a NOT NULL here. Changed from the proposal: `notes` is not in V1-1 (§13.2 N3)
+and `archived_by` is dropped (the audit log records who archived; a cabinet
+step adds the column if a screen shows it).
-### 4.2 Animal
+Name rule (D4a): `display_name` is the single reference for display, search,
+sorting and documents. V1-1 stores no separate first and last name
+(recommendation §13.2 N2). If a later step adds optional `given_name` and
+`family_name` for persons, the rule is priority, not synchronisation:
+`display_name` stays required and wins wherever a name is shown; the parts are
+optional complements read only where a step requires them (a formal invoice
+heading, a sort by family name); an organization never carries them (CHECK);
+the server never derives one representation from the other; the form proposes
+`display_name` from the parts only while `display_name` is empty and never
+rewrites it afterwards.
+
+### 5.2 Animal (D5, D6, D6a, D6b, approved)
| Field | Rule | Required |
|---|---|---|
-| `species_id` | an active row of `species` (§4.4) | yes (D5) |
-| `species_detail` | free text, 1 to 80 characters, required with `other` and refused with any other species | if `other` (D5) |
-| `name` | 1 to 80 characters | yes (D6) |
-| `sex` | `male`, `female`, `unknown`; defaults to `unknown` | column always set, nothing to type (D6) |
-| `breed` | free text, at most 80 characters (no breed list in V1-1) | no |
-| `birth_year` | four-digit year, not in the future | no |
-| `birth_date` | the full date, only when it is known; not in the future; when present, `birth_year` equals its year (CHECK) | no |
-| `neutered` | `yes`, `no`, `unknown`; together with `sex` it gives stallion, gelding, mare in the equine UI | no, proposal (D6a) |
-| `identification` | microchip, UELN, tattoo: at most 64 characters, letters, digits, spaces and hyphens, stored upper-case; no per-species format check | no, proposal (D6a) |
-| `colour` | at most 80 characters | no, proposal (D6a) |
-| `notes` | private to the workspace, at most 4 000 characters | no, proposal (D6a) |
-| `deceased_on` | date not in the future; a deceased animal stays readable and is never archived implicitly | no, proposal (D6a) |
-| `archived_at`, `archived_by` | archive RPC only | n/a |
+| `name` | 1 to 80 characters | yes |
+| `species_id` | an active row of `species` (§5.4) | yes |
+| `species_detail` | 1 to 80 characters; required when `species_id = 'other'`, refused with any other species | with « Autre » |
+| `sex` | `male`, `female` or `unknown`; no default: the practitioner picks one, « Inconnu » included (§13.2 N8) | yes |
+| `breed` | free text, at most 80 characters (no breed list) | no |
+| `birth_year` | 1900 to the year of tomorrow's UTC date (same tolerance as the dates, §9.3) | no |
+| `birth_date` | the full date, only when known; not in the future; requires `birth_year` equal to its year | no |
+| `revision`, `archived_at`, `created_at`, `updated_at` | server-maintained | n/a |
-A year alone never becomes a date: an animal born « in 2015 » has
-`birth_year = 2015` and no `birth_date`, never a stored 1 January (D6, D6b).
-Deferred to a later step (D6): weight (it belongs to a visit, not to the
-animal) and photo (it needs the `animal-files` rules and a worker job). The
-fields marked « proposal » go beyond the owner's list of 2026-10-25; the
-owner keeps or drops each before the migration (D6a).
+Birth representation (D6b): each state has one meaning, and a year never
+becomes a date.
-### 4.3 Client and animal relation
+| `birth_year` | `birth_date` | Meaning |
+|---|---|---|
+| null | null | birth unknown |
+| 2015 | null | born in 2015, day unknown |
+| 2015 | 2015-04-12 | born on 12 April 2015 |
+| null | 2015-04-12 | refused (CHECK) |
+| 2016 | 2015-04-12 | refused (CHECK) |
-Table `animal_clients` (orientation D7): `animal_id`, `client_id`, `role`
-(`owner`, `keeper`, `contact`), `created_at`, `ended_at`. Rules:
+The year of a full date is stored again in `birth_year`, so sorting and
+filtering by year read one column. The age shown is computed for display only:
+from the date when present, else « environ N ans » from the year.
-- many-to-many: an animal links to several clients and a client to several
- animals, each link with its role; co-ownership is several `owner` links,
- and owner and keeper are distinct links;
-- client and animal belong to the same workspace (composite foreign keys on
- `(workspace_id, id)`);
-- one current row per (animal, client, role) (partial unique index on rows
- with no `ended_at`);
-- no owner is required: an animal may have no current `owner` link, because
- the owner is unknown or not entered yet. No SQL constraint and no RPC
- refuses it, and the app never creates a placeholder client; it shows
- « Propriétaire non renseigné ». Whether a business operation (bilan,
- invoice, sharing) later requires an owner is decided by the step that
- introduces the operation;
-- ending a relation (horse sold, keeper changed) sets `ended_at`; the row
- stays as history and the former owner or keeper is shown as such (D7a,
- historical relations kept under D8).
+Deferred to a later step (D6), each one an additive nullable column when its
+step needs it: weight (it belongs to a visit), photo (it needs the
+`animal-files` rules and a worker job), detailed identification (microchip,
+UELN, tattoo), coat colour, neutering status, date of death, general notes. No
+complete veterinary record is created.
-### 4.4 Species
+### 5.3 Client and animal relation (D7, D7a, approved)
-The species list is reference data written by migration (orientation D5):
-the nine species of this contract's first version, horse (the existing row
-`equine`), donkey, dog, cat, cattle, goat, sheep, pig and rabbit, plus
-« Autre » (`other`) with its required `species_detail`. No other species is
-added. The slugs of the new rows follow the format of the `equine` row and are
-fixed with the migration.
+Table `animal_client_relations`:
-A species carries no anatomical sheet by itself: an animal of any listed
-species can be recorded while no usable sheet exists for it (today only the
-equine draft exists), and nothing links a species to a sheet automatically.
-V1-1 shows no sheet information; V1-3 decides what a bilan does for an animal
-whose species has no sheet.
+| Field | Rule |
+|---|---|
+| `animal_id`, `client_id` | same workspace, enforced by composite foreign keys |
+| `relation_role` | `owner`, `keeper` or `contact` |
+| `started_on` | date the relation began, when known; null when unknown; never filled by default |
+| `ended_at` | null while the relation is current; set to the recording time when the end is recorded (§13.2 N5); a technical time, never shown as the end date |
+| `ended_on` | date the relation ended, when known; only on an ended relation; not before `started_on` |
+| `voided_at` | null for a relation that existed; set when a relation entered by mistake is voided (§13.2 N4) |
+| `revision`, `created_at`, `updated_at` | server-maintained |
+
+Rules:
+
+- many-to-many, one role per relation: co-ownership is several current `owner`
+ relations; owner and keeper are separate relations; the same client may hold
+ two roles for one animal (an owner who keeps the horse at home);
+- an animal may have no owner because the owner is unknown or not entered yet;
+ no SQL constraint and no RPC refuses it, the app never creates a placeholder
+ client and shows « Propriétaire non renseigné »; whether a later business
+ operation (bilan, invoice, sharing) needs an owner is decided by the step
+ that introduces it;
+- an animal always belongs to one valid workspace, with or without relations;
+- client and animal of a relation are always in the same workspace: the
+ composite foreign keys make any other row impossible, whatever writes it;
+- at most one current relation per (animal, client, role): a partial unique
+ index on rows with no `ended_at`; successive relations of the same triple are
+ allowed once the previous one has ended;
+- historical periods may overlap (dates are optional and approximate): no
+ constraint on overlaps;
+- `animal_id`, `client_id` and `relation_role` never change after creation;
+ dates can be corrected;
+- change of owner or keeper: add the relation of the new client, then end the
+ previous one with its end date when known. Both rows stay; the former owner
+ keeps their other animals and appears as « ancien propriétaire » on the
+ animal's page. Between the two actions the animal has two current owners or
+ none, two valid states, so no atomic transfer operation is needed;
+- ending is not deleting: an ended relation stays readable as a former
+ relation, with its dates;
+- voiding is not ending (N4): a relation that never existed (wrong client,
+ wrong animal, wrong role) is voided, never ended, so it never appears as a
+ former owner or keeper and no end date is invented for a period that never
+ was. The row keeps every value as entered, gains `voided_at`, and becomes
+ frozen (no end, no date change, no un-voiding); the audit log records who
+ voided it and when (§9.3). Voided relations are left out of every list, of
+ the current-relation index, of the derived values (§9.3) and of the current
+ cap; they count in the 200 total per animal, so a create-and-void loop
+ cannot grow a table without bound. No V1-1 screen shows them; the row stays
+ for the lifecycle contract (export, erasure) and incident work;
+- an end recorded on the wrong relation is voided like any wrong relation,
+ then the right one is created. An end recorded with a wrong date is
+ corrected by `update_animal_client_relation`. Re-opening a relation whose
+ end never happened (clearing `ended_at`) is not offered in V1-1: the
+ relation is voided and created again as current, with the same start date;
+ the owner may ask for an explicit reopening at V1-1.4.
+
+Date rules (N5), all enforced by SQL CHECK except « not in the future »,
+which needs the clock and is checked by the RPCs (tomorrow's UTC date, §9.3):
+
+| Constraint | SQL |
+|---|---|
+| dates optional, no default | `started_on date`, `ended_on date`, both nullable, no `default` |
+| plausible lower bound | `started_on >= '1900-01-01'`, `ended_on >= '1900-01-01'` |
+| an end date only on an ended relation | `ended_on is null or ended_at is not null` |
+| order when both are known | `started_on is null or ended_on is null or started_on <= ended_on` |
+| a voided relation keeps its state | `voided_at` set only by the void RPC; every other write RPC refuses a voided row (`invalid_input`) |
+| one current relation per triple | unique index on `(animal_id, client_id, relation_role) where ended_at is null and voided_at is null` |
+
+### 5.4 Species (D5, approved)
+
+Reference data written by migration: the nine species of the contract (the
+existing `equine` row plus eight) and « Autre ». No other species is added.
+Slugs, names and order approved by the owner (§13.2 N1). Compatibility,
+checked on 2026-10-25: species are rows of `public.species` (text `id`,
+CHECK `^[a-z0-9][a-z0-9_-]{0,63}$`, which every slug below satisfies), never a
+SQL enum, so M3 adds rows and freezes no new enumeration; the Rust core
+carries `species_id` / `speciesId` as a free string (report identity, sheet
+document, snapshot, sheet index) with no species list, and the only existing
+id, `equine`, is kept unchanged:
+
+| `id` | `name_fr` | `name_en` | `sort_order` |
+|---|---|---|---|
+| `equine` (existing) | Cheval | Horse | 10 |
+| `asinine` | Âne | Donkey | 20 |
+| `canine` | Chien | Dog | 30 |
+| `feline` | Chat | Cat | 40 |
+| `bovine` | Bovin | Cattle | 50 |
+| `caprine` | Chèvre | Goat | 60 |
+| `ovine` | Mouton | Sheep | 70 |
+| `porcine` | Porc | Pig | 80 |
+| `leporine` | Lapin | Rabbit | 90 |
+| `other` | Autre | Other | 1000 |
+
+A recordable species does not mean an anatomical sheet exists. Only the equine
+content exists, as an unpublished draft, and nothing in V1-1 publishes it or
+links a species to a sheet. V1-1 shows no sheet information; V1-3 decides what
+a bilan does for an animal whose species has no sheet. The migration updates
+the table comment (« species of animals and of anatomical sheets »). A sheet
+for `other` makes no sense; the sheet RPCs are platform-admin only and V1-2
+adds the refusal if it opens sheet creation.
---
-## 5. Permissions
+## 6. Permissions
-### 5.1 Matrix
+### 6.1 Matrix (C5, D16, approved)
| Actor | Read | Create | Edit | Archive / restore | Delete |
|---|---|---|---|---|---|
-| Workspace member with role `owner` (V1-1: the practitioner in their personal workspace) | yes | yes | yes, active records only | yes | no (§6) |
-| Future cabinet roles `manager`, `practitioner`, `secretary` | per the cabinet step | per the cabinet step | per the cabinet step | per the cabinet step | no |
+| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no; a relation entered by mistake is voided, never deleted (§13.2 N4) |
+| Future cabinet roles | defined by the cabinet step | | | | |
+| The same account with an unconfirmed email | no | no | no | no | no |
| Another signed-in account | no | no | no | no | no |
| Platform owner, admin, moderator, support | no | no | no | no | no |
| Deactivated profile | no | no | no | no | no |
| Anonymous | no | no | no | no | no |
+| Service key (`service_role`: worker, operator scripts) | no table privilege (§13.2 N7) | no | no | no | no |
-Orientation C5: writes belong to the members who hold a write right in the
-workspace concerned. In V1-1 that is only the practitioner who owns the
-personal workspace. Future cabinets may add permissions (business
-architecture §2.2: a secretary manages customers and animals); the helper's
-shape allows them, and they are built with the cabinet step.
+C5: writes belong to the members who hold a write right in the workspace
+concerned; in V1-1 that is only the holder of the personal workspace. Future
+cabinet roles (business architecture §2.2: a secretary manages customers and
+animals) plug into the helpers of §9.1 and are built with the cabinet step.
-Orientation D16: Faunosteo staff have no ordinary business access to private
-records. No platform role (owner, admin, moderator, support) reads or writes
-clients, animals or bilans through a policy or an RPC, and no admin screen
-lists or opens them. That rule is distinct from exceptional privileged
-technical operations (database maintenance, backup restore, incident response
-through the service key or a database superuser): those exist by construction
-of the hosting, and before any publication a separate contract frames,
-justifies and audits them. V1-1 creates no exceptional access mechanism (no
-impersonation, no break-glass RPC), and no worker job reads these tables.
+### 6.2 Email, verification and platform roles (C6, approved)
-### 5.2 Verification (C6)
+| Notion | Where it lives | Effect in V1-1 |
+|---|---|---|
+| Email confirmed | `auth.users.email_confirmed_at`, set by GoTrue | required for every V1-1 read and write. GoTrue gives no session before confirmation, and the workspace helpers check the column again in SQL. Limit: with `enable_confirmations` off, GoTrue stamps the column at sign-up, so the SQL check proves only that GoTrue considers the address confirmed; a config test pins `enable_confirmations = true`. A GoTrue ban (`banned_until`) does not end an issued token before it expires (`jwt_expiry` 3 600 s); `profiles.active = false` cuts access at the next request |
+| Professional status verified | plan Step 9, not built; no column exists | none; never granted by default; required later by public features that present an account as a verified practitioner (public profile, community publication, booking) |
+| Platform role | `profile_roles`, `platform_role` | none: it grants no access to clients, animals or bilans (D16) |
-Orientation C6: email confirmation and professional verification are two
-distinct things. An account with a confirmed email has private use of the
-application, within the permissions and features available: V1-1 is open to
-any active account with a session (GoTrue gives no session before
-confirmation). Professional verification (plan Step 9; BDR-041 said Step 11,
-corrected by BDR-072) is required for the public features that present a
-practitioner as a verified professional (public profile, community
-publication, booking); it is not built in V1-1 and does not gate it.
Professional statuses (practitioner, student, professor) come from
-verification and are never platform roles (BDR-026).
+verification and are never platform roles (BDR-026). BDR-041 said Step 11 for
+verification; BDR-072 corrects it to Step 9.
-### 5.3 Edits and finished bilans (C5)
+### 6.3 Platform staff (D16, approved)
+
+Faunosteo staff have no ordinary right to read clients, animals or bilans. No
+policy or RPC has a platform-role branch, no admin screen lists or opens these
+records, and V1-1 builds no impersonation, support access or break-glass
+mechanism. No worker job reads these tables.
+
+Residual technical paths, named so nobody believes them closed:
+
+- the service key gets no table or RPC privilege on V1-1 (§13.2 N7), but it is
+ also the GoTrue admin key: its holder can generate a magic link or set a
+ password for any account and then read that workspace as its practitioner,
+ leaving no trace in the application. The worker and the operator scripts
+ hold it. The service key and the JWT secret are therefore full-access
+ credentials, bounded only by their custody; the exceptional-access contract
+ covers them, with two follow-ups in §14 (a narrower worker credential,
+ monitoring of GoTrue admin actions in `auth.audit_log_entries`);
+- the table owner (`postgres`, not a superuser on Supabase, but holding
+ `BYPASSRLS` on the Supabase image, checked on 17.11.0.004) and any database
+ superuser read past RLS: maintenance, backup restore and incident response
+ are exceptional privileged operations that the separate contract frames,
+ justifies and audits before any publication.
+
+Both paths were exercised on the isolated stack of V1-1.1 (§8.1): the service
+key reads nothing through PostgREST (`permission denied`), yet it obtains a
+session for any account through GoTrue's admin link generation and then reads
+that account's workspace like its practitioner. Removing table privileges
+narrows the direct path only; the residual risk stays on the security track
+before production (RR-4), as the owner required (N7).
+
+The existing audit policy lets platform owners and admins read audit rows. The
+V1-1 rows carry the actor, the resource id, the action, the time and the
+workspace id. Read with the staff policy on profiles, that would reveal
+per-practitioner volumes, working hours and events such as « relation ended »:
+activity metadata, never names or contacts. N9 (§13.2): platform staff get no
+general view of the private records, so M2 removes the `client.*`, `animal.*`
+and `animal_client_relation.*` actions from `audit_logs_select_admin`.
+
+### 6.4 Edits and finished bilans (C5, approved)
V1-1 holds no bilan. The rule binds V1-3: a bilan keeps its own identity
snapshot (already true of the report v3 format); editing an animal or a client
never rewrites a finished bilan, retroactively or silently. Any refresh of a
draft bilan from the animal record is an explicit user action.
-### 5.4 Server rules
+---
-- Reads: SELECT policies on `clients`, `animals`, `animal_clients`,
- `workspaces`, `workspace_members` through the workspace helper, explicit
- column lists in the app (no `select=*`).
-- Writes: security-definer RPCs only (create, update, archive, restore, link,
- end a link). No INSERT, UPDATE or DELETE grant on these tables for API roles.
- Each RPC calls `private.require_actor()`, checks the role in the target
- workspace, answers the same 42501 for an unknown id and a forbidden id, and
- writes one `log_event` row with ids and changed field names, never names,
- contacts or notes.
-- Concurrency: update RPCs take the `updated_at` the form loaded and refuse a
- stale write with a closed `conflict` kind, so two tabs never overwrite each
- other silently.
-- Archived records are read-only until restored.
-- Helpers in `private` follow the project rule: security definer,
- `set search_path = ''`, EXECUTE revoked from public, granted only where
- evaluated; census tests updated.
+## 7. Archive, deletion and data protection
+
+### 7.1 Archive (D8, approved)
+
+Archiving is a functional state, read-only and reversible.
+
+- An archived record is hidden from default lists and search, stays readable
+ from its page and under the « archivés » filter, and refuses every edit
+ (`archived` failure) until it is restored. Restore is always possible.
+- Relations are kept. Archiving a client archives none of its animals;
+ archiving an animal ends none of its relations. An archived client stays on
+ its animals' pages, marked archived.
+- Relation writes: creating a relation needs both the animal and the client
+ active; ending a relation, correcting its dates or removing it needs the
+ animal active (the client may be archived, so the history of an active
+ animal stays maintainable); the relations of an archived animal are frozen.
+- The confirmation before archiving a client lists the active animals for
+ which it is the only current owner.
+- Archiving erases nothing. It is not the deletion or anonymisation of
+ personal data, and no retention duration is attached to it.
+
+### 7.2 Account deletion and the data lifecycle (D9, D9a, approved)
+
+V1-1 implements no account closure, deletion, anonymisation or export, and sets
+no retention duration.
+
+Temporary DEV protection (D9a): the records reference their workspace with
+`on delete restrict`, and the personal workspace follows its account. Deleting
+an account whose workspace holds at least one client or animal is therefore
+refused by the database; an account whose workspace holds nothing is deleted
+as today, its workspace with it. In DEV a test account with records is removed
+by deleting its records first from a privileged SQL session, or by
+`pnpm db:reset`. The protection is not a ban: the lifecycle contract (plan
+Step 26) will process the records first (export, erasure or anonymisation,
+retention where justified, reassignment inside a cabinet) and the deletion then
+passes. It forbids one thing permanently: records disappearing as a side
+effect of deleting an account.
+
+The future lifecycle distinguishes closing an account, deleting or anonymising
+data, legally justified retention, records of a workspace shared by a cabinet,
+and reassignment of responsibilities in a cabinet. What V1-1 does so that it
+stays possible:
+
+- records belong to a workspace, never to a user column, so a cabinet's records
+ survive a member leaving and a personal workspace can be exported, anonymised
+ or erased as one unit;
+- authorship is ids in the audit log only, so anonymising a profile rewrites no
+ record;
+- a client's personal data sits in identified columns of one table; the folded
+ keys and phone digits (§8) derive from the same row and follow any rewrite; no copy goes
+ into audit rows, logs, error messages or URLs, so erasure or anonymisation is
+ a bounded update.
+
+### 7.3 Data protection (principles approved; legal framing before exposure)
+
+Nothing here is a legal policy. The owner frames the legal basis, the
+information texts, the retention durations and the rights procedures with
+counsel before any public exposure (§13.4).
+
+| Category | V1-1 data | Whom it concerns | Stored in | Read by |
+|---|---|---|---|---|
+| Practitioner's professional data | profile (existing): name, practice name, title, SIRET, email | the practitioner, as a user | `profiles`, `auth.users` | the practitioner; staff per the existing policies |
+| Clients' personal data | display name, email, phone, postal address | clients who are natural persons, and in practice structures too (a sole trader, an écurie named after a person, a named contact) | `clients` | members of the workspace only |
+| Animal information | name, species, sex, breed, birth | the animal, and through its link the client | `animals` | members of the workspace only |
+| Relations | owner, keeper or contact, dates | links a person to animals | `animal_client_relations` | members of the workspace only |
+| Technical traces | audit rows (actor, ids, actions), server logs | pseudonymised data, still personal data | `audit.audit_logs`, logs | platform owner and admin for audit rows (§6.3) |
+
+Design rule: the lifecycle contract treats every client row, organizations
+included, every relation and every audit row as personal data, whatever counsel
+later concludes about each category.
+
+Elements to prepare for the information of the persons concerned (GDPR
+articles 13 and 14), to be written with counsel (D10): identity of the
+controller, purposes, legal basis per purpose, recipients (Faunosteo as host),
+retention, rights and how to exercise them, and, under article 14, the source
+of the data when the practitioner records a person's details received from
+someone else (a keeper giving the owner's phone).
+
+Hypotheses to submit to counsel, not decisions: the practitioner or the cabinet
+is the controller of client and animal records and Faunosteo its processor
+(processor terms in the conditions of use); consent is not presumed to be the
+legal basis; the care relationship and the practitioner's legal obligations are
+the likely bases for identity and contact data; consent would cover optional
+purposes only (marketing, sharing with another practitioner), none of which
+V1-1 implements; data of a structure without a named person may fall outside
+personal data, and animal data may be personal data only through its link to
+a client.
+
+Rights in V1-1: rectification is the edit form. Access, export, erasure,
+restriction and portability come with the lifecycle contract. Until the legal
+framing exists, DEV holds fictitious data only: no real client is entered in
+V1-1 before the framing (recommendation, §14 risks).
+
+Minimisation: the field list of §5 is closed; no free-text notes in V1-1; the
+fields of D6 are deferred. No personal data in URLs (ids are uuids, the search
+term travels in a POST body), audit rows, application logs or error messages
+(§10.6).
---
-## 6. Archive, deletion and privacy
+## 8. SQL schema (M1, M2 and M3 written)
-### 6.1 Archive (D8)
+Three forward-only migrations, one per data step, each with its pgTAP files,
+the regenerated `database.types.ts` and the census updates in the same branch
+(plan principle 2). Timestamps are set when written. M1 as built, with its
+differences from the sketch below: §8.1.
-Archiving is a functional state, read-only and reversible. It hides a record
-from default lists and search, keeps it readable from its page and from the
-« archived » filter, and refuses edits until the record is restored. Restore
-is always possible. Relations are kept: an archived client stays on its
-animals' pages, marked archived. Archiving a client never archives its animals;
-the confirmation lists the active animals for which it is the only current
-owner.
+| Migration | Step | Content |
+|---|---|---|
+| M1 `20261025100000_workspaces.sql` (written, V1-1.1) | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS |
+| M2 `20261025110000_clients.sql` (written, V1-1.2) | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS |
+| M3 `20261026100000_animals_relations.sql` (written, V1-1.4) | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS |
-Archiving erases nothing. It is not the deletion or anonymisation of personal
-data (§6.2), and no retention duration is attached to it.
+Why the correlation header in M1: `private.log_event` copies that request
+header verbatim today (foundation migration), the app never sends it, and
+PostgREST exposes every header, so a caller chooses the size of each
+append-only audit row. V1-1 raises the audited write rate to 1 000 an hour
+per workspace (§10), which turns that into a storage risk. The change keeps the
+function's signature and callers.
-### 6.2 Account deletion and the data lifecycle (D9)
+Sketch of the tables. `(c)` abbreviates the text rule of §5:
+`c = btrim(c)` and no character of the explicit control ranges. Constraint
+names follow the existing `__` form.
-V1-1 implements no account closure, deletion, anonymisation or export, and
-sets no retention duration. Orientation D9: no rule may block the deletion of
-an account for good because it holds data. A later lifecycle contract (plan
-Step 26, BDR-033 point 7) will distinguish closing the account, deleting or
-anonymising personal data, keeping some data where a justification exists,
-the records of a workspace shared by a cabinet, and the legal obligations
-that apply. The owner sets the retention durations and the erasure policy;
-nothing here presumes them.
+```sql
+-- M1
+create type public.workspace_kind as enum ('personal');
+create type public.workspace_member_role as enum ('holder');
-What V1-1 does so that contract stays possible:
+create table public.workspaces (
+ id uuid primary key default gen_random_uuid(),
+ kind public.workspace_kind not null,
+ personal_user_id uuid unique references public.profiles (id) on delete cascade,
+ created_at timestamptz not null default now(),
+ constraint workspaces_personal_user_iff_personal
+ check ((kind = 'personal') = (personal_user_id is not null))
+);
-- records belong to a workspace, never to a user column, so a cabinet's
- records survive a member leaving, and a personal workspace can be exported,
- anonymised or erased as one unit;
-- authorship columns (`archived_by`, audit rows) hold ids only, never names,
- so anonymising a profile rewrites no record;
-- a client's personal data sits in the identified columns of one table, with
- no copy in audit rows, logs or URLs, so erasure or anonymisation is a
- bounded update.
+create table public.workspace_members (
+ workspace_id uuid not null references public.workspaces (id) on delete cascade,
+ user_id uuid not null references public.profiles (id) on delete cascade,
+ member_role public.workspace_member_role not null,
+ created_at timestamptz not null default now(),
+ primary key (workspace_id, user_id)
+);
+create index workspace_members_user_idx on public.workspace_members (user_id);
-The one technical choice before the migration is how the database behaves
-when an auth user whose personal workspace holds records is deleted in DEV
-(D9a, §9.2).
+-- M2
+create extension if not exists unaccent with schema extensions;
+-- lower + unaccent with an explicit dictionary, declared immutable so a
+-- generated column can use it.
+-- private.fold_text(p_value text) returns text
-### 6.3 Privacy, legal basis, information
+create type public.client_kind as enum ('person', 'organization');
-To frame with legal counsel before any public exposure (business
-architecture §28); nothing here decides it:
+create table public.clients (
+ id uuid primary key default gen_random_uuid(),
+ workspace_id uuid not null references public.workspaces (id) on delete restrict,
+ kind public.client_kind not null,
+ display_name text not null, -- 1..120,
+ email text, -- <= 254, = lower(email), practical format
+ phone text, -- '^\+[1-9][0-9]{6,14}$'
+ address_line1 text, -- 1..120,
+ address_line2 text, -- 1..120,
+ postal_code text, -- 1..16,
+ city text, -- 1..80,
+ country text, -- '^[A-Z]{2}$'
+ name_key text collate "C"
+ generated always as (private.fold_text(display_name)) stored,
+ search_key text generated always as
+ (private.fold_text(concat_ws(' ', display_name, city, email))) stored,
+ phone_digits text generated always as (ltrim(phone, '+')) stored,
+ create_request_id uuid not null, -- idempotency key sent by the form
+ revision integer not null default 1,
+ archived_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint clients_workspace_id_unique unique (workspace_id, id),
+ constraint clients_create_request_unique unique (workspace_id, create_request_id)
+);
+create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id);
-- likely roles: the practitioner or cabinet is the controller of client and
- animal records, Faunosteo its processor, which needs processor terms in the
- conditions of use;
-- the legal basis is not presumed to be consent. The likely basis for client
- identity and contact data is the care contract between practitioner and
- client and the practitioner's legal obligations (invoicing). Consent would
- apply to optional purposes only (marketing, sharing with another
- practitioner), none of which V1-1 implements;
-- clients must be informed (GDPR articles 13 and 14): the information text,
- and whether the app records that it was given, is decision D10. V1-1 shows
- nothing to clients;
-- retention durations belong to the lifecycle contract (§6.2);
-- minimisation: the field list of §4 is closed; the notes fields carry a hint
- to record only what the care needs;
-- no personal data in URLs (ids are uuids; the search term is never put in the
- query string), in audit rows or in application logs; search goes through a
- POST RPC so the term stays out of access logs.
+-- M3
+create type public.animal_sex as enum ('male', 'female', 'unknown');
+
+create table public.animals (
+ id uuid primary key default gen_random_uuid(),
+ workspace_id uuid not null references public.workspaces (id) on delete restrict,
+ name text not null, -- 1..80,
+ species_id text not null references public.species (id) on delete restrict,
+ species_detail text, -- 1..80,
+ sex public.animal_sex not null, -- no default
+ breed text, -- 1..80,
+ birth_year smallint, -- 1900..2100 (CHECK); <= current year (RPC)
+ birth_date date, -- >= 1900-01-01 (CHECK); not in the future (RPC)
+ name_key text collate "C"
+ generated always as (private.fold_text(name)) stored,
+ search_key text generated always as
+ (private.fold_text(concat_ws(' ', name, breed, species_detail))) stored,
+ create_request_id uuid not null,
+ revision integer not null default 1,
+ archived_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint animals_workspace_id_unique unique (workspace_id, id),
+ constraint animals_create_request_unique unique (workspace_id, create_request_id),
+ constraint animals_species_detail_iff_other
+ check ((species_id = 'other') = (species_detail is not null)),
+ constraint animals_birth_date_year
+ check (birth_date is null
+ or (birth_year is not null
+ and birth_year = extract(year from birth_date)::integer))
+);
+create index animals_workspace_name_idx on public.animals (workspace_id, name_key, id);
+
+-- M3 (continued)
+create type public.animal_relation_role as enum ('owner', 'keeper', 'contact');
+
+create table public.animal_client_relations (
+ id uuid primary key default gen_random_uuid(),
+ workspace_id uuid not null,
+ animal_id uuid not null,
+ client_id uuid not null,
+ relation_role public.animal_relation_role not null,
+ started_on date, -- >= 1900-01-01 (CHECK); not in the future (RPC)
+ ended_on date, -- idem
+ ended_at timestamptz,
+ voided_at timestamptz, -- set once by the void RPC (N4)
+ create_request_id uuid not null,
+ revision integer not null default 1,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint animal_client_relations_animal_fk foreign key (workspace_id, animal_id)
+ references public.animals (workspace_id, id) on delete restrict,
+ constraint animal_client_relations_client_fk foreign key (workspace_id, client_id)
+ references public.clients (workspace_id, id) on delete restrict,
+ constraint animal_client_relations_ended_on_needs_end
+ check (ended_on is null or ended_at is not null),
+ constraint animal_client_relations_dates_order
+ check (started_on is null or ended_on is null or started_on <= ended_on),
+ constraint animal_client_relations_started_on_range check (started_on >= '1900-01-01'),
+ constraint animal_client_relations_ended_on_range check (ended_on >= '1900-01-01'),
+ constraint animal_client_relations_create_request_unique
+ unique (workspace_id, create_request_id)
+);
+create unique index animal_client_relations_current_unique
+ on public.animal_client_relations (animal_id, client_id, relation_role)
+ where ended_at is null and voided_at is null;
+create index animal_client_relations_animal_idx
+ on public.animal_client_relations (workspace_id, animal_id);
+create index animal_client_relations_client_idx
+ on public.animal_client_relations (workspace_id, client_id);
+```
+
+Every table with `updated_at` gets the existing `private.set_updated_at()`
+trigger. `revision` changes only through the RPCs: every successful
+state-changing write (update, archive, restore, end, date correction) adds one;
+a call that changes nothing does not.
+
+`create_request_id` makes creation idempotent: the form generates one uuid per
+create attempt and resends the same one on retry; a replay returns the ids of
+the row already created instead of a duplicate (clients and animals can be
+archived, never deleted, so a duplicate would stay forever and block the
+account's deletion under D9a).
+
+The backfill of M1 is a private function the migration calls once
+(`private.backfill_personal_workspaces()`, idempotent), so pgTAP can prove it
+on data: the migrations run on an empty `profiles` table in both test runners.
+
+Indexes and why:
+
+| Index | Serves |
+|---|---|
+| `workspace_members_user_idx` | the membership lookup of every policy |
+| `clients_workspace_name_idx`, `animals_workspace_name_idx` | workspace filter, keyset pagination in name order, search within one workspace |
+| unique `(workspace_id, id)` on clients and animals | targets of the composite foreign keys |
+| `animal_client_relations_current_unique` | one current relation per (animal, client, role) |
+| unique `(workspace_id, create_request_id)` on the three tables | idempotent creation |
+| `animal_client_relations_animal_idx`, `_client_idx` | an animal's relations, a client's relations, foreign key checks |
+
+Search reads stored columns only: `search_key` (folded name, city and email
+of a client; folded name, breed and species detail of an animal) and
+`phone_digits`. Nothing is folded per row at query time. No trigram index in
+V1-1: a workspace holds at most 20 000 rows per table (§10) and the search
+scans one workspace through the name index. The measurement of step V1-1.2
+decides: above 100 ms at p95 on 20 000 rows, a `pg_trgm` GIN index on
+`search_key` is added (PGlite ships `pg_trgm`).
+
+`name_key` is stored with `collate "C"`, so the order is the same on PGlite and
+on the real stack (rule of the pgTAP files) and, accents and case being folded,
+follows French alphabetical order closely enough for a list. If the dictionary
+of `unaccent` ever changed, stored keys would differ from new ones until their
+rows are rewritten: recorded, low risk.
+
+### 8.1 M1 as built (V1-1.1, 2026-10-25)
+
+`supabase/migrations/20261025100000_workspaces.sql`, tested by
+`supabase/tests/012_workspaces.sql` (85 checks) and the census of
+`001_schema.sql`. Differences from the sketch and from the plan, each
+deliberate:
+
+| Point | Sketch or plan | As built | Why |
+|---|---|---|---|
+| Uniqueness of the personal workspace | inline `unique` | named constraint `workspaces_personal_user_unique` | the single write path targets it with `on conflict`, tests name it |
+| Write path | trigger and backfill | both call `private.ensure_personal_workspace(uuid)`: workspace and holder membership inserted by one statement, `on conflict (personal_user_id) do nothing`, returns whether it created | one place for atomicity and idempotence; a concurrent call waits for the first commit, then writes nothing |
+| Consistency workspace ↔ holder | not in the sketch | deferred constraint triggers `workspaces_personal_holder` and `workspace_members_personal_holder` on `private.check_personal_workspace()`: at commit, a personal workspace has exactly its account as `holder` | the owner asked for a coherence constraint between the workspace's account and its member; it holds for any writer, the table owner included; cabinets are not constrained |
+| Trigger name | not named | `profiles_create_personal_workspace` | |
+| `private.writable_workspace_ids()` | M1 | created in M1, unused until M2's write RPCs | the helper set of §9.1 ships and is tested once |
+| Access layer `packages/supabase/src/workspaces.ts` | planned in V1-1.1 | deferred to V1-1.2 | no consumer before the clients access layer; the brief authorised M1 and its tests |
+| `pnpm db:reset && pnpm db:test` | planned gate | not run: the owner kept the DEV stack untouched | replaced by an isolated real stack (below) |
+
+Not changed by M1: the privileges of existing tables. `service_role` keeps the
+Supabase default privileges it holds today on `profiles`, `profile_roles` and
+`assets` (only the new tables and `private.object_purge_queue` revoke it);
+narrowing them is outside V1-1.1 and needs the owner's decision (N7).
+
+Isolated real-stack verification. A throwaway stack built from the DEV stack's
+images (PostgreSQL 17.11.0.004, GoTrue v2.197.0, Storage v1.79.36, PostgREST
+v16.4, Mailpit v1.31.3) on its own Docker network, ports on the loopback
+only, no Docker volume, DEV containers untouched. Two runs: from zero (all
+migrations then the seeds, as `supabase db reset`), and the DEV path (the
+migrations before M1, the seeds and two accounts created through GoTrue, then
+M1, whose backfill created the five missing workspaces). In both: the twelve
+pgTAP files green (531 checks); real concurrent sessions (two creations of one
+account's workspace: the second waited for the first commit and wrote
+nothing; two racing backfills created 40 workspaces between them, no
+duplicate; commits of a workspace without its holder or with a foreign member
+refused at COMMIT; a rolled-back creation left nothing and the retry created
+one); ten parallel GoTrue sign-ups each with one workspace; 33 HTTP checks
+through GoTrue and PostgREST (sign-up without session, confirmation by the
+mailed link, reads limited to the own workspace, `count=exact` of one,
+refusals with `permission denied` for writes, for the anon key and for the
+service key, `private` functions unreachable, deactivation effective on the
+next request with the same token, the correlation header capped through a
+real request, an empty account deleted by the GoTrue admin API taking its
+workspace along, and the residual admin path of §6.3). The types were
+generated from that database: the diff with the committed file is exactly the
+M1 additions.
+
+### 8.2 M2 as built (V1-1.2, 2026-10-25)
+
+`supabase/migrations/20261025110000_clients.sql`, tested by
+`supabase/tests/013_clients.sql` (130 checks), the census of `001_schema.sql`,
+the parity test `packages/supabase/tests/db/field-limits.test.ts` and the
+sandbox suite `packages/supabase/tests/sandbox/clients.sandbox.ts`.
+Differences from the sketch and the plan:
+
+| Point | Sketch or plan | As built | Why |
+|---|---|---|---|
+| Replay with other content | not covered | column `create_request_digest` (SHA-256 of the normalised creation content, not granted to any API role); a replay with the same id and another digest is refused `request_conflict` (§9.4), never applied | owner brief §11: a reused request id must not silently accept a divergent operation |
+| Text rule in CHECKs | written inline | `private.is_clean_text(value, max)`, immutable, EXECUTE for nobody, used by every text CHECK (M3 reuses it) | one literal for the control ranges |
+| Folding | `lower + unaccent` | `lower(unaccent('extensions.unaccent', value) collate "C")`: accents removed, then ASCII lower case only, identical on PGlite and the real image (checked); Cyrillic or Greek capitals keep their case | the database collations differ (C on PGlite, ICU on the image) |
+| `search_key` | `concat_ws` | `display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, '')` | a generated column needs an immutable expression; `concat_ws` is stable |
+| Write budget | `require_write_budget(p_actor)`, rolling windows | `private.consume_write_budget(p_workspace_id)` over `private.workspace_write_budgets` (one row per workspace), fixed UTC windows (§10) | owner decision N6 and brief §9: transactional counter per workspace, UTC windows |
+| `search_clients` output | with `current_animal_count` | without it | the relations table comes with M3, which recreates the function with the column (return type change) |
+| Access layer `clients.ts` | V1-1.2 | moved to V1-1.5, its first consumer, together with the personal workspace read | the brief's V1-1.2 scope lists no access layer; `field-limits.ts` (D-R7) is written now because the parity test needs it |
+| Real-stack e2e | `clients-animals.e2e.ts` on the DEV stack | the sandbox suite, on the isolated stack | DEV stays untouched (owner) |
+
+Search measurement (owner requirement, §8): 20 000 clients in one workspace,
+21 POST calls through PostgREST mixing name, city, email and phone terms:
+median 9.8 ms, p95 21.4 ms, max 21.9 ms (isolated stack, this host). Under
+the 100 ms threshold, so no trigram index is added.
+
+Residual disclosure found on the real image: a refused direct table access
+(`permission denied for table clients`) carries a hint added by the Supabase
+image, « Grant the required privileges to the current role with: GRANT
+INSERT ON public.clients TO authenticated; ». It names the table, the role
+and the privilege, never a value, and the app never sends such a request.
+The RPC refusals carry no hint (checked on both engines).
+
+### 8.3 M3 as built (V1-1.4, 2026-10-26)
+
+`supabase/migrations/20261026100000_animals_relations.sql`, tested by
+`supabase/tests/014_animals_relations.sql` (258 checks), the census of
+`001_schema.sql` and `013_clients.sql`, the parity test (animal text fields,
+year and date floors) and the sandbox suite
+`packages/supabase/tests/sandbox/animals.sandbox.ts` (18 tests). Differences
+from the sketch and from §9:
+
+| Point | Sketch or contract | As built | Why |
+|---|---|---|---|
+| Replay with other content | clients only (§8.2) | `create_request_digest` on animals and relations too, never granted to an API role; a divergent replay is `request_conflict` | the same rule for every create |
+| Initial relation of `create_animal` | "in the same transaction" | the relation reuses the animal's `create_request_id` (unique per table), so a replay answers the same `relation_id`; it counts as two audited writes in the budget (two audit rows) | idempotence of the two-row create; the budget counts audited writes (§10) |
+| Species filter of `search_animals` | parameter `species_id` | `species_filter` | PostgreSQL refuses a parameter named like the `species_id` output column |
+| Cursor of `list_client_animals` | `after_sort` | each row returns `sort_key`: `0` (current) or `1` (former) followed by the animal's `name_key`; keyset on `(sort_key, relation_id)` | one text cursor covers both groups |
+| Output of `list_client_animals` | "relation and animal columns" | `relation_id`, `relation_role`, `started_on`, `ended_on`, `is_current`, `relation_revision`, `animal_id`, `animal_name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `animal_archived_at`, `sort_key` | what the client page needs to show and to end or void a relation |
+| `client_archive_preview` | `{count, animals}` | `{count, animals: [{id, name}]}`, the first 10 in name order | |
+| Replay of a relation create | archived, then revision, then rules | the replay is answered right after the locks, before `archived`: a retry of a committed create returns it even if the animal or the client was archived since | idempotence |
+| Dates and years | parsed in each body | `private.parse_record_date`, `private.parse_birth_year`, and the bound `private.utc_tomorrow(timestamptz)`, pure, so pgTAP pins « 1 January accepted on 31 December UTC » without the clock | one rule, testable |
+| Opening of the relation writes | per RPC | `private.lock_relation_for_write`: authorise, lock the animal then the relation, refuse `archived`, `conflict`, then a voided row (`invalid_input`) | the same order in the three RPCs |
+| `search_clients` | "recreated with the column" | dropped and created again with the same parameters, rules and privileges, plus `current_animal_count` | a return type change needs a drop |
+| Access layer `animals.ts`, `relations.ts` | V1-1.4 (TODO) | moved to the UI steps | first consumer, as `clients.ts` at V1-1.2 |
+
+Relation states. `ended_at` tells an ended relation from a current one, so a
+relation whose end is recorded without a known date is unambiguous; the
+contract needed no change (owner brief §7).
+
+| State | `ended_at` | `ended_on` | `voided_at` | Shown | Current index, cap of 20 | Totals of 200 and 100 000 |
+|---|---|---|---|---|---|---|
+| current | null | null | null | current | yes | yes |
+| ended, date known | set | the date | null | former, with its date | no | yes |
+| ended, date unknown | set | null | null | former, no end date | no | yes |
+| voided (entered by mistake, current or ended) | as entered | as entered | set | nowhere | no | yes |
+
+Caps: a current relation (`ended_at` and `voided_at` null) counts against
+20 per animal; every row, ended and voided included, counts against 200 per
+animal and 100 000 per workspace, so a create-and-void loop is bounded. The
+200 and 20 are counted under the animal row lock, the 100 000 and the 20 000
+animals under the workspace row lock.
+
+Lock order as built, M2 included. Every write RPC takes the budget row last
+and the others in the order workspace, animal, relation, client; none takes
+two of them the other way round, so no wait cycle can form:
+
+| RPC | Locks, in order |
+|---|---|
+| `create_client` | workspace (no key update), budget |
+| `update_client`, `set_client_archived` | client (update), budget |
+| `create_animal` | workspace (no key update), client (share, with a relation), budget (once, twice with a relation) |
+| `update_animal`, `set_animal_archived` | animal (update), budget |
+| `create_animal_client_relation` | workspace (no key update), animal (update), client (share), budget |
+| `end_`, `update_`, `void_animal_client_relation` | animal (update), relation (update), budget |
+
+The relation RPCs first read the animal's (or the relation's) workspace among
+the caller's writable ones without a lock, so a caller outside the workspace
+takes none: with A's client, animal and relation rows held for 2 s, B's four
+refusals answered in 15 ms.
+
+Results on the isolated stack: 8 identical `create_animal` calls with a
+relation gave one animal, one relation and two counted writes; 10 identical
+relations, one row and nine `duplicate_relation`; end and void racing on one
+revision (6 rounds of 3 calls), exactly one applied each time; 6 links at 18
+current relations, 2 passed; a relation create racing the archive of its
+client or of its animal (10 rounds each), created before or refused
+`archived`; at 990 writes, 30 mixed client, animal and relation writes, exactly
+10 passed; 5 `create_animal` at 19 998 animals and 5 links at 99 998
+relations, 2 each (49 ms for the five links); 96 mixed M2 and M3 writes in one
+workspace, no deadlock (109 ms). Reads over 20 000 animals, 20 000 relations
+and 1 000 clients (24 POST calls): median 7.9 ms, p95 11.8 ms.
+
+Migration states, each from an empty sandbox: from zero; a pre-M1 base
+(seeds, GoTrue accounts) then M1 to M3; the same base, M1 (backfill of five
+workspaces), then M2 and M3 (`pnpm db:sandbox up upgrade 20261025100000
+20261025110000`); an M1 and M2 base then M3. In each: the 14 pgTAP files
+green (919 checks), the generated types identical to the committed file, the
+sandbox suites 46/46. Fourteen deliberate faults of M3 were each caught; two
+only after the tests were strengthened (a client whose only link was voided
+while current; B linking its own animal to a client of A, which made B wait
+on A's lock).
+
+Not built: reopening an ended relation (§5.3: void it and create it again).
+Residual: a privileged SQL writer (the table owner) can still change a
+relation's `animal_id`, `client_id` or `relation_role` inside one workspace,
+and move an animal without relations to another workspace (the evolution path
+of §4); the RPCs never do, and the composite keys refuse any row across
+workspaces whatever writes it.
---
-## 7. Screens and journeys
+## 9. Policies, helpers and RPCs
-Routes (English, like the existing `/app/dashboard` and `/app/account`):
+### 9.1 Helpers (schema `private`)
+
+| Helper | Returns | Rule | EXECUTE |
+|---|---|---|---|
+| `private.caller_workspace_ids()` | `setof uuid` | the single source of the access rule: workspaces where `auth.uid()` is a member, with an active profile and a confirmed email | `authenticated` (policies evaluate it) |
+| `private.writable_workspace_ids()` | `setof uuid` | `caller_workspace_ids()` restricted to a write role (V1-1: `holder`) | none (called inside RPCs) |
+| `private.consume_write_budget(p_workspace_id uuid)` | `void` | counts one write of the workspace in its UTC hour and day (upsert of its row in `private.workspace_write_budgets`, row lock), raises P0001 `rate_limited` past 1 000 / 5 000 (§10); called last by every write RPC (M2, §8.2) | none |
+| `private.is_clean_text(p_value text, p_max integer)` | `boolean` | the text rule of §5 for CHECK constraints (M2) | none |
+| `private.fold_text(p_value text)` | `text` | without accents (`unaccent` with an explicit dictionary), then ASCII lower case (collation "C"), declared immutable for the generated columns (§8.2) | `authenticated` (the invoker search folds the term) |
+| `private.ensure_personal_workspace(p_user_id uuid)` | `boolean` | the single write path: workspace and `holder` membership in one statement, `on conflict do nothing` on `personal_user_id`; true when it created (M1, §8.1) | none |
+| `private.create_personal_workspace()` | trigger | after insert on `profiles`: calls `ensure_personal_workspace(new.id)` | none |
+| `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none |
+| `private.check_personal_workspace()` | constraint trigger | deferred to commit: a personal workspace has exactly its account as `holder` (M1, §8.1) | none |
+| `private.utc_tomorrow(p_now timestamptz)` | `date` | the latest date a record may carry when written at `p_now`: tomorrow's UTC date (M3, §8.3) | none |
+| `private.parse_record_date(p_value text)`, `private.parse_birth_year(p_value text)` | `date`, `smallint` | `YYYY-MM-DD` or four digits, not after `utc_tomorrow(now())` (its year), else `invalid_input` without the value; null stays null (M3) | none |
+| `private.lock_relation_for_write(p_relation_id uuid, p_expected_revision integer)` | relation row | authorises and locks animal then relation; `not_found`, `archived`, `conflict`, voided `invalid_input` (M3) | none |
+
+All are `security definer` (except `fold_text`, `is_clean_text`, `utc_tomorrow` and the two parsers, which read no table),
+`set search_path = ''`, `revoke all ... from public, anon, authenticated,
+service_role` then the grants of the table, and listed in the census of
+`001_schema.sql`. The write RPCs do not call `private.require_actor()`: its
+two messages differ, and V1-1 refusals must be identical (§9.4).
+
+### 9.2 Row-level security and grants
+
+| Table | SELECT policy (role `authenticated`) | Write policies | Column grants to `authenticated` |
+|---|---|---|---|
+| `workspaces` | `id in (select private.caller_workspace_ids())` | none | `id`, `kind`, `personal_user_id`, `created_at` |
+| `workspace_members` | `workspace_id in (select private.caller_workspace_ids())` | none | all columns |
+| `clients` | `workspace_id in (select private.caller_workspace_ids())` | none | all columns |
+| `animals` | same | none | all columns |
+| `animal_client_relations` | same | none | all columns |
+
+- RLS enabled on every table in the migration that creates it.
+- `revoke all ... from public, anon, authenticated, service_role`, then the
+ column grants above. `anon` and `service_role` hold nothing (§13.2 N7).
+- No INSERT, UPDATE or DELETE grant or policy for any API role: every write is
+ an RPC.
+- No policy names a platform role (D16); no `using (true)` (census test).
+- The `in (select ...)` form evaluates the helper once per query, not per row.
+- The app selects explicit column lists, never `select=*`, and never filters a
+ text column in a GET URL (`ilike`, `eq` on a name, a keyset cursor on
+ `name_key`): API URLs land in access logs. Text filters and name-ordered
+ pages go through the POST RPCs below; GET reads filter by id only.
+
+### 9.3 RPCs
+
+Write RPCs: `language plpgsql`, `security definer`, volatile,
+`#variable_conflict use_column`, parameters referenced as
+`.`. Each one, in this order:
+
+1. authorises and locks in one statement: the target row or the workspace is
+ selected `where id = ... and workspace_id in (select
+ private.writable_workspace_ids())` with its lock, so a caller outside the
+ workspace never takes a lock and never waits on one; no row found raises
+ 42501 `not_found`;
+2. checks, in this order, archived (`archived`), then revision (`conflict`),
+ then the rules of the table below; a replayed create or a call that
+ changes nothing returns here, uncounted;
+3. calls `private.consume_write_budget` (as built in M2: last, after the
+ checks, so its lock is the last one taken);
+4. writes, inside a block that turns `check_violation`, `not_null_violation`,
+ `string_data_right_truncation` and `invalid_text_representation` into
+ `invalid_input`, `unique_violation` on the current-relation index into
+ `duplicate_relation` and `foreign_key_violation` into `not_found`;
+5. writes one audit row and returns ids and the new revision only.
+
+Locks: create RPCs of clients and animals lock the workspace row `for no
+key update` (cap, replay check and insert serialised per workspace, foreign
+key checks of other writes not blocked); every relation RPC locks the animal row
+`for update` then the client row `for share`, in that order; the archive RPCs
+lock their row `for update`. So caps, « both active » and « animal active »
+cannot be passed by a concurrent call. The write budget and the 100 000
+relations per workspace count rows that writes on different animals or
+clients can add at the same time: they are counted under a lock that
+serialises those writes per workspace (owner, N6: never a bare count followed
+by an unprotected insert). As built in M2: the budget row of the workspace
+(`private.workspace_write_budgets`) is locked by the upsert of
+`private.consume_write_budget`, which every write RPC calls last, after its
+entity locks and checks; no lock is taken after it, so no cycle can form. The
+lock order of every write RPC is therefore: workspace row (creates), animal
+row, client row, budget row. M3 keeps it: a relation create locks the
+workspace row first (its 100 000 cap), then the animal, then the client, then
+the budget. The budget lock is per workspace: measured on the isolated stack,
+a budget row held for 2 s delayed the create of its workspace by 1.75 s while
+nine creates in nine other workspaces finished in 8 ms; 60 mixed writes in one
+workspace raised no deadlock.
+
+Parameters: dates, years and enum values arrive as `text` and are parsed inside
+the body, so a malformed value (« 2015-02-30 ») is answered `invalid_input`
+without being echoed in the error or the server log. Create RPCs give optional
+fields a `null` default, after the required ones; update RPCs have no
+defaults, so an omitted field is an error and never a silent erasure. An
+update that changes nothing writes nothing and returns the current revision.
+
+| RPC | Parameters | Returns | Specific rules | Audit action |
+|---|---|---|---|---|
+| `create_client` | `workspace_id`, `create_request_id`, `kind`, `display_name`, then optional `email`, `phone`, `address_line1`, `address_line2`, `postal_code`, `city`, `country` | `{id, revision}` | replay of a known `create_request_id` returns the existing row; cap 20 000 clients | `client.created` |
+| `update_client` | `client_id`, `expected_revision`, the nine fields | `{revision}` | | `client.updated` |
+| `set_client_archived` | `client_id`, `archived` | `{revision}` | same state: no write | `client.archived` / `client.restored` |
+| `create_animal` | `workspace_id`, `create_request_id`, `name`, `species_id`, `sex`, then optional `species_detail`, `breed`, `birth_year`, `birth_date`, and optional initial relation `client_id`, `relation_role`, `started_on` | `{id, revision, relation_id}` | replay returns the existing row; cap 20 000 animals; species active; birth not in the future; the optional relation follows the rules of `create_animal_client_relation` in the same transaction | `animal.created` (+ `animal_client_relation.created`) |
+| `update_animal` | `animal_id`, `expected_revision`, the seven fields | `{revision}` | species active or unchanged; birth not in the future | `animal.updated` |
+| `set_animal_archived` | `animal_id`, `archived` | `{revision}` | same state: no write | `animal.archived` / `animal.restored` |
+| `create_animal_client_relation` | `animal_id`, `client_id`, `create_request_id`, `relation_role`, optional `started_on` | `{id, revision}` | both in one writable workspace (else 42501); both active; no current duplicate; at most 20 current and 200 total relations per animal and 100 000 per workspace (`limit_reached`); `started_on` not in the future | `animal_client_relation.created` |
+| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; not voided; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` |
+| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; not voided; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` |
+| `void_animal_client_relation` | `relation_id`, `expected_revision` | `{revision}` | N4: a relation entered by mistake, current or ended; animal active; not already voided; sets `voided_at = now()`, changes no other column; explicit confirmation in the UI; no deletion | `animal_client_relation.voided` |
+
+The combined journeys use the atomic `create_animal` with its optional
+relation. « New client with a first animal » is two calls (`create_client`,
+then `create_animal` with the relation); each carries its own
+`create_request_id`, the form keeps the ids it has received, and a retry
+after a failure resumes at the missing call and never creates a second client.
+
+"Not in the future" allows up to the UTC date of tomorrow (and its year for
+`birth_year`), so a date that is today in any time zone is accepted; the form
+checks against the device's local date. Audit rows (N9) hold the technical
+ids (actor, resource, workspace in `metadata` as `{workspace_id}`), the
+action and its time: no relation role, no changed-field list, no name,
+contact, date or search term. A row exists only for a committed write, so its
+presence is the result; refusals write nothing, which keeps a caller from
+growing the log by failing on purpose.
+
+Read RPCs: `language plpgsql`, `security invoker` (RLS applies), stable,
+`set search_path = ''`, `#variable_conflict use_column`, parameters referenced
+as `.`, EXECUTE for `authenticated`. The app calls them
+with POST, so terms and cursors stay out of URLs and access logs.
+
+| RPC | Parameters | Returns (one row per record) | Rules |
+|---|---|---|---|
+| `search_clients` | `workspace_id`, `query`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `kind`, `display_name`, `city`, `phone`, `email`, `archived_at`, `name_key`; `current_animal_count` added by M3 (§8.2) | see below; also serves the client picker of the relation forms |
+| `search_animals` | `workspace_id`, `query`, `species_filter` (§8.3), `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `archived_at`, `name_key`, `current_owners`, `current_owner_count` | see below; optional species filter |
+| `list_client_animals` | `client_id`, `page_size`, `after_sort`, `after_id` | relation and animal columns | a client's relations with their animals, current first then former, each group by animal `name_key`, then `id`; keyset on that order; 50 by default, 100 at most |
+| `client_archive_preview` | `client_id` | `{count, animals}` | active animals for which this client holds the only current `owner` relation: their count and the first 10 by name |
+
+Search rules: `query` trimmed, 0 to 100 characters, empty lists everything. The
+term is folded, then `\`, `%` and `_` are escaped (backslash first), and it
+must appear inside `search_key`. Phone: when the term holds at least four
+digits and only digits, spaces, dots, hyphens and `+`, its digits are also
+looked for inside `phone_digits`, after dropping one leading `0` (so
+« 06 12 », « 0612345678 » and « +33 6 12 » all find `+33612345678`).
+`archived = false` lists active records, `true` archived ones. `page_size` 1 to
+100, 25 by default; keyset on `(name_key, id)`.
+
+Derived values:
+
+| Value | Exact rule |
+|---|---|
+| `current_animal_count` | `count(distinct animal_id)` over the client's relations with `ended_at is null` and `voided_at is null`, any role, animals not archived |
+| `current_owners` | the animal's relations with `relation_role = 'owner'`, `ended_at is null` and `voided_at is null`, archived clients included and flagged, ordered by client `name_key` then `id`, first three as `{client_id, display_name, archived}` |
+| `current_owner_count` | the count of those relations |
+| « only current owner » (archive preview) | the animal is active, this client has a current `owner` relation, and no other client, archived or not, has one |
+
+The animal page reads its relations with one select by animal id (at most 200
+by the cap, ids in the URL only). Dashboard counts (D12) use `count=exact` with
+`head=true` filtered by workspace id and `archived_at`. The app finds its
+personal workspace with `workspaces?personal_user_id=eq.`. Nested selects
+are bounded by the per-animal cap and by the role's `statement_timeout`,
+pinned by a test.
+
+### 9.4 Failures
+
+Closed kinds, mapped by the access layer (`packages/supabase`), phrased by i18n
+in FR and EN, like the auth and asset failures:
+
+| From the server | Kind | When |
+|---|---|---|
+| 42501 `not_found` | `not_found` | inactive account, unconfirmed email, not a member, unknown id, id of another workspace: one SQLSTATE and one message for all of them (`anon` gets PostgREST's « permission denied », having no EXECUTE) |
+| P0001 `archived` | `archived` | write on an archived record (checked before the revision) |
+| P0001 `conflict` | `conflict` | `expected_revision` differs: the form shows the saved values beside the typed ones and keeps the typed ones |
+| P0001 `limit_reached` | `limit_reached` | a cap of §10 |
+| P0001 `rate_limited` | `rate_limited` | the write budget of §10 |
+| P0001 `duplicate_relation` | `duplicate_relation` | same current (animal, client, role), including the loser of a race |
+| P0001 `already_ended` | `already_ended` | ending an ended relation |
+| P0001 `invalid_input` | `invalid_input` | an RPC rule or a constraint or parse error caught inside the RPC |
+| P0001 `request_conflict` | `request_conflict` | a create replayed with a known `create_request_id` but other content (§8.2); the first record is kept unchanged |
+| anything else | `unavailable` | network, server |
+
+pgTAP compares the whole error (SQLSTATE, message, detail, hint) of a foreign id
+and of a random uuid. An `invalid_input` from a CHECK means the TypeScript
+rules drifted from the SQL: the parity test of §12.2 exists to catch it first.
+
+### 9.5 SECURITY DEFINER functions: owner, path, privileges, trust
+
+- Owner: the role that runs the migrations and owns the tables (`postgres` on
+ the CLI stack, the same on any Supabase project; a table owner, not a
+ superuser on Supabase), like every existing function; no
+ `alter function ... owner to`. RLS is not forced on these tables, so the
+ owner reads past the policies: the function body is the only authorisation
+ and checks the workspace role before reading, locking or writing any record.
+- `set search_path = ''`; every object is schema-qualified; no dynamic SQL, no
+ `execute`, no `format()`.
+- EXECUTE: `revoke all ... from public, anon, authenticated, service_role`,
+ then granted to `authenticated` for the RPCs and for the two helpers that
+ policies or the invoker searches evaluate, to nobody for the internal
+ helpers. `service_role` gets no EXECUTE.
+- Trust boundary: the function trusts `auth.uid()` (a JWT verified by
+ PostgREST) and its own checks, nothing else from the caller; every parameter
+ is untrusted. It returns ids, revisions and closed codes, never a record of
+ another workspace, and has no platform-role branch.
+- pgTAP pins `prosecdef`, the `search_path` setting and the ACL of each one.
+
+---
+
+## 10. Technical limits (D15, principle approved, thresholds proposed)
+
+These caps protect the service. They are not commercial quotas: any quota
+comes from the entitlement step (plan Step 11), and changing a cap here is a
+migration.
+
+| Limit | Proposed value | Justification | Enforced by |
+|---|---|---|---|
+| Text fields | display name 120, email 254, phone E.164, address lines 120, postal code 16, city 80, country 2; animal name 80, breed 80, species detail 80; years 1900 to tomorrow's UTC year | long structure names fit in 120; 254 is the SMTP path limit; the rest bounds a record to about 3 KB | SQL CHECK; same constants in the forms (§12.2); years and dates also in the RPC |
+| Request size | one record per call (plus one optional relation in `create_animal`), about 3 KB of text at most by the field caps | no bulk operation in V1-1 | SQL; reverse proxy body cap of 64 KiB on `/rest/v1` in production (deploy notes, RR-5) |
+| Items per operation | one record and its audit row per write RPC; two in `create_animal` with a relation | imports are out of scope | RPC design |
+| Pagination | search pages of 25 by default, 100 at most; a client's animals 50 by default, 100 at most; an animal's relations at most 200 by the cap; PostgREST `max_rows = 1000` limits the top level of a direct select, and `statement_timeout` bounds nested ones | a phone list needs 25; 100 bounds the work of one call | RPC; `config.toml`; role setting |
+| Search term | 0 to 100 characters after trimming | a name or a phone fits; longer is noise | RPC |
+| Records per workspace | 20 000 clients, 20 000 animals, 100 000 relations | a full-time practitioner sees roughly 1 000 to 2 000 visits a year, so 20 000 animals is more than a decade of distinct animals for one person | RPC, under the workspace or animal row lock |
+| Relations per animal | 20 current, 200 in total | co-owners, keeper and contacts fit in 20; 200 covers decades of sales; the animal page reads them in one select | RPC |
+| Write rate | 1 000 audited writes per workspace per UTC hour and 5 000 per UTC day (owner, N6), fixed windows: the hour from hh:00:00 to hh:59:59.999 UTC, the day from 00:00:00 UTC; the first write of a new window restarts its count at 1; the 1 000th write of the hour passes, the 1 001st is refused `rate_limited`. Across an hour boundary up to 2 000 writes can land in 2 minutes; the daily 5 000 still holds. Counted per workspace under the budget row lock (§9.3); a refused write, a replayed create and a call that changes nothing are not counted (the count is rolled back with the refusal) | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.consume_write_budget`) |
+| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to the workspace id (N9) | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) |
+| Concurrent writes | optimistic `revision` on every update; locks of §9.3 (workspace row for creates, animal then client row for relations, the row itself for archive); idempotent creates through `create_request_id` | no silent overwrite between two tabs or devices, no cap overshoot, no duplicate on retry | SQL and RPC |
+| Enumeration | random uuid ids; one 42501 `not_found` for an unknown and a forbidden id in every RPC, with no lock taken outside the caller's workspaces; reads filtered by RLS return empty, never an error that says "exists"; searches limited to one workspace of the caller; closed codes, never values, in errors | | RLS, RPC |
+| Login, sign-up, email sending | existing GoTrue limits (`[auth.rate_limit]` in `config.toml`); per-IP limits on `/rest/v1` at the production reverse proxy | | GoTrue; infrastructure (deploy notes) |
+
+Growth bound of one misused confirmed account, from the figures above: at most
+20 000 clients, 20 000 animals and 100 000 relations (about 150 MB with their
+indexes at the field caps), and at most 5 000 audit rows a day of a few hundred
+bytes each (about 0.5 GB a year). The audit log is append-only and never
+cleaned today: its retention belongs to the lifecycle contract. GoTrue's
+sign-up limits bound the number of accounts.
+
+§10.6 Logs and errors: inside the write RPCs, constraint and parse errors
+become `invalid_input` (§9.3), so PostgreSQL never logs a failing row, whose
+detail would contain names, and no submitted value is echoed. PostgreSQL does
+not log statement parameters on error by default
+(`log_parameter_max_length_on_error = 0`). Residual: a value PostgREST cannot
+cast before the function runs (a non-uuid id) is echoed in the response; ids
+are not personal data. The production log settings go to the deploy notes with
+RR-5. The app logs no record content.
+
+---
+
+## 11. Screens and journeys
+
+### 11.1 Routes
+
+English, like the existing `/app/dashboard` and `/app/account`; identifiers
+only, never a name or a search term.
| Route | Content |
|---|---|
-| `/app/clients` | list (name, kind, city, phone, animal count), search, archived filter, « new client » |
-| `/app/clients/new` | form; optional « add a first animal » section in the same flow |
-| `/app/clients/:clientId` | identity and contact, animals with their role (current and former), edit, archive or restore, add an animal |
-| `/app/animals` | list (name, species, breed, sex, owners or « Propriétaire non renseigné »), search, species and archived filters, « new animal » |
-| `/app/animals/new` | form with optional client selection or inline client creation; prefilled when opened from a client |
-| `/app/animals/:animalId` | identity, owners, keepers and contacts (current and former), edit, archive or restore |
+| `/app/clients` | list (name, kind, city, phone, number of animals), search, « archivés » filter, « Nouveau client » |
+| `/app/clients/new` | client form; optional « Ajouter un premier animal » section in the same flow |
+| `/app/clients/:clientId` | identity and contact (phone as a `tel:` link, email as `mailto:`), animals with their role, current then former, edit, archive or restore, add an animal |
+| `/app/clients/:clientId/edit` | client form |
+| `/app/animals` | list (name, species, breed, sex, current owners or « Propriétaire non renseigné »), search, species filter, « archivés » filter, « Nouvel animal » |
+| `/app/animals/new` | animal form with optional client selection or inline client creation; prefilled when opened from a client |
+| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct the dates of, or void (N4) a relation; edit, archive or restore |
+| `/app/animals/:animalId/edit` | animal form |
-An unknown id and a forbidden id show the same « not found » screen.
+An unknown id and a forbidden id show the same « introuvable » screen.
-Journeys:
+### 11.2 Journeys
-1. New client calling about a horse: Clients → new client → type the name,
- add the first animal in the same form → save → client page with the animal.
-2. Find an animal from a phone in a stable: Animaux → type part of the name or
- the identification → open the animal → see owners and keeper with the phone
- as a `tel:` link.
-3. Horse sold: animal page → add the new owner → end the old owner's relation
- → the old client stays, with its other animals, and appears as former owner
- on the horse's page.
-4. Owner unknown: a rider brings a horse without its owner's details → the
- animal is created with no client → its page and the list show
- « Propriétaire non renseigné », no placeholder client exists → the owner
- is added later.
+1. New client calling about a horse: Clients → Nouveau client → type the name,
+ add the first animal in the same flow → save → client page with the animal
+ linked as owner.
+2. Find an animal from a phone in a stable: Animaux → type part of the name →
+ open the animal → owners and keeper with their phone as a `tel:` link.
+3. Horse sold: animal page → add the new owner → end the former owner's
+ relation with the sale date if known → the former owner keeps their other
+ animals and appears as « ancien propriétaire ».
+4. Owner unknown: a rider brings a horse without the owner's details → animal
+ created with no client → its page and the list show « Propriétaire non
+ renseigné », no placeholder exists → the owner is added later.
5. Client archived: the confirmation lists the animals for which it is the
only current owner → archived → hidden from lists, visible under the
- archived filter, still shown on its animals' pages, restorable.
-6. Animal deceased, if `deceased_on` is kept (D6a): mark deceased with a date
- → the animal stays in lists with a « deceased » badge.
+ « archivés » filter, still shown on its animals' pages, restorable.
+6. A stable as keeper: create the structure « Écurie du Lac », link it as
+ keeper of a horse whose owner is a person.
+7. Species « Autre »: create a ferret as « Autre » with the detail « Furet ».
+
+Journeys run on desktop and phone, in FR and EN, and journey 1 also with the
+keyboard only.
+
+### 11.3 Forms
+
+- Client: « Personne / Structure » control at the top (« Personne » visibly
+ selected), then the name field whose label follows the kind, then contact
+ and address. Phone: international entry (`+32…`) accepted as typed; a
+ French national entry (`06 12 34 56 78`) is converted to `+33…` only when
+ the country is empty or France, and the converted value is shown in the
+ field before saving; with another country a national entry is refused with
+ « Indiquez le numéro avec son indicatif (+32…) ». Country: empty select,
+ never prefilled.
+- Animal: name, species (with the detail field shown and required for
+ « Autre »), sex as three explicit choices with none preselected (N8), breed,
+ birth as a year field plus an optional full date: entering the date fills
+ and locks the year, clearing it unlocks the year.
+- Relation: client picker with search, role, start date (optional); ending
+ asks for an optional end date.
+- Every form: labels on every field, required fields marked in the label,
+ errors under the field linked with `aria-describedby` and announced, focus
+ on the first error on submit; unsaved changes protected by a
+ `beforeunload` guard and by a confirmation on the form's own Cancel and
+ back actions (the app's declarative router has no navigation blocker, and a
+ data-router migration is out of scope); `conflict` shows the saved values
+ beside the typed ones and keeps the typed ones; after a partial failure of a
+ two-call creation the form keeps what was saved and retries the missing call
+ with the same request ids (§9.3).
+
+### 11.4 Layout and navigation
Desktop: the sidebar entries Clients and Animaux of the validated mockup become
-active; list and detail use the existing `Card`, `FormField` and `Button`
-components; no new visual direction. Mobile: single column, rows as cards with
-44 px targets, forms as full pages (no modal form), save bar reachable with
-the keyboard open. The tab bar question is decision D11; dashboard tiles are
-decision D12.
+active, in the mockup's order; list and detail use the existing `Card`,
+`FormField`, `Button` and `Badge` components; no new visual direction. Mobile:
+single column, list rows as cards with 44 px targets, forms as full pages (no
+modal form), the save action reachable with the keyboard open, « Afficher
+plus » at the end of a list (keyset pages), the drawer as navigation (D11).
+Dashboard tiles: D12. The screens follow `docs/design/` and are built with the
+project's design workflow.
-Accessibility applied in V1-1, not deferred to V1-5: every field labelled,
-errors linked with `aria-describedby` and announced, focus moved to the first
-error on submit and to the page heading on navigation, visible focus, no
-action reachable only by pointer, confirmation dialogs with focus trap and
-focus restore (decision D13), an axe check per screen in the browser tests.
-Unsaved form changes ask before leaving. Failure kinds are closed and phrased
-by i18n (FR and EN), like the auth and asset failures.
+### 11.5 Accessibility, applied in V1-1
+
+Every field labelled; errors announced; focus to the page heading on
+navigation and to the first error on submit; visible focus; nothing reachable
+only by pointer; confirmation dialogs with focus containment and focus
+restored to the opener, no new dependency (D13, final behaviour in §11.6);
+status changes (saved, archived) announced through a live region; an axe check
+per screen in the browser tests.
+
+### 11.6 V1-1.3 as built (2026-10-25)
+
+D13, final behaviour. `components/ui/ModalDialog.tsx` is the one modal
+primitive, on the platform's `` and `showModal()` (no dependency: none
+of the project's dependencies holds an accessibility primitive, and the
+browser's modal dialog is the proven one). `Dialog` and the mobile drawer are
+built on it.
+
+| Need | Behaviour |
+|---|---|
+| Name and description | the `` is named by its visible title (`aria-labelledby`); `Dialog`'s optional `description` is wired with `aria-describedby`; the four confirmations pass their message there (photo removal, replace session, held session, sheet disclaimer); long bodies (forms, drawings) carry no description; the drawer is named « Navigation principale » |
+| Opening | focus on the first control of the dialog (the close button for `Dialog`, the brand link for the drawer), set explicitly: Chromium would otherwise focus a scrollable panel when the content is long |
+| Containment | the rest of the page is inert (top layer): no focus, no click, no screen-reader access; the page does not scroll behind (`html:has(dialog:modal)`); Tab past the last control reaches the browser's own interface for one step, then the first control again, never the page (the platform's choice, kept: no hand-written trap) |
+| Escape and close requests | a request to the consumer through `onClose`, never a close by itself: the dialog leaves only when the consumer stops rendering it. The Escape keydown is cancelled, so Chromium's rule that closes a dialog on a second Escape after a cancelled one never applies; a close the platform forces anyway is reported to the consumer |
+| Closing controls | the close button (« Fermer » / « Close »), the backdrop and the consumer's own buttons, all through the same request |
+| Focus return | after the commit, to the opener when it can still take focus; otherwise to the first control of the opener's nearest container still on the page; nothing when the dialog opened without a focused opener (the disclaimer at editor load) |
+| Pending actions | a confirmation whose action is in flight refuses to close (Escape, Cancel, backdrop) and closes when the action settles: the photo removal now does so, so focus moves past the vanished button instead of falling on the page |
+
+Closing a dialog is never a save or a confirmed cancel: the consumer decides
+what a request means. The V1-1 forms are full pages (§11.4), so the unsaved
+changes confirmation of §11.3 belongs to the page, not to a dialog.
+
+D14, as built. `@playwright/test` 1.64.1 and `@axe-core/playwright` 4.14.0
+(axe-core 4.14.0), dev dependencies of `apps/app`, pinned; five packages in
+the lockfile (Apache-2.0 for Playwright, MPL-2.0 for axe, used unmodified).
+`pnpm e2e:ui` (no backend) and `pnpm e2e:shell` (the isolated stack), Chromium
+desktop and 375 × 667; details, guarantees and limits in
+`docs/development/BROWSER_TESTS.md`. Deviation from §12.5: the suites run
+against the isolated stack, not against DEV, which holds neither M1 nor M2 and
+stays untouched (owner choice, 2026-10-25).
+
+D11, the mobile navigation conflict, documented for the decision before
+V1-1.6 (owner, 2026-10-25: no tab bar in V1-1.3, current navigation kept, the
+validated mockups unchanged).
+
+| Source | Mobile navigation |
+|---|---|
+| Implemented | top bar (menu button, brand, language switcher, avatar link to Mon compte); the drawer (modal since V1-1.3) with the sidebar entries Tableau de bord, Mon compte, Outil de bilan, then the user badge and « Se déconnecter »; no bottom tab bar |
+| Validated mockups (`docs/design/README.md` items 5 to 7) | the same drawer, plus a bottom tab bar on the dashboard and the profile: Accueil, Bilans, Agenda, Profil; the README places the bar « with the first list screens » |
+| D11 recommendation (§13.3) | drawer only in V1-1; the mockup's tab bar arrives with Bilans (V1-3), when its entries lead somewhere |
+
+| Option for the Clients and Animaux routes | Consequence |
+|---|---|
+| Drawer only (D11) | Clients and Animaux join the drawer and the sidebar; two taps from any page; no destination that leads nowhere; the README line moves to V1-3 once decided |
+| The mockup's bar now | Bilans and Agenda lead nowhere until V1-3 and later (hidden or disabled tabs); Clients and Animaux stay in the drawer anyway; a fixed bottom bar competes with the save action that §11.4 keeps reachable with the keyboard open |
+| A bar adapted to V1-1 (Accueil, Clients, Animaux, Profil) | one tap to the V1-1 screens; departs from the validated mockup, so it needs a new validated design file first; the bar changes again when Bilans and Agenda arrive |
+
+### 11.7 V1-1.5 as built (2026-10-26)
+
+Owner choices of 2026-10-26, asked before the screens: U1 « Afficher plus »
+(keyset pages of 25, no numbered page), U2 one « Afficher les archivés »
+toggle, the client page shows its animals read-only (no link, no « ajouter »
+until the animal screens), the « Ajouter un premier animal » section of
+`/app/clients/new` moves to V1-1.6 with the animal screens.
+
+| Part | As built |
+|---|---|
+| Access layer | `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspaceId`), `clients.ts` (search with one probe row for « Afficher plus », read by id with an explicit column list and no request for an id that is not a uuid, create with a request id, update sending every field, archive, client animals, archive preview), `species.ts` (labels), `records.ts`: the closed kinds of §9.4 plus `session_expired` (HTTP 401, PGRST30x) and `network` (no answer); every RPC answer checked by Zod. Proven by unit tests and by `tests/sandbox/clients-access.sandbox.ts`, the same functions through supabase-js against the sandbox's real GoTrue and PostgREST |
+| Personal workspace | read by `state/authStore.ts` with the account: `loading`, `ready`, `inactive` (profile deactivated), `unconfirmed` (no confirmed email), `missing`, `error`; never created in the browser. A change of account drops profile, roles, avatar and workspace in the same update, and an answer that arrives for the previous account is ignored. `app/guards/RequireWorkspace.tsx` renders the client routes only when ready and remounts them per workspace |
+| Routes | `/app/clients`, `/app/clients/new`, `/app/clients/:clientId`, `/app/clients/:clientId/edit` (`app/routes/app/clients/`); an unknown, foreign or malformed id shows the same « Client introuvable » inside the shell |
+| List | search sent after 300 ms without typing (POST, the term never in a URL), the archived toggle, rows with kind, city, phone and `current_animal_count`, « Afficher plus », loading, empty, no-result, error and retry states, the row count announced |
+| Form | `clients/validation.ts` on `field-limits.ts` (D-R7: code points, control ranges, email pattern, ISO country list); the phone entry rule of §11.3, shown converted when the field is left; « Personne » checked, the name label follows the kind, required and optional marked in the labels, the first error focused; one request id per creation intent, sent again on a retry; on `conflict` the stored values appear under the fields that differ, the typed ones stay, the next save applies them knowingly; submit guarded against double clicks; the save bar stays reachable at the bottom on a phone |
+| Page | identity, kind and archived badges, phone as `tel:`, email as `mailto:`, address and country name, the animals read-only (current then former, role, dates when known, species name); archive through a confirmation listing the active animals for which the client is the only current owner (it refuses to close while the request runs), restore by one button, outcomes announced |
+| Leave guard | `useLeaveGuard`: `beforeunload` while the form holds changes, and `AppLayout` asks before following any in-app link (sidebar, drawer, top bar, the form's own « Annuler »); the browser's back and forward buttons are not intercepted (declarative router, §11.3) |
+| Navigation | « Clients » in the sidebar and the drawer after « Tableau de bord » (the validated mockup's order); no tab bar (D11 unchanged) |
+| Focus | each client page focuses its heading when it opens, also when opened from the drawer (after the drawer closed and returned focus) |
+
+Deviations and limits: the contract's `beforeunload` plus Cancel guard is
+extended to every in-app link; the search term and the archived toggle are not
+kept when returning from a client page (no storage of terms); phones show in
+E.164 as stored; the dashboard tiles (D12) are not built. The shell's top bar
+already carried an `h1` with the page title on large screens before V1-1.5;
+the client pages add their own `h1` in `main`, as the existing pages do.
+
+Tests: supabase vitest 92 (access layer 33), sandbox suites 54 (access layer
+8); app vitest 509 (client screens 22, form schema 20, store 16); Chromium
+`e2e:shell` 42 (client journeys 36: create, search, edit, archive, archived
+filter, restore, pages, keyboard only, two accounts, concurrent edit, retry
+after a lost answer, network failures, leave guard, change of language; FR
+and EN, desktop and 375 px, axe on every state with no exception of RR-7
+inherited). Report check: the shell suite's HTML report kept the typed
+passwords of its throwaway accounts; it was removed (`BROWSER_TESTS.md` §3).
+Gates also found: a re-read of the same account (`USER_UPDATED`) set the
+workspace back to loading and unmounted an open form (fixed: a ready workspace
+stays on screen until the answer); the « introuvable » screen did not focus its
+heading (fixed).
+
+### 11.8 V1-1.6 as built (2026-10-26)
+
+Owner decisions of 2026-10-26: D11 drawer only for V1-1 (the mockup's tab bar
+is not reproduced, stays the direction for a later UX step, the mockup is
+unchanged); the first animal of a client is created from the client page
+(« Ajouter un premier animal ») with that client pre-associated, in one
+`create_animal` call, so the client form does not change; no relation role is
+preselected; linking a client or an animal is a panel inside the page, ending,
+correcting dates and voiding are confirmations; U3 as recommended (a full date
+fills and locks the year). The dashboard tiles (D12) are outside the brief's
+scope and not built.
+
+| Part | As built |
+|---|---|
+| Access layer | `packages/supabase/src/animals.ts`: `searchAnimals` (POST, 25 + one probe row, `species_filter`), `fetchAnimalRecord` (explicit columns, no request for a non-uuid id), `createAnimalRecord` (the optional first relation in the same call, `{id, revision, relationId}`), `updateAnimalRecord` (the seven fields, null included), `setAnimalArchived`. `relations.ts`: `fetchAnimalRelations` (one select by animal id, the client embedded through `animal_client_relations_client_fk`, `voided_at is null`, at most 200), `createAnimalClientRelation`, `endAnimalClientRelation`, `updateAnimalClientRelation`, `voidAnimalClientRelation`. `records.ts`: kinds `duplicate_relation`, `already_ended`; every answer checked by Zod |
+| Routes | `/app/animals`, `/app/animals/new`, `/app/animals/:animalId`, `/app/animals/:animalId/edit`, under the same `RequireWorkspace` as the client routes (one gate, remount per workspace); an unknown, foreign or malformed id shows « Animal introuvable » |
+| Species | read once per workspace, when a page needs them (`SpeciesProvider` inside `RequireWorkspace`), dropped with the workspace on a change of account |
+| List | search after 300 ms (name, breed, species detail; POST), species filter over the active rows, « Afficher les archivés », « Afficher plus »; rows with species (and detail), breed, sex, the current owners (three names and the rest counted) or « Propriétaire non renseigné » |
+| Form | identity: name; species from the active rows; detail shown and required for « Autre », dropped for any other species; sex as three choices, none checked; breed. Birth: a year, or a full date that fills and locks the year (clearing it leaves the year editable); not after the device's date, not before 1900. On a creation, the optional client: a search among the active clients, then the role (required, none preselected) and the start date. One request id per form, sent again on a retry; `conflict` shows the stored values; leave guard |
+| First animal | « Ajouter un (premier) animal » on an active client's page opens the form with the client id in the navigation state, never in the URL; the form reads the client again and pre-associates it only when it is active in this workspace, else says so; the client can be removed before saving; the save returns to the client page |
+| Animal page | identity (species, sex, breed, birth with its precision: a date and the age, a year and « environ », or « Inconnue »; status), then « Clients liés »: current relations by role then name, the history by end, each with the client's page link, an archived badge, the phone as `tel:` and the dates when known; « Propriétaire non renseigné » without a current owner. On an active animal: « Ajouter un client » (panel), « Terminer » (optional end date, not before the start), « Corriger les dates », « Erreur de saisie » (voiding, explained as for a relation that never existed, final). An archived animal shows no action. Voided relations are never read |
+| Confirmations | `Dialog` on `ModalDialog`; while the write and the reload that shows it run, the dialog refuses to close, so focus returns once the row has moved (to the opener, or the first control of its section when the opener left); `conflict` or `not_found` reloads the relations and says the relation changed elsewhere; any other failure stays in the dialog with the typed date |
+| Client page | the animals once per animal and group (current, former) with every role the client holds and the dates, each a link to the animal; « Ajouter un premier animal » / « Ajouter un animal » and « Associer un animal existant » (panel: search among the active animals, role, start date); neither on an archived client |
+| Navigation | « Animaux » after « Clients » in the sidebar and the drawer (the mockup's order); no tab bar |
+| Shared components | `Card` now passes `aria-labelledby`: it dropped it silently, so the section cards of V1-1.5 had no accessible name (found by the browser suite); `Button` takes `ref` (a React 19 prop); `ChoiceRadios` (the client kind's look) for sex and role |
+| Technology boundary | no new business rule outside SQL: caps, duplicates, archived states, dates, revisions and idempotence are the M3 RPCs'; the TypeScript schemas are the D-R7 form checks on the constants proven equal to the CHECKs; age, grouping and order are display formatting. Nothing was added to `crates/`: no rule here is shared with a service or worth a wasm call |
+
+Deviations and limits: a write on a voided relation is `invalid_input` on the
+server, but a page that still shows the relation holds an older revision and
+gets `conflict` first (lock order archived, revision, voided), so the page
+reloads and the row is gone, with no separate « annulée » message; the
+confirmations leave without their exit animation; the picker lists active
+records only (an archived client or animal cannot be linked, §7.1); the
+browser's own date control shows the browser's date format; the limits of
+V1-1.5 stay (search not kept on return, E.164 display, back and forward not
+guarded).
+
+Tests: supabase vitest 127 (animal and relation access 35); sandbox suites 61
+(`animals-access.sandbox.ts` 7: the same functions through supabase-js against
+the sandbox's GoTrue and PostgREST); app vitest 566 (animal screens 35, form
+schema and display rules 22); Chromium `e2e:shell` 82 (animal journeys 40:
+an « Autre » without owner, search, species filter, edit, archive and
+restore; pages of 25; the first animal from a client page and an existing
+animal linked; co-owners, a keeper structure, a refused duplicate, a voided
+mistake, the sale ended with its date; two accounts and a change of session;
+keyboard only; a concurrent edit; a retry after a lost answer; network
+failures and an archived client refused; a change of language; FR and EN,
+desktop and 375 px, axe on every state). Counter-checks: 12 deliberate faults
+(request id per attempt, voided rows read, a detail kept for any species, a
+date that does not fill the year, a dialog closing on failure, a preselected
+role, an archived origin client, no grouping per animal, the species filter
+dropped, a default sex, an end before the start, a conflict without reload)
+caught by the unit suites; `Card` dropping its name and a request id per
+attempt caught by the browser journeys. Gates: security audit PASS (no
+HIGH; LOW: an operator can still ask Playwright for a trace on the command
+line); independent verifier CONFORME 12/12 at the third round. It found the
+client journey failing after its end on a late reload (fixed for every shell
+suite) and a pgTAP check of V1-1.4 reading a workspace uuid as a date (« …2012-… »),
+which would have stopped `db:test` in the DEV procedure (fixed in the test, no
+migration).
---
-## 8. Tests and Definition of Done
+## 12. Tests and Definition of Done
-### 8.1 SQL (pgTAP, PGlite and real stack)
+### 12.1 SQL (pgTAP, on PGlite and on the real stack)
-- RLS enabled, no API write grant, explicit column grants; census tests
- (`001`, schema↔types) updated.
-- Allowed and denied per actor of §5.1: member reads and writes; second
- account, anonymous, deactivated account and each platform role read
- nothing and every RPC refuses with 42501; unknown id and forbidden id give
- the same error.
-- Every CHECK of §4 accepted at its bound and refused one step past it; a
- client with only a display name accepted; `species_detail` required with
- `other` and refused otherwise; a `birth_date` whose year differs from
- `birth_year` refused, a `birth_year` alone accepted.
-- Same-workspace link rule; an animal with no owner link accepted; a second
- current (animal, client, role) row refused; an ended relation kept and
- readable; archived records refuse edits; archiving a client leaves its
- animals and links unchanged; stale `updated_at` refused.
-- Audit rows written for each RPC, with no name, contact or note in them.
-- Personal workspace created for a new profile and backfilled for existing
- ones; the D9a behaviour as decided.
+Files: `012_workspaces.sql`, `013_clients.sql`,
+`014_animals_relations.sql` (258 checks); updates to `001_schema.sql` (tables, RLS,
+privileges, helper census) and to `packages/supabase/tests/db/schema-types.test.ts`;
+the PGlite harness loads `unaccent`.
-### 8.2 Cross-account on the real stack
+Actors: A and B, two confirmed active accounts with their workspaces WA and
+WB; C, an account with an unconfirmed email; D, an account deactivated after
+creating records; S, a platform owner and admin; `anon`; `service_role`.
-An e2e file beside `avatar-flow.e2e.ts`: two users created through the admin
-API on the local stack; A creates a client and an animal; B lists (empty),
-reads by id (nothing), updates, archives, links (42501); the anon key reads
-nothing; A deactivated by SQL loses access. Run by `pnpm` script on the DEV
-origin.
+| Owner's case | Proof |
+|---|---|
+| Two accounts, two workspaces | A and B each get exactly one personal workspace with a `holder` membership (trigger); the backfill function, called on a profile inserted with the trigger disabled inside the test transaction, creates one and is idempotent on a second call; a second personal workspace for A is refused |
+| Read allowed | A reads its workspace, membership, clients, animals and relations |
+| Read forbidden | B, C, D and S read zero rows of WA in every table, through `search_clients`, `search_animals`, `list_client_animals` and `client_archive_preview` with WA's ids, and through a `count` query; `anon` and `service_role` get `permission denied` |
+| Write allowed | A runs every RPC on WA records |
+| Write forbidden | B, C, D and S calling every RPC on WA ids get the same whole error (SQLSTATE, message, detail, hint) as with a random uuid, and take no lock on WA rows; `anon` cannot execute any RPC |
+| Reference between workspaces refused | B linking its animal to A's client gets 42501; a direct insert as `postgres` with mismatched workspaces fails on the composite foreign key |
+| Archive and restore | an archived client or animal refuses updates (`archived`), keeps its relations, leaves search by default and appears with the archived filter; restore re-enables edits; archiving a client changes none of its animals |
+| Historical relations | ending keeps the row with `ended_at`; a second current identical relation is refused; a successive one after the end is accepted; `ended_on` refused on a current relation and before `started_on`; ending an ended relation gives `already_ended`; relations of an archived animal are frozen |
-### 8.3 Application
+Also: a client with only a name and a kind accepted; the five birth states
+of §5.2 (bounds of the fields with a TypeScript twin are proven by §12.2);
+`species_detail` with and without `other`; an inactive species refused; dates
+in the future refused, and 1 January accepted on 31 December UTC; a malformed
+date answered `invalid_input` without its value; stale revision refused, and
+`archived` reported before `conflict`; a replayed `create_request_id` returns
+the first row; caps reached with rows inserted by `generate_series`; the write
+budget (hour and day) reached with audit rows inserted as `postgres`; one audit
+row per write with no name, contact or date in it; an oversized or malformed
+`x-correlation-id` stored as null; search folding accents and case, escaping
+`\`, `%` and `_`, matching « 06 12 », « 0612345678 » and « +33 6 12 »,
+the species filter excluding a row, keyset pages without gaps or duplicates;
+derived values of §9.3 (two roles on one animal counted once, archived owner
+shown); two concurrent identical relations giving one row and one
+`duplicate_relation`; D9a (an account with records cannot be deleted, an empty
+one is, with its workspace); each definer function pinned (owner context,
+search path, ACL); a config test pinning `enable_confirmations = true`.
-- Unit and component tests: form schemas (each rule, i18n keys), list and
- search states (empty, results, error), archive and restore flow, conflict
- message, « Propriétaire non renseigné » state, route guard, i18n key parity.
-- Constraint parity test (D-R7): the TypeScript constants equal the SQL CHECK
- bounds read from `pg_constraint` on PGlite.
+### 12.2 Constraint parity (D-R7)
-### 8.4 Real browsers
+`packages/supabase/src/field-limits.ts` holds the V1-1 bounds and patterns
+(lengths, years, email and phone patterns, control ranges), read by the app's
+Zod schemas. `packages/supabase/tests/db/field-limits.test.ts` proves them by
+behaviour on PGlite: for each constant it inserts a value at the bound and one
+step past it and expects acceptance then refusal, so no SQL text is parsed.
+Counting rule: `char_length` counts code points, so the TypeScript check counts
+`[...value].length`; Zod's `.max()` counts UTF-16 units and is not used alone
+on these fields. The existing auth and account forms stay with the separate
+D-R7 chore.
-A Playwright suite under `apps/app/e2e` (decision D14: `@playwright/test`
-and `@axe-core/playwright` as dev dependencies), run against `pnpm dev` and
-the local stack on the DEV origin:
+### 12.3 Real stack (integration)
-- desktop Chromium, Firefox and WebKit; phone viewports 375 × 667 and
- 412 × 915;
-- journeys 1 to 6 of §7;
-- the creation journey with the keyboard only;
-- two browser contexts: B opens A's client URL and gets « not found »;
-- no client or animal name in any URL;
-- an axe scan on each screen, zero serious or critical violation.
+`packages/supabase/tests/e2e/clients-animals.e2e.ts`, beside
+`avatar-flow.e2e.ts`, run by a root script on the DEV origin: A and B created
+through the admin API; A creates a client, an animal and a relation; B lists
+nothing, reads nothing by id, and every RPC answers 42501; the anon key reads
+nothing; the service key's select on `clients` is refused; an unconfirmed user
+cannot obtain a session; A deactivated by SQL loses access; deleting A
+through the GoTrue admin API while A holds records fails and leaves user,
+profile and records intact. Seeding (20 000 clients for the measurement) and
+teardown go through the privileged SQL helper the avatar e2e already uses
+(`docker exec ... psql`): `afterAll` deletes the run's records, then its users.
+The search time on 20 000 clients is a recorded measurement, not a pass/fail
+assertion.
-Then the owner's manual check on a real phone and a computer over the LAN.
+### 12.4 Application
-### 8.5 Definition of Done
+Unit and component tests: form schemas per rule with i18n keys and the code
+point count; phone conversion rule; birth input states; list and search states
+(empty, results, error, more pages); archive and restore flow with the dialog
+focus trap; conflict message; archived read-only state; « Propriétaire non
+renseigné »; not-found screen for unknown and forbidden ids; route guard; i18n
+key parity.
+
+### 12.5 Real browsers (Playwright and axe, D14)
+
+A suite under `apps/app/e2e`, run against the isolated stack of
+`pnpm db:sandbox` and a loopback dev server of its own (V1-1.3 deviation: DEV
+holds neither M1 nor M2 and stays untouched, §11.6). In V1-1: Chromium, desktop and a 375 × 667 phone viewport (Firefox,
+WebKit and 412 × 915 join at V1-5: WebKit's system libraries need `sudo`, a
+user action, and desktop WebKit is not iOS Safari, which the owner's real
+phone covers); journeys 1 to 7 of §11.2; the creation journey with the
+keyboard only; two browser contexts where B opens A's client URL and gets
+« introuvable »; every request the page sends (`page.on('request')`) checked
+to hold no fixture name or search term in its URL; an axe scan on each screen
+with zero serious or critical violation. Then the owner's manual check on a
+real phone and a computer over the LAN.
+
+### 12.6 Definition of Done
All tests above green; `pnpm check:all`; `pnpm db:reset && pnpm db:test`;
-regenerated `database.types.ts`; fresh verifier and security gates; docs
-(a domain document for clients and animals, CLAUDE.md folder map and
-architecture, `docs/design/README.md` owners table); report format, PDF,
-sheets and local tool unchanged; nothing deployed, Supabase DEV untouched
-outside `db:reset` of the local stack.
+`pnpm db:types:check`; fresh verifier and security gates; documents updated
+(this contract's "as built" notes, `CLAUDE.md` folder map and architecture,
+`docs/design/README.md` owners table, `SUPABASE.md`); report format, PDF,
+sheets and local tool unchanged; nothing deployed; no merge into `develop`
+without the owner's go.
---
-## 9. Orientations and decisions
+## 13. Decisions
-### 9.1 Owner orientations of 2026-10-25 (proposed, awaiting ratification)
+### 13.1 Approved by the owner on 2026-10-25 (BDR-073)
-All are needed before the first migration. « SQL » marks an orientation that
-fixes a table shape or a constraint, « permissions » one that fixes a policy
-or an RPC check.
+| Id | Decision |
+|---|---|
+| D1 | Interface term « Clients » (EN "Clients"); a client is a natural person or a professional or associative structure; Propriétaire, Détenteur and Contact are roles of its relation to an animal, distinct from its identity; consistent FR and EN terms; no platform role reused as the owner of an animal |
+| D2 / C4 | `workspaces` and `workspace_members`; one personal workspace per practitioner in V1-1; cabinet workspaces possible later without destructive transfer; no global client directory; no data visible between practitioners; no sharing, invitations or cabinet permissions in V1-1 |
+| D3 | Two client kinds: natural person, structure |
+| D4 | Required: a display name for a person, a name (dénomination) for a structure; every other detail optional at creation; no country imposed silently; no email or phone imposed; billing, booking and regulatory needs belong to their steps |
+| D4a | Optional separate first and last names allowed for persons; the display name stays the required reference; the contract defines the rule between them (§5.1) |
+| D5 | Exactly the nine species of the contract plus « Autre » with a required detail; no invented species; a recordable species does not mean a sheet exists; the equine draft is never published automatically |
+| D6 | Required: name, species, sex with an explicit `unknown`; optional: breed, full birth date when known, birth year alone when only the year is known; weight, photo, detailed identification, coat colour, neutering status, date of death and further notes deferred; no complete veterinary record |
+| D6a | The fields beyond the owner's list (neutering, identification, colour, notes, date of death) are deferred, not built in V1-1 |
+| D6b | A year is never turned into a date; the representation keeps the precision given, with coherence constraints and tests (§5.2) |
+| D7 | Many-to-many relation with an explicit role (owner, keeper, contact); co-ownership allowed; an animal may have no identified owner and always belongs to a valid workspace; no fictitious client to satisfy a constraint; never a relation across workspaces |
+| D7a | Relation history with a start date when known and a nullable end (`ended_at`); no incoherent current duplicates, successive relations allowed; a change of owner or keeper never deletes history silently |
+| D8 | Functional archive, read-only, reversible; historical relations kept; archiving a client does not archive its animals; archiving an animal does not delete its relations; archive is not erasure; no retention duration |
+| D9 / D9a | A temporary DEV protection may block an account deletion that would leave incoherent data, never a permanent ban; the future lifecycle distinguishes closure, deletion or anonymisation, justified retention, shared records and reassignment in cabinets; V1-1 implements none of it and makes none of it impossible; no legal retention invented |
+| C5 | V1-1 writes only by the authorised practitioner in their personal workspace; data isolated between workspaces; model ready for cabinet permissions; current-data edits never change finished bilans silently |
+| C6 | Email confirmed, professional status verified and platform role are three distinct notions; a confirmed email gives private use of the workspace; verification required later for public features; no verified status by default; verification stays plan Step 9 |
+| D16 | No ordinary staff access to clients, animals or private bilans; no general admin screen on them; exceptional privileged access framed and audited by a separate policy before publication; no impersonation or exceptional support access in V1-1 |
+| D15 | Principle of technical caps protecting the service, distinct from commercial quotas; thresholds proposed in §10 for validation before the RPCs |
+| Naming | Explicit nomenclature (§3); no generic `owner_id` |
-| Id | Orientation | Impact |
-|---|---|---|
-| D1 | Interface term « Clients »; Propriétaire, Détenteur and Contact are roles of the relation to an animal; the client entity is never confused with its role | SQL: table `clients`, link roles `owner` / `keeper` / `contact` |
-| D2 / C4 | `workspaces` and `workspace_members`; one personal workspace per practitioner in V1-1; records attached to a workspace; no global client directory; cabinets later, not built in V1-1 | SQL and permissions: every policy and RPC goes through the workspace helper |
-| D3 | Persons and structures (écuries, haras, associations, entreprises, other legal entities), with an explicit distinction in the model | SQL: `kind` column and CHECK |
-| D4 | The display name or company name is the only required field; contact details optional at creation; later steps set their own requirements | SQL: one required column; no NOT NULL on contact columns |
-| D5 | The nine species of this contract plus « Autre » with a detail; no new species; no automatic sheet per species; a species may exist with no usable sheet | SQL: reference rows by migration; `species_detail` CHECK |
-| D6 | Name and species required; sex with `unknown`; breed optional; birth year optional; a full date when known, never invented from a year; weight and photo deferred | SQL: `sex` CHECK and default; `birth_year` / `birth_date` coherence CHECK |
-| D7 | Many-to-many relation with an explicit role per link; co-ownership; owner unknown or not entered allowed with no fake client; no SQL rule forcing an owner while that is undecided | SQL: link table with no minimum-owner constraint |
-| D8 | Archive read-only and reversible; historical relations kept; no cascade from a client to its animals; no retention duration; archive is not erasure | SQL and permissions: `archived_at` columns, RPCs refuse edits on archived rows |
-| D9 | No rule blocking an account's deletion for good; a later lifecycle contract (closure, deletion or anonymisation, justified retention, cabinet records, legal obligations); nothing implemented in V1-1, nothing in the model preventing it | SQL: delete behaviour of the keys to the profile (D9a) |
-| D16 | No ordinary staff access to private records; no admin screen on clients, animals or bilans; exceptional technical operations framed, justified and audited before publication; no exceptional access mechanism in V1-1 | permissions: no platform-role branch in any policy or RPC |
-| C5 | Writes reserved to workspace members with a write right; in V1-1 only the practitioner in their personal workspace; finished bilans never changed retroactively or silently | permissions |
-| C6 | Email confirmation distinct from professional verification; a confirmed email gives private use; verification required for public professional features; statuses are not platform roles; verification process not built now | permissions: the V1-1 gate is an active session |
+### 13.2 Technical choices, decided by the owner on 2026-10-25 (BDR-074)
-### 9.2 Sub-choices the orientations leave open (SQL, before the migration)
+The owner validated N1 to N9 with the precisions of the last column; they
+prevail over the recommendation where they differ (N4, N6, N9).
-| Id | Question | Recommendation | Alternative |
+| Id | Question | Recommendation (preparation) | Owner decision, 2026-10-25 |
|---|---|---|---|
-| D4a | Structured first and last name for persons | not in V1-1: one `display_name`; nullable columns can be added later without touching existing rows | a required `last_name` for persons (a second required field, against D4) |
-| D6a | Fields beyond the owner's list: `neutered`, `identification`, `colour`, `notes`, `deceased_on` | keep all five, optional | drop any of them; adding one later is an additive column |
-| D6b | Birth date model | `birth_year` plus an optional `birth_date`, with the coherence CHECK | one `date` with a precision flag: stores an invented day for a year-only birth, which D6 refuses |
-| D7a | Ending a relation | `ended_at` on the link, the row kept as history | delete the row; the history then survives only as ids in the audit log |
-| D9a | Deleting, in DEV, an auth user whose personal workspace holds records | a temporary guard refuses it, replaced by the lifecycle contract; an account with no record is deleted as today | cascade (erases the records with the account, deciding the policy early) or keep an orphaned workspace (records nobody can read) |
+| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | approved: exactly the nine species of the contract plus `other` with a required detail, no invented species, no historical anatomical id renamed; compatibility with the Rust model and Supabase checked before freezing anything (§5.4: rows, not an enum) |
+| N2 | First and last names for persons (D4a) | not in V1-1 | approved: no separate names in V1-1; `display_name` is the required reference and the single source of truth |
+| N3 | Client notes | defer, like animal notes (minimisation) | approved: deferred; no free-text field without an identified business need |
+| N4 | Correcting a relation entered by mistake | an explicit, audited deletion | changed: a traceable logical voiding (`voided_at`, `void_animal_client_relation`), distinct from the normal end of a relation; a voided relation stops appearing as current or former without its history being falsified; `ended_on` never represents a period that never existed; minimised audit row (§5.3, §9.3); nothing built before V1-1.4 |
+| N5 | Relation dates | optional `started_on` and `ended_on`, plus `ended_at` recording time | approved: both dates optional, never invented, ordered when both are known; an end date is not a deletion; SQL constraints written in §5.3 before V1-1.4 |
+| N6 | Thresholds of §10 | as proposed, write budget per actor | approved as technical caps (not commercial quotas), with the write budget per workspace: 1 000 an hour, 5 000 a day; caps enforced consistently under concurrency, never a bare count then an unprotected insert; counters and locks documented when the RPCs are written; no quota system in V1-1.1 |
+| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` | approved as minimisation, without claiming it removes every administrative path: effective grants examined, direct privileges removed, EXECUTE limited, definer owners checked, access tested for anon, authenticated and service_role; global Supabase privileges and existing tables unchanged without a specific decision; the GoTrue admin residual risk stays on the pre-production security track (§6.3) |
+| N8 | Sex in the form | three explicit choices, none preselected | approved: nothing preselected, « Inconnu » chosen explicitly, a missing answer never turned into a value |
+| N9 | Audit rows read by platform owners and admins | exclude the V1-1 actions from `audit_logs_select_admin` (M2) | approved: no general staff view of private client and animal data; audit rows limited to technical id, operation, time, result and bounded validated correlation ids; no name, contact, observation or business data; append-only kept; caller-controlled growth bounded (correlation cap in M1, §8.1) |
-### 9.3 Decisions still open
+### 13.3 Interface decisions still open
-Not arbitrated by the owner; status open, recommendation and impact given.
-
-Before the RPCs are written (they change server behaviour):
+Not ratified; recommendation and impact given.
| Id | Decision | Recommendation | Impact |
|---|---|---|---|
-| D15 | Abuse guard | per-workspace caps (20 000 clients, 50 000 animals) refused by the create RPCs | RPC behaviour, no table change |
-
-Before or during the interface work (no table impact):
-
-| Id | Decision | Recommendation | Impact |
-|---|---|---|---|
-| D10 | Client information notice: text, and whether the app records that it was given | decide with the legal texts; nothing recorded in V1-1 | none in V1-1; recording it later adds a column; required before public exposure |
-| D11 | Mobile navigation | drawer only in V1-1; the tab bar of the mockup arrives with Bilans (V1-3), since two of its four entries would lead nowhere today | UI |
-| D12 | Dashboard tiles | show the two real tiles (clients, animals) now; bilans and appointments when their tables exist | UI |
-| D13 | Shared `Dialog` focus trap and restore | fix it in V1-1 (it also improves the editor dialogs; partial RR-7) | UI, shared component |
-| D14 | Real-browser test tooling | add `@playwright/test` and `@axe-core/playwright` as dev dependencies | manifest and lockfile change at implementation |
+| D10 | Client information notice: text, and whether the app records that it was given | decide with the legal texts; nothing shown or recorded in V1-1 | none in V1-1; recording it later adds a column; required before public exposure |
+| D11 | Mobile navigation | decided by the owner on 2026-10-26: the drawer only for V1-1, Clients and Animaux in it; the mockup's tab bar is not reproduced and stays the direction for a later UX step (§11.8, `docs/design/README.md`) | UI |
+| D12 | Dashboard tiles | open: outside the V1-1.6 brief, not built; recommendation unchanged (the two real tiles from live counts when the owner asks; bilans and appointments when their tables exist) | UI |
+| D13 | Shared `Dialog` focus containment and restore | approved 2026-10-25, built in V1-1.3 on the native modal dialog (§11.6) | shared component |
+| D14 | Real-browser test tooling | approved 2026-10-25, built in V1-1.3: Playwright 1.64.1 and axe 4.14.0, Chromium desktop and 375 px, against the isolated stack (§11.6) | manifest and lockfile; Chromium build 1248, no `sudo` |
| D17 | Bridge to the local tool (« start a bilan for this animal », prefill only) | no: V1-3 links bilans to animals properly; a prefill now would be a second path to delete later | none |
+| U1 | Long lists | « Afficher plus » (keyset pages of 25), no numbered pages | UI |
+| U2 | Archived records | one « archivés » toggle on each list, not a separate tab | UI |
+| U3 | Birth input | decided 2026-10-26 as recommended: year field plus optional full date that fills and locks the year (§11.8) | UI |
-### 9.4 Never assumed, framed before any public exposure
+### 13.4 Never assumed, framed before any public exposure
-The legal basis of the processing (consent is not presumed to be required),
+The legal basis of each processing (consent is not presumed to be required),
the information given to clients, the retention durations, the deletion and
-anonymisation rules, the legal qualification of each party. None of them
-blocks a DEV implementation once §9.1 is ratified; each blocks any public
-exposure.
+anonymisation rules, the legal qualification of each party. None of them blocks
+a DEV implementation with fictitious data; each blocks any public exposure.
-Ratifying §9.1, answering §9.2 and settling D15 unlock the first migration,
-on a `feature/` branch off `develop`.
+---
+
+## 14. Implementation steps and risks
+
+Each step is a vertical, testable unit on `feature/v1-1-clients-animals`,
+detailed in `.claude/tasks/TODO.md` (objective, dependencies, files,
+migration, tests, acceptance, security checks, stop conditions). The owner
+validates after V1-1.1 and after the first UI step; nothing merges into
+`develop` without the owner's go.
+
+| Step | Content |
+|---|---|
+| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), validated 2026-10-25; not applied to DEV |
+| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, sandbox suite. Written and tested on the isolated stack (§8.2), validated 2026-10-25; not applied to DEV |
+| V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13). Built (§11.6), validated 2026-10-26 |
+| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof. Written and tested on the isolated stack (§8.3), validated 2026-10-26; not applied to DEV |
+| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry. Built and tested on the isolated stack (§11.7), validated 2026-10-26 |
+| V1-1.6 | Animals and relations UI, navigation (D11: drawer only), documents, closure inventory (§15). Built and tested on the isolated stack (§11.8), validated 2026-10-26; D12 not in its brief; the owner's check over the LAN needs M1 to M3 on DEV |
+
+Recommended first step: V1-1.1. It is SQL only, has no visible choice, and
+every later step depends on its helpers.
+
+Risks and dependencies:
+
+- the service key and the JWT secret give full access through GoTrue admin
+ (§6.3); follow-ups outside V1-1, on the release track (RR-4): a narrower
+ worker credential (a dedicated Postgres role behind a custom-role JWT, which
+ GoTrue admin refuses) and monitoring of `auth.audit_log_entries`;
+- `unaccent` must load on PGlite (the contrib ships with 0.3.16; the harness
+ needs it) and on the CLI stack; otherwise the fold falls back to
+ `translate()` over a committed accent table, a decision for the owner;
+- the D9a guard makes GoTrue's admin delete fail (« Database error deleting
+ user ») for an account with records: expected, documented, tested;
+- the audit log stays append-only with no retention: its growth is bounded
+ (§10), its retention belongs to the lifecycle contract;
+- DEV holds fictitious data only until the legal framing (§7.3);
+- `docs/design/README.md` places the mobile tab bar « with the first list
+ screens », which D11 contradicts until the owner decides;
+- the RPC surface grows by fourteen functions (RR-4 review); N4 replaces the
+ delete RPC by `void_animal_client_relation`, so the count is unchanged;
+- the D-R7 chore for the existing forms reuses the V1-1 constants module;
+- no CI runs on the forge: every gate is local;
+- two old R5.6 rehearsal worktrees in an earlier session's scratchpad hold
+ uncommitted edits; they are not V1-1 work and are left to the owner.
+
+---
+
+## 15. Closure inventory (V1-1.6, 2026-10-26)
+
+Owner brief §21. Status words: **done** (built, tested on the isolated stack),
+**debt** (non-blocking, documented, kept in the product follow-up),
+**deferred** (left out on purpose, with who decided), **blocking** (before a
+merge into `develop`), **DEV** (to verify once M1 to M3 are applied, SUPABASE.md
+§3.3). Nothing below is verified on DEV: no V1-1 migration is applied there. The
+read-only preflight of DEV (2026-10-26) found M1 to M3 pending and nothing
+else, and none of their objects present (SUPABASE.md §3.3).
+
+| Area | Item | Status | Proof or reason |
+|---|---|---|---|
+| Workspaces | creation at sign-up, one per account | done | trigger and backfill (§8.1); pgTAP 012; `workspaces.sandbox.ts` (sign-up, parallel GoTrue sign-ups, races, rollback) |
+| Workspaces | read, isolation, account change in the app | done | RLS helpers; `authStore` states and reset; `RequireWorkspace` remount; two-account and change-of-session journeys |
+| Workspaces | catch-up of existing accounts (backfill) | done; DEV | rehearsed in three migration states on the sandbox; the DEV run is the §3.3 count « 0 profiles without exactly one workspace » |
+| Clients | create, search, read, edit, archive, restore | done | §11.7; `clients.spec.ts` 36 runs |
+| Animals | create (with or without a client), search, species filter, read, edit, archive, restore | done | §11.8; `animals.spec.ts` |
+| Animals | « Autre » with its detail; birth year or full date (D6b, U3) | done | form schema tests; the « Autre » journey |
+| Relations | link from both pages, several roles, co-ownership, a keeper structure | done | `animals.spec.ts` co-owner journey; sandbox duplicate race |
+| Relations | history, normal end with or without a date, date correction | done | end and dates dialogs; the sale journey; client page « Ancien propriétaire » |
+| Relations | voiding a mistake (N4), never deleted, shown nowhere | done | void dialog; the row checked voided in SQL; absent from both pages and from the counts |
+| Relations | no link across workspaces | done | composite keys; pgTAP 014; `animals.sandbox.ts` (B linking to A's client: `not_found`, no lock) |
+| Quality | SQL | done | pgTAP 919 on the real image and on PGlite; types identical |
+| Quality | integration (real GoTrue and PostgREST) | done | sandbox suites 61, in place of the DEV-origin file of §12.3 (`clients-animals.e2e.ts` not written: DEV holds none of M1 to M3, and the sandbox suites cover its cases: two accounts, refusals per role, anon and service keys, unconfirmed and deactivated accounts, D9a) |
+| Quality | browsers, accessibility, FR/EN, desktop and 375 px | done | `e2e:shell` 82, axe on every state; Chromium only until V1-5 (§12.5) |
+| Quality | `pnpm db:reset && pnpm db:test` of §12.6 | replaced | `db:reset` is forbidden on DEV (owner); the same proof runs on a fresh sandbox (`db:sandbox up fresh`, `test-db`) |
+| Promised, not built | « Ajouter un premier animal » section inside `/app/clients/new` (§11.1, §11.3 two-call creation) | deferred | owner decision 2026-10-26: the first animal is created from the client page in one atomic call |
+| Promised, not built | inline client creation from `/app/animals/new` (§11.1) | deferred | the V1-1.6 brief asks for a choice among existing clients only |
+| Promised, not built | dashboard tiles (D12) | deferred | outside the V1-1.6 brief; D12 stays open |
+| Promised, not built | mobile tab bar of the mockup | deferred | owner decision D11, 2026-10-26: drawer only in V1-1 |
+| Debt | search and archived toggle not kept on return; phones in E.164; back and forward not guarded | debt | accepted by the owner for V1-1 (brief V1-1.6 §1) |
+| Debt | no separate message for a relation voided elsewhere (seen as `conflict`) | debt | §11.8 |
+| Debt | pre-existing axe exceptions of RR-7 (language switcher, top bar account link, dashboard `dl`) | debt | scoped to their element and route; no V1-1 page relies on them for its own elements |
+| Debt | GoTrue admin with the service key, `service_role` on the species table, no read limit of its own, partial Unicode folding | debt | release track RR-3, RR-4 (§14) |
+| DEV | M1 to M3 applied, workspaces and ten active species counted, pgTAP, types | DEV | SUPABASE.md §3.3, owner action; read-only preflight conform 2026-10-26, backup, restore check and migration not run |
+| DEV | browser acceptance on a phone and a computer over the LAN | DEV | SUPABASE.md §3.3 « Browser acceptance on DEV »; not done |
+| Merge | owner's go after the V1-1.6 checkpoint and the DEV acceptance | blocking | §14; nothing merges into `develop` without it |
diff --git a/package.json b/package.json
index 17d5e60d..51fc100b 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"db:test": "bash scripts/supabase.sh test db",
"db:types": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript > packages/supabase/src/database.types.ts",
"db:types:check": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts",
+ "db:sandbox": "bash scripts/db-sandbox.sh",
"assets:upload": "bash scripts/upload-sheet-assets.sh",
"e2e:sheet-assets": "bash scripts/sheet-assets-e2e.sh",
"build:preview": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build",
@@ -45,7 +46,9 @@
"wasm:build:docker": "bash docker/rust-run.sh bash scripts/wasm-build.sh",
"worker:test": "docker build -f crates/worker/Dockerfile --target test -t faunosteo_worker:test .",
"worker:image": "docker build -f crates/worker/Dockerfile -t faunosteo_worker:dev .",
- "e2e:avatar": "bash scripts/avatar-e2e.sh"
+ "e2e:avatar": "bash scripts/avatar-e2e.sh",
+ "e2e:ui": "pnpm --filter @faunosteo/app e2e:ui",
+ "e2e:shell": "bash scripts/db-sandbox.sh e2e-shell"
},
"devDependencies": {
"pnpm": "10.13.1",
diff --git a/packages/supabase/package.json b/packages/supabase/package.json
index 1f07f8f2..1c496f10 100644
--- a/packages/supabase/package.json
+++ b/packages/supabase/package.json
@@ -17,7 +17,8 @@
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit",
- "test:e2e": "vitest run --config vitest.e2e.config.ts"
+ "test:e2e": "vitest run --config vitest.e2e.config.ts",
+ "test:sandbox": "vitest run --config vitest.sandbox.config.ts"
},
"dependencies": {
"@supabase/supabase-js": "^2.100.0",
diff --git a/packages/supabase/src/animals.ts b/packages/supabase/src/animals.ts
new file mode 100644
index 00000000..f6ea41c7
--- /dev/null
+++ b/packages/supabase/src/animals.ts
@@ -0,0 +1,235 @@
+import { z } from 'zod'
+import type { FaunosteoClient } from './client'
+import type { Database, Tables } from './database.types'
+import {
+ RevisionSchema,
+ type AnimalRelationRole,
+ type NameCursor,
+} from './clients'
+import {
+ failRecord,
+ parseRecordAnswer,
+ UUID_PATTERN,
+ type RecordPage,
+} from './records'
+
+/**
+ * Browser side of the animals of a workspace (contract §5.2, §8.3, §9.3): one
+ * read by id under RLS with an explicit column list, the POST search, the
+ * three write RPCs. `create_animal` takes the optional initial relation in the
+ * same transaction, so an animal and its first client are never half made.
+ * The database rules decide; every failure is a RecordFailure of a closed kind.
+ */
+
+/** Columns the page reads; the derived keys and the request digest stay server-side. */
+export const ANIMAL_COLUMNS =
+ 'id, name, species_id, species_detail, sex, breed, birth_year, birth_date, revision, archived_at, created_at, updated_at'
+
+export type AnimalRecord = Pick<
+ Tables<'animals'>,
+ | 'id'
+ | 'name'
+ | 'species_id'
+ | 'species_detail'
+ | 'sex'
+ | 'breed'
+ | 'birth_year'
+ | 'birth_date'
+ | 'revision'
+ | 'archived_at'
+ | 'created_at'
+ | 'updated_at'
+>
+
+/** The seven fields an animal is created or replaced with; an absent value is null, never ''. */
+export type AnimalFields = Pick<
+ AnimalRecord,
+ | 'name'
+ | 'species_id'
+ | 'species_detail'
+ | 'sex'
+ | 'breed'
+ | 'birth_year'
+ | 'birth_date'
+>
+
+const AnimalListItemSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ species_id: z.string(),
+ species_detail: z.string().nullable(),
+ sex: z.enum(['male', 'female', 'unknown']),
+ breed: z.string().nullable(),
+ birth_year: z.number().int().nullable(),
+ archived_at: z.string().nullable(),
+ name_key: z.string(),
+ /** The first three current owners in name order, archived clients flagged. */
+ current_owners: z.array(
+ z.object({
+ client_id: z.string().uuid(),
+ display_name: z.string(),
+ archived: z.boolean(),
+ }),
+ ),
+ current_owner_count: z.number().int(),
+})
+export type AnimalListItem = z.infer
+
+export interface AnimalSearch {
+ workspaceId: string
+ /** Trimmed by the server; 0 to 100 characters. */
+ query: string
+ /** A species id, or null for every species. */
+ speciesId: string | null
+ archived: boolean
+ /** 1 to 99; one more row is asked to know whether a next page exists. */
+ pageSize?: number
+ after?: NameCursor | null
+}
+
+/** One page of `search_animals` (POST: the term stays out of the URL). */
+export async function searchAnimals(
+ client: FaunosteoClient,
+ search: AnimalSearch,
+): Promise> {
+ const size = search.pageSize ?? 25
+ const { data, error, status } = await client.rpc('search_animals', {
+ workspace_id: search.workspaceId,
+ query: search.query,
+ species_filter: search.speciesId ?? undefined,
+ archived: search.archived,
+ page_size: size + 1,
+ after_name_key: search.after?.nameKey,
+ after_id: search.after?.id,
+ })
+ if (error) failRecord(error, status)
+ const found = parseRecordAnswer(z.array(AnimalListItemSchema), data)
+ const rows = found.slice(0, size)
+ const last = rows.at(-1)
+ return {
+ rows,
+ next:
+ found.length > size && last
+ ? { nameKey: last.name_key, id: last.id }
+ : null,
+ }
+}
+
+/** The animal, or null for an unknown id and for an id of another workspace alike. */
+export async function fetchAnimalRecord(
+ client: FaunosteoClient,
+ animalId: string,
+): Promise {
+ if (!UUID_PATTERN.test(animalId)) return null
+ const { data, error, status } = await client
+ .from('animals')
+ .select(ANIMAL_COLUMNS)
+ .eq('id', animalId)
+ .maybeSingle()
+ if (error) failRecord(error, status)
+ return data
+}
+
+/** The client the animal is linked to at creation, with an explicit role. */
+export interface InitialRelation {
+ clientId: string
+ relationRole: AnimalRelationRole
+ /** YYYY-MM-DD when known, else null (never filled by default). */
+ startedOn: string | null
+}
+
+export interface CreateAnimalInput {
+ workspaceId: string
+ /** One per creation intent, sent again on a retry: the server answers the first animal. */
+ requestId: string
+ fields: AnimalFields
+ relation: InitialRelation | null
+}
+
+const CreatedAnimalSchema = z.object({
+ id: z.string().uuid(),
+ revision: z.number().int(),
+ relation_id: z.string().uuid().nullable(),
+})
+
+/** Years and dates travel as text: the RPC parses them and answers invalid_input on a bad one. */
+const yearText = (year: number | null) =>
+ year === null ? undefined : String(year)
+
+export async function createAnimalRecord(
+ client: FaunosteoClient,
+ input: CreateAnimalInput,
+): Promise<{ id: string; revision: number; relationId: string | null }> {
+ const f = input.fields
+ const r = input.relation
+ const { data, error, status } = await client.rpc('create_animal', {
+ workspace_id: input.workspaceId,
+ create_request_id: input.requestId,
+ name: f.name,
+ species_id: f.species_id,
+ sex: f.sex,
+ species_detail: f.species_detail ?? undefined,
+ breed: f.breed ?? undefined,
+ birth_year: yearText(f.birth_year),
+ birth_date: f.birth_date ?? undefined,
+ client_id: r?.clientId,
+ relation_role: r?.relationRole,
+ started_on: r?.startedOn ?? undefined,
+ })
+ if (error) failRecord(error, status)
+ const created = parseRecordAnswer(CreatedAnimalSchema, data)
+ return {
+ id: created.id,
+ revision: created.revision,
+ relationId: created.relation_id,
+ }
+}
+
+type UpdateAnimalArgs = Database['public']['Functions']['update_animal']['Args']
+
+export interface UpdateAnimalInput {
+ animalId: string
+ expectedRevision: number
+ fields: AnimalFields
+}
+
+/** Replaces the seven fields at `expectedRevision`; a stale revision is `conflict`. */
+export async function updateAnimalRecord(
+ client: FaunosteoClient,
+ input: UpdateAnimalInput,
+): Promise<{ revision: number }> {
+ const f = input.fields
+ // The update RPC has no defaults: every field is sent, null included (see
+ // updateClientRecord for why the generated type is widened this way).
+ const args = {
+ animal_id: input.animalId,
+ expected_revision: input.expectedRevision,
+ name: f.name,
+ species_id: f.species_id,
+ sex: f.sex,
+ species_detail: f.species_detail,
+ breed: f.breed,
+ birth_year: f.birth_year === null ? null : String(f.birth_year),
+ birth_date: f.birth_date,
+ } satisfies { [K in keyof UpdateAnimalArgs]: UpdateAnimalArgs[K] | null }
+ const { data, error, status } = await client.rpc(
+ 'update_animal',
+ args as UpdateAnimalArgs,
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
+
+/** Archives or restores; the relations are kept either way (contract §7.1). */
+export async function setAnimalArchived(
+ client: FaunosteoClient,
+ animalId: string,
+ archived: boolean,
+): Promise<{ revision: number }> {
+ const { data, error, status } = await client.rpc('set_animal_archived', {
+ animal_id: animalId,
+ archived,
+ })
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
diff --git a/packages/supabase/src/clients.ts b/packages/supabase/src/clients.ts
new file mode 100644
index 00000000..5b312254
--- /dev/null
+++ b/packages/supabase/src/clients.ts
@@ -0,0 +1,283 @@
+import { z } from 'zod'
+import type { FaunosteoClient } from './client'
+import type { Database, Enums, Tables } from './database.types'
+import {
+ failRecord,
+ parseRecordAnswer,
+ RecordFailure,
+ UUID_PATTERN,
+ type RecordPage,
+} from './records'
+
+/**
+ * Browser side of the clients of a workspace (contract §5.1, §8.2, §9.3):
+ * one read by id under RLS with an explicit column list, the POST searches,
+ * the three write RPCs. Validation of what the user types lives in the app's
+ * form schemas (D-R7); the database rules decide. Every failure is a
+ * RecordFailure of a closed kind.
+ */
+
+export type ClientKind = Enums<'client_kind'>
+export type AnimalRelationRole = Enums<'animal_relation_role'>
+export type AnimalSex = Enums<'animal_sex'>
+
+/** Columns the page reads; the derived keys and the request digest stay server-side. */
+export const CLIENT_COLUMNS =
+ 'id, kind, display_name, email, phone, address_line1, address_line2, postal_code, city, country, revision, archived_at, created_at, updated_at'
+
+export type ClientRecord = Pick<
+ Tables<'clients'>,
+ | 'id'
+ | 'kind'
+ | 'display_name'
+ | 'email'
+ | 'phone'
+ | 'address_line1'
+ | 'address_line2'
+ | 'postal_code'
+ | 'city'
+ | 'country'
+ | 'revision'
+ | 'archived_at'
+ | 'created_at'
+ | 'updated_at'
+>
+
+/** The nine fields a client is created or replaced with; an absent value is null, never ''. */
+export type ClientFields = Pick<
+ ClientRecord,
+ | 'kind'
+ | 'display_name'
+ | 'email'
+ | 'phone'
+ | 'address_line1'
+ | 'address_line2'
+ | 'postal_code'
+ | 'city'
+ | 'country'
+>
+
+/** Keyset position in name order: the last row's name_key and id. */
+export interface NameCursor {
+ nameKey: string
+ id: string
+}
+
+const ClientListItemSchema = z.object({
+ id: z.string().uuid(),
+ kind: z.enum(['person', 'organization']),
+ display_name: z.string(),
+ city: z.string().nullable(),
+ phone: z.string().nullable(),
+ email: z.string().nullable(),
+ archived_at: z.string().nullable(),
+ name_key: z.string(),
+ current_animal_count: z.number().int(),
+})
+export type ClientListItem = z.infer
+
+export interface ClientSearch {
+ workspaceId: string
+ /** Trimmed by the server; 0 to 100 characters. */
+ query: string
+ archived: boolean
+ /** 1 to 99; one more row is asked to know whether a next page exists. */
+ pageSize?: number
+ after?: NameCursor | null
+}
+
+/** One page of `search_clients` (POST: the term stays out of the URL). */
+export async function searchClients(
+ client: FaunosteoClient,
+ search: ClientSearch,
+): Promise> {
+ const size = search.pageSize ?? 25
+ const { data, error, status } = await client.rpc('search_clients', {
+ workspace_id: search.workspaceId,
+ query: search.query,
+ archived: search.archived,
+ page_size: size + 1,
+ after_name_key: search.after?.nameKey,
+ after_id: search.after?.id,
+ })
+ if (error) failRecord(error, status)
+ const parsed = z.array(ClientListItemSchema).safeParse(data)
+ if (!parsed.success) throw new RecordFailure('unavailable', parsed.error)
+ const rows = parsed.data.slice(0, size)
+ const last = rows.at(-1)
+ return {
+ rows,
+ next:
+ parsed.data.length > size && last
+ ? { nameKey: last.name_key, id: last.id }
+ : null,
+ }
+}
+
+/** The client, or null for an unknown id and for an id of another workspace alike. */
+export async function fetchClientRecord(
+ client: FaunosteoClient,
+ clientId: string,
+): Promise {
+ if (!UUID_PATTERN.test(clientId)) return null
+ const { data, error, status } = await client
+ .from('clients')
+ .select(CLIENT_COLUMNS)
+ .eq('id', clientId)
+ .maybeSingle()
+ if (error) failRecord(error, status)
+ return data
+}
+
+const CreatedSchema = z.object({
+ id: z.string().uuid(),
+ revision: z.number().int(),
+})
+/** The answer of every update, archive and relation write RPC. */
+export const RevisionSchema = z.object({ revision: z.number().int() })
+
+export interface CreateClientInput {
+ workspaceId: string
+ /** One per creation intent, sent again on a retry: the server answers the first client. */
+ requestId: string
+ fields: ClientFields
+}
+
+export async function createClientRecord(
+ client: FaunosteoClient,
+ input: CreateClientInput,
+): Promise<{ id: string; revision: number }> {
+ const f = input.fields
+ const { data, error, status } = await client.rpc('create_client', {
+ workspace_id: input.workspaceId,
+ create_request_id: input.requestId,
+ kind: f.kind,
+ display_name: f.display_name,
+ email: f.email ?? undefined,
+ phone: f.phone ?? undefined,
+ address_line1: f.address_line1 ?? undefined,
+ address_line2: f.address_line2 ?? undefined,
+ postal_code: f.postal_code ?? undefined,
+ city: f.city ?? undefined,
+ country: f.country ?? undefined,
+ })
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(CreatedSchema, data)
+}
+
+type UpdateClientArgs = Database['public']['Functions']['update_client']['Args']
+
+export interface UpdateClientInput {
+ clientId: string
+ expectedRevision: number
+ fields: ClientFields
+}
+
+/** Replaces the nine fields at `expectedRevision`; a stale revision is `conflict`. */
+export async function updateClientRecord(
+ client: FaunosteoClient,
+ input: UpdateClientInput,
+): Promise<{ revision: number }> {
+ const f = input.fields
+ // The update RPC has no defaults: every field is sent, null included. The
+ // generator types SQL parameters as non-null, so the keys and value types
+ // are checked against it with null allowed, then handed over.
+ const args = {
+ client_id: input.clientId,
+ expected_revision: input.expectedRevision,
+ kind: f.kind,
+ display_name: f.display_name,
+ email: f.email,
+ phone: f.phone,
+ address_line1: f.address_line1,
+ address_line2: f.address_line2,
+ postal_code: f.postal_code,
+ city: f.city,
+ country: f.country,
+ } satisfies { [K in keyof UpdateClientArgs]: UpdateClientArgs[K] | null }
+ const { data, error, status } = await client.rpc(
+ 'update_client',
+ args as UpdateClientArgs,
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
+
+export async function setClientArchived(
+ client: FaunosteoClient,
+ clientId: string,
+ archived: boolean,
+): Promise<{ revision: number }> {
+ const { data, error, status } = await client.rpc('set_client_archived', {
+ client_id: clientId,
+ archived,
+ })
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
+
+const ArchivePreviewSchema = z.object({
+ count: z.number().int(),
+ animals: z.array(z.object({ id: z.string().uuid(), name: z.string() })),
+})
+export type ClientArchivePreview = z.infer
+
+/** Active animals for which the client is the only current owner (first 10 by name). */
+export async function fetchClientArchivePreview(
+ client: FaunosteoClient,
+ clientId: string,
+): Promise {
+ const { data, error, status } = await client.rpc('client_archive_preview', {
+ client_id: clientId,
+ })
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(ArchivePreviewSchema, data)
+}
+
+const ClientAnimalSchema = z.object({
+ relation_id: z.string().uuid(),
+ relation_role: z.enum(['owner', 'keeper', 'contact']),
+ started_on: z.string().nullable(),
+ ended_on: z.string().nullable(),
+ is_current: z.boolean(),
+ animal_id: z.string().uuid(),
+ animal_name: z.string(),
+ species_id: z.string(),
+ species_detail: z.string().nullable(),
+ animal_archived_at: z.string().nullable(),
+ sort_key: z.string(),
+})
+/** A relation of the client with its animal: read-only view of V1-1.5. */
+export type ClientAnimalItem = z.infer
+
+/** Keyset position of `list_client_animals`: the last row's sort_key and relation id. */
+export interface RelationCursor {
+ sortKey: string
+ relationId: string
+}
+
+/** The client's relations, current first then former, each in animal name order. */
+export async function listClientAnimals(
+ client: FaunosteoClient,
+ clientId: string,
+ options: { pageSize?: number; after?: RelationCursor | null } = {},
+): Promise> {
+ const size = options.pageSize ?? 50
+ const { data, error, status } = await client.rpc('list_client_animals', {
+ client_id: clientId,
+ page_size: size + 1,
+ after_sort: options.after?.sortKey,
+ after_id: options.after?.relationId,
+ })
+ if (error) failRecord(error, status)
+ const rows = parseRecordAnswer(z.array(ClientAnimalSchema), data)
+ const page = rows.slice(0, size)
+ const last = page.at(-1)
+ return {
+ rows: page,
+ next:
+ rows.length > size && last
+ ? { sortKey: last.sort_key, relationId: last.relation_id }
+ : null,
+ }
+}
diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts
index ad4cdb51..0a063c59 100644
--- a/packages/supabase/src/database.types.ts
+++ b/packages/supabase/src/database.types.ts
@@ -239,6 +239,149 @@ export type Database = {
},
]
}
+ animal_client_relations: {
+ Row: {
+ animal_id: string
+ client_id: string
+ create_request_digest: string
+ create_request_id: string
+ created_at: string
+ ended_at: string | null
+ ended_on: string | null
+ id: string
+ relation_role: Database['public']['Enums']['animal_relation_role']
+ revision: number
+ started_on: string | null
+ updated_at: string
+ voided_at: string | null
+ workspace_id: string
+ }
+ ComputedFields: never
+ Insert: {
+ animal_id: string
+ client_id: string
+ create_request_digest: string
+ create_request_id: string
+ created_at?: string
+ ended_at?: string | null
+ ended_on?: string | null
+ id?: string
+ relation_role: Database['public']['Enums']['animal_relation_role']
+ revision?: number
+ started_on?: string | null
+ updated_at?: string
+ voided_at?: string | null
+ workspace_id: string
+ }
+ Update: {
+ animal_id?: string
+ client_id?: string
+ create_request_digest?: string
+ create_request_id?: string
+ created_at?: string
+ ended_at?: string | null
+ ended_on?: string | null
+ id?: string
+ relation_role?: Database['public']['Enums']['animal_relation_role']
+ revision?: number
+ started_on?: string | null
+ updated_at?: string
+ voided_at?: string | null
+ workspace_id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'animal_client_relations_animal_fk'
+ columns: ['workspace_id', 'animal_id']
+ isOneToOne: false
+ referencedRelation: 'animals'
+ referencedColumns: ['workspace_id', 'id']
+ },
+ {
+ foreignKeyName: 'animal_client_relations_client_fk'
+ columns: ['workspace_id', 'client_id']
+ isOneToOne: false
+ referencedRelation: 'clients'
+ referencedColumns: ['workspace_id', 'id']
+ },
+ ]
+ }
+ animals: {
+ Row: {
+ archived_at: string | null
+ birth_date: string | null
+ birth_year: number | null
+ breed: string | null
+ create_request_digest: string
+ create_request_id: string
+ created_at: string
+ id: string
+ name: string
+ name_key: string | null
+ revision: number
+ search_key: string | null
+ sex: Database['public']['Enums']['animal_sex']
+ species_detail: string | null
+ species_id: string
+ updated_at: string
+ workspace_id: string
+ }
+ ComputedFields: never
+ Insert: {
+ archived_at?: string | null
+ birth_date?: string | null
+ birth_year?: number | null
+ breed?: string | null
+ create_request_digest: string
+ create_request_id: string
+ created_at?: string
+ id?: string
+ name: string
+ name_key?: never
+ revision?: number
+ search_key?: never
+ sex: Database['public']['Enums']['animal_sex']
+ species_detail?: string | null
+ species_id: string
+ updated_at?: string
+ workspace_id: string
+ }
+ Update: {
+ archived_at?: string | null
+ birth_date?: string | null
+ birth_year?: number | null
+ breed?: string | null
+ create_request_digest?: string
+ create_request_id?: string
+ created_at?: string
+ id?: string
+ name?: string
+ name_key?: never
+ revision?: number
+ search_key?: never
+ sex?: Database['public']['Enums']['animal_sex']
+ species_detail?: string | null
+ species_id?: string
+ updated_at?: string
+ workspace_id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'animals_species_id_fkey'
+ columns: ['species_id']
+ isOneToOne: false
+ referencedRelation: 'species'
+ referencedColumns: ['id']
+ },
+ {
+ foreignKeyName: 'animals_workspace_id_fkey'
+ columns: ['workspace_id']
+ isOneToOne: false
+ referencedRelation: 'workspaces'
+ referencedColumns: ['id']
+ },
+ ]
+ }
assets: {
Row: {
attempts: number
@@ -308,6 +451,84 @@ export type Database = {
},
]
}
+ clients: {
+ Row: {
+ address_line1: string | null
+ address_line2: string | null
+ archived_at: string | null
+ city: string | null
+ country: string | null
+ create_request_digest: string
+ create_request_id: string
+ created_at: string
+ display_name: string
+ email: string | null
+ id: string
+ kind: Database['public']['Enums']['client_kind']
+ name_key: string | null
+ phone: string | null
+ phone_digits: string | null
+ postal_code: string | null
+ revision: number
+ search_key: string | null
+ updated_at: string
+ workspace_id: string
+ }
+ ComputedFields: never
+ Insert: {
+ address_line1?: string | null
+ address_line2?: string | null
+ archived_at?: string | null
+ city?: string | null
+ country?: string | null
+ create_request_digest: string
+ create_request_id: string
+ created_at?: string
+ display_name: string
+ email?: string | null
+ id?: string
+ kind: Database['public']['Enums']['client_kind']
+ name_key?: never
+ phone?: string | null
+ phone_digits?: never
+ postal_code?: string | null
+ revision?: number
+ search_key?: never
+ updated_at?: string
+ workspace_id: string
+ }
+ Update: {
+ address_line1?: string | null
+ address_line2?: string | null
+ archived_at?: string | null
+ city?: string | null
+ country?: string | null
+ create_request_digest?: string
+ create_request_id?: string
+ created_at?: string
+ display_name?: string
+ email?: string | null
+ id?: string
+ kind?: Database['public']['Enums']['client_kind']
+ name_key?: never
+ phone?: string | null
+ phone_digits?: never
+ postal_code?: string | null
+ revision?: number
+ search_key?: never
+ updated_at?: string
+ workspace_id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'clients_workspace_id_fkey'
+ columns: ['workspace_id']
+ isOneToOne: false
+ referencedRelation: 'workspaces'
+ referencedColumns: ['id']
+ },
+ ]
+ }
profile_roles: {
Row: {
granted_at: string
@@ -444,6 +665,73 @@ export type Database = {
}
Relationships: []
}
+ workspace_members: {
+ Row: {
+ created_at: string
+ member_role: Database['public']['Enums']['workspace_member_role']
+ user_id: string
+ workspace_id: string
+ }
+ ComputedFields: never
+ Insert: {
+ created_at?: string
+ member_role: Database['public']['Enums']['workspace_member_role']
+ user_id: string
+ workspace_id: string
+ }
+ Update: {
+ created_at?: string
+ member_role?: Database['public']['Enums']['workspace_member_role']
+ user_id?: string
+ workspace_id?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'workspace_members_user_id_fkey'
+ columns: ['user_id']
+ isOneToOne: false
+ referencedRelation: 'profiles'
+ referencedColumns: ['id']
+ },
+ {
+ foreignKeyName: 'workspace_members_workspace_id_fkey'
+ columns: ['workspace_id']
+ isOneToOne: false
+ referencedRelation: 'workspaces'
+ referencedColumns: ['id']
+ },
+ ]
+ }
+ workspaces: {
+ Row: {
+ created_at: string
+ id: string
+ kind: Database['public']['Enums']['workspace_kind']
+ personal_user_id: string | null
+ }
+ ComputedFields: never
+ Insert: {
+ created_at?: string
+ id?: string
+ kind: Database['public']['Enums']['workspace_kind']
+ personal_user_id?: string | null
+ }
+ Update: {
+ created_at?: string
+ id?: string
+ kind?: Database['public']['Enums']['workspace_kind']
+ personal_user_id?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: 'workspaces_personal_user_id_fkey'
+ columns: ['personal_user_id']
+ isOneToOne: true
+ referencedRelation: 'profiles'
+ referencedColumns: ['id']
+ },
+ ]
+ }
}
Views: {
[_ in never]: never
@@ -483,6 +771,7 @@ export type Database = {
object_name: string
}[]
}
+ client_archive_preview: { Args: { client_id: string }; Returns: Json }
complete_avatar_job: {
Args: {
asset_id: string
@@ -509,6 +798,49 @@ export type Database = {
}
Returns: string
}
+ create_animal: {
+ Args: {
+ birth_date?: string
+ birth_year?: string
+ breed?: string
+ client_id?: string
+ create_request_id: string
+ name: string
+ relation_role?: string
+ sex: string
+ species_detail?: string
+ species_id: string
+ started_on?: string
+ workspace_id: string
+ }
+ Returns: Json
+ }
+ create_animal_client_relation: {
+ Args: {
+ animal_id: string
+ client_id: string
+ create_request_id: string
+ relation_role: string
+ started_on?: string
+ }
+ Returns: Json
+ }
+ create_client: {
+ Args: {
+ address_line1?: string
+ address_line2?: string
+ city?: string
+ country?: string
+ create_request_id: string
+ display_name: string
+ email?: string
+ kind: string
+ phone?: string
+ postal_code?: string
+ workspace_id: string
+ }
+ Returns: Json
+ }
create_sheet_draft: {
Args: {
change_note?: string
@@ -524,6 +856,14 @@ export type Database = {
Args: { reason?: string; version_id: string }
Returns: string
}
+ end_animal_client_relation: {
+ Args: {
+ ended_on?: string
+ expected_revision: number
+ relation_id: string
+ }
+ Returns: Json
+ }
expire_pending_uploads: {
Args: { max_age_seconds: number }
Returns: number
@@ -544,6 +884,31 @@ export type Database = {
}
Returns: string
}
+ list_client_animals: {
+ Args: {
+ after_id?: string
+ after_sort?: string
+ client_id: string
+ page_size?: number
+ }
+ Returns: {
+ animal_archived_at: string
+ animal_id: string
+ animal_name: string
+ birth_year: number
+ breed: string
+ ended_on: string
+ is_current: boolean
+ relation_id: string
+ relation_revision: number
+ relation_role: Database['public']['Enums']['animal_relation_role']
+ sex: Database['public']['Enums']['animal_sex']
+ sort_key: string
+ species_detail: string
+ species_id: string
+ started_on: string
+ }[]
+ }
mark_quarantine_purged: { Args: { asset_id: string }; Returns: undefined }
publish_sheet_version: { Args: { version_id: string }; Returns: string }
register_sheet_asset: {
@@ -569,6 +934,59 @@ export type Database = {
}
Returns: string
}
+ search_animals: {
+ Args: {
+ after_id?: string
+ after_name_key?: string
+ archived?: boolean
+ page_size?: number
+ query?: string
+ species_filter?: string
+ workspace_id: string
+ }
+ Returns: {
+ archived_at: string
+ birth_year: number
+ breed: string
+ current_owner_count: number
+ current_owners: Json
+ id: string
+ name: string
+ name_key: string
+ sex: Database['public']['Enums']['animal_sex']
+ species_detail: string
+ species_id: string
+ }[]
+ }
+ search_clients: {
+ Args: {
+ after_id?: string
+ after_name_key?: string
+ archived?: boolean
+ page_size?: number
+ query?: string
+ workspace_id: string
+ }
+ Returns: {
+ archived_at: string
+ city: string
+ current_animal_count: number
+ display_name: string
+ email: string
+ id: string
+ kind: Database['public']['Enums']['client_kind']
+ name_key: string
+ phone: string
+ }[]
+ }
+ set_animal_archived: {
+ Args: { animal_id: string; archived: boolean }
+ Returns: Json
+ }
+ set_client_archived: {
+ Args: { archived: boolean; client_id: string }
+ Returns: Json
+ }
set_sheet_visibility: {
Args: {
sheet_id: string
@@ -576,18 +994,66 @@ export type Database = {
}
Returns: string
}
+ update_animal: {
+ Args: {
+ animal_id: string
+ birth_date: string
+ birth_year: string
+ breed: string
+ expected_revision: number
+ name: string
+ sex: string
+ species_detail: string
+ species_id: string
+ }
+ Returns: Json
+ }
+ update_animal_client_relation: {
+ Args: {
+ ended_on: string
+ expected_revision: number
+ relation_id: string
+ started_on: string
+ }
+ Returns: Json
+ }
+ update_client: {
+ Args: {
+ address_line1: string
+ address_line2: string
+ city: string
+ client_id: string
+ country: string
+ display_name: string
+ email: string
+ expected_revision: number
+ kind: string
+ phone: string
+ postal_code: string
+ }
+ Returns: Json
+ }
+ void_animal_client_relation: {
+ Args: { expected_revision: number; relation_id: string }
+ Returns: Json
+ }
}
Enums: {
+ animal_relation_role: 'owner' | 'keeper' | 'contact'
+ animal_sex: 'male' | 'female' | 'unknown'
asset_status:
| 'pending_upload'
| 'uploaded'
| 'clean'
| 'rejected'
| 'deleted'
+ client_kind: 'person' | 'organization'
platform_role: 'owner' | 'admin' | 'moderator' | 'support'
sheet_status: 'active' | 'archived' | 'deleted'
sheet_version_status: 'draft' | 'published' | 'deprecated'
sheet_visibility: 'private' | 'public'
+ workspace_kind: 'personal'
+ workspace_member_role: 'holder'
}
CompositeTypes: {
[_ in never]: never
@@ -715,6 +1181,8 @@ export type CompositeTypes<
export const Constants = {
public: {
Enums: {
+ animal_relation_role: ['owner', 'keeper', 'contact'],
+ animal_sex: ['male', 'female', 'unknown'],
asset_status: [
'pending_upload',
'uploaded',
@@ -722,10 +1190,13 @@ export const Constants = {
'rejected',
'deleted',
],
+ client_kind: ['person', 'organization'],
platform_role: ['owner', 'admin', 'moderator', 'support'],
sheet_status: ['active', 'archived', 'deleted'],
sheet_version_status: ['draft', 'published', 'deprecated'],
sheet_visibility: ['private', 'public'],
+ workspace_kind: ['personal'],
+ workspace_member_role: ['holder'],
},
},
} as const
diff --git a/packages/supabase/src/field-limits.ts b/packages/supabase/src/field-limits.ts
new file mode 100644
index 00000000..24133e90
--- /dev/null
+++ b/packages/supabase/src/field-limits.ts
@@ -0,0 +1,59 @@
+/**
+ * Bounds and patterns of the V1-1 record fields, shared by the forms (Zod
+ * schemas, D-R7) and proven equal to the SQL CHECK constraints by
+ * tests/db/field-limits.test.ts (behaviour on the migrated schema, never by
+ * parsing SQL). Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §12.2.
+ *
+ * Lengths count code points, as PostgreSQL's char_length does: use
+ * codePointLength, never String.length (UTF-16 units) or Zod's .max() alone.
+ */
+
+export const CLIENT_FIELD_LIMITS = {
+ displayName: 120,
+ email: 254,
+ addressLine: 120,
+ postalCode: 16,
+ city: 80,
+} as const
+
+export const ANIMAL_FIELD_LIMITS = {
+ name: 80,
+ breed: 80,
+ speciesDetail: 80,
+} as const
+
+/**
+ * Lower bounds of the SQL CHECKs on birth years and on every record date
+ * (birth, relation start and end). The upper bound is "not in the future":
+ * the form checks the device's local date, the RPCs tomorrow's UTC date.
+ */
+export const BIRTH_YEAR_MIN = 1900
+export const RECORD_DATE_MIN = '1900-01-01'
+
+/** U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029 (the SQL literal starts at U+0001: text cannot hold U+0000). */
+export const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u
+
+/** Applied to the lower-cased value. JavaScript's \s is wider than SQL's, so the form refuses at least what SQL refuses. */
+export const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/u
+
+export const PHONE_E164_PATTERN = /^\+[1-9][0-9]{6,14}$/
+
+export const COUNTRY_CODE_PATTERN = /^[A-Z]{2}$/
+
+export function codePointLength(value: string): number {
+ return [...value].length
+}
+
+/**
+ * The text rule of contract §5: 1 to max code points, no leading or trailing
+ * space (U+0020, as SQL btrim checks), no control character.
+ */
+export function isCleanText(value: string, max: number): boolean {
+ const length = codePointLength(value)
+ return (
+ length >= 1 &&
+ length <= max &&
+ value === value.replace(/^ +| +$/g, '') &&
+ !CONTROL_CHARACTERS.test(value)
+ )
+}
diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts
index 501f1149..7c0cc634 100644
--- a/packages/supabase/src/index.ts
+++ b/packages/supabase/src/index.ts
@@ -89,3 +89,76 @@ export type SheetVisibility = Enums<'sheet_visibility'>
export type SheetStatus = Enums<'sheet_status'>
/** draft | published | deprecated. */
export type SheetVersionStatus = Enums<'sheet_version_status'>
+export {
+ RECORD_FAILURE_KINDS,
+ RecordFailure,
+ classifyRecordError,
+ parseRecordAnswer,
+ UUID_PATTERN,
+ type RecordFailureKind,
+ type RecordPage,
+} from './records'
+export { fetchPersonalWorkspaceId } from './workspaces'
+export { fetchSpeciesLabels, type SpeciesLabel } from './species'
+export {
+ CLIENT_COLUMNS,
+ createClientRecord,
+ fetchClientArchivePreview,
+ fetchClientRecord,
+ listClientAnimals,
+ searchClients,
+ setClientArchived,
+ updateClientRecord,
+ type AnimalRelationRole,
+ type AnimalSex,
+ type ClientAnimalItem,
+ type ClientArchivePreview,
+ type ClientFields,
+ type ClientKind,
+ type ClientListItem,
+ type ClientRecord,
+ type ClientSearch,
+ type CreateClientInput,
+ type NameCursor,
+ type RelationCursor,
+ type UpdateClientInput,
+} from './clients'
+export {
+ ANIMAL_COLUMNS,
+ createAnimalRecord,
+ fetchAnimalRecord,
+ searchAnimals,
+ setAnimalArchived,
+ updateAnimalRecord,
+ type AnimalFields,
+ type AnimalListItem,
+ type AnimalRecord,
+ type AnimalSearch,
+ type CreateAnimalInput,
+ type InitialRelation,
+ type UpdateAnimalInput,
+} from './animals'
+export {
+ ANIMAL_RELATION_COLUMNS,
+ createAnimalClientRelation,
+ endAnimalClientRelation,
+ fetchAnimalRelations,
+ updateAnimalClientRelation,
+ voidAnimalClientRelation,
+ type AnimalRelationItem,
+ type CreateRelationInput,
+ type EndRelationInput,
+ type UpdateRelationDatesInput,
+} from './relations'
+export {
+ ANIMAL_FIELD_LIMITS,
+ BIRTH_YEAR_MIN,
+ CLIENT_FIELD_LIMITS,
+ CONTROL_CHARACTERS,
+ COUNTRY_CODE_PATTERN,
+ EMAIL_PATTERN,
+ PHONE_E164_PATTERN,
+ RECORD_DATE_MIN,
+ codePointLength,
+ isCleanText,
+} from './field-limits'
diff --git a/packages/supabase/src/records.ts b/packages/supabase/src/records.ts
new file mode 100644
index 00000000..f8f34b58
--- /dev/null
+++ b/packages/supabase/src/records.ts
@@ -0,0 +1,94 @@
+import type { z } from 'zod'
+
+/**
+ * Closed failure kinds of the V1-1 record reads and RPCs (clients, animals,
+ * relations): contract docs/development/V1-1_OWNERS_ANIMALS.md §9.4. The
+ * server answers closed codes, never values; this module folds them, the
+ * session and the network into one kind the UI phrases. A foreign id and an
+ * unknown one are the same `not_found`, as the server makes them.
+ */
+
+export const RECORD_FAILURE_KINDS = [
+ 'not_found',
+ 'archived',
+ 'conflict',
+ 'request_conflict',
+ 'limit_reached',
+ 'rate_limited',
+ 'invalid_input',
+ 'duplicate_relation',
+ 'already_ended',
+ 'session_expired',
+ 'network',
+ 'unavailable',
+] as const
+export type RecordFailureKind = (typeof RECORD_FAILURE_KINDS)[number]
+
+export class RecordFailure extends Error {
+ readonly kind: RecordFailureKind
+ constructor(kind: RecordFailureKind, cause?: unknown) {
+ super(`record: ${kind}`, { cause })
+ this.name = 'RecordFailure'
+ this.kind = kind
+ }
+}
+
+/** Messages the record RPCs raise with SQLSTATE P0001 (contract §9.4). */
+const RPC_MESSAGE_KINDS: ReadonlySet = new Set([
+ 'archived',
+ 'conflict',
+ 'request_conflict',
+ 'limit_reached',
+ 'rate_limited',
+ 'invalid_input',
+ 'duplicate_relation',
+ 'already_ended',
+])
+
+interface PostgrestLikeError {
+ code?: string | null
+ message?: string
+}
+
+/**
+ * Folds a PostgREST answer into a closed kind. `status` is the HTTP status
+ * postgrest-js returns beside the error: 0 when the request never got an
+ * answer, 401 when the JWT is missing or expired (PGRST30x).
+ */
+export function classifyRecordError(
+ error: unknown,
+ status?: number,
+): RecordFailureKind {
+ if (error instanceof RecordFailure) return error.kind
+ if (error instanceof TypeError) return 'network'
+ const e = (error ?? {}) as PostgrestLikeError
+ if (e.code === '42501' && e.message === 'not_found') return 'not_found'
+ if (e.code === 'P0001' && e.message && RPC_MESSAGE_KINDS.has(e.message)) {
+ return e.message as RecordFailureKind
+ }
+ if (status === 401 || e.code?.startsWith('PGRST30')) return 'session_expired'
+ if (status === 0) return 'network'
+ return 'unavailable'
+}
+
+/** Throws the closed failure of a PostgREST answer. */
+export function failRecord(error: unknown, status?: number): never {
+ throw new RecordFailure(classifyRecordError(error, status), error)
+}
+
+/** The RPC answer checked against its contract; a different shape is `unavailable`. */
+export function parseRecordAnswer(schema: z.ZodType, data: unknown): T {
+ const result = schema.safeParse(data)
+ if (!result.success) throw new RecordFailure('unavailable', result.error)
+ return result.data
+}
+
+/** Ids are uuids: anything else is answered as unknown without a request. */
+export const UUID_PATTERN =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+/** One page of a keyset list; `next` is null on the last page. */
+export interface RecordPage {
+ rows: Row[]
+ next: Cursor | null
+}
diff --git a/packages/supabase/src/relations.ts b/packages/supabase/src/relations.ts
new file mode 100644
index 00000000..8b956305
--- /dev/null
+++ b/packages/supabase/src/relations.ts
@@ -0,0 +1,165 @@
+import { z } from 'zod'
+import type { FaunosteoClient } from './client'
+import type { Database } from './database.types'
+import { RevisionSchema } from './clients'
+import { failRecord, parseRecordAnswer, UUID_PATTERN } from './records'
+
+/**
+ * Browser side of the relations between an animal and its clients (contract
+ * §5.3, §8.3, §9.3). The animal page reads them with one select by animal id
+ * (at most 200 by the cap), the client embedded through the composite foreign
+ * key; voided relations are left out, as every V1-1 screen leaves them out.
+ * Writes go through the four relation RPCs only.
+ */
+
+const RELATION_ROLES = ['owner', 'keeper', 'contact'] as const
+
+/**
+ * `ended_at` tells a current relation from a former one; it is a technical
+ * time, never shown as the end date (`ended_on` is).
+ */
+export const ANIMAL_RELATION_COLUMNS =
+ 'id, relation_role, started_on, ended_on, ended_at, revision, client:clients!animal_client_relations_client_fk(id, kind, display_name, phone, email, archived_at)'
+
+const AnimalRelationSchema = z.object({
+ id: z.string().uuid(),
+ relation_role: z.enum(RELATION_ROLES),
+ started_on: z.string().nullable(),
+ ended_on: z.string().nullable(),
+ ended_at: z.string().nullable(),
+ revision: z.number().int(),
+ client: z.object({
+ id: z.string().uuid(),
+ kind: z.enum(['person', 'organization']),
+ display_name: z.string(),
+ phone: z.string().nullable(),
+ email: z.string().nullable(),
+ archived_at: z.string().nullable(),
+ }),
+})
+export type AnimalRelationItem = z.infer
+
+/** The cap of relations per animal (contract §10), ended and voided included. */
+const RELATIONS_PER_ANIMAL = 200
+
+/** The animal's relations that existed (voided ones left out), in creation order. */
+export async function fetchAnimalRelations(
+ client: FaunosteoClient,
+ animalId: string,
+): Promise {
+ if (!UUID_PATTERN.test(animalId)) return []
+ const { data, error, status } = await client
+ .from('animal_client_relations')
+ .select(ANIMAL_RELATION_COLUMNS)
+ .eq('animal_id', animalId)
+ .is('voided_at', null)
+ .order('created_at')
+ .order('id')
+ .limit(RELATIONS_PER_ANIMAL)
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(z.array(AnimalRelationSchema), data)
+}
+
+export interface CreateRelationInput {
+ animalId: string
+ clientId: string
+ /** One per creation intent, sent again on a retry: the server answers the first relation. */
+ requestId: string
+ relationRole: (typeof RELATION_ROLES)[number]
+ /** YYYY-MM-DD when known, else null (never filled by default). */
+ startedOn: string | null
+}
+
+const CreatedSchema = z.object({
+ id: z.string().uuid(),
+ revision: z.number().int(),
+})
+
+/** A current relation between an active animal and an active client of one workspace. */
+export async function createAnimalClientRelation(
+ client: FaunosteoClient,
+ input: CreateRelationInput,
+): Promise<{ id: string; revision: number }> {
+ const { data, error, status } = await client.rpc(
+ 'create_animal_client_relation',
+ {
+ animal_id: input.animalId,
+ client_id: input.clientId,
+ create_request_id: input.requestId,
+ relation_role: input.relationRole,
+ started_on: input.startedOn ?? undefined,
+ },
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(CreatedSchema, data)
+}
+
+export interface EndRelationInput {
+ relationId: string
+ expectedRevision: number
+ /** The real end date when known; null records the end without one. */
+ endedOn: string | null
+}
+
+/** Ends a current relation: it stays as a former one, with its dates. */
+export async function endAnimalClientRelation(
+ client: FaunosteoClient,
+ input: EndRelationInput,
+): Promise<{ revision: number }> {
+ const { data, error, status } = await client.rpc(
+ 'end_animal_client_relation',
+ {
+ relation_id: input.relationId,
+ expected_revision: input.expectedRevision,
+ ended_on: input.endedOn ?? undefined,
+ },
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
+
+type UpdateRelationArgs =
+ Database['public']['Functions']['update_animal_client_relation']['Args']
+
+export interface UpdateRelationDatesInput {
+ relationId: string
+ expectedRevision: number
+ startedOn: string | null
+ /** Only on an ended relation; the server refuses one on a current relation. */
+ endedOn: string | null
+}
+
+/** Corrects the dates; both are sent, an empty one is null (the RPC has no defaults). */
+export async function updateAnimalClientRelation(
+ client: FaunosteoClient,
+ input: UpdateRelationDatesInput,
+): Promise<{ revision: number }> {
+ const args = {
+ relation_id: input.relationId,
+ expected_revision: input.expectedRevision,
+ started_on: input.startedOn,
+ ended_on: input.endedOn,
+ } satisfies { [K in keyof UpdateRelationArgs]: UpdateRelationArgs[K] | null }
+ const { data, error, status } = await client.rpc(
+ 'update_animal_client_relation',
+ args as UpdateRelationArgs,
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
+
+/** Voids a relation entered by mistake (N4): kept, frozen and shown nowhere; never a deletion. */
+export async function voidAnimalClientRelation(
+ client: FaunosteoClient,
+ input: { relationId: string; expectedRevision: number },
+): Promise<{ revision: number }> {
+ const { data, error, status } = await client.rpc(
+ 'void_animal_client_relation',
+ {
+ relation_id: input.relationId,
+ expected_revision: input.expectedRevision,
+ },
+ )
+ if (error) failRecord(error, status)
+ return parseRecordAnswer(RevisionSchema, data)
+}
diff --git a/packages/supabase/src/species.ts b/packages/supabase/src/species.ts
new file mode 100644
index 00000000..15e1e40e
--- /dev/null
+++ b/packages/supabase/src/species.ts
@@ -0,0 +1,17 @@
+import type { FaunosteoClient } from './client'
+import type { Tables } from './database.types'
+import { failRecord } from './records'
+
+export type SpeciesLabel = Pick, 'id' | 'name_fr' | 'name_en'>
+
+/** The active species with their names, in the reference order (RLS: active rows only). */
+export async function fetchSpeciesLabels(
+ client: FaunosteoClient,
+): Promise {
+ const { data, error, status } = await client
+ .from('species')
+ .select('id, name_fr, name_en')
+ .order('sort_order')
+ if (error) failRecord(error, status)
+ return data ?? []
+}
diff --git a/packages/supabase/src/workspaces.ts b/packages/supabase/src/workspaces.ts
new file mode 100644
index 00000000..d63ad4ff
--- /dev/null
+++ b/packages/supabase/src/workspaces.ts
@@ -0,0 +1,22 @@
+import type { FaunosteoClient } from './client'
+import { failRecord } from './records'
+
+/**
+ * The signed-in account's personal workspace (contract §4, M1). It is
+ * created by the server in the sign-up transaction, never by the browser;
+ * RLS returns it only to its member with an active profile and a confirmed
+ * email, so null means "not readable now", not "create one". Its id is a
+ * context for the RPCs, which check the caller's rights again themselves.
+ */
+export async function fetchPersonalWorkspaceId(
+ client: FaunosteoClient,
+ userId: string,
+): Promise {
+ const { data, error, status } = await client
+ .from('workspaces')
+ .select('id')
+ .eq('personal_user_id', userId)
+ .maybeSingle()
+ if (error) failRecord(error, status)
+ return data?.id ?? null
+}
diff --git a/packages/supabase/tests/animals.test.ts b/packages/supabase/tests/animals.test.ts
new file mode 100644
index 00000000..53121f03
--- /dev/null
+++ b/packages/supabase/tests/animals.test.ts
@@ -0,0 +1,592 @@
+import {
+ ANIMAL_COLUMNS,
+ ANIMAL_RELATION_COLUMNS,
+ RECORD_FAILURE_KINDS,
+ RecordFailure,
+ classifyRecordError,
+ createAnimalClientRelation,
+ createAnimalRecord,
+ endAnimalClientRelation,
+ fetchAnimalRecord,
+ fetchAnimalRelations,
+ parseRecordAnswer,
+ searchAnimals,
+ setAnimalArchived,
+ updateAnimalClientRelation,
+ updateAnimalRecord,
+ voidAnimalClientRelation,
+ type AnimalFields,
+ type FaunosteoClient,
+} from '../src'
+import { z } from 'zod'
+
+/**
+ * Call shapes and closed failure kinds of the animals and relations access
+ * layer. The argument names are checked by the compiler against the generated
+ * types; the RPC bodies by supabase/tests/014_animals_relations.sql; the same
+ * functions run against real PostgREST in tests/sandbox/animals-access.sandbox.ts.
+ */
+type Answer = { data?: unknown; error?: unknown; status?: number }
+
+function stubClient(answers: { rpc?: Answer; select?: Answer } = {}) {
+ const rpcCalls: Array<[string, Record]> = []
+ const query: Record = {}
+ const orders: string[] = []
+ const settle = (a: Answer = {}) => ({
+ data: a.data ?? null,
+ error: a.error ?? null,
+ status: a.status ?? (a.error ? 400 : 200),
+ })
+ const chain = {
+ select: (cols: string) => ((query.select = cols), chain),
+ eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain),
+ is: (col: string, value: unknown) => ((query[`is:${col}`] = value), chain),
+ order: (col: string) => (orders.push(col), chain),
+ limit: (n: number) => ((query.limit = n), chain),
+ maybeSingle: async () => settle(answers.select),
+ then: (resolve: (v: unknown) => void) => resolve(settle(answers.select)),
+ }
+ const client = {
+ from: (table: string) => ((query.table = table), chain),
+ rpc: async (name: string, args: Record) => {
+ rpcCalls.push([name, args])
+ return settle(answers.rpc)
+ },
+ } as unknown as FaunosteoClient
+ return { client, rpcCalls, query, orders }
+}
+
+const WS = '11111111-1111-4111-8111-111111111111'
+const ID = '22222222-2222-4222-8222-222222222222'
+const REQUEST = '33333333-3333-4333-8333-333333333333'
+const CLIENT = '44444444-4444-4444-8444-444444444444'
+const RELATION = '55555555-5555-4555-8555-555555555555'
+
+const fields: AnimalFields = {
+ name: 'Éclair',
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: null,
+ birth_year: 2015,
+ birth_date: null,
+}
+
+function listRow(i: number) {
+ return {
+ id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
+ name: `Animal ${i}`,
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'unknown',
+ breed: null,
+ birth_year: null,
+ archived_at: null,
+ name_key: `animal ${String(i).padStart(3, '0')}`,
+ current_owners: [],
+ current_owner_count: 0,
+ }
+}
+
+function relationRow(patch: Record = {}) {
+ return {
+ id: RELATION,
+ relation_role: 'owner',
+ started_on: null,
+ ended_on: null,
+ ended_at: null,
+ revision: 1,
+ client: {
+ id: CLIENT,
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ phone: null,
+ email: null,
+ archived_at: null,
+ },
+ ...patch,
+ }
+}
+
+async function kindOf(promise: Promise) {
+ try {
+ await promise
+ return 'no failure'
+ } catch (error) {
+ return error instanceof RecordFailure ? error.kind : 'not a RecordFailure'
+ }
+}
+
+describe('relation failure kinds', () => {
+ it('are closed kinds of the record failures', () => {
+ expect(RECORD_FAILURE_KINDS).toContain('duplicate_relation')
+ expect(RECORD_FAILURE_KINDS).toContain('already_ended')
+ })
+
+ it.each(['duplicate_relation', 'already_ended'])(
+ 'P0001 %s is that kind',
+ (message) => {
+ expect(classifyRecordError({ code: 'P0001', message }, 400)).toBe(message)
+ },
+ )
+
+ it('parseRecordAnswer returns the parsed value or throws unavailable', async () => {
+ const schema = z.object({ revision: z.number().int() })
+ expect(parseRecordAnswer(schema, { revision: 2 })).toEqual({ revision: 2 })
+ expect(
+ await kindOf(Promise.resolve().then(() => parseRecordAnswer(schema, {}))),
+ ).toBe('unavailable')
+ })
+})
+
+describe('searchAnimals', () => {
+ it('posts the term, every species when null, one row more than the page', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } })
+ const page = await searchAnimals(client, {
+ workspaceId: WS,
+ query: 'ecl',
+ speciesId: null,
+ archived: false,
+ })
+ expect(rpcCalls).toEqual([
+ [
+ 'search_animals',
+ {
+ workspace_id: WS,
+ query: 'ecl',
+ species_filter: undefined,
+ archived: false,
+ page_size: 26,
+ after_name_key: undefined,
+ after_id: undefined,
+ },
+ ],
+ ])
+ expect(page).toEqual({ rows: [listRow(1)], next: null })
+ })
+
+ it('sends the species filter and the cursor; the probe row becomes next', async () => {
+ const rows = Array.from({ length: 11 }, (_, i) => listRow(i + 1))
+ const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
+ const page = await searchAnimals(client, {
+ workspaceId: WS,
+ query: '',
+ speciesId: 'canine',
+ archived: true,
+ pageSize: 10,
+ after: { nameKey: 'animal 000', id: ID },
+ })
+ expect(rpcCalls[0][1]).toMatchObject({
+ species_filter: 'canine',
+ archived: true,
+ page_size: 11,
+ after_name_key: 'animal 000',
+ after_id: ID,
+ })
+ expect(page.rows).toHaveLength(10)
+ expect(page.next).toEqual({ nameKey: rows[9].name_key, id: rows[9].id })
+ })
+
+ it('refuses an answer of another shape as unavailable', async () => {
+ const { client } = stubClient({ rpc: { data: [{ id: ID }] } })
+ expect(
+ await kindOf(
+ searchAnimals(client, {
+ workspaceId: WS,
+ query: '',
+ speciesId: null,
+ archived: false,
+ }),
+ ),
+ ).toBe('unavailable')
+ })
+})
+
+describe('fetchAnimalRecord', () => {
+ it('reads one animal by id with the explicit column list', async () => {
+ const { client, query } = stubClient({ select: { data: { id: ID } } })
+ expect(await fetchAnimalRecord(client, ID)).toEqual({ id: ID })
+ expect(query).toEqual({
+ table: 'animals',
+ select: ANIMAL_COLUMNS,
+ 'eq:id': ID,
+ })
+ expect(ANIMAL_COLUMNS).not.toContain('*')
+ expect(ANIMAL_COLUMNS).not.toContain('create_request')
+ expect(ANIMAL_COLUMNS).not.toContain('workspace_id')
+ })
+
+ it('answers null for an id that is not a uuid, without a request', async () => {
+ const { client, query } = stubClient()
+ expect(await fetchAnimalRecord(client, 'not-a-uuid')).toBeNull()
+ expect(query.table).toBeUndefined()
+ })
+
+ it('maps a lost answer to network and an expired session to session_expired', async () => {
+ const lost = stubClient({
+ select: { error: { code: '', message: 'FetchError' }, status: 0 },
+ })
+ expect(await kindOf(fetchAnimalRecord(lost.client, ID))).toBe('network')
+ const expired = stubClient({
+ select: {
+ error: { code: 'PGRST301', message: 'JWT expired' },
+ status: 401,
+ },
+ })
+ expect(await kindOf(fetchAnimalRecord(expired.client, ID))).toBe(
+ 'session_expired',
+ )
+ })
+})
+
+describe('animal writes', () => {
+ it('creates without relation: optionals left to their defaults, year as text', async () => {
+ const { client, rpcCalls } = stubClient({
+ rpc: { data: { id: ID, revision: 1, relation_id: null } },
+ })
+ expect(
+ await createAnimalRecord(client, {
+ workspaceId: WS,
+ requestId: REQUEST,
+ fields,
+ relation: null,
+ }),
+ ).toEqual({ id: ID, revision: 1, relationId: null })
+ expect(rpcCalls[0]).toEqual([
+ 'create_animal',
+ {
+ workspace_id: WS,
+ create_request_id: REQUEST,
+ name: 'Éclair',
+ species_id: 'equine',
+ sex: 'female',
+ species_detail: undefined,
+ breed: undefined,
+ birth_year: '2015',
+ birth_date: undefined,
+ client_id: undefined,
+ relation_role: undefined,
+ started_on: undefined,
+ },
+ ])
+ })
+
+ it('creates with an initial relation in the same call', async () => {
+ const { client, rpcCalls } = stubClient({
+ rpc: { data: { id: ID, revision: 1, relation_id: RELATION } },
+ })
+ const created = await createAnimalRecord(client, {
+ workspaceId: WS,
+ requestId: REQUEST,
+ fields: {
+ ...fields,
+ species_id: 'other',
+ species_detail: 'Furet',
+ birth_year: 2015,
+ birth_date: '2015-04-12',
+ },
+ relation: {
+ clientId: CLIENT,
+ relationRole: 'keeper',
+ startedOn: '2020-01-02',
+ },
+ })
+ expect(created.relationId).toBe(RELATION)
+ expect(rpcCalls[0][1]).toMatchObject({
+ species_id: 'other',
+ species_detail: 'Furet',
+ birth_year: '2015',
+ birth_date: '2015-04-12',
+ client_id: CLIENT,
+ relation_role: 'keeper',
+ started_on: '2020-01-02',
+ })
+ const noDate = stubClient({
+ rpc: { data: { id: ID, revision: 1, relation_id: RELATION } },
+ })
+ await createAnimalRecord(noDate.client, {
+ workspaceId: WS,
+ requestId: REQUEST,
+ fields: { ...fields, birth_year: null },
+ relation: { clientId: CLIENT, relationRole: 'owner', startedOn: null },
+ })
+ expect(noDate.rpcCalls[0][1]).toMatchObject({
+ birth_year: undefined,
+ started_on: undefined,
+ client_id: CLIENT,
+ })
+ })
+
+ it('updates with every field, null included, at the expected revision', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
+ expect(
+ await updateAnimalRecord(client, {
+ animalId: ID,
+ expectedRevision: 2,
+ fields: { ...fields, birth_year: null },
+ }),
+ ).toEqual({ revision: 3 })
+ expect(rpcCalls[0]).toEqual([
+ 'update_animal',
+ {
+ animal_id: ID,
+ expected_revision: 2,
+ name: 'Éclair',
+ species_id: 'equine',
+ sex: 'female',
+ species_detail: null,
+ breed: null,
+ birth_year: null,
+ birth_date: null,
+ },
+ ])
+ const withYear = stubClient({ rpc: { data: { revision: 3 } } })
+ await updateAnimalRecord(withYear.client, {
+ animalId: ID,
+ expectedRevision: 2,
+ fields,
+ })
+ expect(withYear.rpcCalls[0][1].birth_year).toBe('2015')
+ })
+
+ it('archives and restores through set_animal_archived', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
+ expect(await setAnimalArchived(client, ID, false)).toEqual({ revision: 2 })
+ expect(rpcCalls[0]).toEqual([
+ 'set_animal_archived',
+ { animal_id: ID, archived: false },
+ ])
+ })
+
+ it.each([
+ 'conflict',
+ 'request_conflict',
+ 'archived',
+ 'rate_limited',
+ 'limit_reached',
+ 'invalid_input',
+ ])('a %s refusal reaches the caller as that kind', async (message) => {
+ const { client } = stubClient({
+ rpc: { error: { code: 'P0001', message } },
+ })
+ expect(
+ await kindOf(
+ updateAnimalRecord(client, {
+ animalId: ID,
+ expectedRevision: 1,
+ fields,
+ }),
+ ),
+ ).toBe(message)
+ })
+
+ it('an unknown or foreign id is not_found; a created answer of another shape is unavailable', async () => {
+ const { client } = stubClient({
+ rpc: { error: { code: '42501', message: 'not_found' }, status: 403 },
+ })
+ expect(await kindOf(setAnimalArchived(client, ID, true))).toBe('not_found')
+ const odd = stubClient({ rpc: { data: { id: ID, revision: 1 } } })
+ expect(
+ await kindOf(
+ createAnimalRecord(odd.client, {
+ workspaceId: WS,
+ requestId: REQUEST,
+ fields,
+ relation: null,
+ }),
+ ),
+ ).toBe('unavailable')
+ })
+})
+
+describe('fetchAnimalRelations', () => {
+ it('reads by animal id, voided left out, explicit columns, bounded and ordered', async () => {
+ const { client, query, orders } = stubClient({
+ select: { data: [relationRow()] },
+ })
+ expect(await fetchAnimalRelations(client, ID)).toEqual([relationRow()])
+ expect(query).toEqual({
+ table: 'animal_client_relations',
+ select: ANIMAL_RELATION_COLUMNS,
+ 'eq:animal_id': ID,
+ 'is:voided_at': null,
+ limit: 200,
+ })
+ expect(orders).toEqual(['created_at', 'id'])
+ expect(ANIMAL_RELATION_COLUMNS).not.toContain('*')
+ expect(ANIMAL_RELATION_COLUMNS).not.toContain('create_request')
+ })
+
+ it('answers [] for an id that is not a uuid, without a request', async () => {
+ const { client, query } = stubClient()
+ expect(await fetchAnimalRelations(client, 'nope')).toEqual([])
+ expect(query.table).toBeUndefined()
+ })
+
+ it('refuses a row without its client as unavailable, maps failures', async () => {
+ const { client } = stubClient({
+ select: { data: [relationRow({ client: null })] },
+ })
+ expect(await kindOf(fetchAnimalRelations(client, ID))).toBe('unavailable')
+ const lost = stubClient({
+ select: { error: { message: 'TypeError: Failed to fetch' }, status: 0 },
+ })
+ expect(await kindOf(fetchAnimalRelations(lost.client, ID))).toBe('network')
+ })
+})
+
+describe('relation writes', () => {
+ it('creates with the request id; a missing start date is left to its default', async () => {
+ const { client, rpcCalls } = stubClient({
+ rpc: { data: { id: RELATION, revision: 1 } },
+ })
+ expect(
+ await createAnimalClientRelation(client, {
+ animalId: ID,
+ clientId: CLIENT,
+ requestId: REQUEST,
+ relationRole: 'contact',
+ startedOn: null,
+ }),
+ ).toEqual({ id: RELATION, revision: 1 })
+ expect(rpcCalls[0]).toEqual([
+ 'create_animal_client_relation',
+ {
+ animal_id: ID,
+ client_id: CLIENT,
+ create_request_id: REQUEST,
+ relation_role: 'contact',
+ started_on: undefined,
+ },
+ ])
+ })
+
+ it('ends with or without a date', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
+ await endAnimalClientRelation(client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ endedOn: null,
+ })
+ await endAnimalClientRelation(client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ endedOn: '2024-05-01',
+ })
+ expect(rpcCalls).toEqual([
+ [
+ 'end_animal_client_relation',
+ { relation_id: RELATION, expected_revision: 1, ended_on: undefined },
+ ],
+ [
+ 'end_animal_client_relation',
+ { relation_id: RELATION, expected_revision: 1, ended_on: '2024-05-01' },
+ ],
+ ])
+ })
+
+ it('corrects the dates sending both, null included', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
+ expect(
+ await updateAnimalClientRelation(client, {
+ relationId: RELATION,
+ expectedRevision: 2,
+ startedOn: '2020-01-01',
+ endedOn: null,
+ }),
+ ).toEqual({ revision: 3 })
+ expect(rpcCalls[0]).toEqual([
+ 'update_animal_client_relation',
+ {
+ relation_id: RELATION,
+ expected_revision: 2,
+ started_on: '2020-01-01',
+ ended_on: null,
+ },
+ ])
+ })
+
+ it('voids at the expected revision', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
+ expect(
+ await voidAnimalClientRelation(client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ }),
+ ).toEqual({ revision: 2 })
+ expect(rpcCalls[0]).toEqual([
+ 'void_animal_client_relation',
+ { relation_id: RELATION, expected_revision: 1 },
+ ])
+ })
+
+ it.each([
+ ['duplicate_relation', 'P0001', 400],
+ ['already_ended', 'P0001', 400],
+ ['conflict', 'P0001', 400],
+ ['archived', 'P0001', 400],
+ ['limit_reached', 'P0001', 400],
+ ['not_found', '42501', 403],
+ ])(
+ 'a %s refusal reaches the caller as that kind',
+ async (message, code, status) => {
+ const { client } = stubClient({
+ rpc: { error: { code, message }, status },
+ })
+ expect(
+ await kindOf(
+ createAnimalClientRelation(client, {
+ animalId: ID,
+ clientId: CLIENT,
+ requestId: REQUEST,
+ relationRole: 'owner',
+ startedOn: null,
+ }),
+ ),
+ ).toBe(message)
+ expect(
+ await kindOf(
+ endAnimalClientRelation(client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ endedOn: null,
+ }),
+ ),
+ ).toBe(message)
+ },
+ )
+
+ it('an expired session, a lost answer and an odd answer are closed kinds', async () => {
+ const expired = stubClient({
+ rpc: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 },
+ })
+ expect(
+ await kindOf(
+ voidAnimalClientRelation(expired.client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ }),
+ ),
+ ).toBe('session_expired')
+ const lost = stubClient({
+ rpc: { error: { message: 'TypeError: Failed to fetch' }, status: 0 },
+ })
+ expect(
+ await kindOf(
+ voidAnimalClientRelation(lost.client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ }),
+ ),
+ ).toBe('network')
+ const odd = stubClient({ rpc: { data: { revision: 'x' } } })
+ expect(
+ await kindOf(
+ voidAnimalClientRelation(odd.client, {
+ relationId: RELATION,
+ expectedRevision: 1,
+ }),
+ ),
+ ).toBe('unavailable')
+ })
+})
diff --git a/packages/supabase/tests/clients.test.ts b/packages/supabase/tests/clients.test.ts
new file mode 100644
index 00000000..87cf0b5e
--- /dev/null
+++ b/packages/supabase/tests/clients.test.ts
@@ -0,0 +1,347 @@
+import {
+ RecordFailure,
+ classifyRecordError,
+ createClientRecord,
+ fetchClientArchivePreview,
+ fetchClientRecord,
+ fetchPersonalWorkspaceId,
+ listClientAnimals,
+ searchClients,
+ setClientArchived,
+ updateClientRecord,
+ type ClientFields,
+ type FaunosteoClient,
+} from '../src'
+
+/**
+ * Call shapes and closed failure kinds of the workspaces and clients access
+ * layer. The argument names are checked by the compiler against the generated
+ * types; the RPC bodies by supabase/tests/013_clients.sql and 014; the same
+ * functions run against real PostgREST in tests/sandbox/clients-access.sandbox.ts.
+ */
+type Answer = { data?: unknown; error?: unknown; status?: number }
+
+function stubClient(answers: { rpc?: Answer; select?: Answer } = {}) {
+ const rpcCalls: Array<[string, Record]> = []
+ const query: Record = {}
+ const settle = (a: Answer = {}) => ({
+ data: a.data ?? null,
+ error: a.error ?? null,
+ status: a.status ?? (a.error ? 400 : 200),
+ })
+ const chain = {
+ select: (cols: string) => ((query.select = cols), chain),
+ eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain),
+ maybeSingle: async () => settle(answers.select),
+ }
+ const client = {
+ from: (table: string) => ((query.table = table), chain),
+ rpc: async (name: string, args: Record) => {
+ rpcCalls.push([name, args])
+ return settle(answers.rpc)
+ },
+ } as unknown as FaunosteoClient
+ return { client, rpcCalls, query }
+}
+
+const WS = '11111111-1111-4111-8111-111111111111'
+const ID = '22222222-2222-4222-8222-222222222222'
+const REQUEST = '33333333-3333-4333-8333-333333333333'
+
+const fields: ClientFields = {
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ email: null,
+ phone: '+33612345678',
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: 'Lyon',
+ country: null,
+}
+
+function listRow(i: number) {
+ return {
+ id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
+ kind: 'person',
+ display_name: `Client ${i}`,
+ city: null,
+ phone: null,
+ email: null,
+ archived_at: null,
+ name_key: `client ${String(i).padStart(3, '0')}`,
+ current_animal_count: 0,
+ }
+}
+
+async function kindOf(promise: Promise) {
+ try {
+ await promise
+ return 'no failure'
+ } catch (error) {
+ return error instanceof RecordFailure ? error.kind : 'not a RecordFailure'
+ }
+}
+
+describe('classifyRecordError', () => {
+ it.each([
+ [{ code: '42501', message: 'not_found' }, 403, 'not_found'],
+ [{ code: 'P0001', message: 'archived' }, 400, 'archived'],
+ [{ code: 'P0001', message: 'conflict' }, 400, 'conflict'],
+ [{ code: 'P0001', message: 'request_conflict' }, 400, 'request_conflict'],
+ [{ code: 'P0001', message: 'limit_reached' }, 400, 'limit_reached'],
+ [{ code: 'P0001', message: 'rate_limited' }, 400, 'rate_limited'],
+ [{ code: 'P0001', message: 'invalid_input' }, 400, 'invalid_input'],
+ [{ code: 'P0001', message: 'something else' }, 400, 'unavailable'],
+ [
+ { code: '42501', message: 'permission denied for table clients' },
+ 403,
+ 'unavailable',
+ ],
+ [{ code: 'PGRST301', message: 'JWT expired' }, 401, 'session_expired'],
+ [{ code: '', message: 'anything' }, 401, 'session_expired'],
+ [{ code: '', message: 'TypeError: Failed to fetch' }, 0, 'network'],
+ [
+ {
+ code: '57014',
+ message: 'canceling statement due to statement timeout',
+ },
+ 500,
+ 'unavailable',
+ ],
+ ])('%o with HTTP %i is %s', (error, status, kind) => {
+ expect(classifyRecordError(error, status)).toBe(kind)
+ })
+
+ it('reads a thrown TypeError as the network', () => {
+ expect(classifyRecordError(new TypeError('Failed to fetch'))).toBe(
+ 'network',
+ )
+ })
+})
+
+describe('fetchPersonalWorkspaceId', () => {
+ it('reads the id of the workspace whose personal user is the caller', async () => {
+ const { client, query } = stubClient({ select: { data: { id: WS } } })
+ expect(await fetchPersonalWorkspaceId(client, 'user-1')).toBe(WS)
+ expect(query).toEqual({
+ table: 'workspaces',
+ select: 'id',
+ 'eq:personal_user_id': 'user-1',
+ })
+ })
+
+ it('answers null when RLS returns no row, and a closed kind on failure', async () => {
+ expect(
+ await fetchPersonalWorkspaceId(stubClient().client, 'user-1'),
+ ).toBeNull()
+ const failing = stubClient({
+ select: { error: { code: '', message: 'FetchError' }, status: 0 },
+ })
+ expect(
+ await kindOf(fetchPersonalWorkspaceId(failing.client, 'user-1')),
+ ).toBe('network')
+ })
+})
+
+describe('searchClients', () => {
+ it('posts the term, asks one row more than the page and leaves the cursor out on page one', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } })
+ const page = await searchClients(client, {
+ workspaceId: WS,
+ query: 'marie',
+ archived: false,
+ })
+ expect(rpcCalls).toEqual([
+ [
+ 'search_clients',
+ {
+ workspace_id: WS,
+ query: 'marie',
+ archived: false,
+ page_size: 26,
+ after_name_key: undefined,
+ after_id: undefined,
+ },
+ ],
+ ])
+ expect(page).toEqual({ rows: [listRow(1)], next: null })
+ })
+
+ it('keeps 25 rows and turns the 26th into a next cursor at the 25th', async () => {
+ const rows = Array.from({ length: 26 }, (_, i) => listRow(i + 1))
+ const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
+ const page = await searchClients(client, {
+ workspaceId: WS,
+ query: '',
+ archived: true,
+ after: { nameKey: 'client 000', id: ID },
+ })
+ expect(page.rows).toHaveLength(25)
+ expect(page.next).toEqual({ nameKey: rows[24].name_key, id: rows[24].id })
+ expect(rpcCalls[0][1]).toMatchObject({
+ after_name_key: 'client 000',
+ after_id: ID,
+ archived: true,
+ })
+ })
+
+ it('refuses an answer of another shape as unavailable', async () => {
+ const { client } = stubClient({ rpc: { data: [{ id: 'x' }] } })
+ expect(
+ await kindOf(
+ searchClients(client, { workspaceId: WS, query: '', archived: false }),
+ ),
+ ).toBe('unavailable')
+ })
+})
+
+describe('fetchClientRecord', () => {
+ it('reads one client by id with the explicit column list', async () => {
+ const { client, query } = stubClient({ select: { data: { id: ID } } })
+ expect(await fetchClientRecord(client, ID)).toEqual({ id: ID })
+ expect(query.table).toBe('clients')
+ expect(query['eq:id']).toBe(ID)
+ expect(String(query.select)).not.toContain('*')
+ expect(String(query.select)).not.toContain('create_request_digest')
+ })
+
+ it('answers null for an id that is not a uuid, without a request', async () => {
+ const { client, query } = stubClient()
+ expect(await fetchClientRecord(client, 'not-a-uuid')).toBeNull()
+ expect(query.table).toBeUndefined()
+ })
+})
+
+describe('client writes', () => {
+ it('creates with the request id and leaves absent optionals to their defaults', async () => {
+ const { client, rpcCalls } = stubClient({
+ rpc: { data: { id: ID, revision: 1 } },
+ })
+ expect(
+ await createClientRecord(client, {
+ workspaceId: WS,
+ requestId: REQUEST,
+ fields,
+ }),
+ ).toEqual({
+ id: ID,
+ revision: 1,
+ })
+ expect(rpcCalls[0]).toEqual([
+ 'create_client',
+ {
+ workspace_id: WS,
+ create_request_id: REQUEST,
+ kind: 'person',
+ display_name: 'Marie Dupont',
+ email: undefined,
+ phone: '+33612345678',
+ address_line1: undefined,
+ address_line2: undefined,
+ postal_code: undefined,
+ city: 'Lyon',
+ country: undefined,
+ },
+ ])
+ })
+
+ it('updates with every field, null included, at the expected revision', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } })
+ expect(
+ await updateClientRecord(client, {
+ clientId: ID,
+ expectedRevision: 2,
+ fields,
+ }),
+ ).toEqual({ revision: 3 })
+ expect(rpcCalls[0]).toEqual([
+ 'update_client',
+ { client_id: ID, expected_revision: 2, ...fields },
+ ])
+ })
+
+ it('archives and restores through set_client_archived', async () => {
+ const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } })
+ expect(await setClientArchived(client, ID, true)).toEqual({ revision: 2 })
+ expect(rpcCalls[0]).toEqual([
+ 'set_client_archived',
+ { client_id: ID, archived: true },
+ ])
+ })
+
+ it.each([
+ 'conflict',
+ 'request_conflict',
+ 'archived',
+ 'rate_limited',
+ 'limit_reached',
+ 'invalid_input',
+ ])('a %s refusal reaches the caller as that kind', async (message) => {
+ const { client } = stubClient({
+ rpc: { error: { code: 'P0001', message } },
+ })
+ expect(
+ await kindOf(
+ updateClientRecord(client, {
+ clientId: ID,
+ expectedRevision: 1,
+ fields,
+ }),
+ ),
+ ).toBe(message)
+ })
+
+ it('an unknown or foreign id is not_found', async () => {
+ const { client } = stubClient({
+ rpc: { error: { code: '42501', message: 'not_found' }, status: 403 },
+ })
+ expect(await kindOf(setClientArchived(client, ID, true))).toBe('not_found')
+ })
+})
+
+describe('client animals and archive preview', () => {
+ it('lists 50 relations per page by default with a cursor on sort_key and relation id', async () => {
+ const row = (i: number) => ({
+ relation_id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
+ relation_role: 'owner',
+ started_on: null,
+ ended_on: null,
+ is_current: true,
+ relation_revision: 1,
+ animal_id: ID,
+ animal_name: `Animal ${i}`,
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'female',
+ breed: null,
+ birth_year: null,
+ animal_archived_at: null,
+ sort_key: `0animal ${String(i).padStart(3, '0')}`,
+ })
+ const rows = Array.from({ length: 51 }, (_, i) => row(i + 1))
+ const { client, rpcCalls } = stubClient({ rpc: { data: rows } })
+ const page = await listClientAnimals(client, ID)
+ expect(rpcCalls[0]).toEqual([
+ 'list_client_animals',
+ {
+ client_id: ID,
+ page_size: 51,
+ after_sort: undefined,
+ after_id: undefined,
+ },
+ ])
+ expect(page.rows).toHaveLength(50)
+ expect(page.next).toEqual({
+ sortKey: rows[49].sort_key,
+ relationId: rows[49].relation_id,
+ })
+ })
+
+ it('reads the archive preview', async () => {
+ const preview = { count: 1, animals: [{ id: ID, name: 'Éclair' }] }
+ const { client, rpcCalls } = stubClient({ rpc: { data: preview } })
+ expect(await fetchClientArchivePreview(client, ID)).toEqual(preview)
+ expect(rpcCalls[0]).toEqual(['client_archive_preview', { client_id: ID }])
+ })
+})
diff --git a/packages/supabase/tests/db/config.test.ts b/packages/supabase/tests/db/config.test.ts
new file mode 100644
index 00000000..4ed86b19
--- /dev/null
+++ b/packages/supabase/tests/db/config.test.ts
@@ -0,0 +1,38 @@
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { supabaseDir } from './harness'
+
+/**
+ * Settings the workspace access rule depends on (V1-1 contract §6.2, §9.1).
+ * private.caller_workspace_ids() requires auth.users.email_confirmed_at, but
+ * with confirmations off GoTrue stamps that column at sign-up; the helpers
+ * live in `private`, which must stay out of the PostgREST schemas.
+ */
+async function readSetting(
+ section: string,
+ key: string,
+): Promise {
+ const config = await readFile(join(supabaseDir, 'config.toml'), 'utf8')
+ let current = ''
+ for (const line of config.split('\n')) {
+ const header = line.match(/^\[([^\]]+)\]\s*$/)
+ if (header) current = header[1]
+ const setting = line.match(/^(\w+)\s*=\s*(.+?)\s*$/)
+ if (current === section && setting?.[1] === key) return setting[2]
+ }
+ return undefined
+}
+
+describe('config.toml settings the access rules rely on', () => {
+ it('requires email confirmation before any session', async () => {
+ expect(await readSetting('auth.email', 'enable_confirmations')).toBe('true')
+ })
+
+ it('keeps anonymous sign-ins off (no account without an email)', async () => {
+ expect(await readSetting('auth', 'enable_anonymous_sign_ins')).toBe('false')
+ })
+
+ it('exposes only the public schema through PostgREST', async () => {
+ expect(await readSetting('api', 'schemas')).toBe('["public"]')
+ })
+})
diff --git a/packages/supabase/tests/db/field-limits.test.ts b/packages/supabase/tests/db/field-limits.test.ts
new file mode 100644
index 00000000..badebf09
--- /dev/null
+++ b/packages/supabase/tests/db/field-limits.test.ts
@@ -0,0 +1,280 @@
+/**
+ * D-R7 parity: the constants of src/field-limits.ts behave like the SQL CHECK
+ * constraints of public.clients, public.animals and
+ * public.animal_client_relations, proven by inserting values at and past each
+ * bound into the migrated PGlite schema (contract §12.2). The form may refuse
+ * more than SQL (never less): a value the TypeScript rule accepts must be
+ * accepted by SQL, and the listed samples must agree both ways.
+ */
+import type { PGlite } from '@electric-sql/pglite'
+import {
+ ANIMAL_FIELD_LIMITS,
+ BIRTH_YEAR_MIN,
+ CLIENT_FIELD_LIMITS,
+ COUNTRY_CODE_PATTERN,
+ EMAIL_PATTERN,
+ PHONE_E164_PATTERN,
+ RECORD_DATE_MIN,
+ codePointLength,
+ isCleanText,
+} from '../../src/field-limits'
+import { createMigratedDatabase } from './harness'
+
+type Column =
+ | 'display_name'
+ | 'email'
+ | 'phone'
+ | 'address_line1'
+ | 'postal_code'
+ | 'city'
+ | 'country'
+
+let db: PGlite
+let workspaceId: string
+
+async function sqlAccepts(column: Column, value: string): Promise {
+ const name = column === 'display_name' ? value : 'Parity'
+ const extra = column === 'display_name' ? '' : `, ${column}`
+ await db.exec('begin')
+ try {
+ await db.query(
+ `insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest${extra})
+ values ($1, 'person', $2, gen_random_uuid(), '\\x00'${column === 'display_name' ? '' : ', $3'})`,
+ column === 'display_name'
+ ? [workspaceId, name]
+ : [workspaceId, name, value],
+ )
+ return true
+ } catch {
+ return false
+ } finally {
+ await db.exec('rollback')
+ }
+}
+
+const textSamples = (max: number): string[] => [
+ 'a'.repeat(max),
+ 'a'.repeat(max + 1),
+ 'é'.repeat(max),
+ 'é'.repeat(max + 1),
+ '𝄞'.repeat(max),
+ '𝄞'.repeat(max + 1),
+ '',
+ ' a',
+ 'a ',
+ 'a\tb',
+ 'a\u007Fb',
+ 'a\u0085b',
+ 'a\u2028b',
+ 'a\u2029b',
+ '\u00A0a',
+]
+
+const textFields: [Column, number][] = [
+ ['display_name', CLIENT_FIELD_LIMITS.displayName],
+ ['address_line1', CLIENT_FIELD_LIMITS.addressLine],
+ ['postal_code', CLIENT_FIELD_LIMITS.postalCode],
+ ['city', CLIENT_FIELD_LIMITS.city],
+]
+
+/** One animal row in a rolled-back transaction: does the schema accept these columns? */
+async function animalAccepts(
+ columns: Record,
+): Promise {
+ const row = { name: 'Parity', species_id: 'equine', ...columns }
+ const names = Object.keys(row)
+ await db.exec('begin')
+ try {
+ await db.query(
+ `insert into public.animals (workspace_id, sex, create_request_id, create_request_digest, ${names.join(', ')})
+ values ($1, 'unknown', gen_random_uuid(), '\\x00', ${names.map((_, i) => `$${i + 2}`).join(', ')})`,
+ [workspaceId, ...Object.values(row)],
+ )
+ return true
+ } catch {
+ return false
+ } finally {
+ await db.exec('rollback')
+ }
+}
+
+/** One relation row (ended, so both dates are allowed) to a fresh animal and client. */
+async function relationAccepts(
+ column: 'started_on' | 'ended_on',
+ value: string,
+): Promise {
+ await db.exec('begin')
+ try {
+ await db.query(
+ `with a as (insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+ values ($1, 'Parity', 'equine', 'unknown', gen_random_uuid(), '\\x00') returning id),
+ c as (insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+ values ($1, 'person', 'Parity', gen_random_uuid(), '\\x00') returning id)
+ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, ${column},
+ create_request_id, create_request_digest)
+ select $1, a.id, c.id, 'owner', now(), $2, gen_random_uuid(), '\\x00' from a, c`,
+ [workspaceId, value],
+ )
+ return true
+ } catch {
+ return false
+ } finally {
+ await db.exec('rollback')
+ }
+}
+
+const tsEmail = (v: string) =>
+ isCleanText(v, CLIENT_FIELD_LIMITS.email) &&
+ v === v.toLowerCase() &&
+ EMAIL_PATTERN.test(v)
+const emailSamples = [
+ 'a@b.co',
+ 'A@b.co',
+ 'a b@c.de',
+ 'a@b',
+ '@b.co',
+ 'a@@b.co',
+ 'a'.repeat(246) + '@ex.test',
+ 'a'.repeat(247) + '@ex.test',
+ 'é@exemple.fr',
+]
+/** JavaScript's \s covers U+00A0, PostgreSQL's does not: the form refuses, SQL would accept. */
+const emailTsStricter = ['a\u00A0b@c.de']
+
+describe('field limits match the SQL constraints (D-R7)', () => {
+ beforeAll(async () => {
+ db = await createMigratedDatabase()
+ await db.exec(`insert into auth.users (id, email, email_confirmed_at)
+ values ('7a000000-0000-0000-0000-000000000001', 'parity@test.local', now())`)
+ const { rows } = await db.query<{ id: string }>(
+ `select id from public.workspaces where personal_user_id = '7a000000-0000-0000-0000-000000000001'`,
+ )
+ workspaceId = rows[0].id
+ })
+
+ afterAll(async () => {
+ await db?.close()
+ })
+
+ it('counts code points like char_length', () => {
+ expect(codePointLength('𝄞é')).toBe(2)
+ expect('𝄞é'.length).toBe(3)
+ })
+
+ it.each(textFields)(
+ '%s: the text rule and its bound %i agree',
+ async (column, max) => {
+ for (const value of textSamples(max)) {
+ expect([
+ column,
+ JSON.stringify(value).slice(0, 24),
+ await sqlAccepts(column, value),
+ ]).toEqual([
+ column,
+ JSON.stringify(value).slice(0, 24),
+ isCleanText(value, max),
+ ])
+ }
+ },
+ )
+
+ it('email: bound, lower case and pattern agree', async () => {
+ for (const value of emailSamples) {
+ expect([value.slice(0, 24), await sqlAccepts('email', value)]).toEqual([
+ value.slice(0, 24),
+ tsEmail(value),
+ ])
+ }
+ for (const value of emailTsStricter) {
+ expect(tsEmail(value)).toBe(false)
+ }
+ })
+
+ it('phone: E.164 agrees', async () => {
+ const samples = [
+ '+33612345678',
+ '+1234567',
+ '+123456',
+ '+123456789012345',
+ '+1234567890123456',
+ '0612345678',
+ '+0612345678',
+ '+33 612345678',
+ ]
+ for (const value of samples) {
+ expect([value, await sqlAccepts('phone', value)]).toEqual([
+ value,
+ PHONE_E164_PATTERN.test(value),
+ ])
+ }
+ })
+
+ it('country: ISO alpha-2 upper case agrees', async () => {
+ for (const value of ['FR', 'fr', 'FRA', 'F1', 'F']) {
+ expect([value, await sqlAccepts('country', value)]).toEqual([
+ value,
+ COUNTRY_CODE_PATTERN.test(value),
+ ])
+ }
+ })
+
+ it.each([
+ ['name', ANIMAL_FIELD_LIMITS.name],
+ ['breed', ANIMAL_FIELD_LIMITS.breed],
+ ] as const)(
+ 'animals.%s: the text rule and its bound %i agree',
+ async (column, max) => {
+ for (const value of textSamples(max)) {
+ expect([
+ column,
+ JSON.stringify(value).slice(0, 24),
+ await animalAccepts({ [column]: value }),
+ ]).toEqual([
+ column,
+ JSON.stringify(value).slice(0, 24),
+ isCleanText(value, max),
+ ])
+ }
+ },
+ )
+
+ it('animals.species_detail: the text rule and its bound agree (with other)', async () => {
+ for (const value of textSamples(ANIMAL_FIELD_LIMITS.speciesDetail)) {
+ expect([
+ JSON.stringify(value).slice(0, 24),
+ await animalAccepts({ species_id: 'other', species_detail: value }),
+ ]).toEqual([
+ JSON.stringify(value).slice(0, 24),
+ isCleanText(value, ANIMAL_FIELD_LIMITS.speciesDetail),
+ ])
+ }
+ })
+
+ it('birth year: the floor agrees', async () => {
+ for (const year of [BIRTH_YEAR_MIN - 1, BIRTH_YEAR_MIN, 2015]) {
+ expect([year, await animalAccepts({ birth_year: String(year) })]).toEqual(
+ [year, year >= BIRTH_YEAR_MIN],
+ )
+ }
+ })
+
+ it('record dates: the floor agrees on birth and relation dates', async () => {
+ const before = '1899-12-31'
+ for (const value of [before, RECORD_DATE_MIN, '2015-04-12']) {
+ const expected = value >= RECORD_DATE_MIN
+ const year = value.slice(0, 4)
+ expect([
+ value,
+ await animalAccepts({ birth_year: year, birth_date: value }),
+ ]).toEqual([value, expected])
+ expect([value, await relationAccepts('started_on', value)]).toEqual([
+ value,
+ expected,
+ ])
+ expect([value, await relationAccepts('ended_on', value)]).toEqual([
+ value,
+ expected,
+ ])
+ }
+ })
+})
diff --git a/packages/supabase/tests/db/harness.ts b/packages/supabase/tests/db/harness.ts
index 228a6540..80006b5e 100644
--- a/packages/supabase/tests/db/harness.ts
+++ b/packages/supabase/tests/db/harness.ts
@@ -11,6 +11,7 @@ import { resolve, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PGlite } from '@electric-sql/pglite'
import { pgtap } from '@electric-sql/pglite/pgtap'
+import { unaccent } from '@electric-sql/pglite/contrib/unaccent'
const here = fileURLToPath(new URL('.', import.meta.url))
export const repoRoot = resolve(here, '../../../..')
@@ -41,7 +42,8 @@ export async function listSeeds(): Promise {
/** Boots PGlite, installs the shim and applies all migrations. */
export async function createMigratedDatabase(): Promise {
- const db = await PGlite.create({ extensions: { pgtap } })
+ // unaccent: created by the clients migration (search keys), as on the real image.
+ const db = await PGlite.create({ extensions: { pgtap, unaccent } })
await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8'))
// Same placement as `supabase test db`: pgTAP lives in extensions, out of public.
await db.exec('create extension if not exists pgtap with schema extensions;')
diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts
index 84da6653..c003c198 100644
--- a/packages/supabase/tests/db/schema-types.test.ts
+++ b/packages/supabase/tests/db/schema-types.test.ts
@@ -20,6 +20,41 @@ type ColumnMap = {
}
const expectedColumns = {
+ animal_client_relations: [
+ 'animal_id',
+ 'client_id',
+ 'create_request_digest',
+ 'create_request_id',
+ 'created_at',
+ 'ended_at',
+ 'ended_on',
+ 'id',
+ 'relation_role',
+ 'revision',
+ 'started_on',
+ 'updated_at',
+ 'voided_at',
+ 'workspace_id',
+ ],
+ animals: [
+ 'archived_at',
+ 'birth_date',
+ 'birth_year',
+ 'breed',
+ 'create_request_digest',
+ 'create_request_id',
+ 'created_at',
+ 'id',
+ 'name',
+ 'name_key',
+ 'revision',
+ 'search_key',
+ 'sex',
+ 'species_detail',
+ 'species_id',
+ 'updated_at',
+ 'workspace_id',
+ ],
anatomical_sheet_assets: [
'byte_size',
'content_type',
@@ -85,6 +120,28 @@ const expectedColumns = {
'status',
'updated_at',
],
+ clients: [
+ 'address_line1',
+ 'address_line2',
+ 'archived_at',
+ 'city',
+ 'country',
+ 'create_request_digest',
+ 'create_request_id',
+ 'created_at',
+ 'display_name',
+ 'email',
+ 'id',
+ 'kind',
+ 'name_key',
+ 'phone',
+ 'phone_digits',
+ 'postal_code',
+ 'revision',
+ 'search_key',
+ 'updated_at',
+ 'workspace_id',
+ ],
profile_roles: [
'granted_at',
'granted_by',
@@ -112,6 +169,8 @@ const expectedColumns = {
'updated_at',
],
species: ['active', 'created_at', 'id', 'name_en', 'name_fr', 'sort_order'],
+ workspace_members: ['created_at', 'member_role', 'user_id', 'workspace_id'],
+ workspaces: ['created_at', 'id', 'kind', 'personal_user_id'],
} as const satisfies ColumnMap
// Compile-time: a column present in the type but absent from the list is an error.
@@ -134,6 +193,7 @@ const expectedFunctionArgs = {
claim_avatar_jobs: ['max_jobs'],
claim_purges: ['max_items'],
claim_quarantine_leftovers: ['max_items', 'older_than_seconds'],
+ client_archive_preview: ['client_id'],
complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'],
confirm_asset_upload: ['asset_id'],
confirm_sheet_asset_upload: ['asset_id'],
@@ -146,14 +206,50 @@ const expectedFunctionArgs = {
'species_id',
'visibility',
],
+ create_animal: [
+ 'birth_date',
+ 'birth_year',
+ 'breed',
+ 'client_id',
+ 'create_request_id',
+ 'name',
+ 'relation_role',
+ 'sex',
+ 'species_detail',
+ 'species_id',
+ 'started_on',
+ 'workspace_id',
+ ],
+ create_animal_client_relation: [
+ 'animal_id',
+ 'client_id',
+ 'create_request_id',
+ 'relation_role',
+ 'started_on',
+ ],
+ create_client: [
+ 'address_line1',
+ 'address_line2',
+ 'city',
+ 'country',
+ 'create_request_id',
+ 'display_name',
+ 'email',
+ 'kind',
+ 'phone',
+ 'postal_code',
+ 'workspace_id',
+ ],
create_sheet_draft: ['change_note', 'from_version_id', 'sheet_id'],
delete_anatomical_sheet: ['sheet_id'],
delete_sheet_asset: ['asset_id'],
delete_sheet_version: ['version_id'],
deprecate_sheet_version: ['reason', 'version_id'],
+ end_animal_client_relation: ['ended_on', 'expected_revision', 'relation_id'],
expire_pending_uploads: ['max_age_seconds'],
fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'],
grant_platform_role: ['role', 'target_user_id'],
+ list_client_animals: ['after_id', 'after_sort', 'client_id', 'page_size'],
mark_quarantine_purged: ['asset_id'],
publish_sheet_version: ['version_id'],
register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'],
@@ -161,7 +257,57 @@ const expectedFunctionArgs = {
remove_avatar: [],
restore_anatomical_sheet: ['sheet_id'],
revoke_platform_role: ['reason', 'role', 'target_user_id'],
+ search_animals: [
+ 'after_id',
+ 'after_name_key',
+ 'archived',
+ 'page_size',
+ 'query',
+ 'species_filter',
+ 'workspace_id',
+ ],
+ search_clients: [
+ 'after_id',
+ 'after_name_key',
+ 'archived',
+ 'page_size',
+ 'query',
+ 'workspace_id',
+ ],
+ set_animal_archived: ['animal_id', 'archived'],
+ set_client_archived: ['archived', 'client_id'],
set_sheet_visibility: ['sheet_id', 'visibility'],
+ update_animal: [
+ 'animal_id',
+ 'birth_date',
+ 'birth_year',
+ 'breed',
+ 'expected_revision',
+ 'name',
+ 'sex',
+ 'species_detail',
+ 'species_id',
+ ],
+ update_animal_client_relation: [
+ 'ended_on',
+ 'expected_revision',
+ 'relation_id',
+ 'started_on',
+ ],
+ update_client: [
+ 'address_line1',
+ 'address_line2',
+ 'city',
+ 'client_id',
+ 'country',
+ 'display_name',
+ 'email',
+ 'expected_revision',
+ 'kind',
+ 'phone',
+ 'postal_code',
+ ],
+ void_animal_client_relation: ['expected_revision', 'relation_id'],
} as const satisfies FunctionArgs
// A function without arguments is generated as `Record`
diff --git a/packages/supabase/tests/sandbox/animals-access.sandbox.ts b/packages/supabase/tests/sandbox/animals-access.sandbox.ts
new file mode 100644
index 00000000..611bd108
--- /dev/null
+++ b/packages/supabase/tests/sandbox/animals-access.sandbox.ts
@@ -0,0 +1,570 @@
+/**
+ * The V1-1.6 access layer (src/animals.ts, src/relations.ts) against the real
+ * GoTrue and PostgREST of `pnpm db:sandbox`, through supabase-js as the
+ * browser uses it: the generated argument names, the explicit columns, the
+ * embedded client of a relation, the keyset pages and every closed failure
+ * kind come from the real server, not from a stub. Fictitious data only.
+ */
+import { randomUUID } from 'node:crypto'
+import { createClient } from '@supabase/supabase-js'
+import {
+ RecordFailure,
+ createAnimalClientRelation,
+ createAnimalRecord,
+ createClientRecord,
+ endAnimalClientRelation,
+ fetchAnimalRecord,
+ fetchAnimalRelations,
+ fetchPersonalWorkspaceId,
+ listClientAnimals,
+ searchAnimals,
+ setAnimalArchived,
+ updateAnimalClientRelation,
+ updateAnimalRecord,
+ voidAnimalClientRelation,
+ type AnimalFields,
+ type Database,
+ type FaunosteoClient,
+} from '../../src'
+import { PASSWORD, confirmedAccount, stack, type Account } from './stack'
+
+const BASE = 'http://sandbox.faunosteo.invalid'
+
+function browserClient(): FaunosteoClient {
+ const mapped: typeof fetch = (input, init) => {
+ const url = String(input instanceof Request ? input.url : input)
+ .replace(`${BASE}/auth/v1`, stack.authUrl)
+ .replace(`${BASE}/rest/v1`, stack.restUrl)
+ return fetch(url, init)
+ }
+ return createClient(BASE, stack.anonKey, {
+ auth: { persistSession: false, autoRefreshToken: false },
+ global: { fetch: mapped },
+ })
+}
+
+async function signedIn(account: Account): Promise {
+ const client = browserClient()
+ const { error } = await client.auth.signInWithPassword({
+ email: account.email,
+ password: PASSWORD,
+ })
+ if (error) throw error
+ return client
+}
+
+async function kindOf(promise: Promise) {
+ try {
+ await promise
+ return 'no failure'
+ } catch (error) {
+ return error instanceof RecordFailure ? error.kind : String(error)
+ }
+}
+
+const animal = (
+ name: string,
+ patch: Partial = {},
+): AnimalFields => ({
+ name,
+ species_id: 'equine',
+ species_detail: null,
+ sex: 'unknown',
+ breed: null,
+ birth_year: null,
+ birth_date: null,
+ ...patch,
+})
+
+describe('animals and relations access layer on the sandbox', () => {
+ let a: Account
+ let b: Account
+ let asA: FaunosteoClient
+ let asB: FaunosteoClient
+ let wA: string
+ let wB: string
+
+ async function clientOfA(name: string): Promise {
+ const { id } = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: {
+ kind: 'person',
+ display_name: name,
+ email: null,
+ phone: '+33612345678',
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: null,
+ country: null,
+ },
+ })
+ return id
+ }
+
+ async function animalOfA(name: string): Promise {
+ return (
+ await createAnimalRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: animal(name),
+ relation: null,
+ })
+ ).id
+ }
+
+ beforeAll(async () => {
+ a = await confirmedAccount('animals-a')
+ b = await confirmedAccount('animals-b')
+ asA = await signedIn(a)
+ asB = await signedIn(b)
+ wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string
+ wB = (await fetchPersonalWorkspaceId(asB, b.id)) as string
+ })
+
+ it('creates without a relation and reads the explicit columns', async () => {
+ const fields = animal('Tornado Fictif', {
+ sex: 'male',
+ breed: 'Selle français',
+ birth_year: 2015,
+ birth_date: '2015-04-12',
+ })
+ const created = await createAnimalRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields,
+ relation: null,
+ })
+ expect(created).toMatchObject({ revision: 1, relationId: null })
+ const record = await fetchAnimalRecord(asA, created.id)
+ expect(Object.keys(record ?? {}).sort()).toEqual(
+ [
+ 'archived_at',
+ 'birth_date',
+ 'birth_year',
+ 'breed',
+ 'created_at',
+ 'id',
+ 'name',
+ 'revision',
+ 'sex',
+ 'species_detail',
+ 'species_id',
+ 'updated_at',
+ ].sort(),
+ )
+ expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null })
+ expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
+ })
+
+ it('creates with an initial relation, replays idempotently, refuses a divergent replay', async () => {
+ const clientId = await clientOfA('Marie Initiale')
+ const requestId = randomUUID()
+ const input = {
+ workspaceId: wA,
+ requestId,
+ fields: animal('Furet Fictif', {
+ species_id: 'other',
+ species_detail: 'Furet',
+ }),
+ relation: {
+ clientId,
+ relationRole: 'owner' as const,
+ startedOn: '2020-01-02',
+ },
+ }
+ const first = await createAnimalRecord(asA, input)
+ expect(first.relationId).not.toBeNull()
+ expect(await createAnimalRecord(asA, input)).toEqual(first)
+ expect(
+ await kindOf(
+ createAnimalRecord(asA, {
+ ...input,
+ fields: animal('Autre Nom', {
+ species_id: 'other',
+ species_detail: 'Furet',
+ }),
+ }),
+ ),
+ ).toBe('request_conflict')
+ const relations = await fetchAnimalRelations(asA, first.id)
+ expect(relations).toEqual([
+ {
+ id: first.relationId,
+ relation_role: 'owner',
+ started_on: '2020-01-02',
+ ended_on: null,
+ ended_at: null,
+ revision: 1,
+ client: {
+ id: clientId,
+ kind: 'person',
+ display_name: 'Marie Initiale',
+ phone: '+33612345678',
+ email: null,
+ archived_at: null,
+ },
+ },
+ ])
+ const found = await searchAnimals(asA, {
+ workspaceId: wA,
+ query: 'furet fictif',
+ speciesId: null,
+ archived: false,
+ })
+ expect(found.rows).toHaveLength(1)
+ expect(found.rows[0]).toMatchObject({
+ id: first.id,
+ current_owner_count: 1,
+ current_owners: [
+ {
+ client_id: clientId,
+ display_name: 'Marie Initiale',
+ archived: false,
+ },
+ ],
+ })
+ })
+
+ it('searches by term, species filter and archived toggle, in pages', async () => {
+ const c = await confirmedAccount('animals-page')
+ const asC = await signedIn(c)
+ const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string
+ for (let i = 1; i <= 12; i++) {
+ await createAnimalRecord(asC, {
+ workspaceId: wC,
+ requestId: randomUUID(),
+ fields: animal(`Cheval ${String(i).padStart(2, '0')}`),
+ relation: null,
+ })
+ }
+ const dog = await createAnimalRecord(asC, {
+ workspaceId: wC,
+ requestId: randomUUID(),
+ fields: animal('Chien Unique', { species_id: 'canine' }),
+ relation: null,
+ })
+ const one = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: 'cheval',
+ speciesId: 'equine',
+ archived: false,
+ pageSize: 10,
+ })
+ expect(one.rows).toHaveLength(10)
+ expect(one.next).not.toBeNull()
+ const two = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: 'cheval',
+ speciesId: 'equine',
+ archived: false,
+ pageSize: 10,
+ after: one.next,
+ })
+ expect(two.rows.map((r) => r.name)).toEqual(['Cheval 11', 'Cheval 12'])
+ expect(two.next).toBeNull()
+ const equines = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: '',
+ speciesId: 'equine',
+ archived: false,
+ pageSize: 50,
+ })
+ expect(equines.rows.map((r) => r.id)).not.toContain(dog.id)
+ const canines = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: '',
+ speciesId: 'canine',
+ archived: false,
+ })
+ expect(canines.rows.map((r) => r.id)).toEqual([dog.id])
+ expect(await setAnimalArchived(asC, dog.id, true)).toEqual({ revision: 2 })
+ const active = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: 'chien',
+ speciesId: null,
+ archived: false,
+ })
+ expect(active.rows).toEqual([])
+ const archived = await searchAnimals(asC, {
+ workspaceId: wC,
+ query: 'chien',
+ speciesId: null,
+ archived: true,
+ })
+ expect(archived.rows.map((r) => r.id)).toEqual([dog.id])
+ })
+
+ it('nothing of A reaches B: reads empty, writes not_found', async () => {
+ const clientId = await clientOfA('Client Secret')
+ const created = await createAnimalRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: animal('Animal Secret'),
+ relation: { clientId, relationRole: 'owner', startedOn: null },
+ })
+ const relationId = created.relationId as string
+ expect(await fetchAnimalRecord(asB, created.id)).toBeNull()
+ expect(await fetchAnimalRecord(asA, randomUUID())).toBeNull()
+ expect(await fetchAnimalRelations(asB, created.id)).toEqual([])
+ const search = await searchAnimals(asB, {
+ workspaceId: wB,
+ query: 'secret',
+ speciesId: null,
+ archived: false,
+ })
+ expect(search.rows).toEqual([])
+ const bAnimal = await createAnimalRecord(asB, {
+ workspaceId: wB,
+ requestId: randomUUID(),
+ fields: animal('Animal de B'),
+ relation: null,
+ })
+ for (const write of [
+ () =>
+ updateAnimalRecord(asB, {
+ animalId: created.id,
+ expectedRevision: 1,
+ fields: animal('X'),
+ }),
+ () => setAnimalArchived(asB, created.id, true),
+ () =>
+ createAnimalClientRelation(asB, {
+ animalId: bAnimal.id,
+ clientId,
+ requestId: randomUUID(),
+ relationRole: 'owner',
+ startedOn: null,
+ }),
+ () =>
+ endAnimalClientRelation(asB, {
+ relationId,
+ expectedRevision: 1,
+ endedOn: null,
+ }),
+ () =>
+ updateAnimalClientRelation(asB, {
+ relationId,
+ expectedRevision: 1,
+ startedOn: null,
+ endedOn: null,
+ }),
+ () => voidAnimalClientRelation(asB, { relationId, expectedRevision: 1 }),
+ () =>
+ createAnimalRecord(asB, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: animal('Intrus'),
+ relation: null,
+ }),
+ ])
+ expect(await kindOf(write())).toBe('not_found')
+ expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
+ })
+
+ it('a relation: duplicate refused, end with and without date, already_ended, dates, conflict', async () => {
+ const animalId = await animalOfA('Relation Fictive')
+ const owner = await clientOfA('Propriétaire Fictif')
+ const keeper = await clientOfA('Détenteur Fictif')
+ const rel = await createAnimalClientRelation(asA, {
+ animalId,
+ clientId: owner,
+ requestId: randomUUID(),
+ relationRole: 'owner',
+ startedOn: '2019-03-01',
+ })
+ expect(rel.revision).toBe(1)
+ expect(
+ await kindOf(
+ createAnimalClientRelation(asA, {
+ animalId,
+ clientId: owner,
+ requestId: randomUUID(),
+ relationRole: 'owner',
+ startedOn: null,
+ }),
+ ),
+ ).toBe('duplicate_relation')
+ const keep = await createAnimalClientRelation(asA, {
+ animalId,
+ clientId: keeper,
+ requestId: randomUUID(),
+ relationRole: 'keeper',
+ startedOn: null,
+ })
+ expect(
+ await endAnimalClientRelation(asA, {
+ relationId: rel.id,
+ expectedRevision: 1,
+ endedOn: '2024-05-01',
+ }),
+ ).toEqual({ revision: 2 })
+ expect(
+ await endAnimalClientRelation(asA, {
+ relationId: keep.id,
+ expectedRevision: 1,
+ endedOn: null,
+ }),
+ ).toEqual({ revision: 2 })
+ expect(
+ await kindOf(
+ endAnimalClientRelation(asA, {
+ relationId: rel.id,
+ expectedRevision: 2,
+ endedOn: null,
+ }),
+ ),
+ ).toBe('already_ended')
+ const relations = await fetchAnimalRelations(asA, animalId)
+ const byId = new Map(relations.map((r) => [r.id, r]))
+ expect(byId.get(rel.id)).toMatchObject({
+ ended_on: '2024-05-01',
+ started_on: '2019-03-01',
+ })
+ expect(byId.get(rel.id)?.ended_at).not.toBeNull()
+ expect(byId.get(keep.id)).toMatchObject({ ended_on: null })
+ expect(byId.get(keep.id)?.ended_at).not.toBeNull()
+ expect(
+ await updateAnimalClientRelation(asA, {
+ relationId: rel.id,
+ expectedRevision: 2,
+ startedOn: null,
+ endedOn: '2024-06-01',
+ }),
+ ).toEqual({ revision: 3 })
+ expect(
+ (await fetchAnimalRelations(asA, animalId)).find((r) => r.id === rel.id),
+ ).toMatchObject({ started_on: null, ended_on: '2024-06-01', revision: 3 })
+ expect(
+ await kindOf(
+ updateAnimalClientRelation(asA, {
+ relationId: rel.id,
+ expectedRevision: 2,
+ startedOn: null,
+ endedOn: null,
+ }),
+ ),
+ ).toBe('conflict')
+ // A successive relation of the same triple once the first has ended.
+ expect(
+ (
+ await createAnimalClientRelation(asA, {
+ animalId,
+ clientId: owner,
+ requestId: randomUUID(),
+ relationRole: 'owner',
+ startedOn: null,
+ })
+ ).revision,
+ ).toBe(1)
+ })
+
+ it('a voided relation leaves the relations, the current owners and the client animals', async () => {
+ const owner = await clientOfA('Erreur de Saisie')
+ const created = await createAnimalRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: animal('Annulation Fictive'),
+ relation: { clientId: owner, relationRole: 'owner', startedOn: null },
+ })
+ const relationId = created.relationId as string
+ expect((await listClientAnimals(asA, owner)).rows).toHaveLength(1)
+ expect(
+ await voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
+ ).toEqual({ revision: 2 })
+ expect(await fetchAnimalRelations(asA, created.id)).toEqual([])
+ const search = await searchAnimals(asA, {
+ workspaceId: wA,
+ query: 'annulation fictive',
+ speciesId: null,
+ archived: false,
+ })
+ expect(search.rows[0]).toMatchObject({
+ current_owners: [],
+ current_owner_count: 0,
+ })
+ expect((await listClientAnimals(asA, owner)).rows).toEqual([])
+ // Voided is frozen: no end, no date change, no second void.
+ expect(
+ await kindOf(
+ endAnimalClientRelation(asA, {
+ relationId,
+ expectedRevision: 2,
+ endedOn: null,
+ }),
+ ),
+ ).toBe('invalid_input')
+ expect(
+ await kindOf(
+ voidAnimalClientRelation(asA, { relationId, expectedRevision: 2 }),
+ ),
+ ).toBe('invalid_input')
+ })
+
+ it('an archived animal refuses its edits and relation writes, then restores', async () => {
+ const clientId = await clientOfA('Client Archive')
+ const created = await createAnimalRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: animal('Archive Fictive'),
+ relation: { clientId, relationRole: 'keeper', startedOn: null },
+ })
+ const relationId = created.relationId as string
+ expect(await setAnimalArchived(asA, created.id, true)).toEqual({
+ revision: 2,
+ })
+ const other = await clientOfA('Autre Client')
+ for (const write of [
+ () =>
+ updateAnimalRecord(asA, {
+ animalId: created.id,
+ expectedRevision: 2,
+ fields: animal('Renommé'),
+ }),
+ () =>
+ createAnimalClientRelation(asA, {
+ animalId: created.id,
+ clientId: other,
+ requestId: randomUUID(),
+ relationRole: 'owner',
+ startedOn: null,
+ }),
+ () =>
+ endAnimalClientRelation(asA, {
+ relationId,
+ expectedRevision: 1,
+ endedOn: null,
+ }),
+ () =>
+ updateAnimalClientRelation(asA, {
+ relationId,
+ expectedRevision: 1,
+ startedOn: '2020-01-01',
+ endedOn: null,
+ }),
+ () => voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }),
+ ])
+ expect(await kindOf(write())).toBe('archived')
+ expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1)
+ expect(await setAnimalArchived(asA, created.id, false)).toEqual({
+ revision: 3,
+ })
+ expect(
+ await updateAnimalRecord(asA, {
+ animalId: created.id,
+ expectedRevision: 3,
+ fields: animal('Restaurée Fictive', { sex: 'female' }),
+ }),
+ ).toEqual({ revision: 4 })
+ expect(
+ await kindOf(
+ updateAnimalRecord(asA, {
+ animalId: created.id,
+ expectedRevision: 3,
+ fields: animal('Périmée'),
+ }),
+ ),
+ ).toBe('conflict')
+ })
+})
diff --git a/packages/supabase/tests/sandbox/animals.sandbox.ts b/packages/supabase/tests/sandbox/animals.sandbox.ts
new file mode 100644
index 00000000..62fe78f6
--- /dev/null
+++ b/packages/supabase/tests/sandbox/animals.sandbox.ts
@@ -0,0 +1,860 @@
+/**
+ * V1-1.4 animals and relations (M3) on the real stack of `pnpm db:sandbox`:
+ * RPCs through PostgREST with real sessions per role, identical refusals, no
+ * lock taken outside the caller's workspace, then concurrent writes (replays,
+ * identical relations, end and void races, caps, the budget shared with the
+ * clients, relation creates against archives, a mixed burst across M2 and
+ * M3 without deadlock), the D9a guard through GoTrue admin, and timings.
+ * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.3, §7.1, §9, §10, §12.
+ */
+import { randomUUID } from 'node:crypto'
+import {
+ adminDeleteUser,
+ confirmedAccount,
+ errorCode,
+ rest,
+ rpc,
+ sql,
+ stack,
+ type Account,
+ type RestResult,
+} from './stack'
+
+const workspaceOf = (userId: string) =>
+ sql(`select id from public.workspaces where personal_user_id = '${userId}'`)
+const budgetOf = (ws: string) =>
+ sql(
+ `select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`,
+ )
+const idOf = (result: RestResult) => (result.body as { id: string }).id
+const messageOf = (result: RestResult) =>
+ result.status === 200 ? 'ok' : (result.body as { message: string }).message
+/** The error as the client sees it: status, code, message, details, hint. */
+const shape = (result: RestResult) => {
+ const body = result.body as Record
+ return [
+ result.status,
+ body.code,
+ body.message,
+ body.details ?? null,
+ body.hint ?? null,
+ ]
+}
+const NOT_FOUND = [403, '42501', 'not_found', null, null]
+
+function createClient(account: Account, ws: string, displayName: string) {
+ return rpc(
+ 'create_client',
+ {
+ workspace_id: ws,
+ create_request_id: randomUUID(),
+ kind: 'person',
+ display_name: displayName,
+ },
+ account.token,
+ )
+}
+function createAnimal(
+ account: Account,
+ ws: string,
+ fields: Record,
+ requestId = randomUUID(),
+) {
+ return rpc(
+ 'create_animal',
+ {
+ workspace_id: ws,
+ create_request_id: requestId,
+ species_id: 'equine',
+ sex: 'unknown',
+ ...fields,
+ },
+ account.token,
+ )
+}
+function link(
+ account: Account,
+ animalId: string,
+ clientId: string,
+ relationRole = 'owner',
+ requestId = randomUUID(),
+) {
+ return rpc(
+ 'create_animal_client_relation',
+ {
+ animal_id: animalId,
+ client_id: clientId,
+ create_request_id: requestId,
+ relation_role: relationRole,
+ },
+ account.token,
+ )
+}
+const animalUpdate = (animalId: string, revision: number, name: string) => ({
+ animal_id: animalId,
+ expected_revision: revision,
+ name,
+ species_id: 'equine',
+ sex: 'unknown',
+ species_detail: null,
+ breed: null,
+ birth_year: null,
+ birth_date: null,
+})
+
+describe('animals and relations through PostgREST, per role', () => {
+ let a: Account
+ let b: Account
+ let wA: string
+ let marie: string
+ let eclair: string
+ let relation: string
+
+ beforeAll(async () => {
+ a = await confirmedAccount('an-a')
+ b = await confirmedAccount('an-b')
+ wA = await workspaceOf(a.id)
+ marie = idOf(await createClient(a, wA, 'Marie Dupont'))
+ const created = await createAnimal(a, wA, {
+ name: 'Éclair',
+ sex: 'male',
+ breed: 'Selle Français',
+ birth_year: '2015',
+ birth_date: '2015-04-12',
+ client_id: marie,
+ relation_role: 'owner',
+ started_on: '2020-01-01',
+ })
+ expect(created.status).toBe(200)
+ eclair = idOf(created)
+ relation = (created.body as { relation_id: string }).relation_id
+ })
+
+ it('A creates, reads by id, searches, lists and changes a relation', async () => {
+ expect(
+ (
+ await rest(
+ `/animals?select=id,name,species_id,sex,birth_year,birth_date,revision&id=eq.${eclair}`,
+ a.token,
+ )
+ ).body,
+ ).toEqual([
+ {
+ id: eclair,
+ name: 'Éclair',
+ species_id: 'equine',
+ sex: 'male',
+ birth_year: 2015,
+ birth_date: '2015-04-12',
+ revision: 1,
+ },
+ ])
+ expect(
+ (
+ await rest(
+ `/animal_client_relations?select=client_id,relation_role,started_on,ended_at,voided_at&animal_id=eq.${eclair}`,
+ a.token,
+ )
+ ).body,
+ ).toEqual([
+ {
+ client_id: marie,
+ relation_role: 'owner',
+ started_on: '2020-01-01',
+ ended_at: null,
+ voided_at: null,
+ },
+ ])
+ const found = await rpc(
+ 'search_animals',
+ { workspace_id: wA, query: 'francais' },
+ a.token,
+ )
+ expect(found.body).toMatchObject([
+ {
+ id: eclair,
+ current_owner_count: 1,
+ current_owners: [
+ { client_id: marie, display_name: 'Marie Dupont', archived: false },
+ ],
+ },
+ ])
+ expect(
+ (
+ await rpc(
+ 'search_clients',
+ { workspace_id: wA, query: 'marie' },
+ a.token,
+ )
+ ).body,
+ ).toMatchObject([{ id: marie, current_animal_count: 1 }])
+ expect(
+ (await rpc('list_client_animals', { client_id: marie }, a.token)).body,
+ ).toMatchObject([
+ { relation_id: relation, animal_id: eclair, is_current: true },
+ ])
+ expect(
+ (await rpc('client_archive_preview', { client_id: marie }, a.token)).body,
+ ).toEqual({ count: 1, animals: [{ id: eclair, name: 'Éclair' }] })
+ expect(
+ (
+ await rpc(
+ 'end_animal_client_relation',
+ { relation_id: relation, expected_revision: 1, ended_on: null },
+ a.token,
+ )
+ ).body,
+ ).toEqual({ revision: 2 })
+ expect(
+ (
+ await rpc(
+ 'update_animal_client_relation',
+ {
+ relation_id: relation,
+ expected_revision: 2,
+ started_on: '2020-01-01',
+ ended_on: '2024-06-30',
+ },
+ a.token,
+ )
+ ).body,
+ ).toEqual({ revision: 3 })
+ expect(
+ (await rpc('list_client_animals', { client_id: marie }, a.token)).body,
+ ).toMatchObject([{ relation_id: relation, is_current: false }])
+ })
+
+ it('B gets nothing of A, and the same refusal as for an unknown id on every write', async () => {
+ expect(
+ (await rest(`/animals?select=id&id=eq.${eclair}`, b.token)).body,
+ ).toEqual([])
+ const head = await rest(
+ `/animal_client_relations?select=id&workspace_id=eq.${wA}`,
+ b.token,
+ { method: 'HEAD', headers: { Prefer: 'count=exact' } },
+ )
+ expect(head.headers.get('content-range')).toBe('*/0')
+ for (const [fn, args] of [
+ ['search_animals', { workspace_id: wA }],
+ ['list_client_animals', { client_id: marie }],
+ ] as const) {
+ expect((await rpc(fn, args, b.token)).body).toEqual([])
+ }
+ expect(
+ (await rpc('client_archive_preview', { client_id: marie }, b.token)).body,
+ ).toEqual({ count: 0, animals: [] })
+ const pairs: [string, Record, Record][] =
+ [
+ [
+ 'update_animal',
+ animalUpdate(eclair, 1, 'X'),
+ animalUpdate(randomUUID(), 1, 'X'),
+ ],
+ [
+ 'set_animal_archived',
+ { animal_id: eclair, archived: true },
+ { animal_id: randomUUID(), archived: true },
+ ],
+ [
+ 'end_animal_client_relation',
+ { relation_id: relation, expected_revision: 3, ended_on: null },
+ { relation_id: randomUUID(), expected_revision: 3, ended_on: null },
+ ],
+ [
+ 'update_animal_client_relation',
+ {
+ relation_id: relation,
+ expected_revision: 3,
+ started_on: null,
+ ended_on: null,
+ },
+ {
+ relation_id: randomUUID(),
+ expected_revision: 3,
+ started_on: null,
+ ended_on: null,
+ },
+ ],
+ [
+ 'void_animal_client_relation',
+ { relation_id: relation, expected_revision: 3 },
+ { relation_id: randomUUID(), expected_revision: 3 },
+ ],
+ [
+ 'create_animal_client_relation',
+ {
+ animal_id: eclair,
+ client_id: marie,
+ create_request_id: randomUUID(),
+ relation_role: 'keeper',
+ },
+ {
+ animal_id: randomUUID(),
+ client_id: marie,
+ create_request_id: randomUUID(),
+ relation_role: 'keeper',
+ },
+ ],
+ ]
+ for (const [fn, foreign, unknown] of pairs) {
+ const x = await rpc(fn, foreign, b.token)
+ const y = await rpc(fn, unknown, b.token)
+ expect([fn, ...shape(x)]).toEqual([fn, ...shape(y)])
+ expect([fn, ...shape(x)]).toEqual([fn, ...NOT_FOUND])
+ }
+ const wB = await workspaceOf(b.id)
+ const bAnimal = idOf(await createAnimal(b, wB, { name: 'Animal B' }))
+ expect(shape(await link(b, bAnimal, marie))).toEqual(NOT_FOUND)
+ expect(
+ shape(
+ await createAnimal(b, wB, {
+ name: 'X',
+ client_id: marie,
+ relation_role: 'owner',
+ }),
+ ),
+ ).toEqual(NOT_FOUND)
+ expect(shape(await createAnimal(b, wA, { name: 'X' }))).toEqual(NOT_FOUND)
+ })
+
+ it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => {
+ const attempts: [string, string, RequestInit, number][] = [
+ [
+ '/animals',
+ a.token,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ workspace_id: wA,
+ name: 'Direct',
+ species_id: 'equine',
+ sex: 'male',
+ }),
+ },
+ 403,
+ ],
+ [
+ `/animals?id=eq.${eclair}`,
+ a.token,
+ { method: 'PATCH', body: JSON.stringify({ workspace_id: wA }) },
+ 403,
+ ],
+ [`/animals?id=eq.${eclair}`, a.token, { method: 'DELETE' }, 403],
+ [
+ `/animal_client_relations?id=eq.${relation}`,
+ a.token,
+ { method: 'PATCH', body: JSON.stringify({ voided_at: null }) },
+ 403,
+ ],
+ [
+ `/animal_client_relations?id=eq.${relation}`,
+ a.token,
+ { method: 'DELETE' },
+ 403,
+ ],
+ ['/animals?select=id', stack.anonKey, {}, 401],
+ [
+ '/rpc/search_animals',
+ stack.anonKey,
+ { method: 'POST', body: JSON.stringify({ workspace_id: wA }) },
+ 401,
+ ],
+ ['/animal_client_relations?select=id', stack.serviceKey, {}, 403],
+ [
+ '/rpc/void_animal_client_relation',
+ stack.serviceKey,
+ {
+ method: 'POST',
+ body: JSON.stringify({ relation_id: relation, expected_revision: 3 }),
+ },
+ 403,
+ ],
+ [
+ '/rpc/lock_relation_for_write',
+ a.token,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ p_relation_id: relation,
+ p_expected_revision: 3,
+ }),
+ },
+ 404,
+ ],
+ ]
+ for (const [path, token, init, status] of attempts) {
+ const result = await rest(path, token, init)
+ expect([path, result.status]).toEqual([path, status])
+ if (status !== 404) expect(errorCode(result)).toBe('42501')
+ expect(result.text).not.toContain('Éclair')
+ }
+ const invalid = await createAnimal(a, wA, {
+ name: 'Secret-Name-Value',
+ birth_year: '2015',
+ birth_date: '2015-02-30',
+ })
+ expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null])
+ expect(invalid.text).not.toMatch(/Secret-Name|2015-02-30/)
+ })
+
+ it('cuts a deactivated or unconfirmed account', async () => {
+ await sql(`update public.profiles set active = false where id = '${a.id}'`)
+ expect((await rest('/animals?select=id', a.token)).body).toEqual([])
+ expect(
+ shape(
+ await rpc(
+ 'set_animal_archived',
+ { animal_id: eclair, archived: true },
+ a.token,
+ ),
+ ),
+ ).toEqual(NOT_FOUND)
+ await sql(`update public.profiles set active = true where id = '${a.id}'`)
+ await sql(
+ `update auth.users set email_confirmed_at = null where id = '${a.id}'`,
+ )
+ expect(
+ (await rest('/animal_client_relations?select=id', a.token)).body,
+ ).toEqual([])
+ await sql(
+ `update auth.users set email_confirmed_at = now() where id = '${a.id}'`,
+ )
+ expect((await rest('/animals?select=id', a.token)).body).toEqual([
+ { id: eclair },
+ ])
+ })
+
+ it('a caller outside the workspace never waits on its locks', async () => {
+ const bAnimal = idOf(
+ await createAnimal(b, await workspaceOf(b.id), { name: 'Lock probe' }),
+ )
+ const holder = sql(`begin;
+ select 1 from public.clients where id = '${marie}' for update;
+ select 1 from public.animals where id = '${eclair}' for update;
+ select 1 from public.animal_client_relations where id = '${relation}' for update;
+ select pg_sleep(2); commit;`)
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ const started = Date.now()
+ const results = await Promise.all([
+ rpc('update_animal', animalUpdate(eclair, 1, 'X'), b.token),
+ rpc(
+ 'void_animal_client_relation',
+ { relation_id: relation, expected_revision: 3 },
+ b.token,
+ ),
+ link(b, eclair, marie, 'contact'),
+ link(b, bAnimal, marie, 'contact'),
+ ])
+ const elapsed = Date.now() - started
+ await holder
+ expect(results.map(shape)).toEqual(Array(4).fill(NOT_FOUND))
+ expect(elapsed).toBeLessThan(1000)
+ console.log(
+ `[measure] A's client, animal and relation locked 2 s: B's four refusals answered in ${elapsed} ms`,
+ )
+ })
+
+ it('hides animal and relation audit rows from the platform owner (N9)', async () => {
+ expect(
+ Number(
+ await sql(
+ `select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}')`,
+ ),
+ ),
+ ).toBe(4)
+ const ownerId = await sql(
+ `select id from auth.users where email = 'owner@faunosteo.local'`,
+ )
+ const asOwner = await sql(`begin; set local role authenticated;
+ select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true);
+ select count(*) from audit.audit_logs where resource_id in ('${eclair}', '${relation}'); commit;`)
+ expect(asOwner.split('\n').pop()).toBe('0')
+ })
+
+ it('D9a: GoTrue admin cannot delete an account whose workspace holds an animal', async () => {
+ const g = await confirmedAccount('an-d9a')
+ const wG = await workspaceOf(g.id)
+ expect((await createAnimal(g, wG, { name: 'Seul' })).status).toBe(200)
+ expect(await adminDeleteUser(g.id)).not.toBe(200)
+ expect(
+ await sql(
+ `select (select count(*) from auth.users where id = '${g.id}') || '/' ||
+ (select count(*) from public.profiles where id = '${g.id}') || '/' ||
+ (select count(*) from public.animals where workspace_id = '${wG}')`,
+ ),
+ ).toBe('1/1/1')
+ })
+})
+
+describe('concurrent writes', () => {
+ let a: Account
+ let wA: string
+ let clients: string[]
+
+ beforeAll(async () => {
+ a = await confirmedAccount('an-race')
+ wA = await workspaceOf(a.id)
+ clients = []
+ for (let i = 0; i < 24; i++)
+ clients.push(idOf(await createClient(a, wA, `Race client ${i}`)))
+ })
+
+ it('one create_animal request sent 8 times at once: one animal, one relation, two writes counted', async () => {
+ const before = Number((await budgetOf(wA)).split('/')[0])
+ const requestId = randomUUID()
+ const results = await Promise.all(
+ Array.from({ length: 8 }, () =>
+ createAnimal(
+ a,
+ wA,
+ { name: 'Replayed', client_id: clients[0], relation_role: 'owner' },
+ requestId,
+ ),
+ ),
+ )
+ expect(results.map((r) => r.status)).toEqual(Array(8).fill(200))
+ expect(new Set(results.map((r) => JSON.stringify(r.body))).size).toBe(1)
+ expect(
+ await sql(
+ `select (select count(*) from public.animals where create_request_id = '${requestId}') || '/' ||
+ (select count(*) from public.animal_client_relations where create_request_id = '${requestId}')`,
+ ),
+ ).toBe('1/1')
+ expect(Number((await budgetOf(wA)).split('/')[0])).toBe(before + 2)
+ })
+
+ it('two contents racing on one request id: one created, the other refused', async () => {
+ const requestId = randomUUID()
+ const results = await Promise.all([
+ createAnimal(a, wA, { name: 'Racer X' }, requestId),
+ createAnimal(a, wA, { name: 'Racer Y' }, requestId),
+ ])
+ expect(results.map(messageOf).sort()).toEqual(['ok', 'request_conflict'])
+ })
+
+ it('10 identical relations at once (distinct request ids): one row, nine duplicate_relation', async () => {
+ const animal = idOf(await createAnimal(a, wA, { name: 'Dup target' }))
+ const results = await Promise.all(
+ Array.from({ length: 10 }, () => link(a, animal, clients[1], 'keeper')),
+ )
+ const messages = results.map(messageOf)
+ expect(messages.filter((m) => m === 'ok')).toHaveLength(1)
+ expect(messages.filter((m) => m === 'duplicate_relation')).toHaveLength(9)
+ expect(
+ await sql(
+ `select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
+ ),
+ ).toBe('1')
+ })
+
+ it('end and void racing on one revision: exactly one applies, the relation is ended or voided, never both', async () => {
+ for (let round = 0; round < 6; round++) {
+ const animal = idOf(
+ await createAnimal(a, wA, { name: `End-void ${round}` }),
+ )
+ const relation = idOf(await link(a, animal, clients[2]))
+ const results = await Promise.all([
+ rpc(
+ 'end_animal_client_relation',
+ { relation_id: relation, expected_revision: 1, ended_on: null },
+ a.token,
+ ),
+ rpc(
+ 'void_animal_client_relation',
+ { relation_id: relation, expected_revision: 1 },
+ a.token,
+ ),
+ rpc(
+ 'end_animal_client_relation',
+ { relation_id: relation, expected_revision: 1, ended_on: null },
+ a.token,
+ ),
+ ])
+ const messages = results.map(messageOf)
+ expect(messages.filter((m) => m === 'ok')).toHaveLength(1)
+ expect(messages.filter((m) => m === 'conflict')).toHaveLength(2)
+ const state = await sql(
+ `select (ended_at is not null) || '/' || (voided_at is not null) || '/' || revision
+ from public.animal_client_relations where id = '${relation}'`,
+ )
+ expect(['true/false/2', 'false/true/2']).toContain(state)
+ }
+ })
+
+ it('at 18 current relations, 6 concurrent links: exactly 2 pass', async () => {
+ const animal = idOf(await createAnimal(a, wA, { name: 'Crowded' }))
+ for (let i = 0; i < 18; i++)
+ expect((await link(a, animal, clients[i], 'contact')).status).toBe(200)
+ const results = await Promise.all(
+ clients.slice(18, 24).map((c) => link(a, animal, c, 'contact')),
+ )
+ const messages = results.map(messageOf)
+ expect(messages.filter((m) => m === 'ok')).toHaveLength(2)
+ expect(messages.filter((m) => m === 'limit_reached')).toHaveLength(4)
+ expect(
+ await sql(
+ `select count(*) from public.animal_client_relations where animal_id = '${animal}' and ended_at is null and voided_at is null`,
+ ),
+ ).toBe('20')
+ })
+
+ it('a relation create racing the archive of its client: created before, or refused archived after', async () => {
+ const outcomes = new Set()
+ for (let round = 0; round < 10; round++) {
+ const client = idOf(await createClient(a, wA, `Archive race ${round}`))
+ const animal = idOf(
+ await createAnimal(a, wA, { name: `Archive race ${round}` }),
+ )
+ const [linked, archived] = await Promise.all([
+ link(a, animal, client),
+ rpc(
+ 'set_client_archived',
+ { client_id: client, archived: true },
+ a.token,
+ ),
+ ])
+ expect(messageOf(archived)).toBe('ok')
+ expect(['ok', 'archived']).toContain(messageOf(linked))
+ outcomes.add(messageOf(linked))
+ const rows = await sql(
+ `select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
+ )
+ expect(rows).toBe(messageOf(linked) === 'ok' ? '1' : '0')
+ }
+ console.log(
+ `[measure] relation create vs client archive, 10 rounds: outcomes ${[...outcomes].join(', ')}`,
+ )
+ })
+
+ it('a relation create racing the archive of its animal: created before, or refused archived after', async () => {
+ for (let round = 0; round < 10; round++) {
+ const animal = idOf(
+ await createAnimal(a, wA, { name: `Animal archive race ${round}` }),
+ )
+ const [linked, archived] = await Promise.all([
+ link(a, animal, clients[3], 'keeper'),
+ rpc(
+ 'set_animal_archived',
+ { animal_id: animal, archived: true },
+ a.token,
+ ),
+ ])
+ expect(messageOf(archived)).toBe('ok')
+ expect(['ok', 'archived']).toContain(messageOf(linked))
+ expect(
+ await sql(
+ `select count(*) from public.animal_client_relations where animal_id = '${animal}'`,
+ ),
+ ).toBe(messageOf(linked) === 'ok' ? '1' : '0')
+ }
+ })
+
+ it('the budget is one counter for clients, animals and relations: at 990, 30 mixed writes, exactly 10 pass', async () => {
+ const animals: string[] = []
+ for (let i = 0; i < 10; i++)
+ animals.push(idOf(await createAnimal(a, wA, { name: `Budget ${i}` })))
+ await sql(
+ `update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`,
+ )
+ const results = await Promise.all(
+ Array.from({ length: 30 }, (_, i) =>
+ i % 3 === 0
+ ? createClient(a, wA, `Budget client ${i}`)
+ : i % 3 === 1
+ ? createAnimal(a, wA, { name: `Budget new ${i}` })
+ : link(a, animals[i % 10], clients[i % 24], 'contact'),
+ ),
+ )
+ const messages = results.map(messageOf)
+ expect(messages.filter((m) => m === 'ok')).toHaveLength(10)
+ expect(messages.filter((m) => m === 'rate_limited')).toHaveLength(20)
+ expect((await budgetOf(wA)).split('/')[0]).toBe('1000')
+ await sql(
+ `update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`,
+ )
+ })
+
+ it('caps of the workspace under concurrency: 20 000 animals and 100 000 relations', async () => {
+ const e = await confirmedAccount('an-caps')
+ const wE = await workspaceOf(e.id)
+ const client = idOf(await createClient(e, wE, 'Cap client'))
+ await sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+ select '${wE}', 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\\x00' from generate_series(1, 19998) g;
+ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest)
+ select '${wE}', a.id, '${client}', 'contact', now(), gen_random_uuid(), '\\x00'
+ from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${wE}') a
+ cross join generate_series(1, 10) g where a.n <= 9999 or (a.n = 10000 and g <= 8);
+ analyze public.animals; analyze public.animal_client_relations;`)
+ const animals = await Promise.all(
+ Array.from({ length: 5 }, () => createAnimal(e, wE, { name: 'Over' })),
+ )
+ expect(animals.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2)
+ expect(
+ animals.map(messageOf).filter((m) => m === 'limit_reached'),
+ ).toHaveLength(3)
+ const free = (
+ await sql(`select id from public.animals a where workspace_id = '${wE}'
+ and not exists (select 1 from public.animal_client_relations r where r.animal_id = a.id) limit 5`)
+ ).split('\n')
+ const started = Date.now()
+ const links = await Promise.all(free.map((id) => link(e, id, client)))
+ const elapsed = Date.now() - started
+ expect(links.map(messageOf).filter((m) => m === 'ok')).toHaveLength(2)
+ expect(
+ links.map(messageOf).filter((m) => m === 'limit_reached'),
+ ).toHaveLength(3)
+ expect(
+ await sql(
+ `select count(*) from public.animal_client_relations where workspace_id = '${wE}'`,
+ ),
+ ).toBe('100000')
+ console.log(
+ `[measure] 5 concurrent links next to 99 998 relations: ${elapsed} ms for the five (cap counted under the workspace lock)`,
+ )
+ })
+
+ it('a mixed burst across clients, animals and relations raises no deadlock', async () => {
+ const animals: string[] = []
+ const relations: string[] = []
+ for (let i = 0; i < 6; i++) {
+ const animal = idOf(await createAnimal(a, wA, { name: `Burst ${i}` }))
+ animals.push(animal)
+ relations.push(idOf(await link(a, animal, clients[i], 'owner')))
+ }
+ const started = Date.now()
+ const results = await Promise.all(
+ Array.from({ length: 96 }, (_, i) => {
+ const animal = animals[i % 6]
+ const client = clients[(i * 7) % 24]
+ switch (i % 8) {
+ case 0:
+ return link(a, animal, client, 'keeper')
+ case 1:
+ return rpc(
+ 'update_animal',
+ animalUpdate(animal, 1, `B${i}`),
+ a.token,
+ )
+ case 2:
+ return rpc(
+ 'set_animal_archived',
+ { animal_id: animal, archived: i % 16 === 2 },
+ a.token,
+ )
+ case 3:
+ return rpc(
+ 'update_client',
+ {
+ client_id: client,
+ expected_revision: 1,
+ kind: 'person',
+ display_name: `Race client edit ${i}`,
+ email: null,
+ phone: null,
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: null,
+ country: null,
+ },
+ a.token,
+ )
+ case 4:
+ return rpc(
+ 'set_client_archived',
+ { client_id: client, archived: i % 16 === 4 },
+ a.token,
+ )
+ case 5:
+ return rpc(
+ 'end_animal_client_relation',
+ {
+ relation_id: relations[i % 6],
+ expected_revision: 1,
+ ended_on: null,
+ },
+ a.token,
+ )
+ case 6:
+ return createAnimal(a, wA, {
+ name: `Burst new ${i}`,
+ client_id: client,
+ relation_role: 'contact',
+ })
+ default:
+ return rpc(
+ 'void_animal_client_relation',
+ { relation_id: relations[i % 6], expected_revision: 1 },
+ a.token,
+ )
+ }
+ }),
+ )
+ const codes = results.map((r) =>
+ r.status === 200 ? 'ok' : `${errorCode(r)}:${messageOf(r)}`,
+ )
+ expect(
+ codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')),
+ ).toEqual([])
+ const allowed = [
+ 'ok',
+ 'P0001:conflict',
+ 'P0001:archived',
+ 'P0001:duplicate_relation',
+ 'P0001:already_ended',
+ 'P0001:invalid_input',
+ ]
+ expect(codes.filter((c) => !allowed.includes(c))).toEqual([])
+ console.log(
+ `[measure] 96 mixed writes over M2 and M3 in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`,
+ )
+ })
+})
+
+describe('search on 20 000 animals', () => {
+ it('records the time of search_animals with owners (measurement, not a gate)', async () => {
+ const v = await confirmedAccount('an-volume')
+ const ws = await workspaceOf(v.id)
+ await sql(`insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+ select '${ws}', 'person', 'Owner ' || g, gen_random_uuid(), '\\x00' from generate_series(1, 1000) g;
+ insert into public.animals (workspace_id, name, species_id, sex, breed, create_request_id, create_request_digest)
+ select '${ws}', 'Animal ' || g, case when g % 3 = 0 then 'canine' else 'equine' end, 'female',
+ 'Race ' || (g % 40), gen_random_uuid(), '\\x00' from generate_series(1, 20000) g;
+ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
+ select '${ws}', a.id, c.id, 'owner', gen_random_uuid(), '\\x00'
+ from (select id, row_number() over (order by id) as n from public.animals where workspace_id = '${ws}') a
+ join (select id, row_number() over (order by id) as n from public.clients where workspace_id = '${ws}') c
+ on c.n = 1 + a.n % 1000;
+ analyze public.animals; analyze public.animal_client_relations; analyze public.clients;`)
+ const owner = await sql(
+ `select id from public.clients where workspace_id = '${ws}' limit 1`,
+ )
+ const calls: [string, Record][] = [
+ ['search_animals', { workspace_id: ws, query: 'animal 1999' }],
+ ['search_animals', { workspace_id: ws, query: 'race 7' }],
+ [
+ 'search_animals',
+ { workspace_id: ws, query: '', species_filter: 'canine' },
+ ],
+ ['search_animals', { workspace_id: ws, query: 'zzz-none' }],
+ ['search_animals', { workspace_id: ws, query: '', page_size: 100 }],
+ ['search_clients', { workspace_id: ws, query: 'owner', page_size: 100 }],
+ ['list_client_animals', { client_id: owner }],
+ ['client_archive_preview', { client_id: owner }],
+ ]
+ const times: number[] = []
+ for (let round = 0; round < 3; round++) {
+ for (const [fn, args] of calls) {
+ const started = performance.now()
+ const result = await rpc(fn, args, v.token)
+ times.push(performance.now() - started)
+ expect([fn, result.status]).toEqual([fn, 200])
+ }
+ }
+ times.sort((x, y) => x - y)
+ const p95 = times[Math.ceil(times.length * 0.95) - 1]
+ console.log(
+ `[measure] reads over 20 000 animals, 20 000 relations, 1 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`,
+ )
+ })
+})
diff --git a/packages/supabase/tests/sandbox/clients-access.sandbox.ts b/packages/supabase/tests/sandbox/clients-access.sandbox.ts
new file mode 100644
index 00000000..38cbbaea
--- /dev/null
+++ b/packages/supabase/tests/sandbox/clients-access.sandbox.ts
@@ -0,0 +1,338 @@
+/**
+ * The V1-1.5 access layer (src/workspaces.ts, src/clients.ts) against the
+ * real GoTrue and PostgREST of `pnpm db:sandbox`, through supabase-js as the
+ * browser uses it: the generated argument names, the explicit columns, the
+ * keyset pages and every closed failure kind come from the real server, not
+ * from a stub. One base URL is mapped onto the sandbox services, as Kong does.
+ */
+import { randomUUID } from 'node:crypto'
+import { createClient } from '@supabase/supabase-js'
+import {
+ RecordFailure,
+ createClientRecord,
+ fetchClientArchivePreview,
+ fetchClientRecord,
+ fetchPersonalWorkspaceId,
+ listClientAnimals,
+ searchClients,
+ setClientArchived,
+ updateClientRecord,
+ type ClientFields,
+ type Database,
+ type FaunosteoClient,
+} from '../../src'
+import { PASSWORD, confirmedAccount, sql, stack, type Account } from './stack'
+
+const BASE = 'http://sandbox.faunosteo.invalid'
+
+/** The browser client of the app, its requests replayed on the sandbox ports. */
+function browserClient(fetchImpl: typeof fetch = fetch): FaunosteoClient {
+ const mapped: typeof fetch = (input, init) => {
+ const url = String(input instanceof Request ? input.url : input)
+ .replace(`${BASE}/auth/v1`, stack.authUrl)
+ .replace(`${BASE}/rest/v1`, stack.restUrl)
+ return fetchImpl(url, init)
+ }
+ return createClient(BASE, stack.anonKey, {
+ auth: { persistSession: false, autoRefreshToken: false },
+ global: { fetch: mapped },
+ })
+}
+
+async function signedIn(account: Account): Promise {
+ const client = browserClient()
+ const { error } = await client.auth.signInWithPassword({
+ email: account.email,
+ password: PASSWORD,
+ })
+ if (error) throw error
+ return client
+}
+
+async function kindOf(promise: Promise) {
+ try {
+ await promise
+ return 'no failure'
+ } catch (error) {
+ return error instanceof RecordFailure ? error.kind : String(error)
+ }
+}
+
+const person = (
+ displayName: string,
+ patch: Partial = {},
+): ClientFields => ({
+ kind: 'person',
+ display_name: displayName,
+ email: null,
+ phone: null,
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city: null,
+ country: null,
+ ...patch,
+})
+
+describe('workspaces and clients access layer on the sandbox', () => {
+ let a: Account
+ let b: Account
+ let asA: FaunosteoClient
+ let asB: FaunosteoClient
+ let wA: string
+
+ beforeAll(async () => {
+ a = await confirmedAccount('acc-a')
+ b = await confirmedAccount('acc-b')
+ asA = await signedIn(a)
+ asB = await signedIn(b)
+ wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string
+ })
+
+ it('finds the personal workspace of the caller only', async () => {
+ expect(wA).toBe(
+ await sql(
+ `select id from public.workspaces where personal_user_id = '${a.id}'`,
+ ),
+ )
+ expect(await fetchPersonalWorkspaceId(asB, a.id)).toBeNull()
+ })
+
+ it('creates idempotently, refuses a divergent replay, reads the explicit columns', async () => {
+ const requestId = randomUUID()
+ const fields = person('Marie Dupont', {
+ email: 'marie@exemple.test',
+ phone: '+33612345678',
+ city: 'Lyon',
+ country: 'FR',
+ })
+ const first = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId,
+ fields,
+ })
+ const replay = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId,
+ fields,
+ })
+ expect(replay).toEqual(first)
+ expect(
+ await kindOf(
+ createClientRecord(asA, {
+ workspaceId: wA,
+ requestId,
+ fields: person('Marie Durand'),
+ }),
+ ),
+ ).toBe('request_conflict')
+ const record = await fetchClientRecord(asA, first.id)
+ expect(Object.keys(record ?? {}).sort()).toEqual(
+ [
+ 'address_line1',
+ 'address_line2',
+ 'archived_at',
+ 'city',
+ 'country',
+ 'created_at',
+ 'display_name',
+ 'email',
+ 'id',
+ 'kind',
+ 'phone',
+ 'postal_code',
+ 'revision',
+ 'updated_at',
+ ].sort(),
+ )
+ expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null })
+ })
+
+ it('updates at the revision, clears a field with null, refuses a stale revision', async () => {
+ const { id } = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: person('Paul Martin', { city: 'Annecy' }),
+ })
+ expect(
+ await updateClientRecord(asA, {
+ clientId: id,
+ expectedRevision: 1,
+ fields: person('Paul Martin', { city: null, phone: '+41791234567' }),
+ }),
+ ).toEqual({ revision: 2 })
+ expect(await fetchClientRecord(asA, id)).toMatchObject({
+ city: null,
+ phone: '+41791234567',
+ revision: 2,
+ })
+ expect(
+ await kindOf(
+ updateClientRecord(asA, {
+ clientId: id,
+ expectedRevision: 1,
+ fields: person('X'),
+ }),
+ ),
+ ).toBe('conflict')
+ expect(
+ await kindOf(
+ updateClientRecord(asA, {
+ clientId: id,
+ expectedRevision: 2,
+ fields: person(''),
+ }),
+ ),
+ ).toBe('invalid_input')
+ })
+
+ it('archives, refuses edits while archived, restores', async () => {
+ const { id } = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: person('Zoé Bernard'),
+ })
+ expect(await setClientArchived(asA, id, true)).toEqual({ revision: 2 })
+ expect(
+ await kindOf(
+ updateClientRecord(asA, {
+ clientId: id,
+ expectedRevision: 2,
+ fields: person('Zoé'),
+ }),
+ ),
+ ).toBe('archived')
+ const archived = await searchClients(asA, {
+ workspaceId: wA,
+ query: 'zoe',
+ archived: true,
+ })
+ expect(archived.rows.map((r) => r.id)).toEqual([id])
+ expect(await setClientArchived(asA, id, false)).toEqual({ revision: 3 })
+ })
+
+ it('pages 25 by 25 in name order without gap or repeat', async () => {
+ const c = await confirmedAccount('acc-page')
+ const asC = await signedIn(c)
+ const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string
+ for (let i = 1; i <= 30; i++) {
+ await createClientRecord(asC, {
+ workspaceId: wC,
+ requestId: randomUUID(),
+ fields: person(`Client ${String(i).padStart(2, '0')}`),
+ })
+ }
+ const one = await searchClients(asC, {
+ workspaceId: wC,
+ query: '',
+ archived: false,
+ })
+ expect(one.rows).toHaveLength(25)
+ expect(one.next).not.toBeNull()
+ const two = await searchClients(asC, {
+ workspaceId: wC,
+ query: '',
+ archived: false,
+ after: one.next,
+ })
+ expect(two.rows.map((r) => r.display_name)).toEqual([
+ 'Client 26',
+ 'Client 27',
+ 'Client 28',
+ 'Client 29',
+ 'Client 30',
+ ])
+ expect(two.next).toBeNull()
+ const ids = new Set([...one.rows, ...two.rows].map((r) => r.id))
+ expect(ids.size).toBe(30)
+ })
+
+ it('lists the client animals and the archive preview from the real RPCs', async () => {
+ const { id } = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: person('Écurie du Lac', { kind: 'organization' }),
+ })
+ const created = await asA.rpc('create_animal', {
+ workspace_id: wA,
+ create_request_id: randomUUID(),
+ name: 'Éclair',
+ species_id: 'equine',
+ sex: 'male',
+ client_id: id,
+ relation_role: 'owner',
+ })
+ expect(created.error).toBeNull()
+ const page = await listClientAnimals(asA, id)
+ expect(page.rows).toMatchObject([
+ { animal_name: 'Éclair', relation_role: 'owner', is_current: true },
+ ])
+ expect(page.next).toBeNull()
+ expect(await fetchClientArchivePreview(asA, id)).toMatchObject({
+ count: 1,
+ animals: [{ name: 'Éclair' }],
+ })
+ const listed = await searchClients(asA, {
+ workspaceId: wA,
+ query: 'ecurie',
+ archived: false,
+ })
+ expect(listed.rows).toMatchObject([{ id, current_animal_count: 1 }])
+ })
+
+ it('gives B nothing of A, with the same not_found as an unknown id', async () => {
+ const { id } = await createClientRecord(asA, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: person('Secret Client'),
+ })
+ expect(await fetchClientRecord(asB, id)).toBeNull()
+ expect(
+ (
+ await searchClients(asB, {
+ workspaceId: wA,
+ query: '',
+ archived: false,
+ })
+ ).rows,
+ ).toEqual([])
+ expect((await listClientAnimals(asB, id)).rows).toEqual([])
+ expect(await fetchClientArchivePreview(asB, id)).toEqual({
+ count: 0,
+ animals: [],
+ })
+ expect(await kindOf(setClientArchived(asB, id, true))).toBe('not_found')
+ expect(await kindOf(setClientArchived(asB, randomUUID(), true))).toBe(
+ 'not_found',
+ )
+ expect(
+ await kindOf(
+ createClientRecord(asB, {
+ workspaceId: wA,
+ requestId: randomUUID(),
+ fields: person('X'),
+ }),
+ ),
+ ).toBe('not_found')
+ })
+
+ it('reads no session as session_expired and an unreachable server as network', async () => {
+ expect(
+ await kindOf(
+ searchClients(browserClient(), {
+ workspaceId: wA,
+ query: '',
+ archived: false,
+ }),
+ ),
+ ).toBe('session_expired')
+ const offline = browserClient(async () => {
+ throw new TypeError('fetch failed')
+ })
+ expect(
+ await kindOf(
+ searchClients(offline, { workspaceId: wA, query: '', archived: false }),
+ ),
+ ).toBe('network')
+ })
+})
diff --git a/packages/supabase/tests/sandbox/clients.sandbox.ts b/packages/supabase/tests/sandbox/clients.sandbox.ts
new file mode 100644
index 00000000..c1a35d18
--- /dev/null
+++ b/packages/supabase/tests/sandbox/clients.sandbox.ts
@@ -0,0 +1,538 @@
+/**
+ * V1-1.2 clients (M2) on the real stack of `pnpm db:sandbox`: RPCs through
+ * PostgREST with real sessions per role, identical refusals, search without
+ * leaks, then concurrent writes (creates, replays, revisions, archive races,
+ * budget at its limit, lock contention) and the search time on 20 000 clients.
+ * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §9, §10, §12.
+ */
+import { randomUUID } from 'node:crypto'
+import {
+ confirmedAccount,
+ errorCode,
+ rest,
+ rpc,
+ sql,
+ stack,
+ type Account,
+ type RestResult,
+} from './stack'
+
+const workspaceOf = (userId: string) =>
+ sql(`select id from public.workspaces where personal_user_id = '${userId}'`)
+const budgetOf = (ws: string) =>
+ sql(
+ `select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`,
+ )
+
+function create(
+ account: Account,
+ ws: string,
+ fields: Record,
+ requestId = randomUUID(),
+) {
+ return rpc(
+ 'create_client',
+ {
+ workspace_id: ws,
+ create_request_id: requestId,
+ kind: 'person',
+ ...fields,
+ },
+ account.token,
+ )
+}
+const idOf = (result: RestResult) => (result.body as { id: string }).id
+const fullUpdate = (
+ clientId: string,
+ revision: number,
+ displayName: string,
+ city: string | null = null,
+) => ({
+ client_id: clientId,
+ expected_revision: revision,
+ kind: 'person',
+ display_name: displayName,
+ email: null,
+ phone: null,
+ address_line1: null,
+ address_line2: null,
+ postal_code: null,
+ city,
+ country: null,
+})
+/** The error as the client sees it: status, code, message, details, hint. */
+const shape = (result: RestResult) => {
+ const body = result.body as Record
+ return [
+ result.status,
+ body.code,
+ body.message,
+ body.details ?? null,
+ body.hint ?? null,
+ ]
+}
+
+describe('clients through PostgREST, per role', () => {
+ let a: Account
+ let b: Account
+ let wA: string
+ let wB: string
+ let lac: string
+
+ beforeAll(async () => {
+ a = await confirmedAccount('cl-a')
+ b = await confirmedAccount('cl-b')
+ wA = await workspaceOf(a.id)
+ wB = await workspaceOf(b.id)
+ const created = await create(a, wA, {
+ kind: 'organization',
+ display_name: 'Écurie du Lac',
+ email: 'Contact@Ecurie-Lac.test',
+ phone: '+33612345678',
+ city: 'Lyon',
+ })
+ expect(created.status).toBe(200)
+ lac = idOf(created)
+ })
+
+ it('A creates, reads, searches with POST, updates and archives', async () => {
+ const row = await rest(
+ `/clients?select=id,kind,display_name,email,revision&id=eq.${lac}`,
+ a.token,
+ )
+ expect(row.body).toEqual([
+ {
+ id: lac,
+ kind: 'organization',
+ display_name: 'Écurie du Lac',
+ email: 'contact@ecurie-lac.test',
+ revision: 1,
+ },
+ ])
+ const found = await rpc(
+ 'search_clients',
+ { workspace_id: wA, query: 'ecu' },
+ a.token,
+ )
+ expect((found.body as { id: string }[]).map((r) => r.id)).toEqual([lac])
+ const phone = await rpc(
+ 'search_clients',
+ { workspace_id: wA, query: '06 12' },
+ a.token,
+ )
+ expect((phone.body as { id: string }[]).map((r) => r.id)).toEqual([lac])
+ expect(
+ (
+ await rpc(
+ 'update_client',
+ fullUpdate(lac, 1, 'Écurie du Lac', 'Annecy'),
+ a.token,
+ )
+ ).body,
+ ).toEqual({ revision: 2 })
+ expect(
+ (
+ await rpc(
+ 'set_client_archived',
+ { client_id: lac, archived: true },
+ a.token,
+ )
+ ).body,
+ ).toEqual({ revision: 3 })
+ expect(
+ (
+ await rpc(
+ 'set_client_archived',
+ { client_id: lac, archived: false },
+ a.token,
+ )
+ ).body,
+ ).toEqual({ revision: 4 })
+ })
+
+ it('B gets nothing of A: reads, counts, search, and the same refusal as for an unknown id', async () => {
+ expect(
+ (await rest(`/clients?select=id&id=eq.${lac}`, b.token)).body,
+ ).toEqual([])
+ const head = await rest(
+ `/clients?select=id&workspace_id=eq.${wA}`,
+ b.token,
+ { method: 'HEAD', headers: { Prefer: 'count=exact' } },
+ )
+ expect(head.headers.get('content-range')).toBe('*/0')
+ expect(
+ (await rpc('search_clients', { workspace_id: wA, query: '' }, b.token))
+ .body,
+ ).toEqual([])
+ const foreign = await rpc('update_client', fullUpdate(lac, 4, 'X'), b.token)
+ const unknown = await rpc(
+ 'update_client',
+ fullUpdate(randomUUID(), 4, 'X'),
+ b.token,
+ )
+ expect(shape(foreign)).toEqual(shape(unknown))
+ expect(shape(foreign)).toEqual([403, '42501', 'not_found', null, null])
+ expect(shape(await create(b, wA, { display_name: 'X' }))).toEqual(
+ shape(await create(b, randomUUID(), { display_name: 'X' })),
+ )
+ expect(
+ shape(
+ await rpc(
+ 'set_client_archived',
+ { client_id: lac, archived: true },
+ b.token,
+ ),
+ ),
+ ).toEqual([403, '42501', 'not_found', null, null])
+ })
+
+ it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => {
+ const attempts: [string, string, RequestInit, number][] = [
+ [
+ '/clients',
+ b.token,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ workspace_id: wB,
+ kind: 'person',
+ display_name: 'Direct',
+ }),
+ },
+ 403,
+ ],
+ [
+ `/clients?id=eq.${lac}`,
+ a.token,
+ { method: 'PATCH', body: JSON.stringify({ display_name: 'Direct' }) },
+ 403,
+ ],
+ [`/clients?id=eq.${lac}`, a.token, { method: 'DELETE' }, 403],
+ ['/clients?select=id', stack.anonKey, {}, 401],
+ [
+ '/rpc/search_clients',
+ stack.anonKey,
+ { method: 'POST', body: JSON.stringify({ workspace_id: wA }) },
+ 401,
+ ],
+ ['/clients?select=id', stack.serviceKey, {}, 403],
+ [
+ '/rpc/create_client',
+ stack.serviceKey,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ workspace_id: wA,
+ create_request_id: randomUUID(),
+ kind: 'person',
+ display_name: 'S',
+ }),
+ },
+ 403,
+ ],
+ ]
+ for (const [path, token, init, status] of attempts) {
+ const result = await rest(path, token, init)
+ expect([path, result.status, errorCode(result)]).toEqual([
+ path,
+ status,
+ '42501',
+ ])
+ expect(result.text).not.toContain('Lac')
+ }
+ const invalid = await create(a, wA, {
+ display_name: 'Name',
+ email: 'secret-value-not-an-email',
+ })
+ expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null])
+ expect(invalid.text).not.toContain('secret-value')
+ })
+
+ it('cuts an unconfirmed or deactivated account', async () => {
+ await sql(`update public.profiles set active = false where id = '${a.id}'`)
+ expect((await rest('/clients?select=id', a.token)).body).toEqual([])
+ expect(
+ shape(await rpc('update_client', fullUpdate(lac, 4, 'X'), a.token)),
+ ).toEqual([403, '42501', 'not_found', null, null])
+ await sql(`update public.profiles set active = true where id = '${a.id}'`)
+ await sql(
+ `update auth.users set email_confirmed_at = null where id = '${a.id}'`,
+ )
+ expect((await rest('/clients?select=id', a.token)).body).toEqual([])
+ await sql(
+ `update auth.users set email_confirmed_at = now() where id = '${a.id}'`,
+ )
+ expect((await rest('/clients?select=id', a.token)).body).toEqual([
+ { id: lac },
+ ])
+ })
+
+ it('hides client audit rows from the platform owner (N9)', async () => {
+ expect(
+ await sql(
+ `select count(*) from audit.audit_logs where resource_id = '${lac}'`,
+ ),
+ ).toBe('4')
+ // audit is not exposed through PostgREST; the owner's view is its RLS-filtered SQL view.
+ const ownerId = await sql(
+ `select id from auth.users where email = 'owner@faunosteo.local'`,
+ )
+ const asOwner = await sql(`begin; set local role authenticated;
+ select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true);
+ select count(*) from audit.audit_logs where resource_id = '${lac}'; commit;`)
+ expect(asOwner.split('\n').pop()).toBe('0')
+ })
+})
+
+describe('concurrent writes', () => {
+ let a: Account
+ let wA: string
+
+ beforeAll(async () => {
+ a = await confirmedAccount('cl-race')
+ wA = await workspaceOf(a.id)
+ })
+
+ it('20 parallel creates in one workspace all land, counted once each', async () => {
+ const results = await Promise.all(
+ Array.from({ length: 20 }, (_, i) =>
+ create(a, wA, { display_name: `Parallel ${i}` }),
+ ),
+ )
+ expect(results.map((r) => r.status)).toEqual(Array(20).fill(200))
+ expect(
+ await sql(
+ `select count(*) from public.clients where workspace_id = '${wA}'`,
+ ),
+ ).toBe('20')
+ expect(await budgetOf(wA)).toBe('20/20')
+ })
+
+ it('the same request id sent 8 times at once creates one client and answers it 8 times', async () => {
+ const requestId = randomUUID()
+ const results = await Promise.all(
+ Array.from({ length: 8 }, () =>
+ create(a, wA, { display_name: 'Replayed' }, requestId),
+ ),
+ )
+ expect(new Set(results.map(idOf)).size).toBe(1)
+ expect(
+ await sql(
+ `select count(*) from public.clients where create_request_id = '${requestId}'`,
+ ),
+ ).toBe('1')
+ expect(await budgetOf(wA)).toBe('21/21')
+ })
+
+ it('two different contents racing on one request id: one created, the other refused', async () => {
+ const requestId = randomUUID()
+ const [x, y] = await Promise.all([
+ create(a, wA, { display_name: 'Racer X' }, requestId),
+ create(a, wA, { display_name: 'Racer Y' }, requestId),
+ ])
+ expect([x.status, y.status].sort()).toEqual([200, 400])
+ expect(
+ [x, y]
+ .map((r) =>
+ r.status === 400 ? (r.body as { message: string }).message : 'ok',
+ )
+ .sort(),
+ ).toEqual(['ok', 'request_conflict'])
+ expect(
+ await sql(
+ `select count(*) from public.clients where create_request_id = '${requestId}'`,
+ ),
+ ).toBe('1')
+ })
+
+ it('two updates from the same revision: one wins, the other gets conflict, nothing lost', async () => {
+ const id = idOf(await create(a, wA, { display_name: 'Revision base' }))
+ const [x, y] = await Promise.all([
+ rpc('update_client', fullUpdate(id, 1, 'Edited in tab X'), a.token),
+ rpc('update_client', fullUpdate(id, 1, 'Edited in tab Y'), a.token),
+ ])
+ const winner = x.status === 200 ? 'Edited in tab X' : 'Edited in tab Y'
+ expect([x.status, y.status].sort()).toEqual([200, 400])
+ expect([x, y].find((r) => r.status === 400)?.body).toMatchObject({
+ message: 'conflict',
+ })
+ expect(
+ await sql(
+ `select display_name || '/' || revision from public.clients where id = '${id}'`,
+ ),
+ ).toBe(`${winner}/2`)
+ })
+
+ it('archive, restore and edits racing on one client end consistent, without deadlock', async () => {
+ const id = idOf(await create(a, wA, { display_name: 'Archive race' }))
+ const calls = Array.from({ length: 30 }, (_, i) =>
+ i % 3 === 0
+ ? rpc('set_client_archived', { client_id: id, archived: true }, a.token)
+ : i % 3 === 1
+ ? rpc(
+ 'set_client_archived',
+ { client_id: id, archived: false },
+ a.token,
+ )
+ : rpc('update_client', fullUpdate(id, 1, `Edit ${i}`), a.token),
+ )
+ const results = await Promise.all(calls)
+ const messages = results.map((r) =>
+ r.status === 200 ? 'ok' : (r.body as { message: string }).message,
+ )
+ expect(
+ messages.every((m) => ['ok', 'archived', 'conflict'].includes(m)),
+ ).toBe(true)
+ const [revision, archived] = (
+ await sql(
+ `select revision || '|' || (archived_at is not null) from public.clients where id = '${id}'`,
+ )
+ ).split('|')
+ const audited = await sql(
+ `select count(*) from audit.audit_logs where resource_id = '${id}'`,
+ )
+ expect(Number(audited)).toBe(Number(revision))
+ expect(['true', 'false']).toContain(archived)
+ })
+
+ it('at the hourly limit, 20 racing writes: exactly the remaining 10 pass, refused ones consume nothing', async () => {
+ await sql(
+ `update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`,
+ )
+ const results = await Promise.all(
+ Array.from({ length: 20 }, (_, i) =>
+ create(a, wA, { display_name: `Limit ${i}` }),
+ ),
+ )
+ const statuses = results.map((r) =>
+ r.status === 200 ? 'ok' : (r.body as { message: string }).message,
+ )
+ expect(statuses.filter((s) => s === 'ok')).toHaveLength(10)
+ expect(statuses.filter((s) => s === 'rate_limited')).toHaveLength(10)
+ expect((await budgetOf(wA)).split('/')[0]).toBe('1000')
+ await sql(
+ `update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`,
+ )
+ })
+
+ it('locks stay per workspace: a held budget row delays its workspace only', async () => {
+ const accounts = await Promise.all(
+ Array.from({ length: 10 }, (_, i) => confirmedAccount(`cl-iso-${i}`)),
+ )
+ const spaces = await Promise.all(accounts.map((x) => workspaceOf(x.id)))
+ expect(
+ (await create(accounts[0], spaces[0], { display_name: 'Seed' })).status,
+ ).toBe(200)
+ const holder =
+ sql(`begin; select 1 from private.workspace_write_budgets where workspace_id = '${spaces[0]}' for update;
+ select pg_sleep(2); commit;`)
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ const started = Date.now()
+ const blocked = create(accounts[0], spaces[0], {
+ display_name: 'Waits',
+ }).then((r) => ({ r, ms: Date.now() - started }))
+ const others = await Promise.all(
+ accounts
+ .slice(1)
+ .map((x, i) =>
+ create(x, spaces[i + 1], { display_name: 'Independent' }),
+ ),
+ )
+ const othersMs = Date.now() - started
+ const waited = await blocked
+ await holder
+ expect(others.map((r) => r.status)).toEqual(Array(9).fill(200))
+ expect(othersMs).toBeLessThan(1000)
+ expect(waited.r.status).toBe(200)
+ expect(waited.ms).toBeGreaterThan(1200)
+ console.log(
+ `[measure] budget row of one workspace held 2 s: 9 creates elsewhere ${othersMs} ms; the create in the held workspace waited ${waited.ms} ms`,
+ )
+ })
+
+ it('a mixed burst of 60 writes in one workspace raises no deadlock', async () => {
+ const ids = await Promise.all(
+ Array.from({ length: 5 }, (_, i) =>
+ create(a, wA, { display_name: `Burst base ${i}` }).then(idOf),
+ ),
+ )
+ const started = Date.now()
+ const results = await Promise.all(
+ Array.from({ length: 60 }, (_, i) => {
+ const id = ids[i % 5]
+ if (i % 4 === 0)
+ return create(a, wA, { display_name: `Burst new ${i}` })
+ if (i % 4 === 1)
+ return rpc(
+ 'set_client_archived',
+ { client_id: id, archived: i % 8 === 1 },
+ a.token,
+ )
+ return rpc(
+ 'update_client',
+ fullUpdate(id, 1, `Burst edit ${i}`),
+ a.token,
+ )
+ }),
+ )
+ const codes = results.map((r) =>
+ r.status === 200
+ ? 'ok'
+ : `${errorCode(r)}:${(r.body as { message: string }).message}`,
+ )
+ expect(
+ codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')),
+ ).toEqual([])
+ expect(
+ codes.every(
+ (c) => c === 'ok' || ['P0001:conflict', 'P0001:archived'].includes(c),
+ ),
+ ).toBe(true)
+ console.log(
+ `[measure] 60 mixed writes in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`,
+ )
+ })
+})
+
+describe('search on 20 000 clients', () => {
+ it('records the time of name and phone searches (measurement, not a gate)', async () => {
+ const a = await confirmedAccount('cl-volume')
+ const ws = await workspaceOf(a.id)
+ await sql(`insert into public.clients (workspace_id, kind, display_name, city, email, phone, create_request_id, create_request_digest)
+ select '${ws}', 'person', 'Client ' || g || ' Dupont', 'Ville ' || (g % 500), 'client' || g || '@example.test',
+ '+336' || lpad(g::text, 8, '0'), gen_random_uuid(), '\\x00'
+ from generate_series(1, 20000) g; analyze public.clients;`)
+ const terms = [
+ 'dupont',
+ 'client 1999',
+ 'ville 42',
+ 'example',
+ '06 00 01',
+ 'zzz-none',
+ '',
+ ]
+ const times: number[] = []
+ for (let round = 0; round < 3; round++) {
+ for (const query of terms) {
+ const started = performance.now()
+ const result = await rpc(
+ 'search_clients',
+ { workspace_id: ws, query },
+ a.token,
+ )
+ times.push(performance.now() - started)
+ expect(result.status).toBe(200)
+ }
+ }
+ times.sort((x, y) => x - y)
+ const p95 = times[Math.ceil(times.length * 0.95) - 1]
+ console.log(
+ `[measure] search_clients over 20 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`,
+ )
+ expect(
+ await sql(
+ `select count(*) from public.clients where workspace_id = '${ws}'`,
+ ),
+ ).toBe('20000')
+ })
+})
diff --git a/packages/supabase/tests/sandbox/stack.ts b/packages/supabase/tests/sandbox/stack.ts
new file mode 100644
index 00000000..f687aa9a
--- /dev/null
+++ b/packages/supabase/tests/sandbox/stack.ts
@@ -0,0 +1,243 @@
+/**
+ * Access to the throwaway stack of `pnpm db:sandbox` (scripts/db-sandbox.sh):
+ * real GoTrue, PostgREST and PostgreSQL sessions, never the DEV stack. The
+ * script passes the endpoints and the generated keys through the environment;
+ * the database password reaches `docker exec` through the environment too,
+ * never through a command argument.
+ */
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+
+const need = (name: string): string => {
+ const value = process.env[name]
+ if (!value)
+ throw new Error(`${name} missing: run through pnpm db:sandbox test`)
+ return value
+}
+
+export const stack = {
+ container: need('SANDBOX_DB_CONTAINER'),
+ authUrl: need('SANDBOX_AUTH_URL'),
+ restUrl: need('SANDBOX_REST_URL'),
+ mailUrl: need('SANDBOX_MAIL_URL'),
+ anonKey: need('SANDBOX_ANON_KEY'),
+ serviceKey: need('SANDBOX_SERVICE_KEY'),
+}
+const PG_PASSWORD = need('SANDBOX_PG_PASSWORD')
+export const PASSWORD = 'Sandbox-only-pw-1'
+
+/** One psql session as postgres; resolves with stdout (tuples only) or rejects with stderr. */
+export function sql(script: string): Promise {
+ return new Promise((resolve, reject) => {
+ const child = execFile(
+ 'docker',
+ [
+ 'exec',
+ '-i',
+ '-e',
+ 'PGPASSWORD',
+ stack.container,
+ 'psql',
+ '-X',
+ '-q',
+ '-t',
+ '-A',
+ '-h',
+ '127.0.0.1',
+ '-U',
+ 'postgres',
+ '-d',
+ 'postgres',
+ '-v',
+ 'ON_ERROR_STOP=1',
+ ],
+ {
+ env: { ...process.env, PGPASSWORD: PG_PASSWORD },
+ maxBuffer: 64 * 1024 * 1024,
+ },
+ (error, stdout, stderr) =>
+ error
+ ? reject(new Error(stderr || error.message))
+ : resolve(stdout.trim()),
+ )
+ child.stdin?.end(script)
+ })
+}
+
+/** Same session, but settles with the outcome instead of throwing (for refusal checks). */
+export async function sqlOutcome(
+ script: string,
+): Promise<{ ok: boolean; out: string }> {
+ try {
+ return { ok: true, out: await sql(script) }
+ } catch (error) {
+ return { ok: false, out: (error as Error).message }
+ }
+}
+
+export const uniqueEmail = (tag: string) =>
+ `${tag}-${randomUUID().slice(0, 8)}@sandbox.local`
+
+async function authCall(
+ path: string,
+ body: unknown,
+ key = stack.anonKey,
+): Promise {
+ return fetch(stack.authUrl + path, {
+ method: 'POST',
+ headers: {
+ apikey: stack.anonKey,
+ Authorization: `Bearer ${key}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(body),
+ })
+}
+
+export async function signIn(
+ email: string,
+ password = PASSWORD,
+): Promise<{ status: number; body: Record }> {
+ const res = await authCall('/token?grant_type=password', { email, password })
+ return {
+ status: res.status,
+ body: (await res.json()) as Record,
+ }
+}
+
+export interface Account {
+ id: string
+ email: string
+ token: string
+}
+
+/** A confirmed account created by the admin API, signed in. */
+export async function confirmedAccount(tag: string): Promise {
+ const email = uniqueEmail(tag)
+ const res = await authCall(
+ '/admin/users',
+ { email, password: PASSWORD, email_confirm: true },
+ stack.serviceKey,
+ )
+ const user = (await res.json()) as { id: string }
+ const session = await signIn(email)
+ return { id: user.id, email, token: session.body.access_token as string }
+}
+
+/** Public sign-up (no session until confirmation). */
+export async function signUp(
+ email: string,
+): Promise<{ status: number; body: Record }> {
+ const res = await authCall('/signup', { email, password: PASSWORD })
+ return {
+ status: res.status,
+ body: (await res.json()) as Record,
+ }
+}
+
+/** Opens the confirmation link GoTrue mailed to this address; returns the HTTP status. */
+export async function confirmByMail(email: string): Promise {
+ const search = (await (
+ await fetch(
+ `${stack.mailUrl}/api/v1/search?query=${encodeURIComponent('to:' + email)}`,
+ )
+ ).json()) as {
+ messages: { ID: string }[]
+ }
+ const message = (await (
+ await fetch(`${stack.mailUrl}/api/v1/message/${search.messages[0].ID}`)
+ ).json()) as { Text: string }
+ const link = message.Text.match(
+ new RegExp(
+ `${stack.authUrl.replace(/[.:/]/g, '\\$&')}/verify\\?[^\\s)\\]]+`,
+ ),
+ )?.[0]
+ if (!link) throw new Error('no confirmation link in the mail')
+ return (await fetch(link.replace(/&/g, '&'), { redirect: 'manual' }))
+ .status
+}
+
+/** GoTrue admin link for any account: the residual path of contract §6.3. */
+export async function adminMagicLinkSession(
+ email: string,
+): Promise {
+ const res = await authCall(
+ '/admin/generate_link',
+ { type: 'magiclink', email },
+ stack.serviceKey,
+ )
+ const body = (await res.json()) as {
+ action_link?: string
+ properties?: { action_link?: string }
+ }
+ const link = body.action_link ?? body.properties?.action_link
+ if (!link) return null
+ const verify = await fetch(link, { redirect: 'manual' })
+ return new URLSearchParams(
+ (verify.headers.get('location') ?? '').split('#')[1] ?? '',
+ ).get('access_token')
+}
+
+export async function adminDeleteUser(id: string): Promise {
+ const res = await fetch(`${stack.authUrl}/admin/users/${id}`, {
+ method: 'DELETE',
+ headers: {
+ apikey: stack.anonKey,
+ Authorization: `Bearer ${stack.serviceKey}`,
+ },
+ })
+ return res.status
+}
+
+export interface RestResult {
+ status: number
+ body: unknown
+ text: string
+ headers: Headers
+}
+
+/** A PostgREST request with the given bearer token (a user's, or the anon / service key). */
+export async function rest(
+ path: string,
+ token: string,
+ init: RequestInit = {},
+): Promise {
+ const res = await fetch(stack.restUrl + path, {
+ ...init,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ ...(init.headers ?? {}),
+ },
+ })
+ const text = await res.text()
+ let body: unknown = text
+ try {
+ body = JSON.parse(text)
+ } catch {
+ // not JSON: keep the text
+ }
+ return { status: res.status, body, text, headers: res.headers }
+}
+
+/** POST /rpc/: the way the app calls every RPC (terms stay out of URLs). */
+export function rpc(
+ fn: string,
+ args: Record,
+ token: string,
+ headers: Record = {},
+) {
+ return rest(`/rpc/${fn}`, token, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ headers,
+ })
+}
+
+/** The PostgREST error code of a refusal, or null. */
+export const errorCode = (result: RestResult): string | null =>
+ typeof result.body === 'object' &&
+ result.body !== null &&
+ 'code' in result.body
+ ? String((result.body as { code: unknown }).code)
+ : null
diff --git a/packages/supabase/tests/sandbox/workspaces.sandbox.ts b/packages/supabase/tests/sandbox/workspaces.sandbox.ts
new file mode 100644
index 00000000..6b1ce5df
--- /dev/null
+++ b/packages/supabase/tests/sandbox/workspaces.sandbox.ts
@@ -0,0 +1,317 @@
+/**
+ * V1-1.1 workspaces (M1) on the real stack of `pnpm db:sandbox`: the sign-up
+ * chain, reads and refusals through PostgREST per role, the residual GoTrue
+ * admin path, the audit correlation cap, and concurrent sessions.
+ * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8.1, §9.
+ */
+import { randomUUID } from 'node:crypto'
+import {
+ adminDeleteUser,
+ adminMagicLinkSession,
+ confirmByMail,
+ confirmedAccount,
+ errorCode,
+ rest,
+ rpc,
+ signIn,
+ signUp,
+ sql,
+ sqlOutcome,
+ stack,
+ uniqueEmail,
+ type Account,
+} from './stack'
+
+const workspaceOf = (userId: string) =>
+ sql(`select id from public.workspaces where personal_user_id = '${userId}'`)
+const holderCount = (userId: string) =>
+ sql(`select count(*) from public.workspaces w join public.workspace_members m
+ on m.workspace_id = w.id and m.user_id = w.personal_user_id and m.member_role = 'holder'
+ where w.personal_user_id = '${userId}'`)
+
+describe('sign-up and confirmation', () => {
+ it('creates the workspace in the sign-up transaction, readable only after confirmation', async () => {
+ const email = uniqueEmail('ws-signup')
+ const signup = await signUp(email)
+ expect(signup.status).toBe(200)
+ expect(signup.body.access_token).toBeUndefined()
+ const id = signup.body.id as string
+ expect(await holderCount(id)).toBe('1')
+ const early = await signIn(email)
+ expect(early.body.error_code).toBe('email_not_confirmed')
+ expect(await confirmByMail(email)).toBe(303)
+ const session = await signIn(email)
+ const read = await rest(
+ '/workspaces?select=id,kind,personal_user_id',
+ session.body.access_token as string,
+ )
+ expect(read.body).toEqual([
+ { id: await workspaceOf(id), kind: 'personal', personal_user_id: id },
+ ])
+ })
+})
+
+describe('reads and refusals per role', () => {
+ let a: Account
+ let b: Account
+ let wA: string
+ let wB: string
+
+ beforeAll(async () => {
+ a = await confirmedAccount('ws-a')
+ b = await confirmedAccount('ws-b')
+ wA = await workspaceOf(a.id)
+ wB = await workspaceOf(b.id)
+ })
+
+ it('each account reads exactly its workspace and membership', async () => {
+ expect((await rest('/workspaces?select=id', a.token)).body).toEqual([
+ { id: wA },
+ ])
+ expect(
+ (await rest('/workspace_members?select=user_id,member_role', a.token))
+ .body,
+ ).toEqual([{ user_id: a.id, member_role: 'holder' }])
+ const head = await rest('/workspaces?select=id', b.token, {
+ method: 'HEAD',
+ headers: { Prefer: 'count=exact' },
+ })
+ expect(head.headers.get('content-range')).toBe('0-0/1')
+ })
+
+ it('naming another account or workspace returns nothing', async () => {
+ expect(
+ (await rest(`/workspaces?select=id&id=eq.${wA}`, b.token)).body,
+ ).toEqual([])
+ expect(
+ (await rest(`/workspaces?select=id&personal_user_id=eq.${a.id}`, b.token))
+ .body,
+ ).toEqual([])
+ expect(
+ (
+ await rest(
+ `/workspace_members?select=user_id&workspace_id=eq.${wA}`,
+ b.token,
+ )
+ ).body,
+ ).toEqual([])
+ })
+
+ it('refuses every write, for a user, the anon key and the service key', async () => {
+ const attempts: [string, string, RequestInit, number][] = [
+ [
+ '/workspaces',
+ b.token,
+ {
+ method: 'POST',
+ body: JSON.stringify({ kind: 'personal', personal_user_id: b.id }),
+ },
+ 403,
+ ],
+ [
+ '/workspace_members',
+ b.token,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ workspace_id: wA,
+ user_id: b.id,
+ member_role: 'holder',
+ }),
+ },
+ 403,
+ ],
+ [
+ `/workspaces?id=eq.${wB}`,
+ b.token,
+ { method: 'PATCH', body: JSON.stringify({ personal_user_id: a.id }) },
+ 403,
+ ],
+ [
+ `/workspace_members?user_id=eq.${b.id}`,
+ b.token,
+ { method: 'DELETE' },
+ 403,
+ ],
+ ['/workspaces?select=id', stack.anonKey, {}, 401],
+ ['/workspace_members?select=user_id', stack.anonKey, {}, 401],
+ ['/workspaces?select=id', stack.serviceKey, {}, 403],
+ [
+ '/workspace_members',
+ stack.serviceKey,
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ workspace_id: wA,
+ user_id: b.id,
+ member_role: 'holder',
+ }),
+ },
+ 403,
+ ],
+ ]
+ for (const [path, token, init, status] of attempts) {
+ const result = await rest(path, token, init)
+ expect([path, result.status, errorCode(result)]).toEqual([
+ path,
+ status,
+ '42501',
+ ])
+ expect(result.text).not.toContain(wA)
+ expect(result.text).not.toContain(a.id)
+ }
+ })
+
+ it('keeps the private helpers out of the API', async () => {
+ expect((await rpc('caller_workspace_ids', {}, b.token)).status).toBe(404)
+ expect(
+ (await rpc('ensure_personal_workspace', { p_user_id: b.id }, b.token))
+ .status,
+ ).toBe(404)
+ const profile = await rest('/rpc/backfill_personal_workspaces', b.token, {
+ method: 'POST',
+ body: '{}',
+ headers: { 'Content-Profile': 'private' },
+ })
+ expect([profile.status, errorCode(profile)]).toEqual([406, 'PGRST106'])
+ })
+
+ it('cuts a deactivated account at its next request, same token', async () => {
+ await sql(`update public.profiles set active = false where id = '${b.id}'`)
+ expect((await rest('/workspaces?select=id', b.token)).body).toEqual([])
+ await sql(`update public.profiles set active = true where id = '${b.id}'`)
+ expect((await rest('/workspaces?select=id', b.token)).body).toEqual([
+ { id: wB },
+ ])
+ })
+
+ it('RESIDUAL (contract §6.3): the service key mints a session for any account through GoTrue admin', async () => {
+ const token = await adminMagicLinkSession(a.email)
+ expect(token).toBeTruthy()
+ expect((await rest('/workspaces?select=id', token ?? '')).body).toEqual([
+ { id: wA },
+ ])
+ })
+
+ it('stores an oversized correlation header as null and keeps a short token', async () => {
+ const owner = await signIn(
+ 'owner@faunosteo.local',
+ 'LocalDev-only-password-1',
+ )
+ const token = owner.body.access_token as string
+ const grant = await rpc(
+ 'grant_platform_role',
+ { target_user_id: b.id, role: 'support' },
+ token,
+ {
+ 'x-correlation-id': 'x'.repeat(6000),
+ },
+ )
+ const revoke = await rpc(
+ 'revoke_platform_role',
+ { target_user_id: b.id, role: 'support', reason: 'sandbox' },
+ token,
+ {
+ 'x-correlation-id': 'req-sandbox-01',
+ },
+ )
+ expect([grant.status, revoke.status]).toEqual([200, 200])
+ expect(
+ await sql(`select string_agg(coalesce(correlation_id, 'NULL'), '|' order by occurred_at, action)
+ from audit.audit_logs where target_user_id = '${b.id}'`),
+ ).toBe('NULL|req-sandbox-01')
+ })
+
+ it('deletes an empty account through GoTrue admin with its workspace', async () => {
+ const e = await confirmedAccount('ws-e')
+ expect(await adminDeleteUser(e.id)).toBe(200)
+ expect(
+ await sql(
+ `select count(*) from public.workspace_members where user_id = '${e.id}'`,
+ ),
+ ).toBe('0')
+ expect(await workspaceOf(e.id)).toBe('')
+ })
+})
+
+describe('concurrent sessions', () => {
+ const ids = Array.from({ length: 20 }, () => randomUUID())
+
+ beforeAll(async () => {
+ const values = ids
+ .map(
+ (id, i) =>
+ `('${id}', 'race-${i}-${id.slice(0, 8)}@sandbox.local', now())`,
+ )
+ .join(',')
+ await sql(`begin;
+ alter table public.profiles disable trigger profiles_create_personal_workspace;
+ insert into auth.users (id, email, email_confirmed_at) values ${values};
+ alter table public.profiles enable trigger profiles_create_personal_workspace;
+ commit;`)
+ })
+
+ it('two sessions creating one workspace: the second waits for the commit, then writes nothing', async () => {
+ const first = sql(
+ `begin; select private.ensure_personal_workspace('${ids[0]}'); select pg_sleep(1.5); commit;`,
+ )
+ await new Promise((resolve) => setTimeout(resolve, 400))
+ const started = Date.now()
+ const second = await sql(
+ `select private.ensure_personal_workspace('${ids[0]}')`,
+ )
+ expect(Date.now() - started).toBeGreaterThan(700)
+ expect(await first).toContain('t')
+ expect(second).toBe('f')
+ expect(await holderCount(ids[0])).toBe('1')
+ })
+
+ it('refuses at COMMIT a workspace without its holder or with a foreign member', async () => {
+ const alone = await sqlOutcome(
+ `begin; insert into public.workspaces (kind, personal_user_id) values ('personal', '${ids[1]}'); commit;`,
+ )
+ expect(alone.ok).toBe(false)
+ expect(alone.out).toContain(
+ 'personal workspace must have exactly its account as holder',
+ )
+ expect(await workspaceOf(ids[1])).toBe('')
+ const foreign =
+ await sqlOutcome(`begin; insert into public.workspace_members (workspace_id, user_id, member_role)
+ select id, '${ids[1]}', 'holder' from public.workspaces where personal_user_id = '${ids[0]}'; commit;`)
+ expect(foreign.ok).toBe(false)
+ })
+
+ it('a rolled-back creation leaves nothing; the retry creates once', async () => {
+ await sql(
+ `begin; select private.ensure_personal_workspace('${ids[1]}'); rollback;`,
+ )
+ expect(await workspaceOf(ids[1])).toBe('')
+ expect(
+ await sql(`select private.ensure_personal_workspace('${ids[1]}')`),
+ ).toBe('t')
+ expect(
+ await sql(`select private.ensure_personal_workspace('${ids[1]}')`),
+ ).toBe('f')
+ })
+
+ it('two racing backfills create each missing workspace once', async () => {
+ const [x, y] = await Promise.all([
+ sql('select private.backfill_personal_workspaces()'),
+ sql('select private.backfill_personal_workspaces()'),
+ ])
+ expect(Number(x) + Number(y)).toBe(18)
+ const counts = await Promise.all(ids.map(holderCount))
+ expect(counts.every((c) => c === '1')).toBe(true)
+ })
+
+ it('parallel GoTrue sign-ups each get one workspace', async () => {
+ const results = await Promise.all(
+ Array.from({ length: 8 }, () => signUp(uniqueEmail('ws-par'))),
+ )
+ expect(results.map((r) => r.status)).toEqual(Array(8).fill(200))
+ const counts = await Promise.all(
+ results.map((r) => holderCount(r.body.id as string)),
+ )
+ expect(counts).toEqual(Array(8).fill('1'))
+ })
+})
diff --git a/packages/supabase/vitest.sandbox.config.ts b/packages/supabase/vitest.sandbox.config.ts
new file mode 100644
index 00000000..dab31ea5
--- /dev/null
+++ b/packages/supabase/vitest.sandbox.config.ts
@@ -0,0 +1,18 @@
+import { defineConfig } from 'vitest/config'
+
+/**
+ * Real-stack suite on the throwaway stack of `pnpm db:sandbox` (tests/sandbox):
+ * HTTP through GoTrue and PostgREST, concurrent SQL sessions. Run only through
+ * `pnpm db:sandbox test`, which provides the endpoints and the generated keys;
+ * kept out of the default `test:run` include on purpose.
+ */
+export default defineConfig({
+ test: {
+ environment: 'node',
+ globals: true,
+ include: ['tests/sandbox/**/*.sandbox.ts'],
+ fileParallelism: false,
+ testTimeout: 120_000,
+ hookTimeout: 120_000,
+ },
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b8b9c5f5..319c7c81 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -45,6 +45,12 @@ importers:
specifier: ^5.0.2
version: 5.0.13(@types/react@19.2.14)(react@19.2.6)
devDependencies:
+ '@axe-core/playwright':
+ specifier: 4.14.0
+ version: 4.14.0(playwright-core@1.64.1)
+ '@playwright/test':
+ specifier: 1.64.1
+ version: 1.64.1
'@tailwindcss/vite':
specifier: ^4.3.0
version: 4.3.0(vite@7.3.6(@types/node@20.19.41)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15))
@@ -161,6 +167,12 @@ packages:
'@adobe/css-tools@4.4.4':
resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==}
+ '@axe-core/playwright@4.14.0':
+ resolution: {integrity: sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==}
+ engines: {node: '>=22.12.0'}
+ peerDependencies:
+ playwright-core: '>= 1.0.0'
+
'@babel/code-frame@7.29.0':
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
engines: {node: '>=6.9.0'}
@@ -424,6 +436,11 @@ packages:
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
engines: {node: ^14.21.3 || >=16}
+ '@playwright/test@1.64.1':
+ resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==}
+ engines: {node: '>=20'}
+ hasBin: true
+
'@rolldown/pluginutils@1.0.0-beta.27':
resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}
@@ -1033,6 +1050,10 @@ packages:
resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}
engines: {node: '>= 0.4'}
+ axe-core@4.14.0:
+ resolution: {integrity: sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==}
+ engines: {node: '>=4'}
+
balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
@@ -1252,6 +1273,7 @@ packages:
eslint@9.39.4:
resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
+ deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options.
hasBin: true
peerDependencies:
jiti: '*'
@@ -1807,6 +1829,16 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
+ playwright-core@1.64.1:
+ resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==}
+ engines: {node: '>=20'}
+ hasBin: true
+
+ playwright@1.64.1:
+ resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==}
+ engines: {node: '>=20'}
+ hasBin: true
+
pnpm@10.13.1:
resolution: {integrity: sha512-N+vxpcejDV+r4MXfRO6NpMllygxa89urKMOhaBtwolYhjQXIHJwNz3Z+9rhVHrW5YAQrntQwDFkkIzY3fgHPrQ==}
engines: {node: '>=18.12'}
@@ -2253,6 +2285,11 @@ snapshots:
'@adobe/css-tools@4.4.4': {}
+ '@axe-core/playwright@4.14.0(playwright-core@1.64.1)':
+ dependencies:
+ axe-core: 4.14.0
+ playwright-core: 1.64.1
+
'@babel/code-frame@7.29.0':
dependencies:
'@babel/helper-validator-identifier': 7.28.5
@@ -2436,6 +2473,10 @@ snapshots:
'@noble/hashes@1.8.0': {}
+ '@playwright/test@1.64.1':
+ dependencies:
+ playwright: 1.64.1
+
'@rolldown/pluginutils@1.0.0-beta.27': {}
'@rollup/rollup-android-arm-eabi@4.60.4':
@@ -2999,6 +3040,8 @@ snapshots:
dependencies:
possible-typed-array-names: 1.1.0
+ axe-core@4.14.0: {}
+
balanced-match@1.0.2: {}
balanced-match@4.0.4: {}
@@ -3868,6 +3911,12 @@ snapshots:
picomatch@4.0.4: {}
+ playwright-core@1.64.1: {}
+
+ playwright@1.64.1:
+ dependencies:
+ playwright-core: 1.64.1
+
pnpm@10.13.1: {}
possible-typed-array-names@1.1.0: {}
diff --git a/scripts/check-all.sh b/scripts/check-all.sh
index 02f70846..edba7074 100755
--- a/scripts/check-all.sh
+++ b/scripts/check-all.sh
@@ -4,14 +4,21 @@
# runner calls these same stages (docs/development/RUST.md §4). Stops at the first failure.
# Needs the native Rust toolchain (RUST.md §1) and Docker for the image stages. The local
# Supabase stack is not required: the SQL suite runs on PGlite inside `pnpm test:run`, and
-# `pnpm db:test` is the real-stack complement after a change under supabase/.
+# `pnpm db:test` is the real-stack complement after a change under supabase/. The browser
+# suite runs when the Chromium of the pinned Playwright is installed, else it is reported
+# SKIPPED with the reason (docs/development/BROWSER_TESTS.md); `pnpm e2e:shell` needs the
+# isolated stack and stays a separate run, reported NOT RUN. The last lines state each
+# browser suite: PASSED, SKIPPED (environment missing) or NOT RUN; a failure is FAILED.
set -euo pipefail
cd "$(dirname "$0")/.."
stage() {
+ current_stage="$1"
printf '\n== %s (%s)\n' "$1" "$(date +%H:%M:%S)"
}
+# A failing stage stops the run and is named as FAILED, never turned into a warning.
+trap 'echo "== FAILED: $current_stage" >&2' ERR
stage "rust: fmt, clippy, tests, ts-rs export, cargo-deny (native toolchain)"
bash scripts/rust-check.sh
@@ -31,6 +38,16 @@ stage "wasm: browser module (the core-wasm proofs run on it in the Node pipeline
bash scripts/wasm-build.sh
stage "node: typecheck, tests, lint, build"
pnpm check
+stage "browser: Chromium UI suite (pnpm e2e:ui), desktop and 375 px, axe"
+chromium="$(cd apps/app && node -e "console.log(require('@playwright/test').chromium.executablePath())")"
+if [ -x "$chromium" ]; then
+ pnpm e2e:ui
+ browser_ui="PASSED"
+else
+ browser_ui="SKIPPED: no Chromium for the pinned Playwright at $chromium"
+ echo "== $browser_ui"
+ echo " install it without sudo: pnpm --filter @faunosteo/app exec playwright install chromium"
+fi
stage "docker: application image"
docker build -t faunosteo:check .
stage "docker: worker sandbox tests and seccomp derivation on the musl binary that ships"
@@ -40,3 +57,5 @@ pnpm worker:image
docker run --rm --read-only --cap-drop ALL --security-opt no-new-privileges:true \
faunosteo_worker:dev run --check
stage "all checks passed"
+echo " browser e2e:ui $browser_ui"
+echo " browser e2e:shell NOT RUN by check:all: it needs the isolated stack (pnpm db:sandbox up fresh, then pnpm e2e:shell)"
diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh
new file mode 100755
index 00000000..fede3b49
--- /dev/null
+++ b/scripts/db-sandbox.sh
@@ -0,0 +1,253 @@
+#!/usr/bin/env bash
+# Throwaway Supabase stack for testing migrations without touching the DEV
+# stack (docs/development/SUPABASE.md §5.1). Same images as the CLI stack,
+# its own Docker network, ports published on 127.0.0.1 only and distinct from
+# DEV, no Docker volume (the images declare none and nothing is mounted), so
+# `down` removes only the containers and network named below.
+#
+# pnpm db:sandbox up fresh all migrations, then the seeds (= db reset)
+# pnpm db:sandbox up upgrade []
+# migrations before , seeds, two GoTrue
+# accounts, then `migration up` (= DEV path); with
+# , the migrations before first, then the rest
+# pnpm db:sandbox test-db the pgTAP files (`supabase test db`)
+# pnpm db:sandbox types [--check] generated types (write, or diff with the committed file)
+# pnpm db:sandbox test packages/supabase/tests/sandbox (HTTP, concurrency)
+# pnpm db:sandbox e2e-shell [args] = pnpm e2e:shell: the /app shell in Chromium (apps/app/e2e); args go to Playwright (a spec file, --grep)
+# pnpm db:sandbox sql psql as postgres on stdin
+# pnpm db:sandbox down
+#
+# Secrets are generated at `up` (random password, JWT secret, keys) into a
+# 600 file under $FAUNOSTEO_SANDBOX_DIR (default ~/.cache/faunosteo-db-sandbox),
+# outside the repository, and never printed. Every Supabase CLI call names the
+# sandbox with --db-url: none may fall back to the local DEV database.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+. scripts/dev-env.sh
+
+PG_IMAGE=public.ecr.aws/supabase/postgres:17.11.0.004
+AUTH_IMAGE=public.ecr.aws/supabase/gotrue:v2.197.0
+REST_IMAGE=public.ecr.aws/supabase/postgrest:v16.4
+STORAGE_IMAGE=public.ecr.aws/supabase/storage-api:v1.79.36
+MAIL_IMAGE=public.ecr.aws/supabase/mailpit:v1.31.3
+NET=faunosteo_dbsandbox_net
+DB=faunosteo_dbsandbox_db
+AUTH=faunosteo_dbsandbox_auth
+REST=faunosteo_dbsandbox_rest
+STORAGE=faunosteo_dbsandbox_storage
+MAIL=faunosteo_dbsandbox_mail
+PORT_DB=57432 PORT_AUTH=57999 PORT_REST=57300 PORT_STORAGE=57500 PORT_MAIL=57025
+STATE="${FAUNOSTEO_SANDBOX_DIR:-$HOME/.cache/faunosteo-db-sandbox}"
+SECRETS="$STATE/secrets.sh"
+CLI=node_modules/.bin/supabase
+
+die() { echo "db-sandbox: $*" >&2; exit 1; }
+case "$(realpath -m "$STATE")" in
+ "$PWD" | "$PWD"/*) die "FAUNOSTEO_SANDBOX_DIR must be outside the repository" ;;
+esac
+# Every value must be present: an empty password would turn --db-url into an
+# argument the CLI might read as absent and fall back to the DEV database.
+load_secrets() {
+ [ -f "$SECRETS" ] || die "not running (pnpm db:sandbox up fresh)"
+ . "$SECRETS"
+ [ -n "${SB_PW:-}" ] && [ -n "${SB_JWT_SECRET:-}" ] && [ -n "${SB_ANON_KEY:-}" ] && [ -n "${SB_SERVICE_KEY:-}" ] \
+ || die "secrets file incomplete (pnpm db:sandbox down, then up)"
+ export PGPASSWORD="$SB_PW"
+}
+# No password in the URL: the CLI reads PGPASSWORD, so no secret is on a command line.
+db_url() { printf 'postgresql://postgres@127.0.0.1:%s/postgres?sslmode=disable' "$PORT_DB"; }
+sb_psql() {
+ docker exec -i -e PGPASSWORD "$DB" \
+ psql -X -q -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 "$@"
+}
+wait_for() {
+ local what="$1"; shift
+ for _ in $(seq 1 120); do "$@" >/dev/null 2>&1 && return 0; sleep 1; done
+ die "timeout waiting for $what"
+}
+
+new_secrets() {
+ mkdir -p "$STATE"; chmod 700 "$STATE"
+ ( umask 077; node -e '
+ const c = require("crypto");
+ const secret = c.randomBytes(32).toString("hex");
+ const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url");
+ const jwt = (p) => { const h = b64({ alg: "HS256", typ: "JWT" }), b = b64(p);
+ return h + "." + b + "." + c.createHmac("sha256", secret).update(h + "." + b).digest("base64url"); };
+ const exp = Math.floor(Date.now() / 1000) + 30 * 86400;
+ console.log("SB_PW=" + c.randomBytes(24).toString("hex"));
+ console.log("SB_JWT_SECRET=" + secret);
+ console.log("SB_ANON_KEY=" + jwt({ role: "anon", iss: "db-sandbox", exp }));
+ console.log("SB_SERVICE_KEY=" + jwt({ role: "service_role", iss: "db-sandbox", exp }));
+ ' > "$SECRETS.new" && mv "$SECRETS.new" "$SECRETS" )
+ load_secrets
+ # The values reach the containers through 600 env files, never through argv.
+ ( umask 077
+ printf 'POSTGRES_PASSWORD=%s\nPGPASSWORD=%s\nJWT_SECRET=%s\n' "$SB_PW" "$SB_PW" "$SB_JWT_SECRET" > "$STATE/db.env"
+ printf 'GOTRUE_DB_DATABASE_URL=postgresql://supabase_auth_admin:%s@%s:5432/postgres\nGOTRUE_JWT_SECRET=%s\n' \
+ "$SB_PW" "$DB" "$SB_JWT_SECRET" > "$STATE/auth.env"
+ printf 'ANON_KEY=%s\nSERVICE_KEY=%s\nAUTH_JWT_SECRET=%s\nDATABASE_URL=postgresql://supabase_storage_admin:%s@%s:5432/postgres\n' \
+ "$SB_ANON_KEY" "$SB_SERVICE_KEY" "$SB_JWT_SECRET" "$SB_PW" "$DB" > "$STATE/storage.env"
+ printf 'PGRST_DB_URI=postgresql://authenticator:%s@%s:5432/postgres\nPGRST_JWT_SECRET=%s\n' \
+ "$SB_PW" "$DB" "$SB_JWT_SECRET" > "$STATE/rest.env"
+ printf 'Authorization: Bearer %s\n' "$SB_SERVICE_KEY" > "$STATE/service-header" )
+}
+
+# The role passwords the CLI sets at db start (its /etc/postgresql.schema.sql),
+# reduced to what the sandbox services use.
+DB_INIT='cat <<'"'"'EOF'"'"' > /etc/postgresql.schema.sql && exec docker-entrypoint.sh postgres -D /etc/postgresql
+\set pgpass `echo "$PGPASSWORD"`
+\set jwt_secret `echo "$JWT_SECRET"`
+ALTER DATABASE postgres SET "app.settings.jwt_secret" TO :'"'"'jwt_secret'"'"';
+ALTER DATABASE postgres SET "app.settings.jwt_exp" TO '"'"'3600'"'"';
+ALTER USER postgres WITH PASSWORD :'"'"'pgpass'"'"';
+ALTER USER authenticator WITH PASSWORD :'"'"'pgpass'"'"';
+ALTER USER supabase_auth_admin WITH PASSWORD :'"'"'pgpass'"'"';
+ALTER USER supabase_storage_admin WITH PASSWORD :'"'"'pgpass'"'"';
+EOF'
+
+start_services() {
+ docker network create "$NET" >/dev/null
+ docker run -d --name "$DB" --network "$NET" -p 127.0.0.1:$PORT_DB:5432 \
+ --env-file "$STATE/db.env" -e POSTGRES_HOST=/var/run/postgresql -e JWT_EXP=3600 \
+ -e POSTGRES_INITDB_ARGS="--allow-group-access --locale-provider=icu --encoding=UTF-8 --icu-locale=en_US.UTF-8" \
+ --entrypoint sh "$PG_IMAGE" -c "$DB_INIT" >/dev/null
+ wait_for "database roles" docker exec -e PGPASSWORD "$DB" \
+ psql -h 127.0.0.1 -U supabase_auth_admin -d postgres -c 'select 1'
+ wait_for "database" docker exec -e PGPASSWORD "$DB" \
+ psql -h 127.0.0.1 -U postgres -d postgres -c 'select 1'
+
+ docker run -d --name "$MAIL" --network "$NET" -p 127.0.0.1:$PORT_MAIL:8025 "$MAIL_IMAGE" >/dev/null
+ docker run -d --name "$AUTH" --network "$NET" -p 127.0.0.1:$PORT_AUTH:9999 \
+ -e GOTRUE_API_HOST=0.0.0.0 -e GOTRUE_API_PORT=9999 -e API_EXTERNAL_URL=http://127.0.0.1:$PORT_AUTH \
+ -e GOTRUE_DB_DRIVER=postgres --env-file "$STATE/auth.env" \
+ -e GOTRUE_DB_MIGRATIONS_PATH=/usr/local/etc/auth/migrations \
+ -e GOTRUE_SITE_URL=http://127.0.0.1:5173 -e GOTRUE_DISABLE_SIGNUP=false \
+ -e GOTRUE_JWT_EXP=3600 \
+ -e GOTRUE_JWT_AUD=authenticated -e GOTRUE_JWT_DEFAULT_GROUP_NAME=authenticated \
+ -e GOTRUE_JWT_ADMIN_ROLES=service_role \
+ -e GOTRUE_EXTERNAL_EMAIL_ENABLED=true -e GOTRUE_EXTERNAL_PHONE_ENABLED=false \
+ -e GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED=false -e GOTRUE_MAILER_AUTOCONFIRM=false \
+ -e GOTRUE_MAILER_URLPATHS_CONFIRMATION=http://127.0.0.1:$PORT_AUTH/verify \
+ -e GOTRUE_SMTP_HOST="$MAIL" -e GOTRUE_SMTP_PORT=1025 \
+ -e GOTRUE_SMTP_ADMIN_EMAIL=admin@sandbox.local -e GOTRUE_SMTP_SENDER_NAME=sandbox \
+ -e GOTRUE_SMTP_MAX_FREQUENCY=1s -e GOTRUE_RATE_LIMIT_EMAIL_SENT=10000 \
+ -e GOTRUE_RATE_LIMIT_VERIFY=10000 -e GOTRUE_RATE_LIMIT_TOKEN_REFRESH=10000 \
+ -e GOTRUE_PASSWORD_MIN_LENGTH=12 "$AUTH_IMAGE" >/dev/null
+ wait_for "auth" curl -fsS http://127.0.0.1:$PORT_AUTH/health
+ docker run -d --name "$STORAGE" --network "$NET" -p 127.0.0.1:$PORT_STORAGE:5000 \
+ --env-file "$STATE/storage.env" \
+ -e FILE_SIZE_LIMIT=52428800 -e STORAGE_BACKEND=file -e FILE_STORAGE_BACKEND_PATH=/mnt \
+ -e TENANT_ID=stub -e STORAGE_S3_REGION=local -e GLOBAL_S3_BUCKET=stub \
+ -e ENABLE_IMAGE_TRANSFORMATION=false -e IMAGE_TRANSFORMATION_ENABLED=false \
+ -e S3_PROTOCOL_ENABLED=false -e DB_MIGRATIONS_FREEZE_AT= "$STORAGE_IMAGE" >/dev/null
+ wait_for "storage" curl -fsS http://127.0.0.1:$PORT_STORAGE/status
+}
+
+start_rest() {
+ docker run -d --name "$REST" --network "$NET" -p 127.0.0.1:$PORT_REST:3000 \
+ --env-file "$STATE/rest.env" \
+ -e PGRST_DB_SCHEMAS=public -e PGRST_DB_EXTRA_SEARCH_PATH=public,extensions \
+ -e PGRST_DB_ANON_ROLE=anon -e PGRST_DB_MAX_ROWS=1000 \
+ "$REST_IMAGE" >/dev/null
+ wait_for "postgrest" curl -fsS -o /dev/null http://127.0.0.1:$PORT_REST/
+}
+
+# The CLI's own migration runner, always against the sandbox URL.
+migrate_up() { # workdir
+ "$CLI" --workdir "$1" migration up --db-url "$(db_url)"
+}
+
+seed() {
+ local paths
+ paths="$(sed -n 's/^sql_paths = \[\(.*\)\]/\1/p' supabase/config.toml | tr -d '" ' | tr ',' ' ')"
+ for f in $paths; do
+ echo " seed ${f#./}"; sb_psql --single-transaction < "supabase/${f#./}" >/dev/null
+ done
+}
+
+gotrue_accounts() {
+ curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/admin/users \
+ -H @"$STATE/service-header" -H 'Content-Type: application/json' \
+ -d '{"email":"pre-confirmed@sandbox.local","password":"Sandbox-only-pw-1","email_confirm":true}' >/dev/null
+ curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/signup -H 'Content-Type: application/json' \
+ -d '{"email":"pre-unconfirmed@sandbox.local","password":"Sandbox-only-pw-1"}' >/dev/null
+}
+
+# A CLI workdir holding only the migrations before ; kept in the
+# state folder and refilled at each run (the CLI writes .temp there).
+upgrade_workdir() { # version
+ local base="$STATE/upgrade-base"
+ mkdir -p "$base/supabase/migrations"
+ rm -f "$base"/supabase/migrations/*.sql
+ cp supabase/config.toml "$base/supabase/"
+ for f in supabase/migrations/*.sql; do
+ if [ "$(basename "$f" | cut -d_ -f1)" \< "$1" ]; then cp "$f" "$base/supabase/migrations/"; fi
+ done
+ printf '%s' "$base"
+}
+
+cmd_up() {
+ local mode="${1:-}"
+ # Arguments checked before anything starts: a refusal leaves no container or secret.
+ case "$mode" in
+ fresh) ;;
+ upgrade) [[ "${2:-}" =~ ^[0-9]{14}$ ]] \
+ || die "up upgrade needs the first new migration version, e.g. 20261025100000"
+ [ -z "${3:-}" ] || { [[ "$3" =~ ^[0-9]{14}$ ]] && [ "$2" \< "$3" ]; } \
+ || die "up upgrade : is a later migration version" ;;
+ *) die "up fresh | up upgrade []" ;;
+ esac
+ docker ps -a --format '{{.Names}}' | grep -q '^faunosteo_dbsandbox_' && die "already up (pnpm db:sandbox down)"
+ new_secrets
+ start_services
+ case "$mode" in
+ fresh)
+ migrate_up . ; seed ;;
+ upgrade)
+ migrate_up "$(upgrade_workdir "$2")"
+ seed; gotrue_accounts
+ echo "== before: $(sb_psql -t -A -c 'select count(*) from public.profiles') profiles"
+ if [ -n "${3:-}" ]; then
+ migrate_up "$(upgrade_workdir "$3")"
+ echo "== between: $(sb_psql -t -A -c 'select count(*) from public.workspaces') workspaces"
+ fi
+ migrate_up . ;;
+ esac
+ start_rest
+ echo "== sandbox up ($mode): db 127.0.0.1:$PORT_DB, auth :$PORT_AUTH, rest :$PORT_REST, mail :$PORT_MAIL"
+}
+
+cmd_down() {
+ docker rm -f "$REST" "$STORAGE" "$AUTH" "$MAIL" "$DB" >/dev/null 2>&1 || true
+ docker network rm "$NET" >/dev/null 2>&1 || true
+ rm -f "$SECRETS" "$STATE/db.env" "$STATE/auth.env" "$STATE/storage.env" "$STATE/rest.env" "$STATE/service-header"
+ echo "== sandbox removed"
+}
+
+# A test runner gets the endpoints and keys through its environment, never argv.
+with_sandbox_env() (
+ export SANDBOX_DB_CONTAINER="$DB" SANDBOX_PG_PASSWORD="$SB_PW"
+ export SANDBOX_AUTH_URL="http://127.0.0.1:$PORT_AUTH" SANDBOX_REST_URL="http://127.0.0.1:$PORT_REST"
+ export SANDBOX_STORAGE_URL="http://127.0.0.1:$PORT_STORAGE" SANDBOX_MAIL_URL="http://127.0.0.1:$PORT_MAIL"
+ export SANDBOX_ANON_KEY="$SB_ANON_KEY" SANDBOX_SERVICE_KEY="$SB_SERVICE_KEY"
+ "$@"
+)
+
+case "${1:-}" in
+ up) shift; cmd_up "$@" ;;
+ down) cmd_down ;;
+ test-db) load_secrets; "$CLI" test db --db-url "$(db_url)" ;;
+ types)
+ load_secrets
+ out="$("$CLI" gen types typescript --db-url "$(db_url)" --schema public | node_modules/.bin/prettier --parser typescript)"
+ if [ "${2:-}" = --check ]; then
+ diff <(printf '%s\n' "$out") packages/supabase/src/database.types.ts && echo "== types match"
+ else
+ printf '%s\n' "$out" > packages/supabase/src/database.types.ts; echo "== types written"
+ fi ;;
+ test) load_secrets; with_sandbox_env node_modules/.bin/pnpm --filter @faunosteo/supabase test:sandbox ;;
+ e2e-shell) shift; load_secrets; with_sandbox_env node_modules/.bin/pnpm --filter @faunosteo/app e2e:shell "$@" ;;
+ sql) load_secrets; sb_psql ;;
+ *) sed -n '2,23p' "$0"; exit 1 ;;
+esac
diff --git a/supabase/migrations/20261025100000_workspaces.sql b/supabase/migrations/20261025100000_workspaces.sql
new file mode 100644
index 00000000..fad6a2cd
--- /dev/null
+++ b/supabase/migrations/20261025100000_workspaces.sql
@@ -0,0 +1,353 @@
+-- V1-1.1 Workspaces (M1): the perimeter that will own and isolate clients,
+-- animals and later bilans. Contract: docs/development/V1-1_OWNERS_ANIMALS.md
+-- §4 (model), §8 (schema), §9 (helpers, RLS), §13.2 N7 / N9 (privileges, audit).
+--
+-- In V1-1 every account has exactly one personal workspace, created by the
+-- server in the transaction that creates its profile (sign-up), never by a
+-- client call. Its only member is the account itself, with member_role
+-- holder. Nothing is shared between accounts; cabinets come with plan Step 10.
+--
+-- Invariants pinned by supabase/tests/012_workspaces.sql:
+-- * one personal workspace per profile (unique personal_user_id), created
+-- with its holder membership in one statement, idempotent under retries
+-- and concurrent calls (ON CONFLICT on the unique key);
+-- * a personal workspace has exactly one member, its account as holder,
+-- checked at commit, so neither row ever survives alone;
+-- * a workspace is readable only by its members whose profile is active and
+-- whose email is confirmed; auth.uid() is the only input of that rule;
+-- * no API role writes either table; anon and service_role hold no
+-- privilege on them; no policy names a platform role (D16);
+-- * the audit correlation id is kept only when it is a short token, so a
+-- caller no longer chooses the size of an append-only audit row.
+
+-- ---------------------------------------------------------------------------
+-- Tables
+-- ---------------------------------------------------------------------------
+-- cabinet joins workspace_kind with the cabinet step; holder is the only
+-- member role until then (no unused cabinet role).
+create type public.workspace_kind as enum ('personal');
+create type public.workspace_member_role as enum ('holder');
+
+create table public.workspaces (
+ id uuid primary key default gen_random_uuid(),
+ kind public.workspace_kind not null,
+ -- The account whose personal workspace this is; null for a future cabinet.
+ -- Deleting the account deletes its personal workspace, unless a record
+ -- table refuses it (D9a, `on delete restrict` from M2 on).
+ personal_user_id uuid references public.profiles (id) on delete cascade,
+ created_at timestamptz not null default now(),
+ constraint workspaces_personal_user_unique unique (personal_user_id),
+ constraint workspaces_personal_user_iff_personal
+ check ((kind = 'personal') = (personal_user_id is not null))
+);
+
+comment on table public.workspaces is
+ 'Perimeter that owns and isolates records. V1-1: one personal workspace per account, created with its profile; no API write path; no archive (it follows its account).';
+comment on column public.workspaces.personal_user_id is
+ 'Account of a personal workspace (unique); null for a cabinet.';
+
+create table public.workspace_members (
+ workspace_id uuid not null references public.workspaces (id) on delete cascade,
+ user_id uuid not null references public.profiles (id) on delete cascade,
+ member_role public.workspace_member_role not null,
+ created_at timestamptz not null default now(),
+ primary key (workspace_id, user_id)
+);
+
+comment on table public.workspace_members is
+ 'Membership and rights of an account in a workspace. V1-1: the holder of each personal workspace only; no API write path.';
+
+-- The membership lookup of every workspace policy (by caller).
+create index workspace_members_user_idx on public.workspace_members (user_id);
+
+-- ---------------------------------------------------------------------------
+-- Invariant: a personal workspace has exactly one member, its account as
+-- holder. Deferred to commit so the two rows may be written in either order
+-- inside one transaction; a workspace or a membership left alone, or a
+-- foreign member added to a personal workspace, fails the commit whatever
+-- role writes it. Cabinets are not constrained here.
+-- ---------------------------------------------------------------------------
+create or replace function private.check_personal_workspace()
+returns trigger
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_ids uuid[];
+begin
+ if tg_table_name = 'workspaces' then
+ v_ids := array[new.id];
+ elsif tg_op = 'INSERT' then
+ v_ids := array[new.workspace_id];
+ elsif tg_op = 'DELETE' then
+ v_ids := array[old.workspace_id];
+ else
+ v_ids := array[old.workspace_id, new.workspace_id];
+ end if;
+
+ -- A deleted workspace has nothing left to check (account deletion cascades).
+ if exists (
+ select 1
+ from public.workspaces w
+ where w.id = any (v_ids)
+ and w.kind = 'personal'
+ and (
+ not exists (
+ select 1 from public.workspace_members m
+ where m.workspace_id = w.id
+ and m.user_id = w.personal_user_id
+ and m.member_role = 'holder'
+ )
+ or exists (
+ select 1 from public.workspace_members m
+ where m.workspace_id = w.id
+ and m.user_id <> w.personal_user_id
+ )
+ )
+ ) then
+ raise exception 'personal workspace must have exactly its account as holder'
+ using errcode = '23514', constraint = 'workspaces_personal_holder';
+ end if;
+ return null;
+end;
+$$;
+
+comment on function private.check_personal_workspace() is
+ 'Deferred constraint trigger: a personal workspace has exactly one member, personal_user_id as holder.';
+
+create constraint trigger workspaces_personal_holder
+ after insert or update on public.workspaces
+ deferrable initially deferred
+ for each row execute function private.check_personal_workspace();
+
+create constraint trigger workspace_members_personal_holder
+ after insert or update or delete on public.workspace_members
+ deferrable initially deferred
+ for each row execute function private.check_personal_workspace();
+
+-- ---------------------------------------------------------------------------
+-- Creation of the personal workspace
+-- ---------------------------------------------------------------------------
+-- The single write path: workspace and holder membership in one statement,
+-- so both rows exist or neither does. A replay, or a call racing another
+-- one, waits on the unique personal_user_id, then writes nothing and
+-- returns false. The id comes from the server (a new profile, the backfill),
+-- never from an API role: EXECUTE is granted to nobody.
+create or replace function private.ensure_personal_workspace(p_user_id uuid)
+returns boolean
+language sql
+volatile
+security definer
+set search_path = ''
+as $$
+ with created as (
+ insert into public.workspaces (kind, personal_user_id)
+ values ('personal', p_user_id)
+ on conflict (personal_user_id) do nothing
+ returning id, personal_user_id
+ ),
+ joined as (
+ insert into public.workspace_members (workspace_id, user_id, member_role)
+ select id, personal_user_id, 'holder' from created
+ returning workspace_id
+ )
+ select exists (select 1 from joined);
+$$;
+
+comment on function private.ensure_personal_workspace(uuid) is
+ 'Creates the personal workspace of an existing profile with its holder membership, atomically; idempotent (false when it already exists).';
+
+-- Sign-up: GoTrue inserts auth.users, private.handle_new_auth_user inserts the
+-- profile, this trigger creates the workspace, all in one transaction. The
+-- workspace exists before the email is confirmed but stays unreadable until
+-- then (private.caller_workspace_ids).
+create or replace function private.create_personal_workspace()
+returns trigger
+language plpgsql
+security definer
+set search_path = ''
+as $$
+begin
+ perform private.ensure_personal_workspace(new.id);
+ return null;
+end;
+$$;
+
+comment on function private.create_personal_workspace() is
+ 'AFTER INSERT on profiles: creates the personal workspace and its holder membership.';
+
+create trigger profiles_create_personal_workspace
+ after insert on public.profiles
+ for each row execute function private.create_personal_workspace();
+
+-- Accounts created before this migration. Called once below; idempotent, so
+-- a second call (or a call racing a sign-up) creates nothing twice.
+create or replace function private.backfill_personal_workspaces()
+returns integer
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_profile_id uuid;
+ v_created integer := 0;
+begin
+ for v_profile_id in
+ select p.id
+ from public.profiles p
+ where not exists (
+ select 1 from public.workspaces w where w.personal_user_id = p.id
+ )
+ order by p.id
+ loop
+ if private.ensure_personal_workspace(v_profile_id) then
+ v_created := v_created + 1;
+ end if;
+ end loop;
+ return v_created;
+end;
+$$;
+
+comment on function private.backfill_personal_workspaces() is
+ 'Creates the missing personal workspaces of existing profiles; returns how many were created. Idempotent.';
+
+-- ---------------------------------------------------------------------------
+-- Access helpers (contract §9.1)
+-- ---------------------------------------------------------------------------
+-- The single source of the access rule of every workspace-scoped table: the
+-- workspaces where the caller is a member, with an active profile and a
+-- confirmed email. No parameter: auth.uid() (a JWT verified by PostgREST) is
+-- the only input, so a caller can name nobody else, and a direct call returns
+-- what the caller may already read. Definer, so it reads auth.users and
+-- workspace_members past their privileges and policies (no RLS recursion).
+create or replace function private.caller_workspace_ids()
+returns setof uuid
+language sql
+stable
+security definer
+set search_path = ''
+as $$
+ select m.workspace_id
+ from public.workspace_members m
+ join public.profiles p on p.id = m.user_id
+ join auth.users u on u.id = m.user_id
+ where m.user_id = (select auth.uid())
+ and p.active
+ and u.email_confirmed_at is not null;
+$$;
+
+comment on function private.caller_workspace_ids() is
+ 'Workspaces of auth.uid() as a member, active profile and confirmed email required. Evaluated by the workspace policies.';
+
+-- The same set restricted to the member roles that may write records (V1-1:
+-- holder). Called inside the write RPCs of M2 and M3 only.
+create or replace function private.writable_workspace_ids()
+returns setof uuid
+language sql
+stable
+security definer
+set search_path = ''
+as $$
+ select m.workspace_id
+ from public.workspace_members m
+ where m.user_id = (select auth.uid())
+ and m.member_role = 'holder'
+ and m.workspace_id in (select private.caller_workspace_ids());
+$$;
+
+comment on function private.writable_workspace_ids() is
+ 'caller_workspace_ids() restricted to a write role (holder). For definer RPCs only.';
+
+-- ---------------------------------------------------------------------------
+-- Audit: cap the caller-controlled correlation id (contract §8, §10, N9)
+-- ---------------------------------------------------------------------------
+-- PostgREST exposes every request header, so x-correlation-id is chosen by
+-- the caller. Kept only when it is a short token, else stored as null. Same
+-- signature, privileges and callers as the foundation version.
+create or replace function private.log_event(
+ p_actor_user_id uuid,
+ p_action text,
+ p_resource_type text,
+ p_resource_id uuid default null,
+ p_target_user_id uuid default null,
+ p_organization_id uuid default null,
+ p_metadata jsonb default '{}'::jsonb
+)
+returns uuid
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_id uuid;
+ v_correlation text;
+begin
+ -- PostgREST exposes request headers as a JSON setting; absent elsewhere.
+ v_correlation := nullif(current_setting('request.headers', true), '')::jsonb ->> 'x-correlation-id';
+ if v_correlation !~ '^[A-Za-z0-9-]{1,64}$' then
+ v_correlation := null;
+ end if;
+
+ insert into audit.audit_logs (
+ actor_user_id, action, resource_type, resource_id,
+ target_user_id, organization_id, metadata, correlation_id
+ )
+ values (
+ p_actor_user_id, p_action, p_resource_type, p_resource_id,
+ p_target_user_id, p_organization_id, coalesce(p_metadata, '{}'::jsonb), v_correlation
+ )
+ returning id into v_id;
+
+ return v_id;
+end;
+$$;
+
+-- New rows only: rows written before this migration keep whatever they hold.
+alter table audit.audit_logs
+ add constraint audit_logs_correlation_id_format
+ check (correlation_id ~ '^[A-Za-z0-9-]{1,64}$') not valid;
+
+-- ---------------------------------------------------------------------------
+-- Privileges + RLS. Supabase default privileges grant ALL on new public
+-- tables to anon, authenticated and service_role: start from zero. The
+-- service key reads nothing here (N7); it remains a GoTrue admin credential
+-- (contract §6.3), which no table privilege can bound.
+-- ---------------------------------------------------------------------------
+revoke all on public.workspaces from public, anon, authenticated, service_role;
+revoke all on public.workspace_members from public, anon, authenticated, service_role;
+grant select (id, kind, personal_user_id, created_at) on public.workspaces to authenticated;
+grant select (workspace_id, user_id, member_role, created_at) on public.workspace_members to authenticated;
+
+alter table public.workspaces enable row level security;
+alter table public.workspace_members enable row level security;
+
+-- Members read their workspaces and the memberships of those workspaces.
+-- No write policy: every write is server-side (trigger, backfill, RPCs).
+create policy workspaces_select_member
+ on public.workspaces
+ for select
+ to authenticated
+ using (id in (select private.caller_workspace_ids()));
+
+create policy workspace_members_select_member
+ on public.workspace_members
+ for select
+ to authenticated
+ using (workspace_id in (select private.caller_workspace_ids()));
+
+revoke all on function private.check_personal_workspace() from public, anon, authenticated, service_role;
+revoke all on function private.ensure_personal_workspace(uuid) from public, anon, authenticated, service_role;
+revoke all on function private.create_personal_workspace() from public, anon, authenticated, service_role;
+revoke all on function private.backfill_personal_workspaces() from public, anon, authenticated, service_role;
+revoke all on function private.writable_workspace_ids() from public, anon, authenticated, service_role;
+revoke all on function private.caller_workspace_ids() from public, anon, authenticated, service_role;
+-- Policies run as the API role: it needs EXECUTE on the predicate.
+grant execute on function private.caller_workspace_ids() to authenticated;
+
+-- ---------------------------------------------------------------------------
+-- Existing accounts. Runs after the trigger exists, so a profile created
+-- while the migration runs is covered by one or the other; a double pass
+-- creates nothing twice (ensure_personal_workspace).
+-- ---------------------------------------------------------------------------
+select private.backfill_personal_workspaces();
diff --git a/supabase/migrations/20261025110000_clients.sql b/supabase/migrations/20261025110000_clients.sql
new file mode 100644
index 00000000..1594bc35
--- /dev/null
+++ b/supabase/migrations/20261025110000_clients.sql
@@ -0,0 +1,514 @@
+-- V1-1.2 Clients (M2): the clients of a workspace, written only through RPCs,
+-- read through RLS, searched through a POST RPC. Contract:
+-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.1 (fields),
+-- §8 (schema), §9 (helpers, RLS, RPCs, failures), §10 (limits), §13.2 (N2,
+-- N3, N6, N7, N9).
+--
+-- Invariants pinned by supabase/tests/013_clients.sql and the sandbox suite:
+-- * a client belongs to one workspace; only a member with a write role of
+-- an active, confirmed account writes it, through the four RPCs; every
+-- foreign or unknown id is answered with the same 42501 `not_found`;
+-- * a create is idempotent by (workspace, create_request_id); a replay
+-- with other content is refused (`request_conflict`), never applied;
+-- * an update needs the current revision; an archived client is read-only
+-- until restored;
+-- * writes are capped per workspace (20 000 clients; 1 000 audited writes
+-- per UTC hour, 5 000 per UTC day) under locks, so concurrent calls
+-- cannot pass a cap and a refused or replayed call consumes nothing;
+-- * audit rows carry ids only, and platform staff do not read them (N9).
+
+-- ---------------------------------------------------------------------------
+-- Text folding for search keys
+-- ---------------------------------------------------------------------------
+create extension if not exists unaccent with schema extensions;
+
+-- Accents removed with the explicit dictionary, then ASCII lower case
+-- (collation "C"), so PGlite and the real image fold identically. Letters
+-- outside ASCII that unaccent keeps (Cyrillic, Greek) keep their case.
+-- Declared immutable for the generated columns: the dictionary is fixed by
+-- the extension version (contract §8).
+create or replace function private.fold_text(p_value text)
+returns text
+language sql
+immutable
+parallel safe
+set search_path = ''
+as $$
+ select lower(extensions.unaccent('extensions.unaccent'::regdictionary, p_value) collate "C");
+$$;
+
+comment on function private.fold_text(text) is
+ 'Search key folding: unaccent (explicit dictionary) then ASCII lower case. Used by generated columns and by search_clients.';
+
+-- The text rule of contract §5: 1 to p_max characters (code points), no
+-- leading or trailing space, no control character of the explicit ranges.
+-- Null passes (an absent value is null, never an empty string).
+create or replace function private.is_clean_text(p_value text, p_max integer)
+returns boolean
+language sql
+immutable
+parallel safe
+set search_path = ''
+as $$
+ select p_value is null
+ or (char_length(p_value) between 1 and p_max
+ and p_value = btrim(p_value)
+ and p_value !~ '[\u0001-\u001f\u007f-\u009f\u2028\u2029]');
+$$;
+
+comment on function private.is_clean_text(text, integer) is
+ 'Contract §5 text rule for CHECK constraints: length 1..p_max in code points, trimmed, no control character.';
+
+-- ---------------------------------------------------------------------------
+-- clients
+-- ---------------------------------------------------------------------------
+create type public.client_kind as enum ('person', 'organization');
+
+create table public.clients (
+ id uuid primary key default gen_random_uuid(),
+ -- restrict: an account whose workspace holds clients cannot be deleted (D9a).
+ workspace_id uuid not null references public.workspaces (id) on delete restrict,
+ kind public.client_kind not null,
+ display_name text not null
+ constraint clients_display_name_text check (private.is_clean_text(display_name, 120)),
+ email text
+ constraint clients_email_format check (
+ private.is_clean_text(email, 254)
+ and email = lower(email)
+ and email ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$'
+ ),
+ phone text
+ constraint clients_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'),
+ address_line1 text
+ constraint clients_address_line1_text check (private.is_clean_text(address_line1, 120)),
+ address_line2 text
+ constraint clients_address_line2_text check (private.is_clean_text(address_line2, 120)),
+ postal_code text
+ constraint clients_postal_code_text check (private.is_clean_text(postal_code, 16)),
+ city text
+ constraint clients_city_text check (private.is_clean_text(city, 80)),
+ country text
+ constraint clients_country_code check (country ~ '^[A-Z]{2}$'),
+ name_key text collate "C"
+ generated always as (private.fold_text(display_name)) stored,
+ search_key text collate "C"
+ generated always as (
+ private.fold_text(display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, ''))
+ ) stored,
+ phone_digits text collate "C" generated always as (ltrim(phone, '+')) stored,
+ -- Idempotency: the form sends one uuid per create attempt. The digest of the
+ -- creation content tells a replay from a divergent reuse; never readable
+ -- through the API.
+ create_request_id uuid not null,
+ create_request_digest bytea not null,
+ revision integer not null default 1
+ constraint clients_revision_positive check (revision >= 1),
+ archived_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint clients_workspace_id_unique unique (workspace_id, id),
+ constraint clients_create_request_unique unique (workspace_id, create_request_id)
+);
+
+comment on table public.clients is
+ 'Clients of a workspace (person or organization). Writes only through create_client, update_client, set_client_archived; reads through RLS and search_clients.';
+comment on column public.clients.display_name is
+ 'The single name reference (N2): display, search, sorting, documents.';
+
+-- Workspace filter, name order, keyset pagination and the search scan.
+create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id);
+
+create trigger clients_set_updated_at
+ before update on public.clients
+ for each row execute function private.set_updated_at();
+
+-- ---------------------------------------------------------------------------
+-- Write budget per workspace (N6, owner decision on the counter)
+-- ---------------------------------------------------------------------------
+-- One row per workspace, fixed UTC windows: the hour starting at hh:00:00 UTC
+-- and the day starting at 00:00:00 UTC. A window that has passed restarts at
+-- 1 on the next write. The row lock of the upsert serialises the writes of
+-- one workspace only; it is the last lock a write RPC takes, so no lock
+-- cycle can form. The counts are rolled back with any refused write.
+create table private.workspace_write_budgets (
+ workspace_id uuid primary key references public.workspaces (id) on delete cascade,
+ hour_start timestamptz not null,
+ hour_count integer not null,
+ day_start timestamptz not null,
+ day_count integer not null
+);
+
+comment on table private.workspace_write_budgets is
+ 'Audited writes per workspace in the current UTC hour and day (contract §10). Written only by private.consume_write_budget.';
+
+create or replace function private.consume_write_budget(p_workspace_id uuid)
+returns void
+language plpgsql
+security definer
+set search_path = ''
+as $$
+declare
+ v_hour timestamptz := date_trunc('hour', now(), 'UTC');
+ v_day timestamptz := date_trunc('day', now(), 'UTC');
+ v_hour_count integer;
+ v_day_count integer;
+begin
+ insert into private.workspace_write_budgets as b (workspace_id, hour_start, hour_count, day_start, day_count)
+ values (p_workspace_id, v_hour, 1, v_day, 1)
+ on conflict (workspace_id) do update set
+ hour_count = case when b.hour_start = excluded.hour_start then b.hour_count + 1 else 1 end,
+ hour_start = excluded.hour_start,
+ day_count = case when b.day_start = excluded.day_start then b.day_count + 1 else 1 end,
+ day_start = excluded.day_start
+ returning b.hour_count, b.day_count into v_hour_count, v_day_count;
+
+ -- Raising undoes the increment with the rest of the refused write.
+ if v_hour_count > 1000 or v_day_count > 5000 then
+ raise exception 'rate_limited' using errcode = 'P0001';
+ end if;
+end;
+$$;
+
+comment on function private.consume_write_budget(uuid) is
+ 'Counts one audited write of the workspace in its UTC hour and day; raises rate_limited past 1 000 / 5 000. Call last, after the entity locks.';
+
+-- ---------------------------------------------------------------------------
+-- Write RPCs (contract §9.3). Each one: authorise and lock in one statement
+-- (no row = 42501 not_found, the same for a foreign and an unknown id), then
+-- archived, then revision, then rules; the budget last; one audit row with
+-- ids only; returns ids and revision.
+-- ---------------------------------------------------------------------------
+create or replace function public.create_client(
+ workspace_id uuid,
+ create_request_id uuid,
+ kind text,
+ display_name text,
+ email text default null,
+ phone text default null,
+ address_line1 text default null,
+ address_line2 text default null,
+ postal_code text default null,
+ city text default null,
+ country text default null
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_kind public.client_kind;
+ v_email text := lower(create_client.email);
+ v_digest bytea;
+ v_existing_id uuid;
+ v_existing_revision integer;
+ v_existing_digest bytea;
+ v_id uuid;
+begin
+ -- Serialises the creates of this workspace (replay check, cap, insert).
+ perform 1 from public.workspaces w
+ where w.id = create_client.workspace_id
+ and w.id in (select private.writable_workspace_ids())
+ for no key update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+
+ begin
+ v_kind := create_client.kind::public.client_kind;
+ exception when invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+ v_digest := sha256(convert_to(jsonb_build_array(
+ v_kind, create_client.display_name, v_email, create_client.phone,
+ create_client.address_line1, create_client.address_line2,
+ create_client.postal_code, create_client.city, create_client.country
+ )::text, 'UTF8'));
+
+ select c.id, c.revision, c.create_request_digest
+ into v_existing_id, v_existing_revision, v_existing_digest
+ from public.clients c
+ where c.workspace_id = create_client.workspace_id
+ and c.create_request_id = create_client.create_request_id;
+ if found then
+ if v_existing_digest <> v_digest then
+ raise exception 'request_conflict' using errcode = 'P0001';
+ end if;
+ return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision);
+ end if;
+
+ if (select count(*) from public.clients c where c.workspace_id = create_client.workspace_id) >= 20000 then
+ raise exception 'limit_reached' using errcode = 'P0001';
+ end if;
+ perform private.consume_write_budget(create_client.workspace_id);
+
+ begin
+ insert into public.clients (
+ workspace_id, kind, display_name, email, phone, address_line1, address_line2,
+ postal_code, city, country, create_request_id, create_request_digest
+ )
+ values (
+ create_client.workspace_id, v_kind, create_client.display_name, v_email, create_client.phone,
+ create_client.address_line1, create_client.address_line2, create_client.postal_code,
+ create_client.city, create_client.country, create_client.create_request_id, v_digest
+ )
+ returning id into v_id;
+ exception when check_violation or not_null_violation or string_data_right_truncation
+ or invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'client.created', 'client', v_id, null, null,
+ jsonb_build_object('workspace_id', create_client.workspace_id)
+ );
+ return jsonb_build_object('id', v_id, 'revision', 1);
+end;
+$$;
+
+create or replace function public.update_client(
+ client_id uuid,
+ expected_revision integer,
+ kind text,
+ display_name text,
+ email text,
+ phone text,
+ address_line1 text,
+ address_line2 text,
+ postal_code text,
+ city text,
+ country text
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.clients;
+ v_kind public.client_kind;
+ v_email text := lower(update_client.email);
+begin
+ select c.* into v_row
+ from public.clients c
+ where c.id = update_client.client_id
+ and c.workspace_id in (select private.writable_workspace_ids())
+ for update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ if v_row.archived_at is not null then
+ raise exception 'archived' using errcode = 'P0001';
+ end if;
+ if update_client.expected_revision is distinct from v_row.revision then
+ raise exception 'conflict' using errcode = 'P0001';
+ end if;
+
+ begin
+ v_kind := update_client.kind::public.client_kind;
+ exception when invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ -- No change: nothing written, nothing counted.
+ if (v_kind, update_client.display_name, v_email, update_client.phone, update_client.address_line1,
+ update_client.address_line2, update_client.postal_code, update_client.city, update_client.country)
+ is not distinct from
+ (v_row.kind, v_row.display_name, v_row.email, v_row.phone, v_row.address_line1,
+ v_row.address_line2, v_row.postal_code, v_row.city, v_row.country) then
+ return jsonb_build_object('revision', v_row.revision);
+ end if;
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ begin
+ update public.clients c
+ set kind = v_kind, display_name = update_client.display_name, email = v_email,
+ phone = update_client.phone, address_line1 = update_client.address_line1,
+ address_line2 = update_client.address_line2, postal_code = update_client.postal_code,
+ city = update_client.city, country = update_client.country,
+ revision = c.revision + 1
+ where c.id = v_row.id;
+ exception when check_violation or not_null_violation or string_data_right_truncation
+ or invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'client.updated', 'client', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+create or replace function public.set_client_archived(
+ client_id uuid,
+ archived boolean
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.clients;
+begin
+ select c.* into v_row
+ from public.clients c
+ where c.id = set_client_archived.client_id
+ and c.workspace_id in (select private.writable_workspace_ids())
+ for update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ if set_client_archived.archived is null then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ -- Already in that state: nothing written, nothing counted.
+ if (v_row.archived_at is not null) = set_client_archived.archived then
+ return jsonb_build_object('revision', v_row.revision);
+ end if;
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ update public.clients c
+ set archived_at = case when set_client_archived.archived then now() end,
+ revision = c.revision + 1
+ where c.id = v_row.id;
+
+ perform private.log_event(
+ auth.uid(),
+ case when set_client_archived.archived then 'client.archived' else 'client.restored' end,
+ 'client', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+-- ---------------------------------------------------------------------------
+-- Search (contract §9.3): security invoker, so RLS limits it to the caller's
+-- workspaces; a foreign workspace id returns no row. Called with POST, so the
+-- term and the cursor stay out of URLs.
+-- ---------------------------------------------------------------------------
+create or replace function public.search_clients(
+ workspace_id uuid,
+ query text default '',
+ archived boolean default false,
+ page_size integer default 25,
+ after_name_key text default null,
+ after_id uuid default null
+)
+returns table (
+ id uuid,
+ kind public.client_kind,
+ display_name text,
+ city text,
+ phone text,
+ email text,
+ archived_at timestamptz,
+ name_key text
+)
+language plpgsql
+stable
+security invoker
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_term text := btrim(coalesce(search_clients.query, ''));
+ v_pattern text;
+ v_digits text;
+begin
+ if char_length(v_term) > 100
+ or search_clients.archived is null
+ or search_clients.page_size is null
+ or search_clients.page_size not between 1 and 100
+ or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+
+ -- Folded term inside search_key; LIKE wildcards escaped, backslash first.
+ v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%';
+ -- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits)
+ -- is also looked for in phone_digits, without one leading 0.
+ if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then
+ v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', '');
+ end if;
+
+ return query
+ select c.id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key
+ from public.clients c
+ where c.workspace_id = search_clients.workspace_id
+ and (c.archived_at is not null) = search_clients.archived
+ and (v_term = ''
+ or c.search_key like v_pattern
+ or (v_digits is not null and c.phone_digits like '%' || v_digits || '%'))
+ and (search_clients.after_name_key is null
+ or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id))
+ order by c.name_key, c.id
+ limit search_clients.page_size;
+end;
+$$;
+
+comment on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) is
+ 'Creates a client in a writable workspace; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision}.';
+comment on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) is
+ 'Replaces the nine fields of an active client at expected_revision. Returns {revision}.';
+comment on function public.set_client_archived(uuid, boolean) is
+ 'Archives or restores a client (same state: no write). Returns {revision}.';
+comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is
+ 'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most.';
+
+-- ---------------------------------------------------------------------------
+-- Audit (N9): platform owners and admins keep reading platform events, not
+-- the activity of private records.
+-- ---------------------------------------------------------------------------
+alter policy audit_logs_select_admin on audit.audit_logs
+ using (
+ private.is_platform_admin((select auth.uid()))
+ and split_part(action, '.', 1) not in ('client', 'animal', 'animal_client_relation')
+ );
+
+-- ---------------------------------------------------------------------------
+-- Privileges + RLS (N7: nothing for anon or service_role)
+-- ---------------------------------------------------------------------------
+revoke all on public.clients from public, anon, authenticated, service_role;
+grant select (
+ id, workspace_id, kind, display_name, email, phone, address_line1, address_line2,
+ postal_code, city, country, name_key, search_key, phone_digits, create_request_id,
+ revision, archived_at, created_at, updated_at
+) on public.clients to authenticated;
+
+alter table public.clients enable row level security;
+
+create policy clients_select_member
+ on public.clients
+ for select
+ to authenticated
+ using (workspace_id in (select private.caller_workspace_ids()));
+
+revoke all on private.workspace_write_budgets from public, anon, authenticated, service_role;
+
+revoke all on function private.fold_text(text) from public, anon, authenticated, service_role;
+revoke all on function private.is_clean_text(text, integer) from public, anon, authenticated, service_role;
+revoke all on function private.consume_write_budget(uuid) from public, anon, authenticated, service_role;
+revoke all on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.set_client_archived(uuid, boolean) from public, anon, authenticated, service_role;
+revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid)
+ from public, anon, authenticated, service_role;
+
+grant execute on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) to authenticated;
+grant execute on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) to authenticated;
+grant execute on function public.set_client_archived(uuid, boolean) to authenticated;
+grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated;
+-- The invoker search folds its term as the caller.
+grant execute on function private.fold_text(text) to authenticated;
diff --git a/supabase/migrations/20261026100000_animals_relations.sql b/supabase/migrations/20261026100000_animals_relations.sql
new file mode 100644
index 00000000..91e4b1b6
--- /dev/null
+++ b/supabase/migrations/20261026100000_animals_relations.sql
@@ -0,0 +1,1166 @@
+-- V1-1.4 Animals and relations (M3): the animals of a workspace and their
+-- relations with its clients (owner, keeper, contact), written only through
+-- RPCs, read through RLS and POST RPCs. Contract:
+-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.2 (animal),
+-- §5.3 (relation), §5.4 (species), §7.1 (archive), §8 (schema), §9 (helpers,
+-- RLS, RPCs, failures), §10 (limits), §13.2 (N1, N4, N5, N6, N8, N9).
+--
+-- Invariants pinned by supabase/tests/014_animals_relations.sql and the
+-- sandbox suite:
+-- * an animal belongs to one workspace; a relation joins an animal and a
+-- client of the same workspace, enforced by composite foreign keys
+-- whatever role writes;
+-- * a relation is current (ended_at and voided_at null), ended (ended_at
+-- set, ended_on when the date is known) or voided (entered by mistake,
+-- voided_at set, frozen); at most one current relation per (animal,
+-- client, role), enforced by a partial unique index;
+-- * only a member with a write role of an active, confirmed account writes,
+-- through the RPCs below; every foreign or unknown id gets the same 42501
+-- `not_found`; creates are idempotent by (workspace, create_request_id),
+-- a divergent replay is refused (`request_conflict`);
+-- * caps (20 000 animals and 100 000 relations per workspace, 20 current and
+-- 200 relations per animal) and the write budget shared with the clients
+-- are checked under locks taken in one order: workspace, animal, relation,
+-- client, budget last;
+-- * audit rows carry ids only, hidden from platform staff (M2's N9 filter
+-- already names the animal and relation actions).
+
+-- ---------------------------------------------------------------------------
+-- Species (contract §5.4, N1): the nine species of the contract and « Autre ».
+-- Rows, not an enum; the existing `equine` row is kept unchanged. A species
+-- row does not mean an anatomical sheet exists.
+-- ---------------------------------------------------------------------------
+insert into public.species (id, name_fr, name_en, sort_order) values
+ ('asinine', 'Âne', 'Donkey', 20),
+ ('canine', 'Chien', 'Dog', 30),
+ ('feline', 'Chat', 'Cat', 40),
+ ('bovine', 'Bovin', 'Cattle', 50),
+ ('caprine', 'Chèvre', 'Goat', 60),
+ ('ovine', 'Mouton', 'Sheep', 70),
+ ('porcine', 'Porc', 'Pig', 80),
+ ('leporine', 'Lapin', 'Rabbit', 90),
+ ('other', 'Autre', 'Other', 1000)
+on conflict (id) do nothing;
+
+comment on table public.species is
+ 'Species of animals and of anatomical sheets. Reference data seeded by migrations; no API write path. A species row does not mean a sheet exists.';
+
+-- ---------------------------------------------------------------------------
+-- Dates and years sent as text (contract §9.3): parsed in the body, so a
+-- malformed value is answered invalid_input without being echoed; "not in the
+-- future" allows up to tomorrow's UTC date, so today in any time zone passes.
+-- ---------------------------------------------------------------------------
+create or replace function private.utc_tomorrow(p_now timestamptz)
+returns date
+language sql
+stable
+parallel safe
+set search_path = ''
+as $$
+ select (p_now at time zone 'UTC')::date + 1;
+$$;
+
+comment on function private.utc_tomorrow(timestamptz) is
+ 'Latest date a record may carry when written at p_now: the UTC date of tomorrow (contract §9.3).';
+
+create or replace function private.parse_record_date(p_value text)
+returns date
+language plpgsql
+stable
+set search_path = ''
+as $$
+declare
+ v_date date;
+begin
+ if p_value is null then
+ return null;
+ end if;
+ if p_value !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ begin
+ v_date := p_value::date;
+ exception when data_exception then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+ if v_date > private.utc_tomorrow(now()) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ return v_date;
+end;
+$$;
+
+comment on function private.parse_record_date(text) is
+ 'YYYY-MM-DD to a date no later than tomorrow UTC, else invalid_input; null stays null. The 1900 floor is a CHECK.';
+
+create or replace function private.parse_birth_year(p_value text)
+returns smallint
+language plpgsql
+stable
+set search_path = ''
+as $$
+begin
+ if p_value is null then
+ return null;
+ end if;
+ -- Two statements: SQL does not promise to test the pattern before the cast.
+ if p_value !~ '^[0-9]{4}$' then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ if p_value::integer > extract(year from private.utc_tomorrow(now()))::integer then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ return p_value::smallint;
+end;
+$$;
+
+comment on function private.parse_birth_year(text) is
+ 'Four digits to a year no later than the year of tomorrow UTC, else invalid_input; null stays null. The 1900 floor is a CHECK.';
+
+-- ---------------------------------------------------------------------------
+-- animals (contract §5.2: D6, D6b, N8)
+-- ---------------------------------------------------------------------------
+create type public.animal_sex as enum ('male', 'female', 'unknown');
+
+create table public.animals (
+ id uuid primary key default gen_random_uuid(),
+ -- restrict: an account whose workspace holds animals cannot be deleted (D9a).
+ workspace_id uuid not null references public.workspaces (id) on delete restrict,
+ name text not null
+ constraint animals_name_text check (private.is_clean_text(name, 80)),
+ species_id text not null references public.species (id) on delete restrict,
+ species_detail text
+ constraint animals_species_detail_text check (private.is_clean_text(species_detail, 80)),
+ -- No default: « inconnu » is chosen explicitly (N8).
+ sex public.animal_sex not null,
+ breed text
+ constraint animals_breed_text check (private.is_clean_text(breed, 80)),
+ birth_year smallint
+ constraint animals_birth_year_range check (birth_year between 1900 and 2100),
+ birth_date date
+ constraint animals_birth_date_range check (birth_date >= date '1900-01-01'),
+ name_key text collate "C"
+ generated always as (private.fold_text(name)) stored,
+ search_key text collate "C"
+ generated always as (
+ private.fold_text(name || ' ' || coalesce(breed, '') || ' ' || coalesce(species_detail, ''))
+ ) stored,
+ create_request_id uuid not null,
+ create_request_digest bytea not null,
+ revision integer not null default 1
+ constraint animals_revision_positive check (revision >= 1),
+ archived_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint animals_workspace_id_unique unique (workspace_id, id),
+ constraint animals_create_request_unique unique (workspace_id, create_request_id),
+ -- « Autre » needs its detail; any other species refuses one.
+ constraint animals_species_detail_iff_other check ((species_id = 'other') = (species_detail is not null)),
+ -- D6b: a full date carries its year again; a year never becomes a date.
+ constraint animals_birth_date_year check (
+ birth_date is null
+ or (birth_year is not null and birth_year = extract(year from birth_date)::integer)
+ )
+);
+
+comment on table public.animals is
+ 'Animals of a workspace. Writes only through create_animal, update_animal, set_animal_archived; reads through RLS and search_animals.';
+comment on column public.animals.birth_year is
+ 'Year of birth when known; repeated from birth_date when the full date is known (D6b).';
+
+create index animals_workspace_name_idx on public.animals (workspace_id, name_key, id);
+
+create trigger animals_set_updated_at
+ before update on public.animals
+ for each row execute function private.set_updated_at();
+
+-- ---------------------------------------------------------------------------
+-- animal_client_relations (contract §5.3: D7, D7a, N4, N5)
+-- ---------------------------------------------------------------------------
+create type public.animal_relation_role as enum ('owner', 'keeper', 'contact');
+
+create table public.animal_client_relations (
+ id uuid primary key default gen_random_uuid(),
+ workspace_id uuid not null,
+ animal_id uuid not null,
+ client_id uuid not null,
+ relation_role public.animal_relation_role not null,
+ -- Real dates when known, never filled by default (N5).
+ started_on date
+ constraint animal_client_relations_started_on_range check (started_on >= date '1900-01-01'),
+ ended_on date
+ constraint animal_client_relations_ended_on_range check (ended_on >= date '1900-01-01'),
+ -- Technical time the end was recorded: null while current, never shown as the end date.
+ ended_at timestamptz,
+ -- Set once by void_animal_client_relation for a relation entered by mistake (N4).
+ voided_at timestamptz,
+ create_request_id uuid not null,
+ create_request_digest bytea not null,
+ revision integer not null default 1
+ constraint animal_client_relations_revision_positive check (revision >= 1),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ -- Animal and client of one workspace, whatever writes the row (not deferrable).
+ constraint animal_client_relations_animal_fk foreign key (workspace_id, animal_id)
+ references public.animals (workspace_id, id) on delete restrict,
+ constraint animal_client_relations_client_fk foreign key (workspace_id, client_id)
+ references public.clients (workspace_id, id) on delete restrict,
+ constraint animal_client_relations_ended_on_needs_end check (ended_on is null or ended_at is not null),
+ constraint animal_client_relations_dates_order
+ check (started_on is null or ended_on is null or started_on <= ended_on),
+ constraint animal_client_relations_create_request_unique unique (workspace_id, create_request_id)
+);
+
+comment on table public.animal_client_relations is
+ 'Relations between an animal and a client of one workspace, with their history. Writes only through the relation RPCs; never deleted (a mistake is voided).';
+
+-- One current relation per (animal, client, role); ended and voided rows are history.
+create unique index animal_client_relations_current_unique
+ on public.animal_client_relations (animal_id, client_id, relation_role)
+ where ended_at is null and voided_at is null;
+create index animal_client_relations_animal_idx on public.animal_client_relations (workspace_id, animal_id);
+create index animal_client_relations_client_idx on public.animal_client_relations (workspace_id, client_id);
+
+create trigger animal_client_relations_set_updated_at
+ before update on public.animal_client_relations
+ for each row execute function private.set_updated_at();
+
+-- ---------------------------------------------------------------------------
+-- Animal write RPCs (contract §9.3): authorise and lock in one statement, then
+-- archived, revision, rules; the budget last; audit rows with ids only.
+-- ---------------------------------------------------------------------------
+create or replace function public.create_animal(
+ workspace_id uuid,
+ create_request_id uuid,
+ name text,
+ species_id text,
+ sex text,
+ species_detail text default null,
+ breed text default null,
+ birth_year text default null,
+ birth_date text default null,
+ client_id uuid default null,
+ relation_role text default null,
+ started_on text default null
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_sex public.animal_sex;
+ v_role public.animal_relation_role;
+ v_birth_year smallint;
+ v_birth_date date;
+ v_started_on date;
+ v_digest bytea;
+ v_existing_id uuid;
+ v_existing_revision integer;
+ v_existing_digest bytea;
+ v_client_archived_at timestamptz;
+ v_id uuid;
+ v_relation_id uuid;
+begin
+ -- Serialises the creates of this workspace (replay check, caps, inserts).
+ perform 1 from public.workspaces w
+ where w.id = create_animal.workspace_id
+ and w.id in (select private.writable_workspace_ids())
+ for no key update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+
+ begin
+ v_sex := create_animal.sex::public.animal_sex;
+ v_role := create_animal.relation_role::public.animal_relation_role;
+ exception when invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+ -- The initial relation is all or nothing: a client and a role, or neither.
+ if (create_animal.client_id is null) <> (v_role is null)
+ or (create_animal.client_id is null and create_animal.started_on is not null) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ v_birth_year := private.parse_birth_year(create_animal.birth_year);
+ v_birth_date := private.parse_record_date(create_animal.birth_date);
+ v_started_on := private.parse_record_date(create_animal.started_on);
+ v_digest := sha256(convert_to(jsonb_build_array(
+ create_animal.name, create_animal.species_id, v_sex, create_animal.species_detail,
+ create_animal.breed, v_birth_year, v_birth_date, create_animal.client_id, v_role, v_started_on
+ )::text, 'UTF8'));
+
+ select a.id, a.revision, a.create_request_digest
+ into v_existing_id, v_existing_revision, v_existing_digest
+ from public.animals a
+ where a.workspace_id = create_animal.workspace_id
+ and a.create_request_id = create_animal.create_request_id;
+ if found then
+ if v_existing_digest <> v_digest then
+ raise exception 'request_conflict' using errcode = 'P0001';
+ end if;
+ -- The initial relation shares the request id of its animal.
+ select r.id into v_relation_id
+ from public.animal_client_relations r
+ where r.workspace_id = create_animal.workspace_id
+ and r.create_request_id = create_animal.create_request_id
+ and r.animal_id = v_existing_id;
+ return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision, 'relation_id', v_relation_id);
+ end if;
+
+ if not exists (select 1 from public.species s where s.id = create_animal.species_id and s.active) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ if (select count(*) from public.animals a where a.workspace_id = create_animal.workspace_id) >= 20000 then
+ raise exception 'limit_reached' using errcode = 'P0001';
+ end if;
+ if create_animal.client_id is not null then
+ select c.archived_at into v_client_archived_at
+ from public.clients c
+ where c.id = create_animal.client_id
+ and c.workspace_id = create_animal.workspace_id
+ for share;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ if v_client_archived_at is not null then
+ raise exception 'archived' using errcode = 'P0001';
+ end if;
+ -- A relation created by another call with this request id would collide.
+ if exists (select 1 from public.animal_client_relations r
+ where r.workspace_id = create_animal.workspace_id
+ and r.create_request_id = create_animal.create_request_id) then
+ raise exception 'request_conflict' using errcode = 'P0001';
+ end if;
+ if (select count(*) from public.animal_client_relations r
+ where r.workspace_id = create_animal.workspace_id) >= 100000 then
+ raise exception 'limit_reached' using errcode = 'P0001';
+ end if;
+ end if;
+
+ -- Two audited writes when the relation comes along.
+ perform private.consume_write_budget(create_animal.workspace_id);
+ if create_animal.client_id is not null then
+ perform private.consume_write_budget(create_animal.workspace_id);
+ end if;
+
+ begin
+ insert into public.animals (
+ workspace_id, name, species_id, species_detail, sex, breed, birth_year, birth_date,
+ create_request_id, create_request_digest
+ )
+ values (
+ create_animal.workspace_id, create_animal.name, create_animal.species_id, create_animal.species_detail,
+ v_sex, create_animal.breed, v_birth_year, v_birth_date, create_animal.create_request_id, v_digest
+ )
+ returning id into v_id;
+ if create_animal.client_id is not null then
+ insert into public.animal_client_relations (
+ workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest
+ )
+ values (
+ create_animal.workspace_id, v_id, create_animal.client_id, v_role, v_started_on,
+ create_animal.create_request_id,
+ sha256(convert_to(jsonb_build_array(v_id, create_animal.client_id, v_role, v_started_on)::text, 'UTF8'))
+ )
+ returning id into v_relation_id;
+ end if;
+ exception
+ when check_violation or not_null_violation or string_data_right_truncation
+ or invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ when foreign_key_violation then
+ raise exception 'not_found' using errcode = '42501';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'animal.created', 'animal', v_id, null, null,
+ jsonb_build_object('workspace_id', create_animal.workspace_id)
+ );
+ if v_relation_id is not null then
+ perform private.log_event(
+ auth.uid(), 'animal_client_relation.created', 'animal_client_relation', v_relation_id, null, null,
+ jsonb_build_object('workspace_id', create_animal.workspace_id)
+ );
+ end if;
+ return jsonb_build_object('id', v_id, 'revision', 1, 'relation_id', v_relation_id);
+end;
+$$;
+
+create or replace function public.update_animal(
+ animal_id uuid,
+ expected_revision integer,
+ name text,
+ species_id text,
+ sex text,
+ species_detail text,
+ breed text,
+ birth_year text,
+ birth_date text
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.animals;
+ v_sex public.animal_sex;
+ v_birth_year smallint;
+ v_birth_date date;
+begin
+ select a.* into v_row
+ from public.animals a
+ where a.id = update_animal.animal_id
+ and a.workspace_id in (select private.writable_workspace_ids())
+ for update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ if v_row.archived_at is not null then
+ raise exception 'archived' using errcode = 'P0001';
+ end if;
+ if update_animal.expected_revision is distinct from v_row.revision then
+ raise exception 'conflict' using errcode = 'P0001';
+ end if;
+
+ begin
+ v_sex := update_animal.sex::public.animal_sex;
+ exception when invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+ v_birth_year := private.parse_birth_year(update_animal.birth_year);
+ v_birth_date := private.parse_record_date(update_animal.birth_date);
+ -- A species may stay as it is; a new one must be active.
+ if update_animal.species_id is distinct from v_row.species_id
+ and not exists (select 1 from public.species s where s.id = update_animal.species_id and s.active) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+
+ -- No change: nothing written, nothing counted.
+ if (update_animal.name, update_animal.species_id, v_sex, update_animal.species_detail, update_animal.breed,
+ v_birth_year, v_birth_date)
+ is not distinct from
+ (v_row.name, v_row.species_id, v_row.sex, v_row.species_detail, v_row.breed,
+ v_row.birth_year, v_row.birth_date) then
+ return jsonb_build_object('revision', v_row.revision);
+ end if;
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ begin
+ update public.animals a
+ set name = update_animal.name, species_id = update_animal.species_id, sex = v_sex,
+ species_detail = update_animal.species_detail, breed = update_animal.breed,
+ birth_year = v_birth_year, birth_date = v_birth_date,
+ revision = a.revision + 1
+ where a.id = v_row.id;
+ exception when check_violation or not_null_violation or string_data_right_truncation
+ or invalid_text_representation or foreign_key_violation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'animal.updated', 'animal', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+create or replace function public.set_animal_archived(
+ animal_id uuid,
+ archived boolean
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.animals;
+begin
+ select a.* into v_row
+ from public.animals a
+ where a.id = set_animal_archived.animal_id
+ and a.workspace_id in (select private.writable_workspace_ids())
+ for update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ if set_animal_archived.archived is null then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ -- Already in that state: nothing written, nothing counted. The relations
+ -- stay as they are either way (§7.1).
+ if (v_row.archived_at is not null) = set_animal_archived.archived then
+ return jsonb_build_object('revision', v_row.revision);
+ end if;
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ update public.animals a
+ set archived_at = case when set_animal_archived.archived then now() end,
+ revision = a.revision + 1
+ where a.id = v_row.id;
+
+ perform private.log_event(
+ auth.uid(),
+ case when set_animal_archived.archived then 'animal.archived' else 'animal.restored' end,
+ 'animal', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+-- ---------------------------------------------------------------------------
+-- Relation write RPCs. The animal's workspace is found among the caller's
+-- writable ones without a lock, then the locks follow the one order: the
+-- workspace (create only: the workspace cap), the animal, the relation, the
+-- client (create only, shared), the budget last.
+-- ---------------------------------------------------------------------------
+create or replace function public.create_animal_client_relation(
+ animal_id uuid,
+ client_id uuid,
+ create_request_id uuid,
+ relation_role text,
+ started_on text default null
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_workspace_id uuid;
+ v_animal_archived_at timestamptz;
+ v_client_archived_at timestamptz;
+ v_role public.animal_relation_role;
+ v_started_on date;
+ v_digest bytea;
+ v_existing_id uuid;
+ v_existing_revision integer;
+ v_existing_digest bytea;
+ v_id uuid;
+begin
+ select a.workspace_id into v_workspace_id
+ from public.animals a
+ where a.id = create_animal_client_relation.animal_id
+ and a.workspace_id in (select private.writable_workspace_ids());
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ perform 1 from public.workspaces w where w.id = v_workspace_id for no key update;
+ select a.archived_at into v_animal_archived_at
+ from public.animals a
+ where a.id = create_animal_client_relation.animal_id
+ and a.workspace_id = v_workspace_id
+ for update;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ -- The client must be of the animal's workspace: any other is unknown.
+ select c.archived_at into v_client_archived_at
+ from public.clients c
+ where c.id = create_animal_client_relation.client_id
+ and c.workspace_id = v_workspace_id
+ for share;
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+
+ begin
+ v_role := create_animal_client_relation.relation_role::public.animal_relation_role;
+ exception when invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+ if v_role is null then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ v_started_on := private.parse_record_date(create_animal_client_relation.started_on);
+ v_digest := sha256(convert_to(jsonb_build_array(
+ create_animal_client_relation.animal_id, create_animal_client_relation.client_id, v_role, v_started_on
+ )::text, 'UTF8'));
+
+ -- A replay answers the relation it created, whatever happened since.
+ select r.id, r.revision, r.create_request_digest
+ into v_existing_id, v_existing_revision, v_existing_digest
+ from public.animal_client_relations r
+ where r.workspace_id = v_workspace_id
+ and r.create_request_id = create_animal_client_relation.create_request_id;
+ if found then
+ if v_existing_digest <> v_digest then
+ raise exception 'request_conflict' using errcode = 'P0001';
+ end if;
+ return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision);
+ end if;
+
+ if v_animal_archived_at is not null or v_client_archived_at is not null then
+ raise exception 'archived' using errcode = 'P0001';
+ end if;
+ if exists (select 1 from public.animal_client_relations r
+ where r.animal_id = create_animal_client_relation.animal_id
+ and r.client_id = create_animal_client_relation.client_id
+ and r.relation_role = v_role
+ and r.ended_at is null and r.voided_at is null) then
+ raise exception 'duplicate_relation' using errcode = 'P0001';
+ end if;
+ -- Current relations count against 20; every row, ended and voided included,
+ -- against 200 per animal and 100 000 per workspace (a create-and-void loop
+ -- cannot grow the table without bound).
+ if (select count(*) from public.animal_client_relations r
+ where r.workspace_id = v_workspace_id and r.animal_id = create_animal_client_relation.animal_id
+ and r.ended_at is null and r.voided_at is null) >= 20
+ or (select count(*) from public.animal_client_relations r
+ where r.workspace_id = v_workspace_id and r.animal_id = create_animal_client_relation.animal_id) >= 200
+ or (select count(*) from public.animal_client_relations r
+ where r.workspace_id = v_workspace_id) >= 100000 then
+ raise exception 'limit_reached' using errcode = 'P0001';
+ end if;
+
+ perform private.consume_write_budget(v_workspace_id);
+ begin
+ insert into public.animal_client_relations (
+ workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest
+ )
+ values (
+ v_workspace_id, create_animal_client_relation.animal_id, create_animal_client_relation.client_id,
+ v_role, v_started_on, create_animal_client_relation.create_request_id, v_digest
+ )
+ returning id into v_id;
+ exception
+ when check_violation or not_null_violation or string_data_right_truncation
+ or invalid_text_representation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ when unique_violation then
+ raise exception 'duplicate_relation' using errcode = 'P0001';
+ when foreign_key_violation then
+ raise exception 'not_found' using errcode = '42501';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'animal_client_relation.created', 'animal_client_relation', v_id, null, null,
+ jsonb_build_object('workspace_id', v_workspace_id)
+ );
+ return jsonb_build_object('id', v_id, 'revision', 1);
+end;
+$$;
+
+-- Shared opening of the three RPCs that change an existing relation: find it
+-- among the caller's writable workspaces, lock its animal then the relation,
+-- refuse an archived animal, a stale revision and a voided relation. Returns
+-- the locked relation row.
+create or replace function private.lock_relation_for_write(p_relation_id uuid, p_expected_revision integer)
+returns public.animal_client_relations
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+declare
+ v_workspace_id uuid;
+ v_animal_id uuid;
+ v_animal_archived_at timestamptz;
+ v_row public.animal_client_relations;
+begin
+ select r.workspace_id, r.animal_id into v_workspace_id, v_animal_id
+ from public.animal_client_relations r
+ where r.id = p_relation_id
+ and r.workspace_id in (select private.writable_workspace_ids());
+ if not found then
+ raise exception 'not_found' using errcode = '42501';
+ end if;
+ select a.archived_at into v_animal_archived_at
+ from public.animals a
+ where a.id = v_animal_id and a.workspace_id = v_workspace_id
+ for update;
+ select r.* into v_row
+ from public.animal_client_relations r
+ where r.id = p_relation_id
+ for update;
+ -- The relations of an archived animal are frozen (§7.1).
+ if v_animal_archived_at is not null then
+ raise exception 'archived' using errcode = 'P0001';
+ end if;
+ if p_expected_revision is distinct from v_row.revision then
+ raise exception 'conflict' using errcode = 'P0001';
+ end if;
+ -- A voided relation keeps its state: no end, no date change, no un-voiding (N4).
+ if v_row.voided_at is not null then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ return v_row;
+end;
+$$;
+
+comment on function private.lock_relation_for_write(uuid, integer) is
+ 'Authorises and locks (animal, then relation) a relation write; refuses not_found, archived, conflict, voided. For the relation RPCs only.';
+
+create or replace function public.end_animal_client_relation(
+ relation_id uuid,
+ expected_revision integer,
+ ended_on text default null
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.animal_client_relations;
+ v_ended_on date;
+begin
+ v_row := private.lock_relation_for_write(end_animal_client_relation.relation_id,
+ end_animal_client_relation.expected_revision);
+ if v_row.ended_at is not null then
+ raise exception 'already_ended' using errcode = 'P0001';
+ end if;
+ v_ended_on := private.parse_record_date(end_animal_client_relation.ended_on);
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ begin
+ update public.animal_client_relations r
+ set ended_at = now(), ended_on = v_ended_on, revision = r.revision + 1
+ where r.id = v_row.id;
+ exception when check_violation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'animal_client_relation.ended', 'animal_client_relation', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+create or replace function public.update_animal_client_relation(
+ relation_id uuid,
+ expected_revision integer,
+ started_on text,
+ ended_on text
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.animal_client_relations;
+ v_started_on date;
+ v_ended_on date;
+begin
+ v_row := private.lock_relation_for_write(update_animal_client_relation.relation_id,
+ update_animal_client_relation.expected_revision);
+ v_started_on := private.parse_record_date(update_animal_client_relation.started_on);
+ v_ended_on := private.parse_record_date(update_animal_client_relation.ended_on);
+ -- An end date belongs to an ended relation only.
+ if v_row.ended_at is null and v_ended_on is not null then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ if (v_started_on, v_ended_on) is not distinct from (v_row.started_on, v_row.ended_on) then
+ return jsonb_build_object('revision', v_row.revision);
+ end if;
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ begin
+ update public.animal_client_relations r
+ set started_on = v_started_on, ended_on = v_ended_on, revision = r.revision + 1
+ where r.id = v_row.id;
+ exception when check_violation then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end;
+
+ perform private.log_event(
+ auth.uid(), 'animal_client_relation.updated', 'animal_client_relation', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+create or replace function public.void_animal_client_relation(
+ relation_id uuid,
+ expected_revision integer
+)
+returns jsonb
+language plpgsql
+volatile
+security definer
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_row public.animal_client_relations;
+begin
+ v_row := private.lock_relation_for_write(void_animal_client_relation.relation_id,
+ void_animal_client_relation.expected_revision);
+
+ perform private.consume_write_budget(v_row.workspace_id);
+ -- Every value stays as entered; the row leaves the lists, the current
+ -- index, the derived values and the current cap (N4).
+ update public.animal_client_relations r
+ set voided_at = now(), revision = r.revision + 1
+ where r.id = v_row.id;
+
+ perform private.log_event(
+ auth.uid(), 'animal_client_relation.voided', 'animal_client_relation', v_row.id, null, null,
+ jsonb_build_object('workspace_id', v_row.workspace_id)
+ );
+ return jsonb_build_object('revision', v_row.revision + 1);
+end;
+$$;
+
+-- ---------------------------------------------------------------------------
+-- Reads (contract §9.3): security invoker, so RLS limits them to the caller's
+-- workspaces; called with POST, so terms and cursors stay out of URLs. Voided
+-- relations are left out of every list and derived value.
+-- ---------------------------------------------------------------------------
+-- The species filter is `species_filter`: a parameter cannot share the name
+-- of the `species_id` output column.
+create or replace function public.search_animals(
+ workspace_id uuid,
+ query text default '',
+ species_filter text default null,
+ archived boolean default false,
+ page_size integer default 25,
+ after_name_key text default null,
+ after_id uuid default null
+)
+returns table (
+ id uuid,
+ name text,
+ species_id text,
+ species_detail text,
+ sex public.animal_sex,
+ breed text,
+ birth_year smallint,
+ archived_at timestamptz,
+ name_key text,
+ current_owners jsonb,
+ current_owner_count integer
+)
+language plpgsql
+stable
+security invoker
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_term text := btrim(coalesce(search_animals.query, ''));
+ v_pattern text;
+begin
+ if char_length(v_term) > 100
+ or search_animals.archived is null
+ or search_animals.page_size is null
+ or search_animals.page_size not between 1 and 100
+ or (search_animals.after_name_key is null) <> (search_animals.after_id is null) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+ v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%';
+
+ return query
+ with page as (
+ select a.id, a.workspace_id, a.name, a.species_id, a.species_detail, a.sex, a.breed, a.birth_year,
+ a.archived_at, a.name_key
+ from public.animals a
+ where a.workspace_id = search_animals.workspace_id
+ and (a.archived_at is not null) = search_animals.archived
+ and (search_animals.species_filter is null or a.species_id = search_animals.species_filter)
+ and (v_term = '' or a.search_key like v_pattern)
+ and (search_animals.after_name_key is null
+ or (a.name_key, a.id) > (search_animals.after_name_key collate "C", search_animals.after_id))
+ order by a.name_key, a.id
+ limit search_animals.page_size
+ )
+ select p.id, p.name, p.species_id, p.species_detail, p.sex, p.breed, p.birth_year, p.archived_at, p.name_key,
+ o.owners, o.owner_count
+ from page p
+ cross join lateral (
+ select coalesce(jsonb_agg(jsonb_build_object('client_id', x.client_id, 'display_name', x.display_name,
+ 'archived', x.archived)
+ order by x.name_key, x.client_id) filter (where x.rank <= 3), '[]'::jsonb) as owners,
+ count(*)::integer as owner_count
+ from (
+ select c.id as client_id, c.display_name, c.archived_at is not null as archived, c.name_key,
+ row_number() over (order by c.name_key, c.id) as rank
+ from public.animal_client_relations r
+ join public.clients c on c.workspace_id = r.workspace_id and c.id = r.client_id
+ where r.workspace_id = p.workspace_id and r.animal_id = p.id
+ and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null
+ ) x
+ ) o
+ order by p.name_key, p.id;
+end;
+$$;
+
+-- A client's relations with their animals: current first, then former, each
+-- group in animal name order, then relation id. `sort_key` is the cursor:
+-- '0' (current) or '1' (former) followed by the animal's name_key.
+create or replace function public.list_client_animals(
+ client_id uuid,
+ page_size integer default 50,
+ after_sort text default null,
+ after_id uuid default null
+)
+returns table (
+ relation_id uuid,
+ relation_role public.animal_relation_role,
+ started_on date,
+ ended_on date,
+ is_current boolean,
+ relation_revision integer,
+ animal_id uuid,
+ animal_name text,
+ species_id text,
+ species_detail text,
+ sex public.animal_sex,
+ breed text,
+ birth_year smallint,
+ animal_archived_at timestamptz,
+ sort_key text
+)
+language plpgsql
+stable
+security invoker
+set search_path = ''
+as $$
+#variable_conflict use_column
+begin
+ if list_client_animals.page_size is null
+ or list_client_animals.page_size not between 1 and 100
+ or (list_client_animals.after_sort is null) <> (list_client_animals.after_id is null) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+
+ return query
+ select s.relation_id, s.relation_role, s.started_on, s.ended_on, s.is_current, s.relation_revision,
+ s.animal_id, s.animal_name, s.species_id, s.species_detail, s.sex, s.breed, s.birth_year,
+ s.animal_archived_at, s.sort_key
+ from (
+ select r.id as relation_id, r.relation_role, r.started_on, r.ended_on, r.ended_at is null as is_current,
+ r.revision as relation_revision, a.id as animal_id, a.name as animal_name, a.species_id,
+ a.species_detail, a.sex, a.breed, a.birth_year, a.archived_at as animal_archived_at,
+ ((case when r.ended_at is null then '0' else '1' end) || a.name_key) collate "C" as sort_key
+ from public.animal_client_relations r
+ join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id
+ where r.client_id = list_client_animals.client_id
+ and r.voided_at is null
+ ) s
+ where list_client_animals.after_sort is null
+ or (s.sort_key, s.relation_id) > (list_client_animals.after_sort collate "C", list_client_animals.after_id)
+ order by s.sort_key, s.relation_id
+ limit list_client_animals.page_size;
+end;
+$$;
+
+-- Before archiving a client: the active animals for which it holds the only
+-- current owner relation (no other client, archived or not, has one).
+create or replace function public.client_archive_preview(client_id uuid)
+returns jsonb
+language plpgsql
+stable
+security invoker
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_count integer;
+ v_animals jsonb;
+begin
+ with sole as (
+ select a.id, a.name, a.name_key
+ from public.animal_client_relations r
+ join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id
+ where r.client_id = client_archive_preview.client_id
+ and r.relation_role = 'owner' and r.ended_at is null and r.voided_at is null
+ and a.archived_at is null
+ and not exists (
+ select 1 from public.animal_client_relations o
+ where o.workspace_id = r.workspace_id and o.animal_id = r.animal_id
+ and o.relation_role = 'owner' and o.ended_at is null and o.voided_at is null
+ and o.client_id <> r.client_id
+ )
+ )
+ select (select count(*)::integer from sole),
+ coalesce((select jsonb_agg(jsonb_build_object('id', f.id, 'name', f.name) order by f.name_key, f.id)
+ from (select * from sole order by sole.name_key, sole.id limit 10) f), '[]'::jsonb)
+ into v_count, v_animals;
+ return jsonb_build_object('count', v_count, 'animals', v_animals);
+end;
+$$;
+
+-- search_clients gains current_animal_count (contract §9.3): a return type
+-- change, so the function is dropped and created again with the same
+-- parameters, rules and privileges.
+drop function public.search_clients(uuid, text, boolean, integer, text, uuid);
+
+create function public.search_clients(
+ workspace_id uuid,
+ query text default '',
+ archived boolean default false,
+ page_size integer default 25,
+ after_name_key text default null,
+ after_id uuid default null
+)
+returns table (
+ id uuid,
+ kind public.client_kind,
+ display_name text,
+ city text,
+ phone text,
+ email text,
+ archived_at timestamptz,
+ name_key text,
+ current_animal_count integer
+)
+language plpgsql
+stable
+security invoker
+set search_path = ''
+as $$
+#variable_conflict use_column
+declare
+ v_term text := btrim(coalesce(search_clients.query, ''));
+ v_pattern text;
+ v_digits text;
+begin
+ if char_length(v_term) > 100
+ or search_clients.archived is null
+ or search_clients.page_size is null
+ or search_clients.page_size not between 1 and 100
+ or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then
+ raise exception 'invalid_input' using errcode = 'P0001';
+ end if;
+
+ -- Folded term inside search_key; LIKE wildcards escaped, backslash first.
+ v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%';
+ -- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits)
+ -- is also looked for in phone_digits, without one leading 0.
+ if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then
+ v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', '');
+ end if;
+
+ return query
+ with page as (
+ select c.id, c.workspace_id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key
+ from public.clients c
+ where c.workspace_id = search_clients.workspace_id
+ and (c.archived_at is not null) = search_clients.archived
+ and (v_term = ''
+ or c.search_key like v_pattern
+ or (v_digits is not null and c.phone_digits like '%' || v_digits || '%'))
+ and (search_clients.after_name_key is null
+ or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id))
+ order by c.name_key, c.id
+ limit search_clients.page_size
+ )
+ -- Distinct animals of the current relations (any role, not voided), active animals only.
+ select p.id, p.kind, p.display_name, p.city, p.phone, p.email, p.archived_at, p.name_key,
+ (select count(distinct r.animal_id)::integer
+ from public.animal_client_relations r
+ join public.animals a on a.workspace_id = r.workspace_id and a.id = r.animal_id
+ where r.workspace_id = p.workspace_id and r.client_id = p.id
+ and r.ended_at is null and r.voided_at is null and a.archived_at is null)
+ from page p
+ order by p.name_key, p.id;
+end;
+$$;
+
+comment on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text) is
+ 'Creates an animal in a writable workspace, with an optional initial relation; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision, relation_id}.';
+comment on function public.update_animal(uuid, integer, text, text, text, text, text, text, text) is
+ 'Replaces the seven fields of an active animal at expected_revision. Returns {revision}.';
+comment on function public.set_animal_archived(uuid, boolean) is
+ 'Archives or restores an animal (same state: no write); its relations are kept. Returns {revision}.';
+comment on function public.create_animal_client_relation(uuid, uuid, uuid, text, text) is
+ 'Creates a current relation between an active animal and an active client of one workspace; idempotent by create_request_id. Returns {id, revision}.';
+comment on function public.end_animal_client_relation(uuid, integer, text) is
+ 'Ends a current relation (ended_at = now, optional ended_on). Returns {revision}.';
+comment on function public.update_animal_client_relation(uuid, integer, text, text) is
+ 'Corrects the dates of a relation that is not voided. Returns {revision}.';
+comment on function public.void_animal_client_relation(uuid, integer) is
+ 'Voids a relation entered by mistake (N4): kept, frozen, left out of lists and derived values. Returns {revision}.';
+comment on function public.search_animals(uuid, text, text, boolean, integer, text, uuid) is
+ 'Folded search (name, breed, species detail) in one workspace, optional species filter, keyset pages on (name_key, id), with the current owners.';
+comment on function public.list_client_animals(uuid, integer, text, uuid) is
+ 'A client''s relations with their animals, current then former, keyset on (sort_key, relation_id); 50 by default, 100 at most.';
+comment on function public.client_archive_preview(uuid) is
+ 'Active animals for which the client is the only current owner: {count, animals: first 10 by name}.';
+comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is
+ 'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most, with current_animal_count.';
+
+-- ---------------------------------------------------------------------------
+-- Privileges + RLS (N7: nothing for anon or service_role)
+-- ---------------------------------------------------------------------------
+revoke all on public.animals from public, anon, authenticated, service_role;
+grant select (
+ id, workspace_id, name, species_id, species_detail, sex, breed, birth_year, birth_date,
+ name_key, search_key, create_request_id, revision, archived_at, created_at, updated_at
+) on public.animals to authenticated;
+
+revoke all on public.animal_client_relations from public, anon, authenticated, service_role;
+grant select (
+ id, workspace_id, animal_id, client_id, relation_role, started_on, ended_on, ended_at, voided_at,
+ create_request_id, revision, created_at, updated_at
+) on public.animal_client_relations to authenticated;
+
+alter table public.animals enable row level security;
+alter table public.animal_client_relations enable row level security;
+
+create policy animals_select_member
+ on public.animals
+ for select
+ to authenticated
+ using (workspace_id in (select private.caller_workspace_ids()));
+
+create policy animal_client_relations_select_member
+ on public.animal_client_relations
+ for select
+ to authenticated
+ using (workspace_id in (select private.caller_workspace_ids()));
+
+revoke all on function private.utc_tomorrow(timestamptz) from public, anon, authenticated, service_role;
+revoke all on function private.parse_record_date(text) from public, anon, authenticated, service_role;
+revoke all on function private.parse_birth_year(text) from public, anon, authenticated, service_role;
+revoke all on function private.lock_relation_for_write(uuid, integer) from public, anon, authenticated, service_role;
+revoke all on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.update_animal(uuid, integer, text, text, text, text, text, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.set_animal_archived(uuid, boolean) from public, anon, authenticated, service_role;
+revoke all on function public.create_animal_client_relation(uuid, uuid, uuid, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.end_animal_client_relation(uuid, integer, text) from public, anon, authenticated, service_role;
+revoke all on function public.update_animal_client_relation(uuid, integer, text, text)
+ from public, anon, authenticated, service_role;
+revoke all on function public.void_animal_client_relation(uuid, integer) from public, anon, authenticated, service_role;
+revoke all on function public.search_animals(uuid, text, text, boolean, integer, text, uuid)
+ from public, anon, authenticated, service_role;
+revoke all on function public.list_client_animals(uuid, integer, text, uuid) from public, anon, authenticated, service_role;
+revoke all on function public.client_archive_preview(uuid) from public, anon, authenticated, service_role;
+revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid)
+ from public, anon, authenticated, service_role;
+
+grant execute on function public.create_animal(uuid, uuid, text, text, text, text, text, text, text, uuid, text, text) to authenticated;
+grant execute on function public.update_animal(uuid, integer, text, text, text, text, text, text, text) to authenticated;
+grant execute on function public.set_animal_archived(uuid, boolean) to authenticated;
+grant execute on function public.create_animal_client_relation(uuid, uuid, uuid, text, text) to authenticated;
+grant execute on function public.end_animal_client_relation(uuid, integer, text) to authenticated;
+grant execute on function public.update_animal_client_relation(uuid, integer, text, text) to authenticated;
+grant execute on function public.void_animal_client_relation(uuid, integer) to authenticated;
+grant execute on function public.search_animals(uuid, text, text, boolean, integer, text, uuid) to authenticated;
+grant execute on function public.list_client_animals(uuid, integer, text, uuid) to authenticated;
+grant execute on function public.client_archive_preview(uuid) to authenticated;
+grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated;
diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql
index 0f99835a..37283f66 100644
--- a/supabase/tests/001_schema.sql
+++ b/supabase/tests/001_schema.sql
@@ -62,7 +62,7 @@ select is(
(select string_agg(p.proname::text, ',' order by p.proname::text collate "C")
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')),
- 'can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
+ 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,fold_text,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
'authenticated executes only the policy predicates in private'
);
diff --git a/supabase/tests/007_equine_seed.sql b/supabase/tests/007_equine_seed.sql
index 0826250c..1923ab6b 100644
--- a/supabase/tests/007_equine_seed.sql
+++ b/supabase/tests/007_equine_seed.sql
@@ -2,7 +2,7 @@
-- present as a platform-owned DRAFT, never published by the seed, publishable
-- by platform admins only, content accepted by the SQL referential gate.
begin;
-select plan(19);
+select plan(20);
insert into auth.users (id, email) values
('40000000-0000-0000-0000-000000000001', 'root-seed@test.local'),
@@ -81,13 +81,27 @@ select is((select count(*) from public.anatomical_sheet_versions where id = pg_t
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('draft')) $$, 'a platform admin could publish it (rolled back here)');
-- 3. Storage: the seed registers metadata only; after the operator upload + confirmation,
--- a platform admin reads the object and a plain user none.
+-- a platform admin reads the object and a plain user none. A base where the operator
+-- already uploaded and confirmed the drawing (DEV) is brought back to the seed's state
+-- inside this transaction: the confirmation is cleared, and the object already in the
+-- bucket stands for the upload (content-addressed key, never written twice). Reads are
+-- counted on the seed's own key: other objects of the bucket do not count.
reset role;
+create table pg_temp.seed_objects as
+ select a.sha256 || '.svg' as name from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet');
+grant select on pg_temp.seed_objects to authenticated, service_role;
+update public.anatomical_sheet_assets set uploaded_at = null where sheet_id = pg_temp.id('sheet');
insert into storage.objects (bucket_id, name)
- select 'anatomical-sheet-assets', a.sha256 || '.svg' from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet');
+ select 'anatomical-sheet-assets', k.name from pg_temp.seed_objects k
+ where not exists (select 1 from storage.objects o where o.bucket_id = 'anatomical-sheet-assets' and o.name = k.name);
+select is(
+ (select count(*) from storage.objects o join pg_temp.seed_objects k on k.name = o.name where o.bucket_id = 'anatomical-sheet-assets'),
+ 1::bigint, 'the drawing is in the bucket once, under its content address'
+);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
-select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'seed objects are not readable before confirmation');
+select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets' and name in (select name from pg_temp.seed_objects)),
+ 0::bigint, 'seed objects are not readable before confirmation');
set local role service_role;
select is(
(select count(*) from public.anatomical_sheet_assets a where a.sheet_id = pg_temp.id('sheet')
@@ -96,9 +110,11 @@ select is(
);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
-select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 1::bigint, 'a platform admin reads the official SVG');
+select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets' and name in (select name from pg_temp.seed_objects)),
+ 1::bigint, 'a platform admin reads the official SVG');
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
-select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets'), 0::bigint, 'a plain user reads no official draft SVG');
+select is((select count(*) from storage.objects where bucket_id = 'anatomical-sheet-assets' and name in (select name from pg_temp.seed_objects)),
+ 0::bigint, 'a plain user reads no official draft SVG');
select * from finish();
rollback;
diff --git a/supabase/tests/010_files_foundation.sql b/supabase/tests/010_files_foundation.sql
index 7389470c..cbcced63 100644
--- a/supabase/tests/010_files_foundation.sql
+++ b/supabase/tests/010_files_foundation.sql
@@ -2,7 +2,7 @@
-- browser and worker RPCs, the purge queue. Every allowed path has its denial
-- twin; the eight scenarios of the Step 8 brief are named in the descriptions.
begin;
-select plan(140);
+select plan(141);
insert into auth.users (id, email) values
('40000000-0000-0000-0000-00000000000a', 'alice-files@test.local'),
@@ -18,6 +18,32 @@ grant all on pg_temp.ids to anon, authenticated, service_role;
grant execute on function pg_temp.id(text) to anon, authenticated, service_role;
grant execute on function pg_temp.row(text) to anon, authenticated, service_role;
+-- ---------------------------------------------------------------------------
+-- 0. Work the base already holds
+-- ---------------------------------------------------------------------------
+-- A used stack (DEV) can hold due purge entries, uploaded avatars waiting for
+-- the worker and uploads begun more than 24 h ago. The worker RPCs serve the
+-- whole queue, oldest first: that work is leased (or expired) here, inside
+-- this transaction and rolled back with it, so the queue assertions below
+-- count this file's rows only. A clean base has nothing to lease.
+set local role service_role;
+select set_config('request.jwt.claims', '{"role":"service_role"}', true);
+do $$
+begin
+ for i in 1..1000 loop
+ exit when not exists (select 1 from public.claim_purges(100))
+ and not exists (select 1 from public.claim_avatar_jobs(10));
+ end loop;
+ perform public.expire_pending_uploads(86400);
+end $$;
+select ok(
+ not exists (select 1 from public.claim_purges(100))
+ and not exists (select 1 from public.claim_avatar_jobs(10))
+ and public.expire_pending_uploads(86400) = 0,
+ 'setup: the base holds no claimable purge entry, avatar job or stale upload of its own'
+);
+reset role;
+
-- ---------------------------------------------------------------------------
-- 1. Buckets and the policy census
-- ---------------------------------------------------------------------------
@@ -414,12 +440,19 @@ select is(
-- ---------------------------------------------------------------------------
-- Objects still present under quarantine/: a1 (its row no longer references
-- it), a2, a3, a4, a5, a6, a7 (terminal rows). None pending or uploaded.
+-- The sweep reads the whole bucket and holds no lease: leftovers of the base
+-- (a used stack) are left out of the counts by this file's key prefix.
set local role service_role;
select set_config('request.jwt.claims', '{"role":"service_role"}', true);
-select is((select count(*) from public.claim_quarantine_leftovers(0, 100)), 7::bigint, 'every quarantine object without a waiting row is a leftover');
-select is((select count(*) from public.claim_quarantine_leftovers(0, 100) l where l.asset_id is null), 1::bigint,
- 'a leftover whose row forgot the key (purged earlier) has no asset_id');
-select is((select count(*) from public.claim_quarantine_leftovers(3600, 100)), 0::bigint, 'nothing younger than the grace is a leftover');
+select is((select count(*) from public.claim_quarantine_leftovers(0, 100) l
+ where l.object_name like 'quarantine/40000000-0000-0000-0000-00000000000_/%'),
+ 7::bigint, 'every quarantine object without a waiting row is a leftover');
+select is((select count(*) from public.claim_quarantine_leftovers(0, 100) l
+ where l.object_name like 'quarantine/40000000-0000-0000-0000-00000000000_/%' and l.asset_id is null),
+ 1::bigint, 'a leftover whose row forgot the key (purged earlier) has no asset_id');
+select is((select count(*) from public.claim_quarantine_leftovers(3600, 100) l
+ where l.object_name like 'quarantine/40000000-0000-0000-0000-00000000000_/%'),
+ 0::bigint, 'nothing younger than the grace is a leftover');
reset role;
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"40000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
diff --git a/supabase/tests/012_workspaces.sql b/supabase/tests/012_workspaces.sql
new file mode 100644
index 00000000..a9de24b1
--- /dev/null
+++ b/supabase/tests/012_workspaces.sql
@@ -0,0 +1,458 @@
+-- V1-1.1 Workspaces (M1): creation with the account, uniqueness, the commit
+-- invariant, the backfill, isolation between accounts, refusals for every
+-- other actor, privileges and the definer census, the audit correlation cap.
+-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8, §9, §12.1.
+-- Actors: A and B confirmed and active; C unconfirmed; D deactivated; S a
+-- platform owner; E an empty account deleted; F and G profiles created with
+-- the trigger disabled (backfill, invariant).
+begin;
+select plan(85);
+
+insert into auth.users (id, email, email_confirmed_at) values
+ ('50000000-0000-0000-0000-00000000000a', 'alice-ws@test.local', now()),
+ ('50000000-0000-0000-0000-00000000000b', 'bob-ws@test.local', now()),
+ ('50000000-0000-0000-0000-00000000000c', 'carol-ws@test.local', null),
+ ('50000000-0000-0000-0000-00000000000d', 'dave-ws@test.local', now()),
+ ('50000000-0000-0000-0000-000000000005', 'staff-ws@test.local', now()),
+ ('50000000-0000-0000-0000-00000000000e', 'empty-ws@test.local', now());
+update public.profiles set active = false where id = '50000000-0000-0000-0000-00000000000d';
+select private.assign_platform_role(null, '50000000-0000-0000-0000-000000000005', 'owner');
+
+-- Fixture readers usable from every role (pg_temp objects belong to postgres).
+create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer
+as $$ select id from public.workspaces where personal_user_id = p_user $$;
+create function pg_temp.act_as(p_user uuid) returns text language sql
+as $$ select set_config('request.jwt.claims',
+ json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$;
+create function pg_temp.writable() returns setof uuid language sql stable security definer
+as $$ select private.writable_workspace_ids() $$;
+create table pg_temp.audit_ids (key text primary key, id uuid not null);
+grant execute on function pg_temp.ws(uuid) to anon, authenticated, service_role;
+grant execute on function pg_temp.act_as(uuid) to anon, authenticated, service_role;
+grant execute on function pg_temp.writable() to anon, authenticated, service_role;
+
+-- ---------------------------------------------------------------------------
+-- 1. Schema
+-- ---------------------------------------------------------------------------
+select has_table('public', 'workspaces', 'table public.workspaces exists');
+select has_table('public', 'workspace_members', 'table public.workspace_members exists');
+select enum_has_labels('public', 'workspace_kind', array['personal'], 'workspace_kind: personal only (cabinet comes with its step)');
+select enum_has_labels('public', 'workspace_member_role', array['holder'], 'workspace_member_role: holder only (no unused cabinet role)');
+select ok((select relrowsecurity from pg_class where oid = 'public.workspaces'::regclass), 'RLS enabled on workspaces');
+select ok((select relrowsecurity from pg_class where oid = 'public.workspace_members'::regclass), 'RLS enabled on workspace_members');
+select is(
+ (select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C")
+ from pg_tables where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')),
+ 'workspace_members:postgres,workspaces:postgres', 'both tables belong to postgres (the migration role)'
+);
+
+-- ---------------------------------------------------------------------------
+-- 2. Creation with the account (sign-up chain auth.users -> profiles -> workspace)
+-- ---------------------------------------------------------------------------
+select is(
+ (select count(*) from public.workspaces where personal_user_id::text like '50000000-%'),
+ 6::bigint, 'every new account got a workspace, confirmed or not'
+);
+select results_eq(
+ $$ select kind::text, personal_user_id from public.workspaces
+ where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$,
+ $$ values ('personal'::text, '50000000-0000-0000-0000-00000000000a'::uuid) $$,
+ 'A has one personal workspace of its own'
+);
+select results_eq(
+ $$ select user_id, member_role::text from public.workspace_members
+ where workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000a') $$,
+ $$ values ('50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$,
+ 'the workspace of A has exactly A as holder'
+);
+select is(
+ (select count(*) from public.workspace_members m join public.workspaces w on w.id = m.workspace_id
+ where w.personal_user_id::text like '50000000-%' and m.user_id = w.personal_user_id and m.member_role = 'holder'),
+ 6::bigint, 'every fixture workspace has its account as holder'
+);
+select isnt(
+ pg_temp.ws('50000000-0000-0000-0000-00000000000a'), pg_temp.ws('50000000-0000-0000-0000-00000000000b'),
+ 'A and B have two distinct workspaces'
+);
+
+-- A sign-up that fails after the chain ran leaves no account, profile or workspace.
+select throws_ok(
+ $$ do $b$ begin
+ insert into auth.users (id, email, email_confirmed_at)
+ values ('50000000-0000-0000-0000-000000000099', 'boom-ws@test.local', now());
+ raise exception 'boom' using errcode = 'P0001';
+ end $b$ $$,
+ 'P0001', 'boom', 'a sign-up transaction that fails after the trigger raises'
+);
+select is(
+ (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000099'),
+ 0::bigint, 'no workspace survives the failed sign-up'
+);
+select is(
+ (select count(*) from public.profiles where id = '50000000-0000-0000-0000-000000000099'),
+ 0::bigint, 'no profile survives the failed sign-up'
+);
+
+-- ---------------------------------------------------------------------------
+-- 3. Uniqueness and idempotence
+-- ---------------------------------------------------------------------------
+select is(private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000a'), false,
+ 'a replayed creation for A writes nothing and says so');
+select is(
+ (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000a'),
+ 1::bigint, 'A still has one workspace after the replay'
+);
+select is(
+ (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a'),
+ 1::bigint, 'A still has one membership after the replay'
+);
+select throws_ok(
+ $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$,
+ '23505', null, 'a second personal workspace for A is refused by the unique key'
+);
+select throws_ok(
+ $$ insert into public.workspaces (kind, personal_user_id) values ('personal', null) $$,
+ '23514', null, 'a personal workspace without an account is refused'
+);
+select throws_ok(
+ $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-0000000000ff') $$,
+ '23503', null, 'a personal workspace for an unknown account is refused'
+);
+select throws_ok(
+ $$ insert into public.workspace_members (workspace_id, user_id, member_role)
+ values (gen_random_uuid(), '50000000-0000-0000-0000-00000000000a', 'holder') $$,
+ '23503', null, 'a membership of an unknown workspace is refused'
+);
+select throws_ok(
+ $$ insert into public.workspace_members (workspace_id, user_id, member_role)
+ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a', 'holder') $$,
+ '23505', null, 'a duplicate membership is refused by the primary key'
+);
+
+-- ---------------------------------------------------------------------------
+-- 4. Backfill of accounts created without the trigger (migration path)
+-- ---------------------------------------------------------------------------
+alter table public.profiles disable trigger profiles_create_personal_workspace;
+insert into auth.users (id, email, email_confirmed_at) values
+ ('50000000-0000-0000-0000-00000000000f', 'backfill-ws@test.local', now()),
+ ('50000000-0000-0000-0000-000000000010', 'invariant-ws@test.local', now());
+alter table public.profiles enable trigger profiles_create_personal_workspace;
+select is(pg_temp.ws('50000000-0000-0000-0000-00000000000f'), null, 'F has no workspace before the backfill');
+select is(private.backfill_personal_workspaces(), 2, 'the backfill creates the two missing workspaces');
+select is(private.backfill_personal_workspaces(), 0, 'a second backfill creates nothing');
+select results_eq(
+ $$ select m.user_id, m.member_role::text from public.workspace_members m
+ where m.workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000f') $$,
+ $$ values ('50000000-0000-0000-0000-00000000000f'::uuid, 'holder'::text) $$,
+ 'the backfilled workspace of F has F as holder'
+);
+
+-- ---------------------------------------------------------------------------
+-- 5. Commit invariant (checked here statement by statement)
+-- ---------------------------------------------------------------------------
+set constraints workspaces_personal_holder, workspace_members_personal_holder immediate;
+delete from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000010';
+select is(pg_temp.ws('50000000-0000-0000-0000-000000000010'), null, 'deleting a personal workspace takes its membership along');
+select throws_ok(
+ $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-000000000010') $$,
+ '23514', 'personal workspace must have exactly its account as holder',
+ 'a personal workspace without its holder cannot be committed'
+);
+select throws_ok(
+ $$ insert into public.workspace_members (workspace_id, user_id, member_role)
+ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$,
+ '23514', 'personal workspace must have exactly its account as holder',
+ 'B cannot be added to the personal workspace of A, even by the table owner'
+);
+select throws_ok(
+ $$ delete from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a' $$,
+ '23514', 'personal workspace must have exactly its account as holder',
+ 'the holder of a personal workspace cannot be removed alone'
+);
+select throws_ok(
+ $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-000000000010'
+ where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$,
+ '23514', 'personal workspace must have exactly its account as holder',
+ 'a personal workspace cannot be handed to another account'
+);
+select is(private.ensure_personal_workspace('50000000-0000-0000-0000-000000000010'), true,
+ 'the single write path passes the invariant (both rows in one statement)');
+set constraints all deferred;
+
+-- ---------------------------------------------------------------------------
+-- 6. Reading: each confirmed active account reads its own workspace only
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000a');
+select results_eq(
+ $$ select id, kind::text, personal_user_id from public.workspaces $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), 'personal'::text,
+ '50000000-0000-0000-0000-00000000000a'::uuid) $$,
+ 'A reads exactly its workspace'
+);
+select results_eq(
+ $$ select workspace_id, user_id, member_role::text from public.workspace_members $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$,
+ 'A reads exactly its membership (no RLS recursion)'
+);
+select is(
+ (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')),
+ 0::bigint, 'A reads nothing of the workspace of B by id'
+);
+select is(
+ (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000b'),
+ 0::bigint, 'A naming B as personal_user_id reads nothing'
+);
+select is(
+ (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000b'
+ or workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')),
+ 0::bigint, 'A reads no membership of B'
+);
+select results_eq(
+ $$ select private.caller_workspace_ids() $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$,
+ 'a direct call of the helper returns only what A may already read'
+);
+select results_eq(
+ $$ select pg_temp.writable() $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$,
+ 'A may write in its workspace (holder)'
+);
+
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000b');
+select results_eq(
+ $$ select id from public.workspaces $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000b')) $$,
+ 'B reads exactly its workspace'
+);
+select is(
+ (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000a')),
+ 0::bigint, 'B reads nothing of the workspace of A'
+);
+
+-- ---------------------------------------------------------------------------
+-- 7. Refused readers: unconfirmed, deactivated, platform staff
+-- ---------------------------------------------------------------------------
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000c');
+select is((select count(*) from public.workspaces), 0::bigint, 'C (email unconfirmed) reads no workspace, not even its own');
+select is((select count(*) from public.workspace_members), 0::bigint, 'C reads no membership');
+select is((select count(*) from private.caller_workspace_ids()), 0::bigint, 'C has no workspace for the helper');
+select is((select count(*) from pg_temp.writable()), 0::bigint, 'C may write nowhere');
+
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000d');
+select is((select count(*) from public.workspaces), 0::bigint, 'D (deactivated) reads no workspace, not even its own');
+select is((select count(*) from public.workspace_members), 0::bigint, 'D reads no membership');
+select is((select count(*) from pg_temp.writable()), 0::bigint, 'D may write nowhere');
+
+select pg_temp.act_as('50000000-0000-0000-0000-000000000005');
+select results_eq(
+ $$ select id from public.workspaces $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-000000000005')) $$,
+ 'S (platform owner) reads its own workspace only: no platform-role branch'
+);
+select is(
+ (select count(*) from public.workspace_members where user_id <> '50000000-0000-0000-0000-000000000005'),
+ 0::bigint, 'S reads no membership of another account'
+);
+reset role;
+
+-- The confirmation flow: confirming the email opens the existing workspace.
+update auth.users set email_confirmed_at = now() where id = '50000000-0000-0000-0000-00000000000c';
+set local role authenticated;
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000c');
+select results_eq(
+ $$ select id from public.workspaces $$,
+ $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000c')) $$,
+ 'once its email is confirmed, C reads the workspace created at sign-up'
+);
+
+-- ---------------------------------------------------------------------------
+-- 8. Refused writes and calls for an authenticated caller
+-- ---------------------------------------------------------------------------
+select pg_temp.act_as('50000000-0000-0000-0000-00000000000a');
+select throws_ok(
+ $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$,
+ '42501', 'permission denied for table workspaces', 'A cannot create a workspace'
+);
+select throws_ok(
+ $$ insert into public.workspace_members (workspace_id, user_id, member_role)
+ values (pg_temp.ws('50000000-0000-0000-0000-00000000000b'), '50000000-0000-0000-0000-00000000000a', 'holder') $$,
+ '42501', 'permission denied for table workspace_members', 'A cannot add itself to the workspace of B'
+);
+select throws_ok(
+ $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-00000000000b' $$,
+ '42501', 'permission denied for table workspaces', 'A cannot rewrite a workspace'
+);
+select throws_ok(
+ $$ update public.workspace_members set member_role = 'holder' $$,
+ '42501', 'permission denied for table workspace_members', 'A cannot rewrite a membership'
+);
+select throws_ok(
+ $$ delete from public.workspaces $$,
+ '42501', 'permission denied for table workspaces', 'A cannot delete a workspace'
+);
+select throws_ok(
+ $$ delete from public.workspace_members $$,
+ '42501', 'permission denied for table workspace_members', 'A cannot delete a membership'
+);
+select throws_ok(
+ $$ select private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000b') $$,
+ '42501', null, 'A cannot call the creation path, for itself or anyone'
+);
+select throws_ok(
+ $$ select private.backfill_personal_workspaces() $$,
+ '42501', null, 'A cannot run the backfill'
+);
+select throws_ok(
+ $$ select private.writable_workspace_ids() $$,
+ '42501', null, 'A cannot call the write helper directly'
+);
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 9. anon and service_role hold no privilege (refused by SQL, not by RLS)
+-- ---------------------------------------------------------------------------
+set local role anon;
+select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'anon cannot read workspaces');
+select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'anon cannot read memberships');
+select throws_ok($$ select private.caller_workspace_ids() $$, '42501', null, 'anon cannot call the access helper');
+reset role;
+
+set local role service_role;
+select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'service_role cannot read workspaces despite BYPASSRLS');
+select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'service_role cannot read memberships');
+select throws_ok(
+ $$ insert into public.workspace_members (workspace_id, user_id, member_role)
+ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$,
+ '42501', 'permission denied for table workspace_members', 'service_role cannot add a member'
+);
+select throws_ok($$ select private.backfill_personal_workspaces() $$, '42501', null, 'service_role cannot run the backfill');
+reset role;
+
+select is(
+ (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name)
+ cross join (values ('anon'), ('service_role')) r(role)
+ cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege(r.role, t.name, p.priv)),
+ 0::bigint, 'anon and service_role hold no table privilege on either table'
+);
+select is(
+ (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name)
+ cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege('authenticated', t.name, p.priv)),
+ 0::bigint, 'authenticated holds no write privilege on either table'
+);
+select ok(
+ has_column_privilege('authenticated', 'public.workspaces', 'personal_user_id', 'select')
+ and has_column_privilege('authenticated', 'public.workspace_members', 'member_role', 'select'),
+ 'authenticated selects the granted columns (RLS then filters rows)'
+);
+
+-- ---------------------------------------------------------------------------
+-- 10. Policies and definer functions
+-- ---------------------------------------------------------------------------
+select is(
+ (select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ','
+ order by tablename collate "C")
+ from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')),
+ 'workspace_members:workspace_members_select_member:SELECT:authenticated,workspaces:workspaces_select_member:SELECT:authenticated',
+ 'one SELECT policy per table, for authenticated only; no write policy'
+);
+select is(
+ (select count(*) from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')
+ and (qual not like '%caller_workspace_ids()%' or qual like '%platform%' or qual like '%support%')),
+ 0::bigint, 'both policies go through caller_workspace_ids() and name no platform role (D16)'
+);
+select is(
+ (select string_agg(p.proname::text, ',' order by p.proname::text collate "C")
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids',
+ 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids')
+ and p.prosecdef and p.proconfig = array['search_path=""']
+ and pg_get_userbyid(p.proowner) = 'postgres'),
+ 'backfill_personal_workspaces,caller_workspace_ids,check_personal_workspace,create_personal_workspace,ensure_personal_workspace,writable_workspace_ids',
+ 'the six workspace functions are security definer, owned by postgres, search_path empty'
+);
+select ok(
+ (select p.prosecdef and p.proconfig = array['search_path=""'] from pg_proc p
+ where p.oid = 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)'::regprocedure),
+ 'log_event keeps security definer and its empty search_path'
+);
+select is(
+ (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C")
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ cross join (values ('anon'), ('authenticated'), ('service_role')) r(role)
+ where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids',
+ 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids')
+ and has_function_privilege(r.role, p.oid, 'execute')),
+ 'authenticated:caller_workspace_ids',
+ 'EXECUTE: authenticated on the policy helper only; anon and service_role on none'
+);
+select ok(
+ has_function_privilege('service_role', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute')
+ and not has_function_privilege('authenticated', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute'),
+ 'log_event keeps the privileges of the foundation (service_role yes, authenticated no)'
+);
+select is(
+ (select count(*) from pg_trigger where not tgisinternal and tgdeferrable and tginitdeferred
+ and tgname in ('workspaces_personal_holder', 'workspace_members_personal_holder')),
+ 2::bigint, 'the invariant triggers are deferred to commit'
+);
+
+-- ---------------------------------------------------------------------------
+-- 11. Account deletion: an empty account takes its workspace along (D9a)
+-- ---------------------------------------------------------------------------
+set constraints workspaces_personal_holder, workspace_members_personal_holder immediate;
+select lives_ok(
+ $$ delete from auth.users where id = '50000000-0000-0000-0000-00000000000e' $$,
+ 'deleting an empty account passes the invariant'
+);
+select is(pg_temp.ws('50000000-0000-0000-0000-00000000000e'), null, 'its workspace is gone');
+select is(
+ (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000e'),
+ 0::bigint, 'its membership is gone'
+);
+set constraints all deferred;
+
+-- ---------------------------------------------------------------------------
+-- 12. Audit correlation id: kept only as a short token (contract §10, N9)
+-- ---------------------------------------------------------------------------
+select set_config('request.headers', '{"x-correlation-id":"req-7f3a-01"}', true);
+insert into pg_temp.audit_ids values ('valid', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 64))::text, true);
+insert into pg_temp.audit_ids values ('max', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 65))::text, true);
+insert into pg_temp.audit_ids values ('long', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', json_build_object('x-correlation-id', repeat('x', 8192))::text, true);
+insert into pg_temp.audit_ids values ('huge', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', '{"x-correlation-id":"a b"}', true);
+insert into pg_temp.audit_ids values ('space', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', '{"x-correlation-id":"abc\n"}', true);
+insert into pg_temp.audit_ids values ('newline', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', '{"x-correlation-id":{"nested":"x"}}', true);
+insert into pg_temp.audit_ids values ('object', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', '{}', true);
+insert into pg_temp.audit_ids values ('absent', private.log_event(null, 'workspace.probed', 'workspace'));
+select set_config('request.headers', '', true);
+
+select is(
+ (select correlation_id from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'valid')),
+ 'req-7f3a-01', 'a short token is kept'
+);
+select is(
+ (select char_length(correlation_id) from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'max')),
+ 64, 'a 64-character token is kept'
+);
+select is(
+ (select string_agg(i.key, ',' order by i.key collate "C") from pg_temp.audit_ids i
+ join audit.audit_logs a on a.id = i.id where a.correlation_id is null),
+ 'absent,huge,long,newline,object,space',
+ 'an oversized, malformed or absent correlation id is stored as null'
+);
+select throws_ok(
+ $$ insert into audit.audit_logs (action, resource_type, correlation_id) values ('workspace.probed', 'workspace', repeat('a', 65)) $$,
+ '23514', null, 'the CHECK refuses an oversized correlation id on a new row, whoever writes it'
+);
+
+select * from finish();
+rollback;
diff --git a/supabase/tests/013_clients.sql b/supabase/tests/013_clients.sql
new file mode 100644
index 00000000..92e6cbd2
--- /dev/null
+++ b/supabase/tests/013_clients.sql
@@ -0,0 +1,452 @@
+-- V1-1.2 Clients (M2): fields and text rules, idempotent creates, revisions,
+-- archive, search, isolation between workspaces, refusals for every other
+-- actor, caps and write budget, minimised audit, privileges and census.
+-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §9, §10, §12.1.
+-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after
+-- creating a client; S a platform owner; E (cap) and F (budget) confirmed;
+-- G an account without clients.
+begin;
+select plan(130);
+
+insert into auth.users (id, email, email_confirmed_at) values
+ ('60000000-0000-0000-0000-00000000000a', 'alice-cl@test.local', now()),
+ ('60000000-0000-0000-0000-00000000000b', 'bob-cl@test.local', now()),
+ ('60000000-0000-0000-0000-00000000000c', 'carol-cl@test.local', null),
+ ('60000000-0000-0000-0000-00000000000d', 'dave-cl@test.local', now()),
+ ('60000000-0000-0000-0000-000000000005', 'staff-cl@test.local', now()),
+ ('60000000-0000-0000-0000-00000000000e', 'cap-cl@test.local', now()),
+ ('60000000-0000-0000-0000-00000000000f', 'budget-cl@test.local', now()),
+ ('60000000-0000-0000-0000-000000000010', 'empty-cl@test.local', now());
+select private.assign_platform_role(null, '60000000-0000-0000-0000-000000000005', 'owner');
+
+create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer
+as $$ select id from public.workspaces where personal_user_id = p_user $$;
+create function pg_temp.act_as(p_user uuid) returns text language sql
+as $$ select set_config('request.jwt.claims',
+ json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$;
+create function pg_temp.client(p_id uuid) returns public.clients language sql stable security definer
+as $$ select c from public.clients c where c.id = p_id $$;
+create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer
+as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$;
+create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer
+as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$;
+-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint.
+create function pg_temp.err(p_sql text) returns text language plpgsql
+as $$
+declare v_state text; v_msg text; v_detail text; v_hint text;
+begin
+ execute p_sql;
+ return 'no error';
+exception when others then
+ get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text,
+ v_detail = pg_exception_detail, v_hint = pg_exception_hint;
+ return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, '');
+end;
+$$;
+-- SQLSTATE and message only: the real image appends a hint to table-privilege
+-- refusals ("Grant the required privileges ..."), PGlite does not.
+create function pg_temp.denial(p_sql text) returns text language sql
+as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$;
+create table pg_temp.ids (key text primary key, id uuid not null);
+grant all on pg_temp.ids to authenticated, anon, service_role;
+grant execute on function pg_temp.ws(uuid), pg_temp.act_as(uuid), pg_temp.client(uuid), pg_temp.budget(uuid),
+ pg_temp.audit_count(uuid), pg_temp.err(text), pg_temp.denial(text) to authenticated, anon, service_role;
+
+-- ---------------------------------------------------------------------------
+-- 1. Schema, privileges, census
+-- ---------------------------------------------------------------------------
+select has_table('public', 'clients', 'table public.clients exists');
+select ok((select relrowsecurity from pg_class where oid = 'public.clients'::regclass), 'RLS enabled on clients');
+select enum_has_labels('public', 'client_kind', array['person', 'organization'], 'client_kind: person, organization');
+select is((select tableowner::text from pg_tables where schemaname = 'public' and tablename = 'clients'), 'postgres', 'clients belongs to postgres');
+select is(
+ (select count(*) from (values ('anon'), ('service_role')) r(role)
+ cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege(r.role, 'public.clients', p.priv)),
+ 0::bigint, 'anon and service_role hold no privilege on clients'
+);
+select is(
+ (select count(*) from (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege('authenticated', 'public.clients', p.priv)),
+ 0::bigint, 'authenticated holds no write privilege on clients'
+);
+select ok(has_column_privilege('authenticated', 'public.clients', 'display_name', 'select')
+ and not has_column_privilege('authenticated', 'public.clients', 'create_request_digest', 'select'),
+ 'authenticated reads the record columns, never the request digest');
+select is(
+ (select count(*) from (values ('anon'), ('authenticated'), ('service_role')) r(role)
+ cross join (values ('select'), ('insert'), ('update'), ('delete')) p(priv)
+ where has_table_privilege(r.role, 'private.workspace_write_budgets', p.priv)),
+ 0::bigint, 'no API role touches the budget table'
+);
+select is(
+ (select string_agg(policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',')
+ from pg_policies where schemaname = 'public' and tablename = 'clients'),
+ 'clients_select_member:SELECT:authenticated', 'one SELECT policy on clients, for authenticated'
+);
+select is(
+ (select count(*) from pg_policies where schemaname = 'public' and tablename = 'clients'
+ and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')),
+ 0::bigint, 'the clients policy goes through caller_workspace_ids() and names no platform role'
+);
+select is(
+ (select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C")
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients',
+ 'fold_text', 'is_clean_text', 'consume_write_budget')
+ and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'),
+ 'consume_write_budget:definer,create_client:definer,fold_text:invoker,is_clean_text:invoker,search_clients:invoker,set_client_archived:definer,update_client:definer',
+ 'definer and invoker as designed; search_path empty; owner postgres'
+);
+select is(
+ (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C")
+ from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role)
+ where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients',
+ 'fold_text', 'is_clean_text', 'consume_write_budget')
+ and has_function_privilege(r.role, p.oid, 'execute')),
+ 'authenticated:create_client,authenticated:fold_text,authenticated:search_clients,authenticated:set_client_archived,authenticated:update_client',
+ 'EXECUTE: authenticated on the four RPCs and the fold; anon and service_role on none'
+);
+
+-- ---------------------------------------------------------------------------
+-- 2. Creation by A: fields, normalisation, derived keys
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000a');
+insert into pg_temp.ids values
+ ('lac', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000001',
+ 'organization', 'Écurie du Lac', 'contact@ecurie-lac.test', '+33612345678', '1 chemin du Lac', null, '69000', 'Lyon', 'FR') ->> 'id')::uuid),
+ ('marie', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
+ 'person', 'Marie Dupont', 'MARIE@Example.TEST', null, null, null, null, 'Évian') ->> 'id')::uuid),
+ ('ab', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000003', 'organization', 'A_B Haras') ->> 'id')::uuid),
+ ('axb', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000004', 'organization', 'AxB Haras') ->> 'id')::uuid),
+ ('pct', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000005', 'person', '100% Cheval') ->> 'id')::uuid),
+ ('bsl', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000006', 'person', 'Back\slash') ->> 'id')::uuid);
+
+select results_eq(
+ $$ select kind::text, display_name, email, phone, city, country, revision, archived_at is null
+ from public.clients where id = (select id from pg_temp.ids where key = 'lac') $$,
+ $$ values ('organization'::text, 'Écurie du Lac'::text, 'contact@ecurie-lac.test'::text, '+33612345678'::text,
+ 'Lyon'::text, 'FR'::text, 1, true) $$,
+ 'A reads the created organization with revision 1'
+);
+select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).email, 'marie@example.test', 'the email is stored lower-case');
+select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).name_key, 'ecurie du lac', 'name_key folds accents and case');
+select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).phone_digits, '33612345678', 'phone_digits drops the +');
+select is((pg_temp.client((select id from pg_temp.ids where key = 'ab'))).country, null, 'no country is set by default');
+select is((select count(*) from public.clients), 6::bigint, 'A reads its six clients');
+
+-- ---------------------------------------------------------------------------
+-- 3. Text rules: refused with the bare code, nothing echoed
+-- ---------------------------------------------------------------------------
+create function pg_temp.try_create(p_kind text, p_name text, p_email text default null, p_phone text default null,
+ p_postal text default null, p_country text default null) returns text language sql
+as $$ select pg_temp.err(format(
+ 'select public.create_client(%L, gen_random_uuid(), %L, %L, %L, %L, null, null, %L, null, %L)',
+ pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_kind, p_name, p_email, p_phone, p_postal, p_country)) $$;
+grant execute on function pg_temp.try_create(text, text, text, text, text, text) to authenticated;
+
+select is(pg_temp.try_create('person', ''), 'P0001|invalid_input||', 'an empty name is refused');
+select is(pg_temp.try_create('person', null), 'P0001|invalid_input||', 'a missing name is refused');
+select is(pg_temp.try_create('person', ' Lead'), 'P0001|invalid_input||', 'a leading space is refused');
+select is(pg_temp.try_create('person', e'Tab\there'), 'P0001|invalid_input||', 'a tab (control character) is refused');
+select is(pg_temp.try_create('person', e'Line\u2028sep'), 'P0001|invalid_input||', 'U+2028 is refused');
+select is(pg_temp.try_create('person', e'C1\u0085'), 'P0001|invalid_input||', 'a C1 control (U+0085) is refused');
+select is(pg_temp.try_create('person', repeat('x', 121)), 'P0001|invalid_input||', '121 characters are refused');
+select is(pg_temp.try_create('person', repeat('é', 121)), 'P0001|invalid_input||', '121 accented characters (code points) are refused');
+select is(pg_temp.try_create('robot', 'Kind'), 'P0001|invalid_input||', 'an unknown kind is refused');
+select is(pg_temp.try_create(null, 'Kind'), 'P0001|invalid_input||', 'a missing kind is refused');
+select is(pg_temp.try_create('person', 'Mail', 'not-an-email'), 'P0001|invalid_input||', 'a malformed email is refused');
+select is(pg_temp.try_create('person', 'Mail', 'a b@c.test'), 'P0001|invalid_input||', 'an email with a space is refused');
+select is(pg_temp.try_create('person', 'Mail', repeat('a', 247) || '@ex.test'), 'P0001|invalid_input||', 'a 255-character email is refused');
+select is(pg_temp.try_create('person', 'Mail', repeat('a', 246) || '@ex.test'), 'no error', 'a 254-character email is accepted');
+select is(pg_temp.try_create('person', 'Phone', null, '0612345678'), 'P0001|invalid_input||', 'a national phone (not E.164) is refused');
+select is(pg_temp.try_create('person', 'Postal', null, null, repeat('9', 17)), 'P0001|invalid_input||', 'a 17-character postal code is refused');
+select is(pg_temp.try_create('person', 'Country', null, null, null, 'fr'), 'P0001|invalid_input||', 'a lower-case country code is refused');
+select is(pg_temp.try_create('person', 'Country', null, null, null, 'FRA'), 'P0001|invalid_input||', 'a three-letter country code is refused');
+select is(pg_temp.try_create('person', repeat('é', 120)), 'no error', '120 accented characters are accepted');
+select is((select count(*) from public.clients), 8::bigint, 'only the two valid creates were written');
+
+-- ---------------------------------------------------------------------------
+-- 4. Idempotent create: replay, normalised replay, divergent replay
+-- ---------------------------------------------------------------------------
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'eight writes counted so far');
+select is(
+ (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
+ 'person', 'Marie Dupont', 'marie@example.test', null, null, null, null, 'Évian') ->> 'id')::uuid,
+ (select id from pg_temp.ids where key = 'marie'),
+ 'a replay (email in another case) returns the first client'
+);
+select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 1::bigint, 'the replay writes no audit row');
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'the replay consumes no budget');
+select is(
+ pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002',
+ 'person', 'Marie Durand') $$),
+ 'P0001|request_conflict||', 'the same request id with other content is refused'
+);
+select is((select count(*) from public.clients where display_name like 'Marie%'), 1::bigint, 'no divergent client was created');
+
+-- ---------------------------------------------------------------------------
+-- 5. Update, revision, archive
+-- ---------------------------------------------------------------------------
+select is(
+ public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie Dupont', 'marie@example.test',
+ '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update at the current revision gives revision 2');
+select is(
+ pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie D.',
+ null, null, null, null, null, null, null) $$),
+ 'P0001|conflict||', 'a stale revision is refused'
+);
+select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).city, 'Vevey', 'the stale update overwrote nothing');
+select is(
+ pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), null, 'person', 'Marie D.',
+ null, null, null, null, null, null, null) $$),
+ 'P0001|conflict||', 'a missing revision is refused'
+);
+select is(
+ public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', 'Marie Dupont', 'MARIE@example.test',
+ '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update that changes nothing keeps the revision');
+select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 2::bigint, 'and writes no audit row');
+select is(
+ pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', '',
+ null, null, null, null, null, null, null) $$),
+ 'P0001|invalid_input||', 'an update breaking a rule is refused'
+);
+select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving adds one revision');
+select ok((pg_temp.client((select id from pg_temp.ids where key = 'axb'))).archived_at is not null, 'the client is archived');
+select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving again changes nothing');
+select is(
+ pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'axb'), 1, 'organization', 'AxB',
+ null, null, null, null, null, null, null) $$),
+ 'P0001|archived||', 'an archived client refuses edits, archived reported before the stale revision'
+);
+select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'axb'), null) $$),
+ 'P0001|invalid_input||', 'a missing archive state is refused');
+
+-- ---------------------------------------------------------------------------
+-- 6. Search: folding, escaping, phone formats, filters, keyset pages
+-- ---------------------------------------------------------------------------
+create function pg_temp.names(p_query text, p_archived boolean default false, p_size integer default 25,
+ p_after_key text default null, p_after_id uuid default null) returns text language sql
+as $$ select coalesce(string_agg(s.display_name, '|' order by s.ord), '')
+ from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_query, p_archived, p_size,
+ p_after_key, p_after_id) with ordinality s(id, kind, display_name, city, phone, email,
+ archived_at, name_key, current_animal_count, ord) $$;
+grant execute on function pg_temp.names(text, boolean, integer, text, uuid) to authenticated;
+
+select is(pg_temp.names(''), '100% Cheval|A_B Haras|Back\slash|Écurie du Lac|' || repeat('é', 120) || '|Mail|Marie Dupont',
+ 'an empty term lists the active clients in name order (archived left out)');
+select is(pg_temp.names('', true), 'AxB Haras', 'the archived filter lists the archived client only');
+select is(pg_temp.names('ECU'), 'Écurie du Lac', 'search folds case and accents');
+select is(pg_temp.names('vevey'), 'Marie Dupont', 'search reads the city');
+select is(pg_temp.names('EXAMPLE.test'), 'Marie Dupont', 'search reads the email');
+select is(pg_temp.names('_'), 'A_B Haras', 'an underscore is a character, not a wildcard');
+select is(pg_temp.names('%'), '100% Cheval', 'a percent sign is a character, not a wildcard');
+select is(pg_temp.names('\'), 'Back\slash', 'a backslash is a character');
+select is(pg_temp.names('06 12'), 'Écurie du Lac', 'a national phone fragment finds the number');
+select is(pg_temp.names('0612345678'), 'Écurie du Lac', 'a full national number finds it');
+select is(pg_temp.names('+33 6 12'), 'Écurie du Lac', 'an international fragment finds it');
+select is(pg_temp.names('061'), '', 'fewer than four digits is not a phone search');
+select is(pg_temp.names(repeat('z', 100)), '', 'a 100-character term is accepted');
+select is(pg_temp.names('', false, 2), '100% Cheval|A_B Haras', 'page 1 of 2');
+select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'ab'))).name_key,
+ (select id from pg_temp.ids where key = 'ab')), 'Back\slash|Écurie du Lac', 'page 2 continues after the cursor, no gap, no repeat');
+select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'marie'))).name_key,
+ (select id from pg_temp.ids where key = 'marie')), '', 'after the last client the page is empty');
+select is(pg_temp.err($$ select pg_temp.names(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused');
+select is(pg_temp.err($$ select pg_temp.names('', false, 0) $$), 'P0001|invalid_input||', 'page size 0 is refused');
+select is(pg_temp.err($$ select pg_temp.names('', false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused');
+select is(pg_temp.err($$ select pg_temp.names('', false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
+select is(pg_temp.err($$ select pg_temp.names('', null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused');
+
+-- Restore: editable again, back in the default list.
+select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), false) ->> 'revision', '3', 'restoring adds one revision');
+select is(public.update_client((select id from pg_temp.ids where key = 'axb'), 3, 'organization', 'AxB Haras', null, null,
+ null, null, null, 'Annecy', null) ->> 'revision', '4', 'a restored client is editable');
+
+-- D creates a client while active (used after its deactivation).
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000d');
+insert into pg_temp.ids values ('dave', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000d'),
+ gen_random_uuid(), 'person', 'Client de Dave') ->> 'id')::uuid);
+reset role;
+update public.profiles set active = false where id = '60000000-0000-0000-0000-00000000000d';
+
+-- ---------------------------------------------------------------------------
+-- 7. Isolation: the same not_found for a foreign and an unknown id
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000b');
+select is((select count(*) from public.clients), 0::bigint, 'B reads no client');
+select is((select count(*) from public.clients where id = (select id from pg_temp.ids where key = 'lac')), 0::bigint,
+ 'B naming a client of A reads nothing');
+select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'))), 0::bigint,
+ 'B searching the workspace of A finds nothing');
+select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), gen_random_uuid(), 'person', 'X') $$),
+ pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
+ 'B creating in the workspace of A gets the error of an unknown workspace');
+select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
+ '42501|not_found||', 'that error is 42501 not_found, no detail, no hint');
+select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
+ pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
+ 'B updating a client of A gets the error of an unknown client');
+select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'lac'), true) $$),
+ '42501|not_found||', 'B archiving a client of A gets not_found');
+select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', '', null, null, null, null, null, null, null) $$),
+ '42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)');
+select is(pg_temp.denial($$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+ values (pg_temp.ws('60000000-0000-0000-0000-00000000000b'), 'person', 'Direct', gen_random_uuid(), '\x00') $$),
+ '42501|permission denied for table clients', 'a direct insert is refused by privilege');
+select is(pg_temp.denial($$ update public.clients set display_name = 'Direct' $$),
+ '42501|permission denied for table clients', 'a direct update is refused by privilege');
+select is(pg_temp.denial($$ delete from public.clients $$),
+ '42501|permission denied for table clients', 'a direct delete is refused by privilege');
+
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000c');
+select is((select count(*) from public.clients), 0::bigint, 'C (unconfirmed) reads no client');
+select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'person', 'X') $$),
+ '42501|not_found||', 'C cannot create, even in its own workspace');
+
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000d');
+select is((select count(*) from public.clients), 0::bigint, 'D (deactivated) no longer reads its own client');
+select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000d'))), 0::bigint,
+ 'D finds nothing through search');
+select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'dave'), true) $$),
+ '42501|not_found||', 'D cannot write its own client');
+
+select pg_temp.act_as('60000000-0000-0000-0000-000000000005');
+select is((select count(*) from public.clients), 0::bigint, 'S (platform owner) reads no client: no platform-role branch');
+select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
+ '42501|not_found||', 'S cannot write a client of A');
+reset role;
+
+set local role anon;
+select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', 'anon cannot read clients');
+select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$),
+ '42501|permission denied for function create_client||', 'anon cannot execute create_client');
+select is(pg_temp.err($$ select * from public.search_clients(gen_random_uuid()) $$),
+ '42501|permission denied for function search_clients||', 'anon cannot execute search_clients');
+reset role;
+set local role service_role;
+select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients',
+ 'service_role cannot read clients despite BYPASSRLS');
+select is(pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$),
+ '42501|permission denied for function update_client||', 'service_role cannot execute update_client');
+select is(pg_temp.err($$ select private.consume_write_budget(gen_random_uuid()) $$),
+ '42501|permission denied for function consume_write_budget||', 'service_role cannot touch the budget');
+reset role;
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000a');
+select is(pg_temp.err($$ select private.consume_write_budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')) $$),
+ '42501|permission denied for function consume_write_budget||', 'A cannot call the budget directly');
+select is(pg_temp.err($$ select private.is_clean_text('x', 1) $$),
+ '42501|permission denied for function is_clean_text||', 'A cannot call the text rule directly');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 8. Write budget per workspace (fixed UTC windows), refused writes not counted
+-- ---------------------------------------------------------------------------
+insert into private.workspace_write_budgets values
+ (pg_temp.ws('60000000-0000-0000-0000-00000000000f'), date_trunc('hour', now(), 'UTC'), 999, date_trunc('day', now(), 'UTC'), 999);
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
+insert into pg_temp.ids values ('f1', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'),
+ '62000000-0000-0000-0000-000000000001', 'person', 'Budget One') ->> 'id')::uuid);
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write of the hour passes');
+select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Two') $$),
+ 'P0001|rate_limited||', 'the 1 001st write of the hour is refused');
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the refused write consumed nothing');
+select is((public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), '62000000-0000-0000-0000-000000000001',
+ 'person', 'Budget One') ->> 'id')::uuid, (select id from pg_temp.ids where key = 'f1'), 'a replay at the limit still answers');
+select is(public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) ->> 'revision', '1',
+ 'a no-op at the limit still answers');
+select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$),
+ 'P0001|rate_limited||', 'an archive at the limit is refused');
+reset role;
+update private.workspace_write_budgets set hour_start = hour_start - interval '1 hour'
+where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f');
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
+select lives_ok($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$,
+ 'a new UTC hour restarts the hourly count');
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/1001', 'hour restarted at 1, the day keeps counting');
+reset role;
+update private.workspace_write_budgets set day_count = 5000 where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f');
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000f');
+select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) $$),
+ 'P0001|rate_limited||', 'the 5 001st write of the UTC day is refused');
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/5000', 'and consumed nothing');
+select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000b')), 'none', 'the budget of another workspace is untouched');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 9. Cap: 20 000 clients per workspace
+-- ---------------------------------------------------------------------------
+insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+select pg_temp.ws('60000000-0000-0000-0000-00000000000e'), 'person', 'Cap ' || g, gen_random_uuid(), '\x00'
+from generate_series(1, 19999) g;
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-00000000000e');
+select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'),
+ '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'the 20 000th client is accepted');
+select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'person', 'Cap over') $$),
+ 'P0001|limit_reached||', 'the 20 001st client is refused');
+select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'),
+ '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'a replay at the cap still answers');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 10. Audit: ids only, hidden from platform staff (N9)
+-- ---------------------------------------------------------------------------
+select is(
+ (select string_agg(action, ',' order by occurred_at, action) from audit.audit_logs
+ where resource_id = (select id from pg_temp.ids where key = 'axb')),
+ 'client.archived,client.created,client.restored,client.updated',
+ 'each write of a client leaves one audit row'
+);
+select is(
+ (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id
+ where a.metadata <> jsonb_build_object('workspace_id', pg_temp.ws('60000000-0000-0000-0000-00000000000a'))
+ and i.key in ('lac', 'marie', 'ab', 'axb', 'pct', 'bsl')),
+ 0::bigint, 'audit metadata is the workspace id only'
+);
+select is(
+ (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id
+ where a.actor_user_id is distinct from '60000000-0000-0000-0000-00000000000a' and i.key in ('lac', 'marie', 'axb')),
+ 0::bigint, 'the actor is the caller'
+);
+select is(
+ (select count(*) from audit.audit_logs where action like 'client.%'
+ and (metadata::text ~* '(lac|marie|dupont|vevey|example|cheval|haras)' or correlation_id is not null)),
+ 0::bigint, 'no name, contact or place in the audit rows'
+);
+set local role authenticated;
+select pg_temp.act_as('60000000-0000-0000-0000-000000000005');
+select is((select count(*) from audit.audit_logs where action like 'client.%'), 0::bigint, 'S reads no client audit row');
+select ok((select count(*) from audit.audit_logs where action like 'platform_role.%') > 0, 'S still reads platform audit rows');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 11. Integrity and account deletion (D9a)
+-- ---------------------------------------------------------------------------
+select throws_ok(
+ $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+ values (gen_random_uuid(), 'person', 'Orphan', gen_random_uuid(), '\x00') $$,
+ '23503', null, 'a client of an unknown workspace is refused by the foreign key'
+);
+select throws_ok(
+ $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+ values (pg_temp.ws('60000000-0000-0000-0000-00000000000a'), 'person', 'Twice', '61000000-0000-0000-0000-000000000001', '\x00') $$,
+ '23505', null, 'a request id is unique per workspace'
+);
+select throws_ok(
+ $$ delete from auth.users where id = '60000000-0000-0000-0000-00000000000a' $$,
+ '23503', null, 'an account whose workspace holds clients cannot be deleted (D9a)'
+);
+select is((select count(*) from public.clients where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000a')),
+ 8::bigint, 'its clients are intact');
+select lives_ok($$ delete from auth.users where id = '60000000-0000-0000-0000-000000000010' $$,
+ 'an account without clients is deleted as before');
+
+select * from finish();
+rollback;
diff --git a/supabase/tests/014_animals_relations.sql b/supabase/tests/014_animals_relations.sql
new file mode 100644
index 00000000..2e4de2be
--- /dev/null
+++ b/supabase/tests/014_animals_relations.sql
@@ -0,0 +1,878 @@
+-- V1-1.4 Animals and relations (M3): species rows, animal fields and the
+-- birth model, idempotent creates, revisions, archive, relations with their
+-- history (current, ended, voided), derived values, searches, isolation
+-- between workspaces, refusals for every other actor, caps and the write
+-- budget shared with the clients, minimised audit, integrity under a
+-- privileged writer, privileges and census.
+-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5.2-§5.4, §7.1, §9, §10, §12.1.
+-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after
+-- creating an animal; S a platform owner; E (per-animal caps, animal cap),
+-- F (budget), H (workspace relation cap) and G (D9a) confirmed.
+begin;
+select plan(258);
+
+insert into auth.users (id, email, email_confirmed_at) values
+ ('70000000-0000-0000-0000-00000000000a', 'alice-an@test.local', now()),
+ ('70000000-0000-0000-0000-00000000000b', 'bob-an@test.local', now()),
+ ('70000000-0000-0000-0000-00000000000c', 'carol-an@test.local', null),
+ ('70000000-0000-0000-0000-00000000000d', 'dave-an@test.local', now()),
+ ('70000000-0000-0000-0000-000000000005', 'staff-an@test.local', now()),
+ ('70000000-0000-0000-0000-00000000000e', 'cap-an@test.local', now()),
+ ('70000000-0000-0000-0000-00000000000f', 'budget-an@test.local', now()),
+ ('70000000-0000-0000-0000-000000000011', 'wscap-an@test.local', now()),
+ ('70000000-0000-0000-0000-000000000012', 'd9a-an@test.local', now());
+select private.assign_platform_role(null, '70000000-0000-0000-0000-000000000005', 'owner');
+-- A species that is later switched off (« species active or unchanged »).
+insert into public.species (id, name_fr, name_en, sort_order) values ('zz-retired', 'Retirée', 'Retired', 5000);
+
+create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer
+as $$ select id from public.workspaces where personal_user_id = p_user $$;
+create function pg_temp.wa() returns uuid language sql stable
+as $$ select pg_temp.ws('70000000-0000-0000-0000-00000000000a') $$;
+create function pg_temp.act_as(p_user uuid) returns text language sql
+as $$ select set_config('request.jwt.claims',
+ json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$;
+create table pg_temp.ids (key text primary key, id uuid not null);
+create function pg_temp.id(p_key text) returns uuid language sql stable
+as $$ select id from pg_temp.ids where key = p_key $$;
+create function pg_temp.animal(p_id uuid) returns public.animals language sql stable security definer
+as $$ select a from public.animals a where a.id = p_id $$;
+create function pg_temp.relation(p_id uuid) returns public.animal_client_relations language sql stable security definer
+as $$ select r from public.animal_client_relations r where r.id = p_id $$;
+create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer
+as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$;
+create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer
+as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$;
+create function pg_temp.tomorrow() returns text language sql stable
+as $$ select ((now() at time zone 'UTC')::date + 1)::text $$;
+-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint.
+create function pg_temp.err(p_sql text) returns text language plpgsql
+as $$
+declare v_state text; v_msg text; v_detail text; v_hint text;
+begin
+ execute p_sql;
+ return 'no error';
+exception when others then
+ get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text,
+ v_detail = pg_exception_detail, v_hint = pg_exception_hint;
+ return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, '');
+end;
+$$;
+-- SQLSTATE and message only: the real image appends a hint to table-privilege refusals.
+create function pg_temp.denial(p_sql text) returns text language sql
+as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$;
+-- create_animal as the current caller in A's workspace, keyed for later use.
+create function pg_temp.new_animal(p_key text, p_name text, p_species text, p_sex text, p_detail text default null,
+ p_breed text default null, p_year text default null, p_date text default null) returns uuid language sql
+as $$ insert into pg_temp.ids values (p_key, (public.create_animal(pg_temp.wa(), gen_random_uuid(), p_name, p_species, p_sex,
+ p_detail, p_breed, p_year, p_date) ->> 'id')::uuid) returning id $$;
+create function pg_temp.new_relation(p_key text, p_animal text, p_client text, p_role text, p_started text default null)
+ returns uuid language sql
+as $$ insert into pg_temp.ids values (p_key, (public.create_animal_client_relation(pg_temp.id(p_animal), pg_temp.id(p_client),
+ gen_random_uuid(), p_role, p_started) ->> 'id')::uuid) returning id $$;
+create function pg_temp.try_animal(p_name text, p_species text, p_sex text, p_detail text default null,
+ p_breed text default null, p_year text default null, p_date text default null) returns text language sql
+as $$ select pg_temp.err(format('select public.create_animal(%L, gen_random_uuid(), %L, %L, %L, %L, %L, %L, %L)',
+ pg_temp.wa(), p_name, p_species, p_sex, p_detail, p_breed, p_year, p_date)) $$;
+grant all on pg_temp.ids to authenticated, anon, service_role;
+grant execute on all functions in schema pg_temp to authenticated, anon, service_role;
+
+-- ---------------------------------------------------------------------------
+-- 1. Schema, species, privileges, census
+-- ---------------------------------------------------------------------------
+select has_table('public', 'animals', 'table public.animals exists');
+select has_table('public', 'animal_client_relations', 'table public.animal_client_relations exists');
+select ok((select bool_and(relrowsecurity) from pg_class
+ where oid in ('public.animals'::regclass, 'public.animal_client_relations'::regclass)),
+ 'RLS enabled on animals and animal_client_relations');
+select enum_has_labels('public', 'animal_sex', array['male', 'female', 'unknown'], 'animal_sex: male, female, unknown');
+select enum_has_labels('public', 'animal_relation_role', array['owner', 'keeper', 'contact'],
+ 'animal_relation_role: owner, keeper, contact');
+select results_eq(
+ $$ select id, name_fr, name_en, sort_order from public.species where id <> 'zz-retired' order by sort_order $$,
+ $$ values ('equine'::text, 'Cheval'::text, 'Horse'::text, 10), ('asinine', 'Âne', 'Donkey', 20), ('canine', 'Chien', 'Dog', 30),
+ ('feline', 'Chat', 'Cat', 40), ('bovine', 'Bovin', 'Cattle', 50), ('caprine', 'Chèvre', 'Goat', 60),
+ ('ovine', 'Mouton', 'Sheep', 70), ('porcine', 'Porc', 'Pig', 80), ('leporine', 'Lapin', 'Rabbit', 90),
+ ('other', 'Autre', 'Other', 1000) $$,
+ 'exactly the nine species of the contract and other, equine unchanged'
+);
+select ok((select bool_and(active) from public.species where id <> 'zz-retired'), 'every species row is active');
+select ok(obj_description('public.species'::regclass, 'pg_class') like 'Species of animals and of anatomical sheets.%',
+ 'the species table comment names animals');
+select is(
+ (select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C") from pg_tables
+ where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')),
+ 'animal_client_relations:postgres,animals:postgres', 'both tables belong to postgres'
+);
+select is(
+ (select count(*) from (values ('anon'), ('service_role')) r(role)
+ cross join (values ('animals'), ('animal_client_relations')) t(tbl)
+ cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege(r.role, 'public.' || t.tbl, p.priv)),
+ 0::bigint, 'anon and service_role hold no privilege on either table'
+);
+select is(
+ (select count(*) from (values ('animals'), ('animal_client_relations')) t(tbl)
+ cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv)
+ where has_table_privilege('authenticated', 'public.' || t.tbl, p.priv)),
+ 0::bigint, 'authenticated holds no write privilege on either table'
+);
+select ok(has_column_privilege('authenticated', 'public.animals', 'name', 'select')
+ and has_column_privilege('authenticated', 'public.animal_client_relations', 'voided_at', 'select')
+ and not has_column_privilege('authenticated', 'public.animals', 'create_request_digest', 'select')
+ and not has_column_privilege('authenticated', 'public.animal_client_relations', 'create_request_digest', 'select'),
+ 'authenticated reads the record columns, never the request digests');
+select is(
+ (select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',' order by tablename collate "C")
+ from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')),
+ 'animal_client_relations:animal_client_relations_select_member:SELECT:authenticated,animals:animals_select_member:SELECT:authenticated',
+ 'one SELECT policy per table, for authenticated'
+);
+select is(
+ (select count(*) from pg_policies where schemaname = 'public' and tablename in ('animals', 'animal_client_relations')
+ and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')),
+ 0::bigint, 'both policies go through caller_workspace_ids() and name no platform role'
+);
+select is(
+ (select string_agg(c.conname || '(' || (select string_agg(a.attname, ',' order by k.i)
+ from unnest(c.conkey) with ordinality k(n, i) join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.n)
+ || ')->' || c.confrelid::regclass::text || ':' || c.condeferrable, ';' order by c.conname collate "C")
+ from pg_constraint c where c.conrelid = 'public.animal_client_relations'::regclass and c.contype = 'f'),
+ 'animal_client_relations_animal_fk(workspace_id,animal_id)->animals:false;animal_client_relations_client_fk(workspace_id,client_id)->clients:false',
+ 'relations reference animal and client through (workspace_id, id), not deferrable'
+);
+select ok(
+ (select indisunique and pg_get_expr(indpred, indrelid) like '%ended_at IS NULL%voided_at IS NULL%'
+ from pg_index where indexrelid = 'public.animal_client_relations_current_unique'::regclass),
+ 'the current-relation index is unique on rows neither ended nor voided'
+);
+select is(
+ (select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C")
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
+ where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation',
+ 'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals',
+ 'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date',
+ 'parse_birth_year', 'lock_relation_for_write')
+ and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'),
+ 'client_archive_preview:invoker,create_animal:definer,create_animal_client_relation:definer,end_animal_client_relation:definer,'
+ || 'list_client_animals:invoker,lock_relation_for_write:definer,parse_birth_year:invoker,parse_record_date:invoker,'
+ || 'search_animals:invoker,search_clients:invoker,set_animal_archived:definer,update_animal:definer,'
+ || 'update_animal_client_relation:definer,utc_tomorrow:invoker,void_animal_client_relation:definer',
+ 'definer and invoker as designed; search_path empty; owner postgres'
+);
+select is(
+ (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C")
+ from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role)
+ where p.proname in ('create_animal', 'update_animal', 'set_animal_archived', 'create_animal_client_relation',
+ 'end_animal_client_relation', 'update_animal_client_relation', 'void_animal_client_relation', 'search_animals',
+ 'list_client_animals', 'client_archive_preview', 'search_clients', 'utc_tomorrow', 'parse_record_date',
+ 'parse_birth_year', 'lock_relation_for_write')
+ and has_function_privilege(r.role, p.oid, 'execute')),
+ 'authenticated:client_archive_preview,authenticated:create_animal,authenticated:create_animal_client_relation,'
+ || 'authenticated:end_animal_client_relation,authenticated:list_client_animals,authenticated:search_animals,'
+ || 'authenticated:search_clients,authenticated:set_animal_archived,authenticated:update_animal,'
+ || 'authenticated:update_animal_client_relation,authenticated:void_animal_client_relation',
+ 'EXECUTE: authenticated on the eleven RPCs; the private helpers for nobody; anon and service_role on none'
+);
+select is(private.utc_tomorrow('2026-12-31 23:30:00+00'), date '2027-01-01',
+ 'on 31 December UTC, 1 January is the latest accepted date');
+select is(private.utc_tomorrow('2026-12-31 23:30:00-05'), date '2027-01-02',
+ 'the UTC date decides, not the caller''s zone');
+
+-- ---------------------------------------------------------------------------
+-- 2. Animals: fields, species, the birth model (D6b), text rules
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
+insert into pg_temp.ids values
+ ('marie', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Marie Dupont') ->> 'id')::uuid),
+ ('lac', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'organization', 'Écurie du Lac') ->> 'id')::uuid),
+ ('paul', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Paul Martin') ->> 'id')::uuid),
+ ('zoe', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Zoé Bernard') ->> 'id')::uuid),
+ ('ana', (public.create_client(pg_temp.wa(), gen_random_uuid(), 'person', 'Ana Petit') ->> 'id')::uuid);
+
+select is(
+ public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null,
+ 'Selle Français', '2015', '2015-04-12') - 'id',
+ '{"revision": 1, "relation_id": null}'::jsonb, 'create_animal answers revision 1 and no relation');
+insert into pg_temp.ids select 'eclair', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000001';
+select results_eq(
+ $$ select name, species_id, sex::text, breed, birth_year::integer, birth_date, revision, archived_at is null
+ from public.animals where id = pg_temp.id('eclair') $$,
+ $$ values ('Éclair'::text, 'equine'::text, 'male'::text, 'Selle Français'::text, 2015, date '2015-04-12', 1, true) $$,
+ 'A reads the created animal'
+);
+select is((pg_temp.animal(pg_temp.id('eclair'))).name_key, 'eclair', 'name_key folds accents and case');
+select is((pg_temp.animal(pg_temp.id('eclair'))).search_key, 'eclair selle francais ', 'search_key holds name, breed and detail');
+select lives_ok($$ select pg_temp.new_animal('bijou', 'Bijou', 'equine', 'female', null, null, '2016') $$,
+ 'year alone: born in 2016, day unknown');
+select is((pg_temp.animal(pg_temp.id('bijou'))).birth_date, null, 'no date is invented from a year');
+select lives_ok($$ select pg_temp.new_animal('sans', 'Sans Maître', 'equine', 'unknown') $$,
+ 'birth unknown and sex unknown, chosen explicitly');
+select lives_ok($$ select pg_temp.new_animal('furet', 'Pistache', 'other', 'unknown', 'Furet') $$,
+ 'other with its detail is accepted');
+select lives_ok($$ select pg_temp.new_animal('rex', 'Rex', 'canine', 'male') $$, 'a canine is accepted');
+select lives_ok($$ select pg_temp.new_animal('luna', 'Luna', 'feline', 'female') $$, 'a feline is accepted');
+select lives_ok($$ select pg_temp.new_animal('quatuor', 'Quatuor', 'equine', 'male') $$, 'another horse');
+select lives_ok($$ select pg_temp.new_animal('retired', 'Ancien', 'zz-retired', 'male') $$, 'an animal of a species still active');
+
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, null, '2015-04-12'), 'P0001|invalid_input||',
+ 'a date without its year is refused');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2016', '2015-04-12'), 'P0001|invalid_input||',
+ 'a date of another year is refused');
+select is(pg_temp.try_animal('Other', 'other', 'male'), 'P0001|invalid_input||', 'other without detail is refused');
+select is(pg_temp.try_animal('Detail', 'equine', 'male', 'Furet'), 'P0001|invalid_input||', 'a detail on another species is refused');
+select is(pg_temp.try_animal('Unicorn', 'unicorn', 'male'), 'P0001|invalid_input||', 'an unknown species is refused');
+select is(pg_temp.try_animal('Nothing', null, 'male'), 'P0001|invalid_input||', 'a missing species is refused');
+select is(pg_temp.try_animal('Sex', 'equine', null), 'P0001|invalid_input||', 'a missing sex is refused (no default)');
+select is(pg_temp.try_animal('Sex', 'equine', 'robot'), 'P0001|invalid_input||', 'an unknown sex is refused');
+select is(pg_temp.try_animal('', 'equine', 'male'), 'P0001|invalid_input||', 'an empty name is refused');
+select is(pg_temp.try_animal(' Lead', 'equine', 'male'), 'P0001|invalid_input||', 'a leading space is refused');
+select is(pg_temp.try_animal(e'Tab\there', 'equine', 'male'), 'P0001|invalid_input||', 'a control character is refused');
+select is(pg_temp.try_animal(repeat('é', 81), 'equine', 'male'), 'P0001|invalid_input||', '81 characters are refused');
+select is(pg_temp.try_animal(repeat('é', 80), 'equine', 'male'), 'no error', '80 accented characters are accepted');
+select is(pg_temp.try_animal('Breed', 'equine', 'male', null, repeat('b', 81)), 'P0001|invalid_input||', 'an 81-character breed is refused');
+select is(pg_temp.try_animal('Detail', 'other', 'male', repeat('d', 81)), 'P0001|invalid_input||', 'an 81-character detail is refused');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1899'), 'P0001|invalid_input||', 'birth year 1899 is refused');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '1900'), 'no error', 'birth year 1900 is accepted');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4)), 'no error',
+ 'the year of tomorrow UTC is accepted');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, (left(pg_temp.tomorrow(), 4)::integer + 1)::text),
+ 'P0001|invalid_input||', 'a later year is refused');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, '15'), 'P0001|invalid_input||', 'a two-digit year is refused');
+select is(pg_temp.try_animal('Year', 'equine', 'male', null, null, 'abcd'), 'P0001|invalid_input||', 'a non-numeric year is refused');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '2015-02-30'), 'P0001|invalid_input||',
+ 'an impossible date is refused without echoing it');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '2015', '12/04/2015'), 'P0001|invalid_input||',
+ 'a date in another format is refused');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, '1899', '1899-12-31'), 'P0001|invalid_input||',
+ 'a date before 1900 is refused');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left(pg_temp.tomorrow(), 4), pg_temp.tomorrow()), 'no error',
+ 'tomorrow UTC is accepted (today somewhere)');
+select is(pg_temp.try_animal('Date', 'equine', 'male', null, null, left((pg_temp.tomorrow()::date + 1)::text, 4),
+ (pg_temp.tomorrow()::date + 1)::text), 'P0001|invalid_input||', 'the day after tomorrow UTC is refused');
+select is((select count(*) from public.animals where workspace_id = pg_temp.wa()), 12::bigint, 'only the valid creates were written');
+
+-- ---------------------------------------------------------------------------
+-- 3. Idempotent create, update, revision, archive
+-- ---------------------------------------------------------------------------
+select is(pg_temp.budget(pg_temp.wa()), '17/17', 'five clients and twelve animals counted so far');
+select is(
+ (public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine', 'male', null,
+ 'Selle Français', '2015', '2015-04-12') ->> 'id')::uuid,
+ pg_temp.id('eclair'), 'a replay returns the first animal');
+select is(pg_temp.audit_count(pg_temp.id('eclair')), 1::bigint, 'the replay writes no audit row');
+select is(pg_temp.budget(pg_temp.wa()), '17/17', 'the replay consumes no budget');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000001', 'Éclair', 'equine',
+ 'female') $$), 'P0001|request_conflict||', 'the same request id with other content is refused');
+
+select is(public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision',
+ '2', 'an update at the current revision gives revision 2');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou II', 'equine', 'female', null, null, null, null) $$),
+ 'P0001|conflict||', 'a stale revision is refused');
+select is((pg_temp.animal(pg_temp.id('bijou'))).breed, 'Pur-sang', 'the stale update overwrote nothing');
+select is(public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'equine', 'female', null, 'Pur-sang', '2016', null) ->> 'revision',
+ '2', 'an update that changes nothing keeps the revision');
+select is(pg_temp.audit_count(pg_temp.id('bijou')), 2::bigint, 'and writes no audit row');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'other', 'female', null, null, '2016', null) $$),
+ 'P0001|invalid_input||', 'an update to other without detail is refused');
+reset role;
+update public.species set active = false where id = 'zz-retired';
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
+select is(public.update_animal(pg_temp.id('retired'), 1, 'Ancien renommé', 'zz-retired', 'male', null, null, null, null) ->> 'revision',
+ '2', 'an animal keeps a species switched off since');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 2, 'Bijou', 'zz-retired', 'female', null, null, '2016', null) $$),
+ 'P0001|invalid_input||', 'an animal cannot move to an inactive species');
+select is(pg_temp.try_animal('Retired', 'zz-retired', 'male'), 'P0001|invalid_input||', 'an inactive species is refused at creation');
+
+-- ---------------------------------------------------------------------------
+-- 4. Relations: owners, roles, history, voiding
+-- ---------------------------------------------------------------------------
+select isnt(
+ public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
+ client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id',
+ null, 'create_animal with an initial owner relation');
+insert into pg_temp.ids select 'tonnerre', id from public.animals where create_request_id = '71000000-0000-0000-0000-000000000002';
+insert into pg_temp.ids select 'r_tonnerre', id from public.animal_client_relations where animal_id = pg_temp.id('tonnerre');
+select results_eq(
+ $$ select client_id, relation_role::text, started_on, ended_at is null, voided_at is null, revision
+ from public.animal_client_relations where animal_id = pg_temp.id('tonnerre') $$,
+ $$ values (pg_temp.id('marie'), 'owner'::text, date '2020-01-01', true, true, 1) $$,
+ 'the initial relation is current, with its start date'
+);
+select is(pg_temp.budget(pg_temp.wa()), '21/21', 'animal and relation are two audited writes');
+select is(
+ public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
+ client_id => pg_temp.id('marie'), relation_role => 'owner', started_on => '2020-01-01') ->> 'relation_id',
+ pg_temp.id('r_tonnerre')::text, 'a replay returns the same relation');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), '71000000-0000-0000-0000-000000000002', 'Tonnerre', 'equine', 'male',
+ client_id => pg_temp.id('marie'), relation_role => 'keeper', started_on => '2020-01-01') $$),
+ 'P0001|request_conflict||', 'a replay with another relation role is refused');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
+ client_id => pg_temp.id('marie')) $$), 'P0001|invalid_input||', 'a client without a role is refused');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
+ relation_role => 'owner') $$), 'P0001|invalid_input||', 'a role without a client is refused');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
+ started_on => '2020-01-01') $$), 'P0001|invalid_input||', 'a start date without a client is refused');
+
+select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_owner', 'eclair', 'marie', 'owner') $$, 'A links an owner');
+select lives_ok($$ select pg_temp.new_relation('r_eclair_paul_owner', 'eclair', 'paul', 'owner') $$, 'co-ownership: a second owner');
+select lives_ok($$ select pg_temp.new_relation('r_eclair_marie_keeper', 'eclair', 'marie', 'keeper') $$,
+ 'the same client may also be the keeper');
+select lives_ok($$ select pg_temp.new_relation('r_eclair_lac_keeper', 'eclair', 'lac', 'keeper') $$, 'a stable as keeper');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$),
+ 'P0001|duplicate_relation||', 'a second current identical relation is refused');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), 'boss') $$),
+ 'P0001|invalid_input||', 'an unknown role is refused');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('ana'), gen_random_uuid(), null) $$),
+ 'P0001|invalid_input||', 'a missing role is refused');
+select is(pg_temp.err(format('select public.create_animal_client_relation(%L, %L, gen_random_uuid(), %L, %L)',
+ pg_temp.id('eclair'), pg_temp.id('ana'), 'contact', (pg_temp.tomorrow()::date + 1)::text)),
+ 'P0001|invalid_input||', 'a start date after tomorrow UTC is refused');
+select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('sans')), 0::bigint,
+ 'an animal may have no owner and no relation');
+
+-- Ending, dates, successive relations.
+select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_1', 'bijou', 'paul', 'owner', '2018-05-01') $$, 'Paul owns Bijou since 2018');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-01-01') $$),
+ 'P0001|invalid_input||', 'an end before the start is refused');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2017-02-30') $$),
+ 'P0001|invalid_input||', 'an impossible end date is refused');
+select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2018-05-01', '2021-06-30') $$),
+ 'P0001|invalid_input||', 'an end date on a current relation is refused');
+select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1, '2021-06-30') ->> 'revision', '2',
+ 'ending the relation with its date gives revision 2');
+select ok((pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_at is not null
+ and (pg_temp.relation(pg_temp.id('r_bijou_paul_1'))).ended_on = date '2021-06-30', 'the ended relation keeps its row and dates');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2) $$),
+ 'P0001|already_ended||', 'ending an ended relation is refused');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 1) $$),
+ 'P0001|conflict||', 'a stale revision is refused before the state');
+select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 2, '2018-05-01', '2021-07-01') ->> 'revision', '3',
+ 'the dates of an ended relation can be corrected');
+select is(public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2018-05-01', '2021-07-01') ->> 'revision', '3',
+ 'a correction that changes nothing keeps the revision');
+select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_1'), 3, '2022-01-01', '2021-07-01') $$),
+ 'P0001|invalid_input||', 'a start after the end is refused');
+select lives_ok($$ select pg_temp.new_relation('r_bijou_paul_2', 'bijou', 'paul', 'owner', '2023-03-01') $$,
+ 'a successive relation of the same triple is accepted once the first has ended');
+select lives_ok($$ select pg_temp.new_relation('r_bijou_lac', 'bijou', 'lac', 'owner') $$, 'Écurie du Lac also owned Bijou');
+select is(public.end_animal_client_relation(pg_temp.id('r_bijou_lac'), 1) ->> 'revision', '2', 'an end with no known date');
+select ok((pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_at is not null and (pg_temp.relation(pg_temp.id('r_bijou_lac'))).ended_on is null,
+ 'ended, date unknown: ended_at set, ended_on null, distinct from a current relation');
+
+-- Voiding (N4).
+select lives_ok($$ select pg_temp.new_relation('r_rex_marie_wrong', 'rex', 'marie', 'owner', '2019-01-01') $$, 'a relation entered by mistake');
+select is(public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 1) ->> 'revision', '2', 'voiding gives revision 2');
+select results_eq(
+ $$ select client_id, relation_role::text, started_on, ended_on, ended_at is null, voided_at is not null
+ from public.animal_client_relations where id = pg_temp.id('r_rex_marie_wrong') $$,
+ $$ values (pg_temp.id('marie'), 'owner'::text, date '2019-01-01', null::date, true, true) $$,
+ 'a voided relation keeps every value as entered and gains voided_at, no end date invented'
+);
+select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$),
+ 'P0001|invalid_input||', 'voiding twice is refused');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2) $$),
+ 'P0001|invalid_input||', 'a voided relation cannot be ended');
+select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_rex_marie_wrong'), 2, null, null) $$),
+ 'P0001|invalid_input||', 'a voided relation cannot be corrected');
+select lives_ok($$ select pg_temp.new_relation('r_rex_marie', 'rex', 'marie', 'owner') $$,
+ 'a voided relation no longer holds the current-relation slot');
+select lives_ok($$ select pg_temp.new_relation('r_sans_ana_wrong', 'sans', 'ana', 'keeper') $$, 'Ana entered as keeper by mistake');
+select is(public.void_animal_client_relation(pg_temp.id('r_sans_ana_wrong'), 1) ->> 'revision', '2', 'voided while current');
+select lives_ok($$ select pg_temp.new_relation('r_rex_lac_contact', 'rex', 'lac', 'contact') $$, 'a contact');
+select is(public.end_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 1, '2024-01-01') ->> 'revision', '2', 'the contact ends');
+select is(public.void_animal_client_relation(pg_temp.id('r_rex_lac_contact'), 2) ->> 'revision', '3',
+ 'an ended relation recorded by mistake can be voided');
+
+-- Four owners for the derived values; a keeper and an owner later archived.
+select lives_ok($$ select pg_temp.new_relation('r_q_ana', 'quatuor', 'ana', 'owner'), pg_temp.new_relation('r_q_lac', 'quatuor', 'lac', 'owner'),
+ pg_temp.new_relation('r_q_marie', 'quatuor', 'marie', 'owner'), pg_temp.new_relation('r_q_paul', 'quatuor', 'paul', 'owner') $$,
+ 'four co-owners');
+select lives_ok($$ select pg_temp.new_relation('r_luna_lac', 'luna', 'lac', 'owner'), pg_temp.new_relation('r_luna_zoe', 'luna', 'zoe', 'owner'),
+ pg_temp.new_relation('r_rex_zoe_keeper', 'rex', 'zoe', 'keeper') $$, 'Luna owned by the stable and Zoé, Zoé keeps Rex');
+
+-- ---------------------------------------------------------------------------
+-- 5. Archive (§7.1): no cascade, frozen relations, archived client
+-- ---------------------------------------------------------------------------
+select is(public.client_archive_preview(pg_temp.id('paul')),
+ jsonb_build_object('count', 1, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('bijou'), 'name', 'Bijou'))),
+ 'preview: Paul is the only current owner of Bijou');
+select is(public.set_client_archived(pg_temp.id('zoe'), true) ->> 'revision', '2', 'Zoé is archived');
+select is((select count(*) from public.animals where id = pg_temp.id('luna') and archived_at is null), 1::bigint,
+ 'archiving a client archives none of its animals');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('luna'), pg_temp.id('zoe'), gen_random_uuid(), 'keeper') $$),
+ 'P0001|archived||', 'a new relation needs an active client');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male',
+ client_id => pg_temp.id('zoe'), relation_role => 'owner') $$), 'P0001|archived||', 'so does the initial relation');
+select is(public.end_animal_client_relation(pg_temp.id('r_rex_zoe_keeper'), 1) ->> 'revision', '2',
+ 'the relation of an archived client with an active animal can still be ended');
+select is(public.client_archive_preview(pg_temp.id('lac')), '{"count": 0, "animals": []}'::jsonb,
+ 'a co-owner, even archived, means the stable is not the only owner of Luna');
+
+select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'Bijou is archived');
+select is(public.set_animal_archived(pg_temp.id('bijou'), true) ->> 'revision', '3', 'archiving again changes nothing');
+select is((select count(*) from public.animal_client_relations where animal_id = pg_temp.id('bijou')
+ and ended_at is null and voided_at is null), 1::bigint, 'archiving an animal ends none of its relations');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('bijou'), pg_temp.id('ana'), gen_random_uuid(), 'keeper') $$),
+ 'P0001|archived||', 'no new relation on an archived animal');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 9) $$),
+ 'P0001|archived||', 'the relations of an archived animal are frozen (archived before conflict)');
+select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1, null, null) $$),
+ 'P0001|archived||', 'no date correction either');
+select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) $$),
+ 'P0001|archived||', 'no voiding either');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('bijou'), 1, 'Bijou', 'equine', 'female', null, null, null, null) $$),
+ 'P0001|archived||', 'an archived animal refuses edits, archived reported before the stale revision');
+select is(public.client_archive_preview(pg_temp.id('paul')), '{"count": 0, "animals": []}'::jsonb,
+ 'the preview lists active animals only');
+select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('bijou'), null) $$), 'P0001|invalid_input||',
+ 'a missing archive state is refused');
+
+-- ---------------------------------------------------------------------------
+-- 6. Reads: searches, derived values, a client's animals
+-- ---------------------------------------------------------------------------
+create function pg_temp.animals(p_query text, p_species text default null, p_archived boolean default false,
+ p_size integer default 25, p_after_key text default null, p_after_id uuid default null) returns text language sql
+as $$ select coalesce(string_agg(s.name, '|' order by s.ord), '')
+ from public.search_animals(pg_temp.wa(), p_query, p_species, p_archived, p_size, p_after_key, p_after_id)
+ with ordinality s(id, name, species_id, species_detail, sex, breed, birth_year, archived_at, name_key,
+ current_owners, current_owner_count, ord) $$;
+create function pg_temp.owners(p_key text) returns text language sql
+as $$ select s.current_owner_count || ' ' || s.current_owners::text
+ from public.search_animals(pg_temp.wa(), (pg_temp.animal(pg_temp.id(p_key))).name,
+ null, (pg_temp.animal(pg_temp.id(p_key))).archived_at is not null) s
+ where s.id = pg_temp.id(p_key) $$;
+create function pg_temp.client_count(p_key text) returns integer language sql
+as $$ select s.current_animal_count from public.search_clients(pg_temp.wa(), '', true) s where s.id = pg_temp.id(p_key)
+ union all
+ select s.current_animal_count from public.search_clients(pg_temp.wa(), '', false) s where s.id = pg_temp.id(p_key) $$;
+create function pg_temp.client_animals(p_key text, p_size integer default 50, p_after_sort text default null,
+ p_after_id uuid default null) returns text language sql
+as $$ select coalesce(string_agg(s.animal_name || ':' || s.relation_role || ':' || case when s.is_current then 'current' else 'former' end,
+ '|' order by s.ord), '')
+ from public.list_client_animals(pg_temp.id(p_key), p_size, p_after_sort, p_after_id)
+ with ordinality s(relation_id, relation_role, started_on, ended_on, is_current, relation_revision, animal_id,
+ animal_name, species_id, species_detail, sex, breed, birth_year, animal_archived_at, sort_key, ord) $$;
+grant execute on function pg_temp.animals(text, text, boolean, integer, text, uuid), pg_temp.owners(text),
+ pg_temp.client_count(text), pg_temp.client_animals(text, integer, text, uuid) to authenticated, anon, service_role;
+
+select is(pg_temp.animals(''), 'Ancien renommé|Date|Éclair|' || repeat('é', 80) || '|Luna|Pistache|Quatuor|Rex|Sans Maître|Tonnerre|Year|Year',
+ 'an empty term lists the active animals in name order (archived left out)');
+select is(pg_temp.animals('', null, true), 'Bijou', 'the archived filter lists the archived animal only');
+select is(pg_temp.animals('ECLA'), 'Éclair', 'search folds case and accents');
+select is(pg_temp.animals('francais'), 'Éclair', 'search reads the breed');
+select is(pg_temp.animals('furet'), 'Pistache', 'search reads the species detail');
+select is(pg_temp.animals('', 'canine'), 'Rex', 'the species filter keeps one species');
+select is(pg_temp.animals('', 'feline'), 'Luna', 'and excludes the others');
+select is(pg_temp.animals('', null, false, 3), 'Ancien renommé|Date|Éclair', 'page 1 of 3');
+select is(pg_temp.animals('', null, false, 3, (pg_temp.animal(pg_temp.id('eclair'))).name_key, pg_temp.id('eclair')),
+ repeat('é', 80) || '|Luna|Pistache', 'page 2 continues after the cursor, no gap, no repeat');
+select is(pg_temp.err($$ select pg_temp.animals(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused');
+select is(pg_temp.err($$ select pg_temp.animals('', null, false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused');
+select is(pg_temp.err($$ select pg_temp.animals('', null, false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
+select is(pg_temp.err($$ select pg_temp.animals('', null, null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused');
+
+select is(pg_temp.owners('eclair'),
+ '2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false),
+ jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text,
+ 'current owners in client name order, keepers left out');
+select is(pg_temp.owners('quatuor'),
+ '4 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('ana'), 'display_name', 'Ana Petit', 'archived', false),
+ jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false),
+ jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text,
+ 'the first three owners, the count of all four');
+select is(pg_temp.owners('luna'),
+ '2 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('lac'), 'display_name', 'Écurie du Lac', 'archived', false),
+ jsonb_build_object('client_id', pg_temp.id('zoe'), 'display_name', 'Zoé Bernard', 'archived', true))::text,
+ 'an archived owner stays, flagged');
+select is(pg_temp.owners('rex'),
+ '1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('marie'), 'display_name', 'Marie Dupont', 'archived', false))::text,
+ 'a voided owner relation is left out');
+select is(pg_temp.owners('sans'), '0 []', 'no owner: an empty list (« Propriétaire non renseigné »)');
+select is(pg_temp.owners('bijou'),
+ '1 ' || jsonb_build_array(jsonb_build_object('client_id', pg_temp.id('paul'), 'display_name', 'Paul Martin', 'archived', false))::text,
+ 'ended relations are left out');
+
+select is(pg_temp.client_count('marie'), 4, 'Marie: Éclair (two roles, counted once), Quatuor, Rex, Tonnerre; the voided one left out');
+select is(pg_temp.client_count('paul'), 2, 'Paul: Éclair and Quatuor; Bijou archived is not counted');
+select is(pg_temp.client_count('lac'), 3, 'the stable: Éclair, Luna, Quatuor; ended and voided relations left out');
+select is(pg_temp.client_count('zoe'), 1, 'archived Zoé: Luna; her ended keeper relation left out');
+select is(pg_temp.client_count('ana'), 1, 'Ana: Quatuor; her voided keeper relation to Sans Maître left out');
+
+select is(pg_temp.client_animals('lac'), 'Éclair:keeper:current|Luna:owner:current|Quatuor:owner:current|Bijou:owner:former',
+ 'a client''s animals: current first, then former, each by name; voided left out');
+select is(pg_temp.client_animals('paul'), 'Bijou:owner:current|Éclair:owner:current|Quatuor:owner:current|Bijou:owner:former',
+ 'successive relations of one animal appear as current and former');
+select is(pg_temp.client_animals('lac', 2), 'Éclair:keeper:current|Luna:owner:current', 'page 1 of 2');
+select is(pg_temp.client_animals('lac', 2,
+ (select s.sort_key from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1),
+ (select s.relation_id from public.list_client_animals(pg_temp.id('lac'), 2) s order by s.sort_key desc limit 1)),
+ 'Quatuor:owner:current|Bijou:owner:former', 'page 2 continues after the cursor');
+select is(pg_temp.err($$ select pg_temp.client_animals('lac', 0) $$), 'P0001|invalid_input||', 'page size 0 is refused');
+select is(pg_temp.err($$ select pg_temp.client_animals('lac', 50, '0x') $$), 'P0001|invalid_input||', 'a cursor without its id is refused');
+select is(public.client_archive_preview(pg_temp.id('marie')),
+ jsonb_build_object('count', 2, 'animals', jsonb_build_array(jsonb_build_object('id', pg_temp.id('rex'), 'name', 'Rex'),
+ jsonb_build_object('id', pg_temp.id('tonnerre'), 'name', 'Tonnerre'))),
+ 'preview: Marie is the only current owner of Rex and Tonnerre (co-owned animals left out)');
+
+-- Restore: editable again.
+select is(public.set_animal_archived(pg_temp.id('bijou'), false) ->> 'revision', '4', 'restoring adds one revision');
+select is(public.end_animal_client_relation(pg_temp.id('r_bijou_paul_2'), 1) ->> 'revision', '2', 'its relations can change again');
+
+-- D creates an animal while active (used after its deactivation).
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000d');
+insert into pg_temp.ids values ('dave', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000d'),
+ gen_random_uuid(), 'Cheval de Dave', 'equine', 'male') ->> 'id')::uuid);
+-- B's own records, for the cross-workspace attempts.
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000b');
+insert into pg_temp.ids values
+ ('b_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'person', 'Client B') ->> 'id')::uuid),
+ ('b_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'Animal B', 'equine', 'male') ->> 'id')::uuid);
+reset role;
+update public.profiles set active = false where id = '70000000-0000-0000-0000-00000000000d';
+
+-- ---------------------------------------------------------------------------
+-- 7. Isolation: the same not_found for a foreign and an unknown id
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000b');
+select is((select count(*) from public.animals), 1::bigint, 'B reads its own animal only');
+select is((select count(*) from public.animal_client_relations), 0::bigint, 'B reads no relation of A');
+select is((select count(*) from public.animals where id = pg_temp.id('eclair')), 0::bigint, 'B naming an animal of A reads nothing');
+select is((select count(*) from public.search_animals(pg_temp.wa())), 0::bigint, 'B searching the workspace of A finds nothing');
+select is((select count(*) from public.list_client_animals(pg_temp.id('lac'))), 0::bigint, 'B listing a client of A finds nothing');
+select is(public.client_archive_preview(pg_temp.id('marie')), '{"count": 0, "animals": []}'::jsonb, 'B previews nothing of A');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.wa(), gen_random_uuid(), 'X', 'equine', 'male') $$),
+ pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
+ 'B creating in the workspace of A gets the error of an unknown workspace');
+select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
+ '42501|not_found||', 'that error is 42501 not_found, no detail, no hint');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, 'X', 'equine', 'male', null, null, null, null) $$),
+ pg_temp.err($$ select public.update_animal(gen_random_uuid(), 1, 'X', 'equine', 'male', null, null, null, null) $$),
+ 'B updating an animal of A gets the error of an unknown animal');
+select is(pg_temp.err($$ select public.update_animal(pg_temp.id('eclair'), 1, '', 'nope', 'robot', null, null, 'x', 'y') $$),
+ '42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)');
+select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('eclair'), true) $$), '42501|not_found||',
+ 'B archiving an animal of A gets not_found');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), pg_temp.id('marie'), gen_random_uuid(), 'owner') $$),
+ pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('b_animal'), gen_random_uuid(), gen_random_uuid(), 'owner') $$),
+ 'B linking its animal to a client of A gets the error of an unknown client');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('eclair'), pg_temp.id('b_client'), gen_random_uuid(), 'owner') $$),
+ '42501|not_found||', 'B linking an animal of A to its client gets not_found');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000b'), gen_random_uuid(), 'X', 'equine',
+ 'male', client_id => pg_temp.id('marie'), relation_role => 'owner') $$), '42501|not_found||',
+ 'B creating an animal linked to a client of A gets not_found');
+select is(pg_temp.err($$ select public.end_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
+ pg_temp.err($$ select public.end_animal_client_relation(gen_random_uuid(), 1) $$),
+ 'B ending a relation of A gets the error of an unknown relation');
+select is(pg_temp.err($$ select public.update_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1, null, null) $$),
+ '42501|not_found||', 'B correcting a relation of A gets not_found');
+select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
+ '42501|not_found||', 'B voiding a relation of A gets not_found');
+select is(pg_temp.denial($$ insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+ values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), 'Direct', 'equine', 'male', gen_random_uuid(), '\x00') $$),
+ '42501|permission denied for table animals', 'a direct insert of an animal is refused by privilege');
+select is(pg_temp.denial($$ update public.animals set name = 'Direct' $$),
+ '42501|permission denied for table animals', 'a direct update of an animal is refused by privilege');
+select is(pg_temp.denial($$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') $$),
+ '42501|permission denied for table animals', 'moving an animal to another workspace is refused by privilege');
+select is(pg_temp.denial($$ delete from public.animals $$),
+ '42501|permission denied for table animals', 'a direct delete of an animal is refused by privilege');
+select is(pg_temp.denial($$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role,
+ create_request_id, create_request_digest) values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('b_animal'),
+ pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$),
+ '42501|permission denied for table animal_client_relations', 'a direct insert of a relation is refused by privilege');
+select is(pg_temp.denial($$ update public.animal_client_relations set voided_at = null $$),
+ '42501|permission denied for table animal_client_relations', 'a direct update of a relation is refused by privilege');
+select is(pg_temp.denial($$ delete from public.animal_client_relations $$),
+ '42501|permission denied for table animal_client_relations', 'a direct delete of a relation is refused by privilege');
+
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000c');
+select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint,
+ 'C (unconfirmed) reads no animal and no relation');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'X', 'equine', 'male') $$),
+ '42501|not_found||', 'C cannot create, even in its own workspace');
+
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000d');
+select is((select count(*) from public.animals), 0::bigint, 'D (deactivated) no longer reads its own animal');
+select is((select count(*) from public.search_animals(pg_temp.ws('70000000-0000-0000-0000-00000000000d'))), 0::bigint,
+ 'D finds nothing through search');
+select is(pg_temp.err($$ select public.set_animal_archived(pg_temp.id('dave'), true) $$), '42501|not_found||',
+ 'D cannot write its own animal');
+
+select pg_temp.act_as('70000000-0000-0000-0000-000000000005');
+select is((select count(*) from public.animals) + (select count(*) from public.animal_client_relations), 0::bigint,
+ 'S (platform owner) reads nothing: no platform-role branch');
+select is(pg_temp.err($$ select public.void_animal_client_relation(pg_temp.id('r_eclair_marie_owner'), 1) $$),
+ '42501|not_found||', 'S cannot write a relation of A');
+reset role;
+
+set local role anon;
+select is(pg_temp.denial($$ select id from public.animals $$), '42501|permission denied for table animals', 'anon cannot read animals');
+select is(pg_temp.denial($$ select id from public.animal_client_relations $$), '42501|permission denied for table animal_client_relations',
+ 'anon cannot read relations');
+select is(pg_temp.err($$ select public.create_animal(gen_random_uuid(), gen_random_uuid(), 'X', 'equine', 'male') $$),
+ '42501|permission denied for function create_animal||', 'anon cannot execute create_animal');
+select is(pg_temp.err($$ select * from public.search_animals(gen_random_uuid()) $$),
+ '42501|permission denied for function search_animals||', 'anon cannot execute search_animals');
+reset role;
+set local role service_role;
+select is(pg_temp.denial($$ select id from public.animal_client_relations $$),
+ '42501|permission denied for table animal_client_relations', 'service_role cannot read relations despite BYPASSRLS');
+select is(pg_temp.err($$ select public.void_animal_client_relation(gen_random_uuid(), 1) $$),
+ '42501|permission denied for function void_animal_client_relation||', 'service_role cannot execute the relation RPCs');
+select is(pg_temp.err($$ select * from public.list_client_animals(gen_random_uuid()) $$),
+ '42501|permission denied for function list_client_animals||', 'service_role cannot execute the reads');
+reset role;
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000a');
+select is(pg_temp.err($$ select private.lock_relation_for_write(pg_temp.id('r_eclair_marie_owner'), 1) $$),
+ '42501|permission denied for function lock_relation_for_write||', 'A cannot call the relation lock directly');
+select is(pg_temp.err($$ select private.parse_record_date('2020-01-01') $$),
+ '42501|permission denied for function parse_record_date||', 'A cannot call the date parser directly');
+select is(pg_temp.err($$ select private.parse_birth_year('2020') $$),
+ '42501|permission denied for function parse_birth_year||', 'A cannot call the year parser directly');
+select is(pg_temp.err($$ select private.utc_tomorrow(now()) $$),
+ '42501|permission denied for function utc_tomorrow||', 'A cannot call the date bound directly');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 8. Write budget shared with the clients (one counter per workspace)
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000f');
+insert into pg_temp.ids values
+ ('f_client', (public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Client') ->> 'id')::uuid);
+reset role;
+update private.workspace_write_budgets set hour_count = 999, day_count = 999
+where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f');
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000f');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'Two writes',
+ 'equine', 'male', client_id => pg_temp.id('f_client'), relation_role => 'owner') $$),
+ 'P0001|rate_limited||', 'an animal with its relation needs two writes: refused at 999 of 1 000');
+select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '999/999', 'the refused create consumed nothing');
+select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000f')), 0::bigint,
+ 'and left no animal behind');
+insert into pg_temp.ids values ('f_animal', (public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'),
+ '72000000-0000-0000-0000-000000000001', 'Budget Animal', 'equine', 'male') ->> 'id')::uuid);
+select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write (an animal) passes');
+select is(pg_temp.err($$ select public.create_client(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Late') $$),
+ 'P0001|rate_limited||', 'the next client write is refused: one budget for clients and animals');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('f_animal'), pg_temp.id('f_client'), gen_random_uuid(), 'owner') $$),
+ 'P0001|rate_limited||', 'so is a relation');
+select is((public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000f'), '72000000-0000-0000-0000-000000000001',
+ 'Budget Animal', 'equine', 'male') ->> 'id')::uuid, pg_temp.id('f_animal'), 'a replay at the limit still answers');
+select is(public.update_animal(pg_temp.id('f_animal'), 1, 'Budget Animal', 'equine', 'male', null, null, null, null) ->> 'revision',
+ '1', 'a no-op at the limit still answers');
+select is(pg_temp.budget(pg_temp.ws('70000000-0000-0000-0000-00000000000f')), '1000/1000', 'neither consumed anything');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 9. Caps: 20 current and 200 relations per animal, 20 000 animals and
+-- 100 000 relations per workspace (rows inserted as postgres)
+-- ---------------------------------------------------------------------------
+insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'person', 'Cap client ' || g, gen_random_uuid(), '\x00'
+from generate_series(1, 22) g;
+insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Cap animal ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
+from generate_series(1, 2) g;
+insert into pg_temp.ids select 'e_animal_' || substr(name, 12), id from public.animals
+where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e');
+insert into pg_temp.ids select 'e_client_' || substr(display_name, 12), id from public.clients
+where workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000e');
+-- Animal 1: 20 current relations with 20 clients.
+insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_1'), pg_temp.id('e_client_' || g), 'contact',
+ gen_random_uuid(), '\x00'
+from generate_series(1, 20) g;
+-- Animal 2: 198 ended relations and one voided current one: 199 rows, none current.
+insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, voided_at,
+ create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), pg_temp.id('e_animal_2'), pg_temp.id('e_client_1'), 'contact',
+ case when g < 199 then now() end, case when g = 199 then now() end, gen_random_uuid(), '\x00'
+from generate_series(1, 199) g;
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$),
+ 'P0001|limit_reached||', 'the 21st current relation of an animal is refused');
+reset role;
+update public.animal_client_relations set voided_at = now()
+where animal_id = pg_temp.id('e_animal_1') and client_id = pg_temp.id('e_client_20');
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
+select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_1'), pg_temp.id('e_client_21'), gen_random_uuid(), 'owner') $$,
+ 'a voided relation frees a current slot');
+select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_2'), gen_random_uuid(), 'owner') $$,
+ 'the 200th relation of an animal is accepted (ended and voided rows count)');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('e_animal_2'), pg_temp.id('e_client_3'), gen_random_uuid(), 'owner') $$),
+ 'P0001|limit_reached||', 'the 201st is refused although only one is current');
+reset role;
+insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-00000000000e'), 'Bulk ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
+from generate_series(1, 19997) g;
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-00000000000e');
+select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001',
+ 'Cap last', 'equine', 'male') $$, 'the 20 000th animal is accepted');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'Cap over',
+ 'equine', 'male') $$), 'P0001|limit_reached||', 'the 20 001st animal is refused');
+select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-00000000000e'), '73000000-0000-0000-0000-000000000001',
+ 'Cap last', 'equine', 'male') $$, 'a replay at the cap still answers');
+reset role;
+
+-- H: 99 999 relations (ended) in one workspace, then the 100 000th through the RPC.
+insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest)
+values (pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'person', 'Bulk client', gen_random_uuid(), '\x00');
+insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-000000000011'), 'H ' || g, 'equine', 'male', gen_random_uuid(), '\x00'
+from generate_series(1, 501) g;
+-- Animals numbered 1 to 501 by name: 1 holds 199 rows, 2 to 500 hold 200, 501 none.
+create table pg_temp.h_animals as
+ select id, substr(name, 3)::integer as n from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011');
+insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, ended_at, create_request_id, create_request_digest)
+select pg_temp.ws('70000000-0000-0000-0000-000000000011'), a.id, c.id, 'contact', now(), gen_random_uuid(), '\x00'
+from pg_temp.h_animals a cross join generate_series(1, 200) g
+cross join (select id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')) c
+where a.n <= 500 and (a.n > 1 or g < 200);
+select is((select count(*) from public.animal_client_relations where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011')),
+ 99999::bigint, 'H holds 99 999 relations');
+insert into pg_temp.ids select 'h_client', id from public.clients where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000011');
+insert into pg_temp.ids select 'h_1', id from pg_temp.h_animals where n = 1;
+insert into pg_temp.ids select 'h_free', id from pg_temp.h_animals where n = 501;
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-000000000011');
+select lives_ok($$ select public.create_animal_client_relation(pg_temp.id('h_1'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$,
+ 'the 100 000th relation of a workspace is accepted');
+select is(pg_temp.err($$ select public.create_animal_client_relation(pg_temp.id('h_free'), pg_temp.id('h_client'), gen_random_uuid(), 'owner') $$),
+ 'P0001|limit_reached||', 'the 100 001st is refused, on an animal without any relation');
+select is(pg_temp.err($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000011'), gen_random_uuid(), 'H new',
+ 'equine', 'male', client_id => pg_temp.id('h_client'), relation_role => 'owner') $$),
+ 'P0001|limit_reached||', 'an animal with an initial relation too');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 10. Audit: one row per write, ids only, hidden from platform staff (N9)
+-- ---------------------------------------------------------------------------
+select is(
+ (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_bijou_paul_1')),
+ 'animal_client_relation.created,animal_client_relation.ended,animal_client_relation.updated',
+ 'each write of a relation leaves one audit row'
+);
+select is(
+ (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs
+ where resource_id in (pg_temp.id('tonnerre'), pg_temp.id('r_tonnerre'))),
+ 'animal.created,animal_client_relation.created', 'create_animal with a relation leaves two rows'
+);
+select is(
+ (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('r_rex_marie_wrong')),
+ 'animal_client_relation.created,animal_client_relation.voided', 'voiding is audited as such'
+);
+select is(
+ (select string_agg(action, ',' order by occurred_at, action collate "C") from audit.audit_logs where resource_id = pg_temp.id('bijou')),
+ 'animal.archived,animal.created,animal.restored,animal.updated', 'archive and restore are audited'
+);
+select is(
+ (select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')
+ and resource_id in (select id from pg_temp.ids)
+ and ((metadata - 'workspace_id') <> '{}'::jsonb
+ or (metadata ->> 'workspace_id')::uuid not in (select id from public.workspaces))),
+ 0::bigint, 'audit metadata is the workspace id only'
+);
+select is(
+ (select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')
+ -- The workspace uuid is left out: its hex digits can read as a year (« …2012-… »); the test above proves it is the only key.
+ and ((metadata - 'workspace_id')::text ~* '(eclair|bijou|tonnerre|furet|selle|owner|keeper|contact|20[0-9]{2}-)'
+ or correlation_id is not null)),
+ 0::bigint, 'no name, role, breed or date in the audit rows'
+);
+select is(
+ (select count(*) from audit.audit_logs where resource_id = pg_temp.id('eclair')
+ and actor_user_id is distinct from '70000000-0000-0000-0000-00000000000a'),
+ 0::bigint, 'the actor is the caller'
+);
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-000000000005');
+select is((select count(*) from audit.audit_logs where split_part(action, '.', 1) in ('animal', 'animal_client_relation')),
+ 0::bigint, 'S reads no animal or relation audit row');
+reset role;
+
+-- ---------------------------------------------------------------------------
+-- 11. Integrity without the RPCs: a privileged writer (postgres, past RLS)
+-- still meets the constraints
+-- ---------------------------------------------------------------------------
+select throws_ok(
+ $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
+ values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner', gen_random_uuid(), '\x00') $$,
+ '23503', null, 'a relation to a client of another workspace is refused by the composite foreign key');
+select throws_ok(
+ $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
+ values (pg_temp.ws('70000000-0000-0000-0000-00000000000b'), pg_temp.id('eclair'), pg_temp.id('b_client'), 'owner',
+ gen_random_uuid(), '\x00') $$,
+ '23503', null, 'a relation claiming the other workspace is refused too (the animal is not there)');
+select throws_ok(
+ $$ update public.animal_client_relations set client_id = pg_temp.id('b_client') where id = pg_temp.id('r_eclair_marie_owner') $$,
+ '23503', null, 'repointing a relation to a client of another workspace is refused');
+select throws_ok(
+ $$ update public.animal_client_relations set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b')
+ where id = pg_temp.id('r_eclair_marie_owner') $$,
+ '23503', null, 'moving a relation to another workspace is refused');
+select throws_ok(
+ $$ update public.animals set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('eclair') $$,
+ '23503', null, 'moving an animal that has relations to another workspace is refused');
+select throws_ok(
+ $$ update public.clients set workspace_id = pg_temp.ws('70000000-0000-0000-0000-00000000000b') where id = pg_temp.id('marie') $$,
+ '23503', null, 'moving a client that has relations to another workspace is refused');
+select throws_ok(
+ $$ insert into public.animal_client_relations (workspace_id, animal_id, client_id, relation_role, create_request_id, create_request_digest)
+ values (pg_temp.wa(), pg_temp.id('eclair'), pg_temp.id('marie'), 'owner', gen_random_uuid(), '\x00') $$,
+ '23505', null, 'a second current identical relation is refused by the partial unique index');
+select throws_ok(
+ $$ update public.animal_client_relations set ended_on = '2020-01-01' where id = pg_temp.id('r_eclair_marie_owner') $$,
+ '23514', null, 'an end date without an end is refused');
+select throws_ok(
+ $$ update public.animal_client_relations set ended_at = now(), started_on = '2021-01-01', ended_on = '2020-01-01'
+ where id = pg_temp.id('r_eclair_marie_owner') $$,
+ '23514', null, 'an end before the start is refused');
+select throws_ok(
+ $$ update public.animal_client_relations set started_on = '1899-12-31' where id = pg_temp.id('r_eclair_marie_owner') $$,
+ '23514', null, 'a start before 1900 is refused');
+select throws_ok(
+ $$ update public.animals set birth_date = '2014-01-01' where id = pg_temp.id('eclair') $$,
+ '23514', null, 'a birth date out of its year is refused');
+select throws_ok(
+ $$ update public.animals set birth_year = null where id = pg_temp.id('eclair') $$,
+ '23514', null, 'a birth date without its year is refused');
+select throws_ok(
+ $$ update public.animals set species_detail = null where id = pg_temp.id('furet') $$,
+ '23514', null, 'other without detail is refused');
+select throws_ok(
+ $$ update public.animals set species_id = 'unicorn' where id = pg_temp.id('rex') $$,
+ '23503', null, 'an unknown species is refused by the foreign key');
+select throws_ok(
+ $$ delete from public.animals where id = pg_temp.id('eclair') $$,
+ '23503', null, 'an animal with relations cannot be deleted');
+select throws_ok(
+ $$ delete from public.clients where id = pg_temp.id('lac') $$,
+ '23503', null, 'a client with relations cannot be deleted');
+
+-- ---------------------------------------------------------------------------
+-- 12. Account deletion (D9a)
+-- ---------------------------------------------------------------------------
+set local role authenticated;
+select pg_temp.act_as('70000000-0000-0000-0000-000000000012');
+select lives_ok($$ select public.create_animal(pg_temp.ws('70000000-0000-0000-0000-000000000012'), gen_random_uuid(), 'Seul', 'equine', 'male') $$,
+ 'G creates one animal and no client');
+reset role;
+select throws_ok(
+ $$ delete from auth.users where id = '70000000-0000-0000-0000-000000000012' $$,
+ '23503', null, 'an account whose workspace holds an animal cannot be deleted (D9a)'
+);
+select is((select count(*) from public.animals where workspace_id = pg_temp.ws('70000000-0000-0000-0000-000000000012')), 1::bigint,
+ 'its animal is intact');
+
+select * from finish();
+rollback;