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 ( +
+
+ + + +
+ +

{clicks}

+ +
+ ) +} + +function Harness() { + const [scenario, setScenario] = useState(null) + const [busy, setBusy] = useState(true) + const [item, setItem] = useState(true) + const close = () => setScenario(null) + return ( +
+

Dialog harness

+ +
+ + {item && ( + + )} +
+ {/* Taller than any viewport: the page would scroll if the dialog let it. */} +
+ ) +} + +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: /^ + + ) +} 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}`)} + +
+ ) + + const record = state.record + const archived = record.archived_at !== null + + return ( +
+ + {t('animals.detail.back')} + +
+
+

+ {record.name} +

+ {archived && {t('animals.archived_badge')}} +
+
+ {archived ? ( + + ) : ( + <> + + {t('animals.detail.edit')} + + + + )} +
+
+ + {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}`)} + +
+ )} + {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" + /> + + + + + +
    + + {/* 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}`)} + +
    + )} + {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 && ( +
    + +
    + )} + + )} +
    + ) +} 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 ( + +

    + {t('clients.detail.contact')} +

    + {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}`)} + +
    + ) + + 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 ? ( + + ) : ( + <> + + {t('clients.detail.edit')} + + + + )} +
    +
    + + {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}`)} + +
    + )} + {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" + /> + + +
    + + {/* 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}`)} + +
    + )} + {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 && ( +
    + +
    + )} + + )} +
    + ) +} 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" + >
    - + + )} + + +

    + {t('animals.form.identity_title')} +

    + {textField( + 'name', + t('animals.form.name'), + ANIMAL_FIELD_LIMITS.name, + true, + )} + + + + {species.status === 'error' && ( +
    + {t('animals.form.species_failed')} + +
    + )} + {values.species_id === OTHER_SPECIES && + textField( + 'species_detail', + t('animals.form.species_detail'), + ANIMAL_FIELD_LIMITS.speciesDetail, + true, + t('animals.form.species_detail_hint'), + )} + ({ + value, + label: t(`animals.sex.${value}`), + }))} + value={values.sex} + onChange={(value) => form.setField('sex')(value)} + hint={storedHint('sex') ?? t('animals.form.sex_hint')} + error={err('sex')} + /> + {textField( + 'breed', + t('animals.form.breed'), + ANIMAL_FIELD_LIMITS.breed, + false, + )} +
    + + +

    + {t('animals.form.birth_title')} +

    +
    + + form.setField('birth_year')(e.target.value)} + readOnly={yearLocked} + maxLength={4} + aria-invalid={Boolean(errors.birth_year)} + aria-describedby={describedBy('birth_year', yearHint)} + className={yearLocked ? 'bg-[var(--color-surface-strong)]' : ''} + /> + + + form.setBirthDate(e.target.value)} + aria-invalid={Boolean(errors.birth_date)} + aria-describedby={describedBy('birth_date', 'hint')} + className="sm:max-w-xs" + /> + +
    +
    + + {form.mode === 'create' && ( + +
    +

    + {t('animals.form.client_title')} +

    +

    + {t('animals.form.client_hint')} +

    +
    + {relation.client ? ( + <> +
    +

    + {t('relations.panel.client_chosen')}{' '} + + {relation.client.display_name} + +

    + +
    + ({ + value, + label: t(`clients.role.${value}`), + }))} + value={relation.relation_role} + onChange={form.setRelationRole} + error={relErr('relation_role')} + /> + + form.setStartedOn(e.target.value)} + aria-invalid={Boolean(relationErrors.started_on)} + aria-describedby={ + relationErrors.started_on + ? `${FIELD_IDS.started_on}-error` + : `${FIELD_IDS.started_on}-hint` + } + className="sm:max-w-xs" + /> + + + ) : ( + + form.chooseClient({ id: chosen.id, display_name: chosen.name }) + } + /> + )} +
    + )} + + {phase.kind === 'failed' && !stored && ( + {t(`animals.failure.${phase.failure}`)} + )} +
    + + {t('common.cancel')} + + +
    + + ) +} 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. */} + + +
    +
    + ) +} 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. */} + + +
    +
    + ) +} 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')} + + +
    + )} +
    + {state.status === 'loading' && ( +

    + {t('clients.animals.loading')} +

    + )} + {state.status === 'error' && ( +
    + {t(`clients.failure.${state.failure}`)} + +
    + )} + {empty && ( +

    + {t('clients.animals.none')} +

    + )} + {state.status === 'ready' && ( + <> + {section(byAnimal(state.rows, true), true)} + {section(byAnimal(state.rows, false), false)} + {state.next && ( + + )} + + )} + {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 ( +
    + {stored && ( + +

    {t('clients.form.conflict_title')}

    +

    {t('clients.form.conflict_body')}

    + +
    + )} + +
    + + {t('clients.form.kind_legend')} + +
    + {(['person', 'organization'] as const).map((kind) => ( + + ))} +
    + {storedHint('kind') && ( +

    + {storedHint('kind')} +

    + )} +
    + + form.setField('display_name')(e.target.value)} + maxLength={CLIENT_FIELD_LIMITS.displayName} + autoComplete="off" + aria-invalid={Boolean(errors.display_name)} + aria-describedby={describedBy('display_name', nameHint)} + required + /> + +
    + + +

    + {t('clients.form.contact_title')} +

    +
    + {textField( + 'email', + t('clients.form.email'), + CLIENT_FIELD_LIMITS.email, + { + type: 'email', + inputMode: 'email', + autoComplete: 'off', + }, + )} + + form.setField('phone')(e.target.value)} + onBlur={form.convertPhone} + maxLength={32} + aria-invalid={Boolean(errors.phone)} + aria-describedby={describedBy('phone', 'hint')} + /> + +
    +
    + + +

    + {t('clients.form.address_title')} +

    + {textField( + 'address_line1', + t('clients.form.address_line1'), + CLIENT_FIELD_LIMITS.addressLine, + { + autoComplete: 'off', + }, + )} + {textField( + 'address_line2', + t('clients.form.address_line2'), + CLIENT_FIELD_LIMITS.addressLine, + { + autoComplete: 'off', + }, + )} +
    + {textField( + 'postal_code', + t('clients.form.postal_code'), + CLIENT_FIELD_LIMITS.postalCode, + { + autoComplete: 'off', + }, + )} + {textField('city', t('clients.form.city'), CLIENT_FIELD_LIMITS.city, { + autoComplete: 'off', + })} +
    + + + +
    + + {phase.kind === 'failed' && !stored && ( + {t(`clients.failure.${phase.failure}`)} + )} +
    + + {t('common.cancel')} + + +
    +
    + ) +} 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) => ( + + ) + 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 ( +
    +

    + {t(key)} +

    +
      + {rows.map(row)} +
    +
    + ) + } + + const groups = + state.status === 'ready' ? groupRelations(state.relations) : null + + return ( + +
    +

    + {t('relations.title')} +

    + {editable && !panelOpen && ( + + )} +
    + {state.status === 'loading' && ( +

    + {t('relations.loading')} +

    + )} + {state.status === 'error' && ( +
    + + {t(`relations.failure.${state.failure}`)} + + +
    + )} + {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}`)} + + +
    + )} + {results.status === 'ready' && results.items.length === 0 && ( +

    + {emptyLabel} +

    + )} + {results.status === 'ready' && results.items.length > 0 && ( +
      + {results.items.map((row) => { + const item = toItem(row) + return ( +
    • + +
    • + ) + })} +
    + )} +
    + ) +} 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. */} + + +
    +
    + ) +} 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 ( +
    +

    + {t( + props.pick === 'client' + ? 'relations.panel.title_client' + : 'relations.panel.title_animal', + )} +

    + {chosen ? ( +
    +

    + {t(pickLabel)} {chosen.name} +

    + +
    + ) : props.pick === 'client' ? ( + + ) : ( + + )} + ({ + value, + label: t(`clients.role.${value}`), + }))} + value={role} + onChange={setRole} + error={err('relation_role')} + /> + + setStartedOn(e.target.value)} + aria-invalid={Boolean(errors.started_on)} + aria-describedby={ + errors.started_on + ? `${FIELD_IDS.started_on}-error` + : `${FIELD_IDS.started_on}-hint` + } + className="sm:max-w-xs" + /> + + {failure && ( + {t(`relations.failure.${failure}`)} + )} +
    + + +
    + + ) +} 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}

    -
    - -
    +
    +
    ) 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', - )} -

    + +
    +
    ) } 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 - -
    {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.

    } + > + +
    , + ) + 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"> + + , + ) + 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( + + + , + ) + 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( + + + , + ) + 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( + + + , + ) + 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 ( +
    +
    + + {openerShown && ( + + )} +
    + setOpen(false)} title="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-