merge: integrate V1-1 clients and animals into develop
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
This commit is contained in:
commit
9135d73cfa
157 files changed
+25273
-704
No files matched your search
@@ -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 `<dialog>` + `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).
|
||||
@@ -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.
|
||||
@@ -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 <v> <then>` (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.
|
||||
@@ -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 <pkg> -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 `<dialog>` 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.
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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_<service>_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 <cmd>`. Root scripts resolve `node_modules/.bin/pnpm`.
|
||||
@@ -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.
|
||||
@@ -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<string, string>`)
|
||||
- Key convention: `<area>.<key>` — 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
|
||||
@@ -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 `⚠`).
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 `<sha256>.svg`; uploads are an operator task
|
||||
(`pnpm assets:upload <seed dir>` with the service key in env), never from the browser.
|
||||
@@ -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/<owner>/<id>/avatar.webp`, `quarantine/<owner>/<id>/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).
|
||||
@@ -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)
|
||||
+153
-3
@@ -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/<ts>_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 `<ts>_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/<ts>_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 `<dialog>` + `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 <version> [<then>]` 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/<ts>_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
|
||||
|
||||
@@ -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.
|
||||
@@ -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 "<read-only SQL>" | 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.
|
||||
@@ -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 "<read-only SQL>" | 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 `<dialog>` + `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.
|
||||
@@ -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
|
||||
`<then>`), 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 "<read-only SQL>" | 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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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/
|
||||
@@ -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`).
|
||||
|
||||
@@ -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 <version> [<then>]|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_<service>_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 <cmd>`. 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 <spec> [--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 <dialog> 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<string, string>`)
|
||||
- Key convention: `<area>.<key>` — 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/<owner>/<id>/avatar.webp`, `quarantine/<owner>/<id>/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 `<sha256>.svg`; uploads are an operator task
|
||||
(`pnpm assets:upload <seed dir>` with the service key in env), never from the browser.
|
||||
|
||||
### Component stubs
|
||||
- Scaffold stubs render <div>ComponentName placeholder</div>
|
||||
- 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/<name>.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.
|
||||
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Dialog harness</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./dialog.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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 (
|
||||
<section className="space-y-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button onClick={() => onOpen('basic')}>Open basic</Button>
|
||||
<Button onClick={() => onOpen('long')}>Open long</Button>
|
||||
<Button onClick={() => onOpen('guarded')}>Open guarded</Button>
|
||||
</div>
|
||||
<Button variant="secondary" onClick={() => setClicks((n) => n + 1)}>
|
||||
Background action
|
||||
</Button>
|
||||
<p data-testid="background-clicks">{clicks}</p>
|
||||
<label className="block text-sm">
|
||||
Background field <input className="border" />
|
||||
</label>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function Harness() {
|
||||
const [scenario, setScenario] = useState<Scenario>(null)
|
||||
const [busy, setBusy] = useState(true)
|
||||
const [item, setItem] = useState(true)
|
||||
const close = () => setScenario(null)
|
||||
return (
|
||||
<main className="mx-auto max-w-2xl space-y-6 p-4">
|
||||
<h1 className="text-xl font-semibold">Dialog harness</h1>
|
||||
<Background onOpen={setScenario} />
|
||||
<section className="flex gap-2" data-testid="items">
|
||||
<Button variant="ghost" onClick={() => setItem(true)}>
|
||||
Add item
|
||||
</Button>
|
||||
{item && (
|
||||
<Button variant="danger" onClick={() => setScenario('vanishing')}>
|
||||
Remove item
|
||||
</Button>
|
||||
)}
|
||||
</section>
|
||||
{/* Taller than any viewport: the page would scroll if the dialog let it. */}
|
||||
<div className="h-[200vh]" aria-hidden="true" />
|
||||
|
||||
<Dialog
|
||||
open={scenario === 'basic'}
|
||||
onClose={close}
|
||||
title="Basic dialog"
|
||||
description={<p>Three controls follow.</p>}
|
||||
>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<Button variant="ghost">First</Button>
|
||||
<Button variant="ghost">Second</Button>
|
||||
<Button onClick={close}>Done</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={scenario === 'long'}
|
||||
onClose={close}
|
||||
title="Long dialog"
|
||||
size="lg"
|
||||
>
|
||||
{Array.from({ length: 60 }, (_, i) => (
|
||||
<p key={i} className="py-1 text-sm">
|
||||
Paragraph {i + 1}: long content that the panel scrolls on its own.
|
||||
</p>
|
||||
))}
|
||||
<Button onClick={close}>End of content</Button>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={scenario === 'guarded'}
|
||||
onClose={() => !busy && close()}
|
||||
title="Guarded dialog"
|
||||
description={<p>Closing is refused while the box is checked.</p>}
|
||||
>
|
||||
<label className="mt-4 flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={busy}
|
||||
onChange={(e) => setBusy(e.target.checked)}
|
||||
/>
|
||||
Busy
|
||||
</label>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={scenario === 'vanishing'}
|
||||
onClose={close}
|
||||
title="Remove the item?"
|
||||
description={<p>The button that opened this dialog disappears.</p>}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button
|
||||
variant="danger"
|
||||
onClick={() => {
|
||||
setItem(false)
|
||||
close()
|
||||
}}
|
||||
>
|
||||
Confirm removal
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<StrictMode>
|
||||
<Harness />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -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<GuardOptions>({
|
||||
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,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -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<GuardOptions>({
|
||||
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: '' },
|
||||
},
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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')
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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`)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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<string[]> {
|
||||
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\/?$/)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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<GuardOptions & { requests: RequestGuard }>({
|
||||
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, '<fixture>'),
|
||||
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: /^<button [^>]*aria-label="(Passer en français|Switch to English)"/,
|
||||
path: /^\//,
|
||||
note: 'LanguageSwitcher (every page): shows « FR » / « EN », named « Passer en français » / « Switch to English »',
|
||||
},
|
||||
{
|
||||
id: 'label-content-name-mismatch',
|
||||
target: /^\.pr-1$/,
|
||||
html: /^<a [^>]*href="\/app\/account"/,
|
||||
path: /^\/app(\/|$)/,
|
||||
note: 'AppLayout top bar account link: shows the display name, named « Mon compte » / « My account »',
|
||||
},
|
||||
{
|
||||
id: 'definition-list',
|
||||
target: /^dl$/,
|
||||
html: /^<dl class="grid gap-2 text-sm">/,
|
||||
path: /^\/app\/?$/,
|
||||
note: 'DashboardRoute account card: the verified-status row is a div without dt/dd inside the dl',
|
||||
},
|
||||
]
|
||||
|
||||
const isKnown = (id: string, target: string, html: string, path: string) =>
|
||||
KNOWN_VIOLATIONS.some(
|
||||
(known) =>
|
||||
known.id === id &&
|
||||
known.target.test(target) &&
|
||||
known.html.test(html) &&
|
||||
known.path.test(path),
|
||||
)
|
||||
|
||||
/**
|
||||
* Zero serious or critical axe violation on the page as it stands (WCAG 2.0 to
|
||||
* 2.2 A and AA rules plus axe best practices), known ones aside; the failure
|
||||
* message lists them.
|
||||
*/
|
||||
export async function expectAccessible(
|
||||
page: Page,
|
||||
state: string,
|
||||
): Promise<void> {
|
||||
// Colours are measured at rest: an entrance animation still running would blend them.
|
||||
await page.waitForFunction(() =>
|
||||
document
|
||||
.getAnimations()
|
||||
.every((animation) => animation.playState !== 'running'),
|
||||
)
|
||||
const { violations } = await new AxeBuilder({ page })
|
||||
.withTags([
|
||||
'wcag2a',
|
||||
'wcag2aa',
|
||||
'wcag21a',
|
||||
'wcag21aa',
|
||||
'wcag22aa',
|
||||
'best-practice',
|
||||
])
|
||||
.analyze()
|
||||
const path = new URL(page.url()).pathname
|
||||
const blocking = violations
|
||||
.filter((v) => v.impact === 'serious' || v.impact === 'critical')
|
||||
.flatMap((v) =>
|
||||
v.nodes
|
||||
.filter(
|
||||
(node) => !isKnown(v.id, node.target.join(' '), node.html, path),
|
||||
)
|
||||
.map(
|
||||
(node) =>
|
||||
`${v.impact} ${v.id}: ${v.help} → ${node.target.join(' ')} on ${path}`,
|
||||
),
|
||||
)
|
||||
expect(blocking, `axe on ${state}`).toEqual([])
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the focus is: in the open modal dialog, in the browser's own interface
|
||||
* (the document lost focus, as Tab past a modal dialog's last control does), or
|
||||
* on something else of the page.
|
||||
*/
|
||||
export function focusOwner(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const active = document.activeElement
|
||||
if (!document.hasFocus()) return 'browser'
|
||||
if (!active || active === document.body) return 'body'
|
||||
if (active.closest('dialog:modal')) return 'dialog'
|
||||
return `outside:${active.tagName.toLowerCase()}:${active.textContent?.trim().slice(0, 40)}`
|
||||
})
|
||||
}
|
||||
|
||||
/** Accessible name of the focused element (aria-label, else its text). */
|
||||
export function focusedName(page: Page): Promise<string> {
|
||||
return page.evaluate(() => {
|
||||
const active = document.activeElement as HTMLElement | null
|
||||
return (
|
||||
active?.getAttribute('aria-label') ?? active?.textContent?.trim() ?? ''
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** No horizontal page scroll: the document is no wider than the viewport. */
|
||||
export async function expectNoHorizontalOverflow(
|
||||
page: Page,
|
||||
state: string,
|
||||
): Promise<void> {
|
||||
const { scrollWidth, clientWidth } = await page.evaluate(() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
}))
|
||||
expect(scrollWidth, `horizontal overflow on ${state}`).toBeLessThanOrEqual(
|
||||
clientWidth,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Setup rows of the shell suites, written as postgres in an account's
|
||||
* workspace of the isolated stack: the subject of a test goes through the
|
||||
* page, its surroundings through here. Values are fictitious literals; each
|
||||
* one is quoted as an SQL literal, never pasted raw.
|
||||
*/
|
||||
import { sql } from '../../../../packages/supabase/tests/sandbox/stack'
|
||||
import { workspaceOf, type SandboxAccount } from './sandbox'
|
||||
|
||||
/** A text as an SQL literal ('' doubles a quote), or null. */
|
||||
export const literal = (value: string | null) =>
|
||||
value === null ? 'null' : `'${value.replaceAll("'", "''")}'`
|
||||
|
||||
export interface ClientSeed {
|
||||
kind?: 'person' | 'organization'
|
||||
city?: string | null
|
||||
phone?: string | null
|
||||
email?: string | null
|
||||
addressLine1?: string | null
|
||||
}
|
||||
|
||||
export async function seedClient(
|
||||
account: SandboxAccount,
|
||||
displayName: string,
|
||||
seed: ClientSeed = {},
|
||||
): Promise<string> {
|
||||
const ws = await workspaceOf(account)
|
||||
return sql(`insert into public.clients (workspace_id, kind, display_name, city, phone, email, address_line1,
|
||||
create_request_id, create_request_digest)
|
||||
values (${literal(ws)}, ${literal(seed.kind ?? 'person')}, ${literal(displayName)}, ${literal(seed.city ?? null)},
|
||||
${literal(seed.phone ?? null)}, ${literal(seed.email ?? null)}, ${literal(seed.addressLine1 ?? null)},
|
||||
gen_random_uuid(), '\\x00') returning id`)
|
||||
}
|
||||
|
||||
export async function seedAnimal(
|
||||
account: SandboxAccount,
|
||||
name: string,
|
||||
speciesId = 'equine',
|
||||
sex: 'male' | 'female' | 'unknown' = 'female',
|
||||
): Promise<string> {
|
||||
const ws = await workspaceOf(account)
|
||||
return sql(`insert into public.animals (workspace_id, name, species_id, sex, create_request_id, create_request_digest)
|
||||
values (${literal(ws)}, ${literal(name)}, ${literal(speciesId)}, ${literal(sex)}, gen_random_uuid(), '\\x00') returning id`)
|
||||
}
|
||||
|
||||
export async function seedRelation(
|
||||
account: SandboxAccount,
|
||||
animalId: string,
|
||||
clientId: string,
|
||||
role: 'owner' | 'keeper' | 'contact',
|
||||
startedOn: string | null = null,
|
||||
): Promise<string> {
|
||||
const ws = await workspaceOf(account)
|
||||
return sql(`insert into public.animal_client_relations
|
||||
(workspace_id, animal_id, client_id, relation_role, started_on, create_request_id, create_request_digest)
|
||||
values (${literal(ws)}, ${literal(animalId)}, ${literal(clientId)}, ${literal(role)}, ${literal(startedOn)},
|
||||
gen_random_uuid(), '\\x00') returning id`)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* The shell suite's backend: the throwaway stack of `pnpm db:sandbox`, never
|
||||
* DEV. The app is built against a fake origin that resolves nowhere; every
|
||||
* request to it is replayed on the sandbox's loopback services, the way Kong
|
||||
* maps them on the CLI stack. Accounts are fictitious and made per test.
|
||||
*/
|
||||
import { createHash, randomBytes, randomUUID } from 'node:crypto'
|
||||
import type { BrowserContext } from '@playwright/test'
|
||||
import { sql, stack } from '../../../../packages/supabase/tests/sandbox/stack'
|
||||
|
||||
/** The Supabase URL the e2e:shell dev server is built with (RFC 6761 `.invalid`). */
|
||||
export const FAKE_SUPABASE_ORIGIN = 'http://sandbox.faunosteo.invalid'
|
||||
|
||||
const storageUrl = process.env.SANDBOX_STORAGE_URL
|
||||
if (!storageUrl)
|
||||
throw new Error('SANDBOX_STORAGE_URL missing: run pnpm e2e:shell')
|
||||
|
||||
const ROUTES: [prefix: string, target: string][] = [
|
||||
['/auth/v1/', `${stack.authUrl}/`],
|
||||
['/rest/v1/', `${stack.restUrl}/`],
|
||||
['/storage/v1/', `${storageUrl}/`],
|
||||
]
|
||||
|
||||
/** The sandbox URL a request to the fake Supabase origin maps to, or null when unmapped. */
|
||||
export function sandboxUrl(url: string): string | null {
|
||||
const { pathname, search } = new URL(url)
|
||||
const path = pathname + search
|
||||
const mapped = ROUTES.find(([prefix]) => path.startsWith(prefix))
|
||||
return mapped ? mapped[1] + path.slice(mapped[0].length) : null
|
||||
}
|
||||
|
||||
/** Replays the page's Supabase calls on the sandbox; an unmapped path is refused. */
|
||||
export async function routeToSandbox(context: BrowserContext): Promise<void> {
|
||||
await context.route(`${FAKE_SUPABASE_ORIGIN}/**`, async (route) => {
|
||||
const target = sandboxUrl(route.request().url())
|
||||
if (!target) return route.abort('blockedbyclient')
|
||||
const response = await route.fetch({ url: target })
|
||||
await route.fulfill({ response })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* After a test: removes the replay without waiting for it. A page may still be
|
||||
* reading (a list, a section reloaded after a change) when the last check
|
||||
* passed; that answer is dropped with the context instead of failing the test.
|
||||
*/
|
||||
export async function dropLateReplays(context: BrowserContext): Promise<void> {
|
||||
await context.unrouteAll({ behavior: 'ignoreErrors' })
|
||||
}
|
||||
|
||||
/** 1 × 1 lossless WebP: a real image for the clean avatar the account starts with. */
|
||||
const AVATAR_WEBP = Buffer.from(
|
||||
'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==',
|
||||
'base64',
|
||||
)
|
||||
|
||||
export interface SandboxAccount {
|
||||
id: string
|
||||
email: string
|
||||
password: string
|
||||
displayName: string
|
||||
}
|
||||
|
||||
async function admin(path: string, init: RequestInit): Promise<Response> {
|
||||
const response = await fetch(`${stack.authUrl}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Authorization: `Bearer ${stack.serviceKey}`,
|
||||
apikey: stack.serviceKey,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
if (!response.ok)
|
||||
throw new Error(`sandbox admin ${path}: HTTP ${response.status}`)
|
||||
return response
|
||||
}
|
||||
|
||||
/** The clean avatar the worker would have produced: row as postgres, object with the service key. */
|
||||
async function seedAvatar(ownerId: string): Promise<void> {
|
||||
const assetId = randomUUID()
|
||||
const key = `profiles/${ownerId}/${assetId}/avatar.webp`
|
||||
const sha256 = createHash('sha256').update(AVATAR_WEBP).digest('hex')
|
||||
const upload = await fetch(`${storageUrl}/object/avatars/${key}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${stack.serviceKey}`,
|
||||
'Content-Type': 'image/webp',
|
||||
},
|
||||
body: AVATAR_WEBP,
|
||||
})
|
||||
if (!upload.ok)
|
||||
throw new Error(`sandbox avatar upload: HTTP ${upload.status}`)
|
||||
await sql(`insert into public.assets
|
||||
(id, owner_id, kind, bucket_id, object_key, status, declared_mime, declared_size, byte_size, sha256)
|
||||
values ('${assetId}', '${ownerId}', 'profile_avatar', 'avatars', '${key}', 'clean',
|
||||
'image/webp', ${AVATAR_WEBP.length}, ${AVATAR_WEBP.length}, '${sha256}')`)
|
||||
}
|
||||
|
||||
/**
|
||||
* A confirmed fictitious account, its profile in `locale`, with or without a
|
||||
* photo; `localPart` starts the address (a long one tests narrow screens).
|
||||
*/
|
||||
export async function createAccount(
|
||||
locale: 'fr' | 'en',
|
||||
withAvatar: boolean,
|
||||
localPart = 'e2e-shell',
|
||||
): Promise<SandboxAccount> {
|
||||
const tag = randomUUID().slice(0, 8)
|
||||
const account = {
|
||||
email: `${localPart}-${tag}@sandbox.local`,
|
||||
password: randomBytes(18).toString('base64url'),
|
||||
displayName: `Praticienne Fictive ${tag}`,
|
||||
}
|
||||
const response = await admin('/admin/users', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
email: account.email,
|
||||
password: account.password,
|
||||
email_confirm: true,
|
||||
user_metadata: { display_name: account.displayName, locale },
|
||||
}),
|
||||
})
|
||||
const { id } = (await response.json()) as { id: string }
|
||||
if (withAvatar) await seedAvatar(id)
|
||||
return { ...account, id }
|
||||
}
|
||||
|
||||
/** The personal workspace of a sandbox account (created by the server at sign-up). */
|
||||
export function workspaceOf(account: SandboxAccount): Promise<string> {
|
||||
return sql(
|
||||
`select id from public.workspaces where personal_user_id = '${account.id}'`,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Dict } from '@/i18n/types'
|
||||
import type { Page } from '@playwright/test'
|
||||
import { expect } from './browser'
|
||||
import type { SandboxAccount } from './sandbox'
|
||||
|
||||
/** Signs in through the login form; resolves on the dashboard once the profile answered. */
|
||||
export async function signIn(page: Page, account: SandboxAccount, dict: Dict) {
|
||||
await page.goto('/login')
|
||||
await page.getByLabel(dict['auth.email']).fill(account.email)
|
||||
await page
|
||||
.getByLabel(dict['auth.password'], { exact: true })
|
||||
.fill(account.password)
|
||||
await page.getByRole('button', { name: dict['auth.login.submit'] }).click()
|
||||
await expect(page).toHaveURL(/\/app\/?$/)
|
||||
// The greeting needs the profile: the session and the first REST call went through.
|
||||
await expect(page.locator('main h1')).toContainText(account.displayName)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node", "vite/client"],
|
||||
"baseUrl": "..",
|
||||
"paths": {
|
||||
"@/*": ["src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["."]
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { en } from '@/i18n/en'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import {
|
||||
expect,
|
||||
expectAccessible,
|
||||
expectNoHorizontalOverflow,
|
||||
focusOwner,
|
||||
focusedName,
|
||||
test,
|
||||
} from '../support/browser'
|
||||
import type { Page } from '@playwright/test'
|
||||
|
||||
// The D13 contract of components/ui/Dialog on its test page (e2e/harness/dialog.tsx).
|
||||
|
||||
async function openScenario(page: Page, opener: string, title: string) {
|
||||
await page.getByRole('button', { name: opener }).focus()
|
||||
await page.keyboard.press('Enter')
|
||||
const dialog = page.getByRole('dialog', { name: title })
|
||||
await expect(dialog).toBeVisible()
|
||||
return dialog
|
||||
}
|
||||
|
||||
/** Names of the elements the focus visits over `count` presses of `key`. */
|
||||
async function focusWalk(page: Page, key: 'Tab' | 'Shift+Tab', count: number) {
|
||||
const visited: { owner: string; name: string }[] = []
|
||||
for (let i = 0; i < count; i++) {
|
||||
await page.keyboard.press(key)
|
||||
visited.push({
|
||||
owner: await focusOwner(page),
|
||||
name: await focusedName(page),
|
||||
})
|
||||
}
|
||||
return visited
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/e2e/harness/dialog.html')
|
||||
await expect(
|
||||
page.getByRole('heading', { name: 'Dialog harness' }),
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
test('is a named, described modal dialog and moves focus into it', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
|
||||
await expect(dialog).toHaveAccessibleDescription('Three controls follow.')
|
||||
expect(
|
||||
await dialog.evaluate((d) => d.tagName === 'DIALOG' && d.matches(':modal')),
|
||||
).toBe(true)
|
||||
expect(await focusOwner(page)).toBe('dialog')
|
||||
expect(await focusedName(page)).toBe(fr['common.close'])
|
||||
})
|
||||
|
||||
// Past either end the focus visits the browser's interface (one step, the page
|
||||
// holds no focus) and comes back into the dialog; it never reaches the page.
|
||||
test('Tab and Shift+Tab cycle through the dialog, never the page', async ({
|
||||
page,
|
||||
}) => {
|
||||
await openScenario(page, 'Open basic', 'Basic dialog')
|
||||
const step = (f: { owner: string; name: string }) =>
|
||||
f.owner === 'dialog' ? f.name : f.owner
|
||||
const forward = await focusWalk(page, 'Tab', 10)
|
||||
expect(forward.map(step)).toEqual([
|
||||
'First',
|
||||
'Second',
|
||||
'Done',
|
||||
'browser',
|
||||
fr['common.close'],
|
||||
'First',
|
||||
'Second',
|
||||
'Done',
|
||||
'browser',
|
||||
fr['common.close'],
|
||||
])
|
||||
const backward = await focusWalk(page, 'Shift+Tab', 10)
|
||||
expect(backward.map(step)).toEqual([
|
||||
'browser',
|
||||
'Done',
|
||||
'Second',
|
||||
'First',
|
||||
fr['common.close'],
|
||||
'browser',
|
||||
'Done',
|
||||
'Second',
|
||||
'First',
|
||||
fr['common.close'],
|
||||
])
|
||||
})
|
||||
|
||||
test('the page behind is inert: no focus, no click, no scroll', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog')
|
||||
const background = page.getByRole('button', {
|
||||
name: 'Background action',
|
||||
includeHidden: true,
|
||||
})
|
||||
const box = await background.boundingBox()
|
||||
if (!box) throw new Error('background button not laid out')
|
||||
await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
|
||||
await background.evaluate((b) => (b as HTMLElement).focus())
|
||||
expect(await focusOwner(page)).toBe('dialog')
|
||||
await page.mouse.move(box.x + 5, box.y + 5)
|
||||
await page.mouse.wheel(0, 800)
|
||||
await page.waitForTimeout(200)
|
||||
expect(await page.evaluate(() => window.scrollY)).toBe(0)
|
||||
await expect(dialog).toBeVisible()
|
||||
await expect(page.getByTestId('background-clicks')).toHaveText('0')
|
||||
})
|
||||
|
||||
test('Escape closes when allowed and focus returns to the opener', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(dialog).toBeHidden()
|
||||
expect(await focusedName(page)).toBe('Open basic')
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Background action' }),
|
||||
).toBeEnabled()
|
||||
})
|
||||
|
||||
test('Escape is only a request: refused twice, the dialog stays open', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog')
|
||||
await page.keyboard.press('Escape')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(dialog).toBeVisible()
|
||||
expect(await dialog.evaluate((d) => (d as HTMLDialogElement).open)).toBe(true)
|
||||
expect(await focusOwner(page)).toBe('dialog')
|
||||
await page.getByRole('checkbox', { name: 'Busy' }).uncheck()
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(dialog).toBeHidden()
|
||||
expect(await focusedName(page)).toBe('Open guarded')
|
||||
})
|
||||
|
||||
test('the close button closes from the keyboard and restores focus', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open basic', 'Basic dialog')
|
||||
expect(await focusedName(page)).toBe(fr['common.close'])
|
||||
await page.keyboard.press('Enter')
|
||||
await expect(dialog).toBeHidden()
|
||||
expect(await focusedName(page)).toBe('Open basic')
|
||||
})
|
||||
|
||||
test('an opener gone on close hands focus to its container’s first control', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Remove item', 'Remove the item?')
|
||||
await page.getByRole('button', { name: 'Confirm removal' }).click()
|
||||
await expect(dialog).toBeHidden()
|
||||
await expect(page.getByRole('button', { name: 'Remove item' })).toHaveCount(0)
|
||||
expect(await focusedName(page)).toBe('Add item')
|
||||
})
|
||||
|
||||
test('long content scrolls inside the panel, the page stays put', async ({
|
||||
page,
|
||||
}) => {
|
||||
const dialog = await openScenario(page, 'Open long', 'Long dialog')
|
||||
const panel = dialog.locator('header').locator('..')
|
||||
const { scrollHeight, clientHeight } = await panel.evaluate((p) => ({
|
||||
scrollHeight: p.scrollHeight,
|
||||
clientHeight: p.clientHeight,
|
||||
}))
|
||||
expect(scrollHeight).toBeGreaterThan(clientHeight)
|
||||
expect(await focusedName(page)).toBe(fr['common.close'])
|
||||
await page.keyboard.press('Tab')
|
||||
const end = page.getByRole('button', { name: 'End of content' })
|
||||
await expect(end).toBeFocused()
|
||||
await expect(end).toBeInViewport()
|
||||
expect(await page.evaluate(() => window.scrollY)).toBe(0)
|
||||
const box = await panel.boundingBox()
|
||||
const viewport = page.viewportSize()
|
||||
expect(
|
||||
box && viewport && box.y >= 0 && box.y + box.height <= viewport.height,
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
test('fits the viewport without horizontal page scroll', async ({ page }) => {
|
||||
await expectNoHorizontalOverflow(page, 'the page')
|
||||
for (const [opener, title] of [
|
||||
['Open basic', 'Basic dialog'],
|
||||
['Open long', 'Long dialog'],
|
||||
]) {
|
||||
const dialog = await openScenario(page, opener, title)
|
||||
const box = await dialog.locator('header').locator('..').boundingBox()
|
||||
const width = page.viewportSize()?.width ?? 0
|
||||
expect(
|
||||
box && box.x >= 0 && box.x + box.width <= width,
|
||||
`${title} inside the viewport`,
|
||||
).toBe(true)
|
||||
await expectNoHorizontalOverflow(page, title)
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(dialog).toBeHidden()
|
||||
}
|
||||
})
|
||||
|
||||
for (const [lang, dict] of [
|
||||
['fr', fr],
|
||||
['en', en],
|
||||
] as const) {
|
||||
test(`axe finds no serious violation, close control named in ${lang}`, async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto(`/e2e/harness/dialog.html?lang=${lang}`)
|
||||
await expectAccessible(page, `the harness (${lang})`)
|
||||
await openScenario(page, 'Open basic', 'Basic dialog')
|
||||
await expect(
|
||||
page.getByRole('button', { name: dict['common.close'] }),
|
||||
).toBeFocused()
|
||||
await expectAccessible(page, `the open dialog (${lang})`)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { en } from '@/i18n/en'
|
||||
import { fr } from '@/i18n/fr'
|
||||
import {
|
||||
expect,
|
||||
expectAccessible,
|
||||
expectNoHorizontalOverflow,
|
||||
focusOwner,
|
||||
focusedName,
|
||||
test,
|
||||
} from '../support/browser'
|
||||
import type { Page } from '@playwright/test'
|
||||
import type { Dict } from '@/i18n/types'
|
||||
|
||||
// The shared Dialog where the local tool uses it, on the real routes with no
|
||||
// backend: the sheet disclaimer, the edit dialog and the replace confirmation.
|
||||
// Fictitious names only.
|
||||
|
||||
const ANIMAL = 'Fictif Alezan'
|
||||
|
||||
/** Required label text without the trailing « * » marker. */
|
||||
const label = (dict: Dict, key: string) => dict[key].replace(/\s*\*$/, '')
|
||||
|
||||
async function startReport(page: Page, dict: Dict) {
|
||||
await page
|
||||
.getByLabel(label(dict, 'form.practitioner.name'))
|
||||
.fill('Praticien Fictif')
|
||||
await page.getByLabel(label(dict, 'form.animal.name')).fill(ANIMAL)
|
||||
await page
|
||||
.getByLabel(label(dict, 'form.owner.name'))
|
||||
.fill('Propriétaire Fictif')
|
||||
await page.getByRole('button', { name: dict['new_report.submit'] }).click()
|
||||
}
|
||||
|
||||
for (const [locale, dict] of [
|
||||
['fr-FR', fr],
|
||||
['en-GB', en],
|
||||
] as const) {
|
||||
test.describe(`local tool (${locale})`, () => {
|
||||
test.use({ locale, forbiddenInUrls: [ANIMAL, 'Fictif'] })
|
||||
|
||||
test('editor dialogs: disclaimer, edit, replace confirmation', async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.goto('/')
|
||||
// Scanned once the sheet is loaded: the import button fades in from disabled.
|
||||
await expect(
|
||||
page.getByRole('button', { name: dict['home.import.cta'] }),
|
||||
).toBeEnabled()
|
||||
await expectAccessible(page, 'home')
|
||||
await page
|
||||
.getByRole('button', { name: dict['home.new_report.cta'] })
|
||||
.click()
|
||||
await expect(page).toHaveURL(/\/new$/)
|
||||
await expectNoHorizontalOverflow(page, 'new report')
|
||||
await startReport(page, dict)
|
||||
|
||||
await expect(page).toHaveURL(/\/editor$/)
|
||||
const disclaimer = page.getByRole('dialog', {
|
||||
name: dict['editor.disclaimer_title'],
|
||||
})
|
||||
await expect(disclaimer).toBeVisible()
|
||||
expect(await disclaimer.getAttribute('aria-describedby')).toBeTruthy()
|
||||
expect(await focusOwner(page)).toBe('dialog')
|
||||
expect(await focusedName(page)).toBe(dict['common.close'])
|
||||
await page.keyboard.press('Tab')
|
||||
expect(await focusedName(page)).toBe(dict['common.understood'])
|
||||
await expectAccessible(page, 'editor with the disclaimer')
|
||||
await expectNoHorizontalOverflow(page, 'editor with the disclaimer')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(disclaimer).toBeHidden()
|
||||
|
||||
const edit = page.getByRole('button', { name: dict['editor.edit_infos'] })
|
||||
await edit.focus()
|
||||
await page.keyboard.press('Enter')
|
||||
const editDialog = page.getByRole('dialog', {
|
||||
name: dict['editor.edit_dialog_title'],
|
||||
})
|
||||
await expect(editDialog).toBeVisible()
|
||||
expect(await focusOwner(page)).toBe('dialog')
|
||||
await expectNoHorizontalOverflow(page, 'edit dialog')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(editDialog).toBeHidden()
|
||||
await expect(edit).toBeFocused()
|
||||
|
||||
// A reload: the bilan stays in the tab, not yet in the store (the « unloaded » message).
|
||||
await page.goto('/new')
|
||||
await startReport(page, dict)
|
||||
const replace = page.getByRole('dialog', {
|
||||
name: dict['session.replace.title'],
|
||||
})
|
||||
await expect(replace).toBeVisible()
|
||||
await expect(replace).toHaveAccessibleDescription(
|
||||
dict['session.replace.body_unloaded'],
|
||||
)
|
||||
await expectAccessible(page, 'replace confirmation')
|
||||
await page.keyboard.press('Escape')
|
||||
await expect(replace).toBeHidden()
|
||||
await expect(page).toHaveURL(/\/new$/)
|
||||
await expect(
|
||||
page.getByRole('button', { name: dict['new_report.submit'] }),
|
||||
).toBeFocused()
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -8,10 +8,12 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc -p tsconfig.json --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p e2e/tsconfig.json --noEmit",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run",
|
||||
"lint": "eslint . --max-warnings 0"
|
||||
"lint": "eslint . --max-warnings 0",
|
||||
"e2e:ui": "playwright test -c e2e/playwright.ui.config.ts",
|
||||
"e2e:shell": "playwright test -c e2e/playwright.shell.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@faunosteo/core-wasm": "workspace:*",
|
||||
@@ -24,6 +26,8 @@
|
||||
"zustand": "^5.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@axe-core/playwright": "4.14.0",
|
||||
"@playwright/test": "1.64.1",
|
||||
"@tailwindcss/vite": "^4.3.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* The age shown on an animal's page, for display only (contract §5.2): from
|
||||
* the full date when known, else « environ N ans » from the year. Nothing is
|
||||
* stored or sent.
|
||||
*/
|
||||
export interface AnimalAge {
|
||||
unit: 'year' | 'month'
|
||||
count: number
|
||||
/** From the year alone: the day is unknown. */
|
||||
about: boolean
|
||||
}
|
||||
|
||||
export function animalAge(
|
||||
birthYear: number | null,
|
||||
birthDate: string | null,
|
||||
today: string,
|
||||
): AnimalAge | null {
|
||||
const [ty, tm, td] = today.split('-').map(Number)
|
||||
if (birthDate) {
|
||||
const [by, bm, bd] = birthDate.split('-').map(Number)
|
||||
const months = (ty - by) * 12 + (tm - bm) - (td < bd ? 1 : 0)
|
||||
if (months < 0) return null
|
||||
return months >= 12
|
||||
? { unit: 'year', count: Math.floor(months / 12), about: false }
|
||||
: { unit: 'month', count: months, about: false }
|
||||
}
|
||||
if (birthYear === null || birthYear > ty) return null
|
||||
return { unit: 'year', count: ty - birthYear, about: true }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchSpeciesLabels,
|
||||
type RecordFailureKind,
|
||||
type SpeciesLabel,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
|
||||
export type SpeciesState =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; labels: SpeciesLabel[] }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
interface SpeciesContextValue {
|
||||
state: SpeciesState
|
||||
/** Starts the read once; later calls change nothing. */
|
||||
request: () => void
|
||||
retry: () => void
|
||||
}
|
||||
|
||||
const SpeciesContext = createContext<SpeciesContextValue | null>(null)
|
||||
|
||||
/**
|
||||
* The active species (reference rows of contract §5.4), read once per
|
||||
* workspace and only when a page needs them: the list filter, the form and
|
||||
* the record pages share one answer. Mounted under RequireWorkspace, it
|
||||
* leaves with the workspace on a change of account.
|
||||
*/
|
||||
export function SpeciesProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SpeciesState>({ status: 'idle' })
|
||||
// 0 until a page asks; each retry bumps it.
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (attempt === 0) return
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
setState({ status: 'loading' })
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
fetchSpeciesLabels(client)
|
||||
.then((labels) => {
|
||||
if (live) setState({ status: 'ready', labels })
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [attempt])
|
||||
|
||||
const request = useCallback(() => setAttempt((n) => (n === 0 ? 1 : n)), [])
|
||||
const retry = useCallback(() => setAttempt((n) => n + 1), [])
|
||||
const value = useMemo(
|
||||
() => ({ state, request, retry }),
|
||||
[state, request, retry],
|
||||
)
|
||||
return (
|
||||
<SpeciesContext.Provider value={value}>{children}</SpeciesContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
/** The species labels of the workspace; the first page that asks starts the read. */
|
||||
export function useSpecies(): Omit<SpeciesContextValue, 'request'> {
|
||||
const context = useContext(SpeciesContext)
|
||||
if (!context) throw new Error('useSpecies needs a SpeciesProvider')
|
||||
const { request } = context
|
||||
useEffect(() => request(), [request])
|
||||
return { state: context.state, retry: context.retry }
|
||||
}
|
||||
|
||||
/** The species name in the locale, followed by the « Autre » detail when there is one. */
|
||||
export function speciesName(
|
||||
labels: readonly SpeciesLabel[],
|
||||
speciesId: string,
|
||||
detail: string | null,
|
||||
locale: Locale,
|
||||
): string {
|
||||
const label = labels.find((s) => s.id === speciesId)
|
||||
const name = label
|
||||
? pickLocaleLabel(label.name_fr, label.name_en, locale, speciesId)
|
||||
: speciesId
|
||||
return detail ? `${name} (${detail})` : name
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { useRef, useState, type FormEvent } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
createAnimalRecord,
|
||||
fetchAnimalRecord,
|
||||
updateAnimalRecord,
|
||||
type AnimalRecord,
|
||||
type AnimalRelationRole,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { generateUuid } from '@/lib/id'
|
||||
import { localDateIso } from '@/lib/dates'
|
||||
import {
|
||||
EMPTY_ANIMAL_VALUES,
|
||||
EMPTY_RELATION_VALUES,
|
||||
animalFieldErrors,
|
||||
animalFormValues,
|
||||
animalSchema,
|
||||
relationIssues,
|
||||
withBirthDate,
|
||||
type AnimalFieldErrors,
|
||||
type AnimalFormValues,
|
||||
type RelationFieldErrors,
|
||||
type RelationFormValues,
|
||||
} from './validation'
|
||||
|
||||
export interface PickedClient {
|
||||
id: string
|
||||
display_name: string
|
||||
}
|
||||
|
||||
export type AnimalFormTarget =
|
||||
| {
|
||||
mode: 'create'
|
||||
workspaceId: string
|
||||
/** The client the form opened from, pre-associated; the practitioner may remove it. */
|
||||
initialClient: PickedClient | null
|
||||
}
|
||||
| { mode: 'edit'; record: AnimalRecord }
|
||||
|
||||
export type AnimalFormPhase =
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'saving' }
|
||||
| { kind: 'failed'; failure: RecordFailureKind }
|
||||
|
||||
export interface AnimalSaved {
|
||||
animalId: string
|
||||
/** The client the new animal was linked to, if any. */
|
||||
linkedClientId: string | null
|
||||
}
|
||||
|
||||
const FIELDS = Object.keys(EMPTY_ANIMAL_VALUES) as (keyof AnimalFormValues)[]
|
||||
|
||||
function sameValues(a: AnimalFormValues, b: AnimalFormValues): boolean {
|
||||
return FIELDS.every((key) => a[key] === b[key])
|
||||
}
|
||||
|
||||
function sameRelation(a: RelationFormValues, b: RelationFormValues): boolean {
|
||||
return (
|
||||
a.client?.id === b.client?.id &&
|
||||
a.relation_role === b.relation_role &&
|
||||
a.started_on === b.started_on
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The animal form: typed values, the D-R7 schema, one save. A create keeps
|
||||
* one request id for the life of the form, and sends the animal with its
|
||||
* optional first client in one create_animal call, so a retry after a lost
|
||||
* answer returns the animal (and relation) already made. An update sends the
|
||||
* revision it was read at; on `conflict` the stored animal is shown beside
|
||||
* the typed values, which stay.
|
||||
*/
|
||||
export function useAnimalForm(
|
||||
target: AnimalFormTarget,
|
||||
activeSpeciesIds: readonly string[],
|
||||
onSaved: (saved: AnimalSaved) => void,
|
||||
) {
|
||||
const initial =
|
||||
target.mode === 'edit'
|
||||
? animalFormValues(target.record)
|
||||
: EMPTY_ANIMAL_VALUES
|
||||
const initialRelation: RelationFormValues =
|
||||
target.mode === 'create'
|
||||
? { ...EMPTY_RELATION_VALUES, client: target.initialClient }
|
||||
: EMPTY_RELATION_VALUES
|
||||
const [values, setValues] = useState<AnimalFormValues>(initial)
|
||||
const [baseline, setBaseline] = useState<AnimalFormValues>(initial)
|
||||
const [relation, setRelation] = useState(initialRelation)
|
||||
const [relationBaseline, setRelationBaseline] = useState(initialRelation)
|
||||
const [errors, setErrors] = useState<AnimalFieldErrors>({})
|
||||
const [relationErrors, setRelationErrors] = useState<RelationFieldErrors>({})
|
||||
const [errorRound, setErrorRound] = useState(0)
|
||||
const [phase, setPhase] = useState<AnimalFormPhase>({ kind: 'idle' })
|
||||
const [stored, setStored] = useState<AnimalRecord | null>(null)
|
||||
const [requestId] = useState(generateUuid)
|
||||
const revision = useRef(target.mode === 'edit' ? target.record.revision : 0)
|
||||
const inFlight = useRef(false)
|
||||
|
||||
const setField = (key: keyof AnimalFormValues) => (value: string) =>
|
||||
setValues((v) => ({ ...v, [key]: value }))
|
||||
const setBirthDate = (value: string) =>
|
||||
setValues((v) => withBirthDate(v, value))
|
||||
const chooseClient = (client: PickedClient | null) =>
|
||||
setRelation((r) => ({ ...r, client }))
|
||||
const setRelationRole = (role: AnimalRelationRole) =>
|
||||
setRelation((r) => ({ ...r, relation_role: role }))
|
||||
const setStartedOn = (value: string) =>
|
||||
setRelation((r) => ({ ...r, started_on: value }))
|
||||
|
||||
/** The species the form may send: on an edit, the stored one even if it left the active list. */
|
||||
const speciesIds =
|
||||
target.mode === 'edit' &&
|
||||
!activeSpeciesIds.includes(target.record.species_id)
|
||||
? [...activeSpeciesIds, target.record.species_id]
|
||||
: activeSpeciesIds
|
||||
|
||||
async function readStored(animalId: string) {
|
||||
const client = getSupabaseClient()
|
||||
const record = client
|
||||
? await fetchAnimalRecord(client, animalId).catch(() => null)
|
||||
: null
|
||||
if (record) {
|
||||
revision.current = record.revision
|
||||
setStored(record)
|
||||
}
|
||||
}
|
||||
|
||||
function validate() {
|
||||
const today = localDateIso()
|
||||
const parsed = animalSchema({ speciesIds, today }).safeParse(values)
|
||||
const linkIssues =
|
||||
target.mode === 'create' ? relationIssues(relation, today, false) : {}
|
||||
const fieldIssues = parsed.success ? {} : animalFieldErrors(parsed.error)
|
||||
setErrors(fieldIssues)
|
||||
setRelationErrors(linkIssues)
|
||||
if (!parsed.success || Object.keys(linkIssues).length > 0) {
|
||||
setErrorRound((n) => n + 1)
|
||||
return null
|
||||
}
|
||||
return parsed.data
|
||||
}
|
||||
|
||||
async function save(fields: NonNullable<ReturnType<typeof validate>>) {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new TypeError('no backend')
|
||||
if (target.mode === 'edit') {
|
||||
revision.current = (
|
||||
await updateAnimalRecord(client, {
|
||||
animalId: target.record.id,
|
||||
expectedRevision: revision.current,
|
||||
fields,
|
||||
})
|
||||
).revision
|
||||
return { animalId: target.record.id, linkedClientId: null }
|
||||
}
|
||||
const linked = relation.client
|
||||
const created = await createAnimalRecord(client, {
|
||||
workspaceId: target.workspaceId,
|
||||
requestId,
|
||||
fields,
|
||||
relation: linked
|
||||
? {
|
||||
clientId: linked.id,
|
||||
relationRole: relation.relation_role as AnimalRelationRole,
|
||||
startedOn: relation.started_on || null,
|
||||
}
|
||||
: null,
|
||||
})
|
||||
return { animalId: created.id, linkedClientId: linked?.id ?? null }
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (inFlight.current) return
|
||||
const fields = validate()
|
||||
if (!fields) return
|
||||
inFlight.current = true
|
||||
setPhase({ kind: 'saving' })
|
||||
try {
|
||||
const saved = await save(fields)
|
||||
setBaseline(values)
|
||||
setRelationBaseline(relation)
|
||||
setPhase({ kind: 'idle' })
|
||||
onSaved(saved)
|
||||
} catch (error) {
|
||||
const failure = classifyRecordError(error)
|
||||
if (failure === 'conflict' && target.mode === 'edit')
|
||||
await readStored(target.record.id)
|
||||
setPhase({ kind: 'failed', failure })
|
||||
} finally {
|
||||
inFlight.current = false
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops the typed values for the stored ones after a conflict. */
|
||||
function takeStored() {
|
||||
if (!stored) return
|
||||
const next = animalFormValues(stored)
|
||||
setValues(next)
|
||||
setBaseline(next)
|
||||
setStored(null)
|
||||
setErrors({})
|
||||
setPhase({ kind: 'idle' })
|
||||
}
|
||||
|
||||
return {
|
||||
mode: target.mode,
|
||||
values,
|
||||
setField,
|
||||
setBirthDate,
|
||||
relation,
|
||||
chooseClient,
|
||||
setRelationRole,
|
||||
setStartedOn,
|
||||
errors,
|
||||
relationErrors,
|
||||
/** Changes after each refused submit, so the form can focus the first error. */
|
||||
errorRound,
|
||||
phase,
|
||||
/** The stored animal after a conflict, shown beside the typed values. */
|
||||
stored,
|
||||
takeStored,
|
||||
dirty:
|
||||
!sameValues(values, baseline) ||
|
||||
!sameRelation(relation, relationBaseline),
|
||||
submit,
|
||||
}
|
||||
}
|
||||
|
||||
export type AnimalForm = ReturnType<typeof useAnimalForm>
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
searchAnimals,
|
||||
type AnimalListItem,
|
||||
type NameCursor,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { SEARCH_DELAY_MS } from '@/clients/useClientList'
|
||||
|
||||
export type AnimalListState =
|
||||
| { status: 'loading' }
|
||||
| {
|
||||
status: 'ready'
|
||||
rows: AnimalListItem[]
|
||||
next: NameCursor | null
|
||||
moreFailure: RecordFailureKind | null
|
||||
}
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/**
|
||||
* The animals of the workspace for a term, a species and the archived
|
||||
* toggle: the server searches (search_animals, POST), pages of 25 in name
|
||||
* order, « Afficher plus » appends the next page. An answer to an older
|
||||
* search is dropped.
|
||||
*/
|
||||
export function useAnimalList(workspaceId: string) {
|
||||
const [query, setQuery] = useState('')
|
||||
const [term, setTerm] = useState('')
|
||||
const [speciesId, setSpeciesId] = useState<string | null>(null)
|
||||
const [archived, setArchived] = useState(false)
|
||||
const [state, setState] = useState<AnimalListState>({ status: 'loading' })
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [reload, setReload] = useState(0)
|
||||
const generation = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [query])
|
||||
|
||||
useEffect(() => {
|
||||
const current = ++generation.current
|
||||
const client = getSupabaseClient()
|
||||
setState({ status: 'loading' })
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
searchAnimals(client, { workspaceId, query: term, speciesId, archived })
|
||||
.then((page) => {
|
||||
if (current === generation.current)
|
||||
setState({
|
||||
status: 'ready',
|
||||
rows: page.rows,
|
||||
next: page.next,
|
||||
moreFailure: null,
|
||||
})
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (current === generation.current)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
}, [workspaceId, term, speciesId, archived, reload])
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
const client = getSupabaseClient()
|
||||
if (state.status !== 'ready' || !state.next || !client || loadingMore)
|
||||
return
|
||||
const current = generation.current
|
||||
setLoadingMore(true)
|
||||
try {
|
||||
const page = await searchAnimals(client, {
|
||||
workspaceId,
|
||||
query: term,
|
||||
speciesId,
|
||||
archived,
|
||||
after: state.next,
|
||||
})
|
||||
if (current === generation.current)
|
||||
setState({
|
||||
status: 'ready',
|
||||
rows: [...state.rows, ...page.rows],
|
||||
next: page.next,
|
||||
moreFailure: null,
|
||||
})
|
||||
} catch (error) {
|
||||
if (current === generation.current)
|
||||
setState({ ...state, moreFailure: classifyRecordError(error) })
|
||||
} finally {
|
||||
setLoadingMore(false)
|
||||
}
|
||||
}, [state, loadingMore, workspaceId, term, speciesId, archived])
|
||||
|
||||
return {
|
||||
query,
|
||||
setQuery,
|
||||
/** The term the shown rows answer (the typed one after the pause). */
|
||||
term,
|
||||
speciesId,
|
||||
setSpeciesId,
|
||||
archived,
|
||||
setArchived,
|
||||
state,
|
||||
loadingMore,
|
||||
loadMore,
|
||||
retry: () => setReload((n) => n + 1),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchAnimalRecord,
|
||||
type AnimalRecord,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
export type AnimalRecordState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; record: AnimalRecord }
|
||||
| { status: 'not_found' }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/** One animal by id; an unknown id and an id of another workspace are both not_found. */
|
||||
export function useAnimalRecord(animalId: string) {
|
||||
const [state, setState] = useState<AnimalRecordState>({ status: 'loading' })
|
||||
const [reload, setReload] = useState(0)
|
||||
const shownId = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
// A refresh of the same animal keeps it on screen until the new answer.
|
||||
if (shownId.current !== animalId) setState({ status: 'loading' })
|
||||
shownId.current = animalId
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
fetchAnimalRecord(client, animalId)
|
||||
.then((record) => {
|
||||
if (live)
|
||||
setState(
|
||||
record ? { status: 'ready', record } : { status: 'not_found' },
|
||||
)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (live)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
})
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [animalId, reload])
|
||||
|
||||
const refresh = useCallback(() => setReload((n) => n + 1), [])
|
||||
return { state, refresh }
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
ANIMAL_FIELD_LIMITS,
|
||||
BIRTH_YEAR_MIN,
|
||||
CONTROL_CHARACTERS,
|
||||
RECORD_DATE_MIN,
|
||||
codePointLength,
|
||||
type AnimalFields,
|
||||
type AnimalRecord,
|
||||
type AnimalRelationRole,
|
||||
type AnimalSex,
|
||||
} from '@faunosteo/supabase'
|
||||
|
||||
/**
|
||||
* The animal form (contract §5.2, §11.3; D-R7): bounds from field-limits,
|
||||
* proven equal to the SQL CHECKs, so the form never sends what the database
|
||||
* refuses. The birth keeps the precision given (D6b): a year alone stays a
|
||||
* year, a full date carries its year again. « Not in the future » is the
|
||||
* device's local date (`today`); the RPCs allow up to tomorrow UTC. Messages
|
||||
* are i18n keys; `|n` carries the {max} placeholder.
|
||||
*/
|
||||
|
||||
export const ANIMAL_SEXES: readonly AnimalSex[] = ['male', 'female', 'unknown']
|
||||
export const RELATION_ROLES: readonly AnimalRelationRole[] = [
|
||||
'owner',
|
||||
'keeper',
|
||||
'contact',
|
||||
]
|
||||
|
||||
/** The species that asks for a detail (« Autre »). */
|
||||
export const OTHER_SPECIES = 'other'
|
||||
|
||||
export interface AnimalFormValues {
|
||||
name: string
|
||||
species_id: string
|
||||
species_detail: string
|
||||
/** '' until the practitioner picks one: no default (N8). */
|
||||
sex: AnimalSex | ''
|
||||
breed: string
|
||||
birth_year: string
|
||||
birth_date: string
|
||||
}
|
||||
|
||||
export const EMPTY_ANIMAL_VALUES: AnimalFormValues = {
|
||||
name: '',
|
||||
species_id: '',
|
||||
species_detail: '',
|
||||
sex: '',
|
||||
breed: '',
|
||||
birth_year: '',
|
||||
birth_date: '',
|
||||
}
|
||||
|
||||
/** The form's view of a stored animal: null fields become empty inputs. */
|
||||
export function animalFormValues(record: AnimalRecord): AnimalFormValues {
|
||||
return {
|
||||
name: record.name,
|
||||
species_id: record.species_id,
|
||||
species_detail: record.species_detail ?? '',
|
||||
sex: record.sex,
|
||||
breed: record.breed ?? '',
|
||||
birth_year: record.birth_year === null ? '' : String(record.birth_year),
|
||||
birth_date: record.birth_date ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* U3: a complete date fills the year (which the form then locks); clearing
|
||||
* the date leaves the year as it was, editable again.
|
||||
*/
|
||||
export function withBirthDate(
|
||||
values: AnimalFormValues,
|
||||
birthDate: string,
|
||||
): AnimalFormValues {
|
||||
const year = /^\d{4}-\d{2}-\d{2}$/.test(birthDate)
|
||||
? birthDate.slice(0, 4)
|
||||
: values.birth_year
|
||||
return { ...values, birth_date: birthDate, birth_year: year }
|
||||
}
|
||||
|
||||
function isCalendarDate(value: string): boolean {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value)
|
||||
if (!match) return false
|
||||
const [y, m, d] = match.slice(1).map(Number)
|
||||
const date = new Date(Date.UTC(y, m - 1, d))
|
||||
return (
|
||||
date.getUTCFullYear() === y &&
|
||||
date.getUTCMonth() === m - 1 &&
|
||||
date.getUTCDate() === d
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The issue of an optional record date (birth, relation start or end), or
|
||||
* null when it is fine: a real calendar date from 1900 to `today` (ISO text
|
||||
* compares in date order).
|
||||
*/
|
||||
export function recordDateIssue(value: string, today: string): string | null {
|
||||
if (value === '') return null
|
||||
if (!isCalendarDate(value)) return 'animals.error.date_format'
|
||||
if (value < RECORD_DATE_MIN || value > today)
|
||||
return 'animals.error.date_range'
|
||||
return null
|
||||
}
|
||||
|
||||
/** Trimmed text of at most `max` code points without control characters. */
|
||||
function textIssue(value: string, max: number): string | null {
|
||||
if (codePointLength(value) > max) return `animals.error.too_long|${max}`
|
||||
if (CONTROL_CHARACTERS.test(value)) return 'animals.error.characters'
|
||||
return null
|
||||
}
|
||||
|
||||
export interface AnimalSchemaContext {
|
||||
/** The species the form may send: the active ones, plus the stored one on an edit. */
|
||||
speciesIds: readonly string[]
|
||||
/** The device's local date, YYYY-MM-DD. */
|
||||
today: string
|
||||
}
|
||||
|
||||
type Issue = { path: keyof AnimalFormValues; message: string }
|
||||
|
||||
function identityIssues(v: AnimalFormValues, ctx: AnimalSchemaContext) {
|
||||
const issues: Issue[] = []
|
||||
const name = v.name.trim()
|
||||
const nameIssue =
|
||||
name === ''
|
||||
? 'animals.error.required'
|
||||
: textIssue(name, ANIMAL_FIELD_LIMITS.name)
|
||||
if (nameIssue) issues.push({ path: 'name', message: nameIssue })
|
||||
if (!ctx.speciesIds.includes(v.species_id))
|
||||
issues.push({ path: 'species_id', message: 'animals.error.species' })
|
||||
if (v.species_id === OTHER_SPECIES) {
|
||||
const detail = v.species_detail.trim()
|
||||
const detailIssue =
|
||||
detail === ''
|
||||
? 'animals.error.species_detail'
|
||||
: textIssue(detail, ANIMAL_FIELD_LIMITS.speciesDetail)
|
||||
if (detailIssue)
|
||||
issues.push({ path: 'species_detail', message: detailIssue })
|
||||
}
|
||||
if (!ANIMAL_SEXES.includes(v.sex as AnimalSex))
|
||||
issues.push({ path: 'sex', message: 'animals.error.sex' })
|
||||
const breedIssue = textIssue(v.breed.trim(), ANIMAL_FIELD_LIMITS.breed)
|
||||
if (breedIssue) issues.push({ path: 'breed', message: breedIssue })
|
||||
return issues
|
||||
}
|
||||
|
||||
function birthIssues(v: AnimalFormValues, today: string) {
|
||||
const issues: Issue[] = []
|
||||
if (v.birth_year !== '') {
|
||||
if (!/^\d{4}$/.test(v.birth_year))
|
||||
issues.push({ path: 'birth_year', message: 'animals.error.year_format' })
|
||||
else if (
|
||||
Number(v.birth_year) < BIRTH_YEAR_MIN ||
|
||||
Number(v.birth_year) > Number(today.slice(0, 4))
|
||||
)
|
||||
issues.push({ path: 'birth_year', message: 'animals.error.year_range' })
|
||||
}
|
||||
const dateIssue = recordDateIssue(v.birth_date, today)
|
||||
if (dateIssue) issues.push({ path: 'birth_date', message: dateIssue })
|
||||
else if (v.birth_date !== '' && v.birth_date.slice(0, 4) !== v.birth_year)
|
||||
issues.push({ path: 'birth_year', message: 'animals.error.date_year' })
|
||||
return issues
|
||||
}
|
||||
|
||||
const nullIfEmpty = (value: string) => (value === '' ? null : value)
|
||||
|
||||
/** Parses the typed values into the seven fields the RPCs take. */
|
||||
export function animalSchema(ctx: AnimalSchemaContext) {
|
||||
return z
|
||||
.object({
|
||||
name: z.string(),
|
||||
species_id: z.string(),
|
||||
species_detail: z.string(),
|
||||
sex: z.string(),
|
||||
breed: z.string(),
|
||||
birth_year: z.string(),
|
||||
birth_date: z.string(),
|
||||
})
|
||||
.superRefine((raw, zctx) => {
|
||||
const v = raw as AnimalFormValues
|
||||
for (const issue of [
|
||||
...identityIssues(v, ctx),
|
||||
...birthIssues(v, ctx.today),
|
||||
])
|
||||
zctx.addIssue({
|
||||
code: 'custom',
|
||||
path: [issue.path],
|
||||
message: issue.message,
|
||||
})
|
||||
})
|
||||
.transform(
|
||||
(v): AnimalFields => ({
|
||||
name: v.name.trim(),
|
||||
species_id: v.species_id,
|
||||
// Any other species refuses a detail: a hidden leftover is dropped, never sent.
|
||||
species_detail:
|
||||
v.species_id === OTHER_SPECIES ? v.species_detail.trim() : null,
|
||||
sex: v.sex as AnimalSex,
|
||||
breed: nullIfEmpty(v.breed.trim()),
|
||||
birth_year: v.birth_year === '' ? null : Number(v.birth_year),
|
||||
birth_date: nullIfEmpty(v.birth_date),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/** The optional client of a new animal, or of a relation added from a page. */
|
||||
export interface RelationFormValues {
|
||||
client: { id: string; display_name: string } | null
|
||||
/** '' until chosen: no role is preselected (owner decision 2026-10-26). */
|
||||
relation_role: AnimalRelationRole | ''
|
||||
started_on: string
|
||||
}
|
||||
|
||||
export const EMPTY_RELATION_VALUES: RelationFormValues = {
|
||||
client: null,
|
||||
relation_role: '',
|
||||
started_on: '',
|
||||
}
|
||||
|
||||
export type RelationFieldErrors = Partial<
|
||||
Record<'client' | 'relation_role' | 'started_on', string>
|
||||
>
|
||||
|
||||
/** Errors of a relation choice; `requireClient` when the client is the point of the form. */
|
||||
export function relationIssues(
|
||||
values: RelationFormValues,
|
||||
today: string,
|
||||
requireClient: boolean,
|
||||
): RelationFieldErrors {
|
||||
const errors: RelationFieldErrors = {}
|
||||
if (!values.client) {
|
||||
if (requireClient) errors.client = 'animals.error.client'
|
||||
return errors
|
||||
}
|
||||
if (!RELATION_ROLES.includes(values.relation_role as AnimalRelationRole))
|
||||
errors.relation_role = 'animals.error.role'
|
||||
const dateIssue = recordDateIssue(values.started_on, today)
|
||||
if (dateIssue) errors.started_on = dateIssue
|
||||
return errors
|
||||
}
|
||||
|
||||
export type AnimalFieldErrors = Partial<Record<keyof AnimalFormValues, string>>
|
||||
|
||||
/** The first message of each field, in form order. */
|
||||
export function animalFieldErrors(error: z.ZodError): AnimalFieldErrors {
|
||||
const errors: AnimalFieldErrors = {}
|
||||
for (const issue of error.issues) {
|
||||
const key = issue.path[0] as keyof AnimalFormValues
|
||||
errors[key] ??= issue.message
|
||||
}
|
||||
return errors
|
||||
}
|
||||
@@ -16,6 +16,15 @@ import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
|
||||
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
|
||||
import DashboardRoute from './routes/app/DashboardRoute'
|
||||
import AccountRoute from './routes/app/AccountRoute'
|
||||
import RequireWorkspace from './guards/RequireWorkspace'
|
||||
import ClientsListRoute from './routes/app/clients/ClientsListRoute'
|
||||
import ClientCreateRoute from './routes/app/clients/ClientCreateRoute'
|
||||
import ClientDetailRoute from './routes/app/clients/ClientDetailRoute'
|
||||
import ClientEditRoute from './routes/app/clients/ClientEditRoute'
|
||||
import AnimalsListRoute from './routes/app/animals/AnimalsListRoute'
|
||||
import AnimalCreateRoute from './routes/app/animals/AnimalCreateRoute'
|
||||
import AnimalDetailRoute from './routes/app/animals/AnimalDetailRoute'
|
||||
import AnimalEditRoute from './routes/app/animals/AnimalEditRoute'
|
||||
import { useUnsavedGuard } from './useUnsavedGuard'
|
||||
|
||||
/** The local tool: unchanged routes, no account needed, shared footer. */
|
||||
@@ -50,6 +59,21 @@ export function AppRoutes() {
|
||||
<Route element={<AppLayout />}>
|
||||
<Route index element={<DashboardRoute />} />
|
||||
<Route path="account" element={<AccountRoute />} />
|
||||
{/* One workspace gate for the records: moving between clients and animals keeps it. */}
|
||||
<Route element={<RequireWorkspace />}>
|
||||
<Route path="clients">
|
||||
<Route index element={<ClientsListRoute />} />
|
||||
<Route path="new" element={<ClientCreateRoute />} />
|
||||
<Route path=":clientId" element={<ClientDetailRoute />} />
|
||||
<Route path=":clientId/edit" element={<ClientEditRoute />} />
|
||||
</Route>
|
||||
<Route path="animals">
|
||||
<Route index element={<AnimalsListRoute />} />
|
||||
<Route path="new" element={<AnimalCreateRoute />} />
|
||||
<Route path=":animalId" element={<AnimalDetailRoute />} />
|
||||
<Route path=":animalId/edit" element={<AnimalEditRoute />} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<NotFoundRoute />} />
|
||||
</Route>
|
||||
</Route>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Fragment } from 'react'
|
||||
import { Outlet, useOutletContext } from 'react-router-dom'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { SpeciesProvider } from '@/animals/species'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface WorkspaceContext {
|
||||
workspaceId: string
|
||||
}
|
||||
|
||||
/** The id of the personal workspace, for the routes under RequireWorkspace. */
|
||||
export function useWorkspaceId(): string {
|
||||
return useOutletContext<WorkspaceContext>().workspaceId
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the record routes (clients and animals): they render only once the
|
||||
* personal workspace is read, and remount when it changes, so no list, form
|
||||
* or species answer of another account survives a change of account. Every
|
||||
* other state is said, never guessed.
|
||||
*/
|
||||
export default function RequireWorkspace() {
|
||||
const t = useT()
|
||||
const workspace = useAuthStore((s) => s.workspace)
|
||||
const refreshWorkspace = useAuthStore((s) => s.refreshWorkspace)
|
||||
|
||||
if (workspace.status === 'ready') {
|
||||
return (
|
||||
<Fragment key={workspace.id}>
|
||||
<SpeciesProvider>
|
||||
<Outlet
|
||||
context={{ workspaceId: workspace.id } satisfies WorkspaceContext}
|
||||
/>
|
||||
</SpeciesProvider>
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
if (workspace.status === 'idle' || workspace.status === 'loading') {
|
||||
return (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('workspace.loading')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (workspace.status === 'inactive' || workspace.status === 'unconfirmed') {
|
||||
return <Notice tone="error">{t(`workspace.${workspace.status}`)}</Notice>
|
||||
}
|
||||
const message =
|
||||
workspace.status === 'missing'
|
||||
? t('workspace.missing')
|
||||
: `${t('workspace.error')} ${t(`clients.failure.${workspace.failure}`)}`
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{message}</Notice>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => void refreshWorkspace().catch(() => undefined)}
|
||||
>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -87,8 +87,9 @@ function AccountCard() {
|
||||
<h2 className="font-serif text-xl">{t('dashboard.account.title')}</h2>
|
||||
<dl className="grid gap-2 text-sm">
|
||||
<div className="flex justify-between gap-4">
|
||||
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.email')}</dt>
|
||||
<dd className="truncate">{user?.email}</dd>
|
||||
<dt className="shrink-0 text-[var(--color-ink-muted)]">{t('dashboard.account.email')}</dt>
|
||||
{/* An address longer than the card wraps: never cut, never wider than the screen. */}
|
||||
<dd className="min-w-0 text-right [overflow-wrap:anywhere]">{user?.email}</dd>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-1.5 text-[var(--color-ink-muted)]">
|
||||
<Icon name={verified ? 'check' : 'alert'} size={16} />
|
||||
@@ -126,7 +127,8 @@ export default function DashboardRoute() {
|
||||
{t('dashboard.intro')}
|
||||
</p>
|
||||
</header>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{/* One explicit column below md: an implicit track would grow to the cards' content. */}
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<ProfileCard missing={missing} />
|
||||
<ToolCard />
|
||||
<AccountCard />
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { UUID_PATTERN } from '@faunosteo/supabase'
|
||||
import AnimalForm from '@/components/animals/AnimalForm'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
|
||||
import { useLeaveGuard } from '@/app/useLeaveGuard'
|
||||
import { usePageHeading } from '@/app/usePageHeading'
|
||||
import { useSpecies } from '@/animals/species'
|
||||
import { useAnimalForm, type PickedClient } from '@/animals/useAnimalForm'
|
||||
import { useClientRecord } from '@/clients/useClientRecord'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import type { ClientFlash } from '../clients/ClientDetailRoute'
|
||||
import type { AnimalFlash } from './AnimalDetailRoute'
|
||||
|
||||
/**
|
||||
* What a client page hands to this page: the client to pre-associate, in
|
||||
* the navigation state, never in the URL (brief V1-1.6 §6).
|
||||
*/
|
||||
export interface AnimalCreateState {
|
||||
clientId: string
|
||||
}
|
||||
|
||||
type Origin =
|
||||
| { status: 'none' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; client: PickedClient }
|
||||
| { status: 'unavailable' }
|
||||
|
||||
/** The client the form opened from, read again: only an active client of this workspace is pre-associated. */
|
||||
function useOrigin(clientId: string | null): Origin {
|
||||
const { state } = useClientRecord(clientId ?? '')
|
||||
if (!clientId) return { status: 'none' }
|
||||
if (state.status === 'loading') return { status: 'loading' }
|
||||
if (state.status === 'ready' && state.record.archived_at === null)
|
||||
return {
|
||||
status: 'ready',
|
||||
client: { id: state.record.id, display_name: state.record.display_name },
|
||||
}
|
||||
return { status: 'unavailable' }
|
||||
}
|
||||
|
||||
function CreateForm({ origin }: { origin: PickedClient | null }) {
|
||||
const t = useT()
|
||||
const navigate = useNavigate()
|
||||
const workspaceId = useWorkspaceId()
|
||||
const { state: species } = useSpecies()
|
||||
const activeIds =
|
||||
species.status === 'ready' ? species.labels.map((s) => s.id) : []
|
||||
const form = useAnimalForm(
|
||||
{ mode: 'create', workspaceId, initialClient: origin },
|
||||
activeIds,
|
||||
(saved) => {
|
||||
if (origin && saved.linkedClientId === origin.id)
|
||||
navigate(`/app/clients/${origin.id}`, {
|
||||
replace: true,
|
||||
state: { flash: 'animal_added' satisfies ClientFlash },
|
||||
})
|
||||
else
|
||||
navigate(`/app/animals/${saved.animalId}`, {
|
||||
replace: true,
|
||||
state: { flash: 'created' satisfies AnimalFlash },
|
||||
})
|
||||
},
|
||||
)
|
||||
useLeaveGuard(form.dirty)
|
||||
return (
|
||||
<AnimalForm
|
||||
form={form}
|
||||
workspaceId={workspaceId}
|
||||
submitLabel={t('animals.form.submit_create')}
|
||||
cancelTo={origin ? `/app/clients/${origin.id}` : '/app/animals'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** /app/animals/new: one creation intent, one request id kept for retries, an optional first client. */
|
||||
export default function AnimalCreateRoute() {
|
||||
const t = useT()
|
||||
const heading = usePageHeading()
|
||||
const location = useLocation()
|
||||
const passed = (location.state as Partial<AnimalCreateState> | null)?.clientId
|
||||
const origin = useOrigin(
|
||||
typeof passed === 'string' && UUID_PATTERN.test(passed) ? passed : null,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('animals.form.create_title')}
|
||||
</h1>
|
||||
{origin.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.form.origin_loading')}
|
||||
</p>
|
||||
)}
|
||||
{origin.status === 'unavailable' && (
|
||||
<Notice tone="info">{t('animals.form.origin_unavailable')}</Notice>
|
||||
)}
|
||||
{origin.status !== 'loading' && (
|
||||
<CreateForm origin={origin.status === 'ready' ? origin.client : null} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import {
|
||||
classifyRecordError,
|
||||
setAnimalArchived,
|
||||
type AnimalRecord,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import AnimalNotFound from '@/components/animals/AnimalNotFound'
|
||||
import ArchiveAnimalDialog from '@/components/animals/ArchiveAnimalDialog'
|
||||
import AnimalRelations from '@/components/relations/AnimalRelations'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import Button from '@/components/ui/Button'
|
||||
import ButtonLink from '@/components/ui/ButtonLink'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
|
||||
import { usePageHeading } from '@/app/usePageHeading'
|
||||
import { animalAge, type AnimalAge } from '@/animals/age'
|
||||
import { speciesName, useSpecies } from '@/animals/species'
|
||||
import { useAnimalRecord } from '@/animals/useAnimalRecord'
|
||||
import { formatDate, localDateIso } from '@/lib/dates'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** What a page that saved the animal asks this page to announce (no value in it). */
|
||||
export type AnimalFlash = 'created' | 'updated'
|
||||
|
||||
type Translate = ReturnType<typeof useT>
|
||||
|
||||
const linkClass =
|
||||
'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
function ageText(age: AnimalAge | null, t: Translate): string | null {
|
||||
if (!age) return null
|
||||
if (age.about && age.count === 0) return t('animals.age.under_one')
|
||||
const unit = age.unit === 'year' ? 'years' : 'months'
|
||||
const base = t(
|
||||
`animals.age.${unit}_${age.count === 1 ? 'one' : 'other'}`,
|
||||
).replace('{count}', String(age.count))
|
||||
return age.about ? t('animals.age.about').replace('{age}', base) : base
|
||||
}
|
||||
|
||||
/** The birth with the precision known (D6b): a date, a year, or « inconnue »; never a made-up day. */
|
||||
function birthText(record: AnimalRecord, t: Translate, locale: 'fr' | 'en') {
|
||||
const age = ageText(
|
||||
animalAge(record.birth_year, record.birth_date, localDateIso()),
|
||||
t,
|
||||
)
|
||||
const when = record.birth_date
|
||||
? t('animals.detail.birth_on').replace(
|
||||
'{date}',
|
||||
formatDate(record.birth_date, locale),
|
||||
)
|
||||
: record.birth_year !== null
|
||||
? t('animals.detail.birth_in').replace(
|
||||
'{year}',
|
||||
String(record.birth_year),
|
||||
)
|
||||
: null
|
||||
if (!when) return t('animals.detail.birth_unknown')
|
||||
return age ? `${when} (${age})` : when
|
||||
}
|
||||
|
||||
function IdentityCard({ record }: { record: AnimalRecord }) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { state: species } = useSpecies()
|
||||
const labels = species.status === 'ready' ? species.labels : []
|
||||
const rows: [string, ReactNode][] = [
|
||||
[
|
||||
t('animals.detail.species'),
|
||||
speciesName(labels, record.species_id, record.species_detail, locale),
|
||||
],
|
||||
[t('animals.detail.sex'), t(`animals.sex.${record.sex}`)],
|
||||
[t('animals.detail.breed'), record.breed ?? t('animals.detail.breed_none')],
|
||||
[t('animals.detail.birth'), birthText(record, t, locale)],
|
||||
[
|
||||
t('animals.detail.status'),
|
||||
record.archived_at
|
||||
? t('animals.detail.status_archived')
|
||||
: t('animals.detail.status_active'),
|
||||
],
|
||||
]
|
||||
return (
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="animal-identity-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="animal-identity-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('animals.detail.identity')}
|
||||
</h2>
|
||||
<dl className="grid gap-x-6 gap-y-3 text-sm sm:grid-cols-[9rem_1fr]">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label} className="contents">
|
||||
<dt className="text-[var(--color-ink-muted)]">{label}</dt>
|
||||
<dd className="min-w-0 text-[var(--color-ink)]">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
/** /app/animals/:animalId: identity, clients current and former, edit, archive or restore. */
|
||||
export default function AnimalDetailRoute() {
|
||||
const t = useT()
|
||||
const heading = usePageHeading()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const workspaceId = useWorkspaceId()
|
||||
const { animalId = '' } = useParams()
|
||||
const { state, refresh } = useAnimalRecord(animalId)
|
||||
const flash = (location.state as { flash?: AnimalFlash } | null)?.flash
|
||||
const [status, setStatus] = useState<string | null>(
|
||||
flash ? t(`animals.detail.${flash}`) : null,
|
||||
)
|
||||
const [archiveOpen, setArchiveOpen] = useState(false)
|
||||
const [restoring, setRestoring] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(null)
|
||||
|
||||
// The announcement is read once; a reload of the page does not repeat it.
|
||||
useEffect(() => {
|
||||
if (flash) navigate(location.pathname, { replace: true, state: null })
|
||||
}, [flash, navigate, location.pathname])
|
||||
|
||||
async function restore() {
|
||||
const client = getSupabaseClient()
|
||||
if (restoring || !client) return
|
||||
setRestoring(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
await setAnimalArchived(client, animalId, false)
|
||||
setStatus(t('animals.detail.restored'))
|
||||
refresh()
|
||||
} catch (error) {
|
||||
setFailure(classifyRecordError(error))
|
||||
} finally {
|
||||
setRestoring(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === 'not_found') return <AnimalNotFound />
|
||||
if (state.status === 'loading')
|
||||
return (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.detail.loading')}
|
||||
</p>
|
||||
)
|
||||
if (state.status === 'error')
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={refresh}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
const record = state.record
|
||||
const archived = record.archived_at !== null
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Link
|
||||
to="/app/animals"
|
||||
className={`${linkClass} inline-flex min-h-11 items-center text-sm`}
|
||||
>
|
||||
{t('animals.detail.back')}
|
||||
</Link>
|
||||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none break-words font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{record.name}
|
||||
</h1>
|
||||
{archived && <Badge tone="warn">{t('animals.archived_badge')}</Badge>}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{archived ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="min-h-11"
|
||||
onClick={() => void restore()}
|
||||
aria-disabled={restoring}
|
||||
>
|
||||
{restoring
|
||||
? t('animals.detail.restoring')
|
||||
: t('animals.detail.restore')}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<ButtonLink
|
||||
to={`/app/animals/${record.id}/edit`}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t('animals.detail.edit')}
|
||||
</ButtonLink>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => setArchiveOpen(true)}
|
||||
>
|
||||
{t('animals.detail.archive')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{status && <Notice tone="success">{status}</Notice>}
|
||||
{failure && (
|
||||
<Notice tone="error">{t(`animals.failure.${failure}`)}</Notice>
|
||||
)}
|
||||
{archived && (
|
||||
<Notice tone="info">{t('animals.detail.archived_notice')}</Notice>
|
||||
)}
|
||||
|
||||
<IdentityCard record={record} />
|
||||
<AnimalRelations
|
||||
key={`${record.id}:${archived}`}
|
||||
animal={record}
|
||||
workspaceId={workspaceId}
|
||||
onStatus={setStatus}
|
||||
/>
|
||||
|
||||
<ArchiveAnimalDialog
|
||||
open={archiveOpen}
|
||||
animalId={record.id}
|
||||
onClose={() => setArchiveOpen(false)}
|
||||
onArchived={() => {
|
||||
setArchiveOpen(false)
|
||||
setStatus(t('animals.detail.archived'))
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import type { AnimalRecord } from '@faunosteo/supabase'
|
||||
import AnimalForm from '@/components/animals/AnimalForm'
|
||||
import AnimalNotFound from '@/components/animals/AnimalNotFound'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
|
||||
import { useLeaveGuard } from '@/app/useLeaveGuard'
|
||||
import { usePageHeading } from '@/app/usePageHeading'
|
||||
import { useSpecies } from '@/animals/species'
|
||||
import { useAnimalForm } from '@/animals/useAnimalForm'
|
||||
import { useAnimalRecord } from '@/animals/useAnimalRecord'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import type { AnimalFlash } from './AnimalDetailRoute'
|
||||
|
||||
function EditForm({ record }: { record: AnimalRecord }) {
|
||||
const t = useT()
|
||||
const navigate = useNavigate()
|
||||
const workspaceId = useWorkspaceId()
|
||||
const { state: species } = useSpecies()
|
||||
const activeIds =
|
||||
species.status === 'ready' ? species.labels.map((s) => s.id) : []
|
||||
const form = useAnimalForm({ mode: 'edit', record }, activeIds, (saved) =>
|
||||
navigate(`/app/animals/${saved.animalId}`, {
|
||||
state: { flash: 'updated' satisfies AnimalFlash },
|
||||
}),
|
||||
)
|
||||
useLeaveGuard(form.dirty)
|
||||
return (
|
||||
<AnimalForm
|
||||
form={form}
|
||||
workspaceId={workspaceId}
|
||||
submitLabel={t('animals.form.submit_update')}
|
||||
cancelTo={`/app/animals/${record.id}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** /app/animals/:animalId/edit: the stored values at their revision; an archived animal is read-only. */
|
||||
export default function AnimalEditRoute() {
|
||||
const t = useT()
|
||||
const heading = usePageHeading()
|
||||
const { animalId = '' } = useParams()
|
||||
const { state, refresh } = useAnimalRecord(animalId)
|
||||
|
||||
if (state.status === 'not_found') return <AnimalNotFound />
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('animals.form.edit_title')}
|
||||
</h1>
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.detail.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={refresh}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.record.archived_at && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="info">{t('animals.detail.archived_notice')}</Notice>
|
||||
<Link
|
||||
to={`/app/animals/${state.record.id}`}
|
||||
className="text-sm underline underline-offset-2"
|
||||
>
|
||||
{t('animals.form.back_to_animal')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && !state.record.archived_at && (
|
||||
<EditForm key={state.record.id} record={state.record} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import { Link } from 'react-router-dom'
|
||||
import type { AnimalListItem, SpeciesLabel } from '@faunosteo/supabase'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import Button from '@/components/ui/Button'
|
||||
import ButtonLink from '@/components/ui/ButtonLink'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { useWorkspaceId } from '@/app/guards/RequireWorkspace'
|
||||
import { usePageHeading } from '@/app/usePageHeading'
|
||||
import { speciesName, useSpecies } from '@/animals/species'
|
||||
import { useAnimalList } from '@/animals/useAnimalList'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
type Translate = ReturnType<typeof useT>
|
||||
|
||||
/** « Propriétaires : A, B, C +2 », or « Propriétaire non renseigné » (no placeholder client). */
|
||||
function ownersText(animal: AnimalListItem, t: Translate): string {
|
||||
if (animal.current_owner_count === 0) return t('animals.no_owner')
|
||||
const names = animal.current_owners
|
||||
.map((o) =>
|
||||
o.archived
|
||||
? t('animals.owner_archived').replace('{name}', o.display_name)
|
||||
: o.display_name,
|
||||
)
|
||||
.join(', ')
|
||||
const more = animal.current_owner_count - animal.current_owners.length
|
||||
const list =
|
||||
more > 0
|
||||
? `${names} ${t('animals.list.owners_more').replace('{count}', String(more))}`
|
||||
: names
|
||||
return t(
|
||||
animal.current_owner_count === 1
|
||||
? 'animals.list.owner'
|
||||
: 'animals.list.owners',
|
||||
).replace('{names}', list)
|
||||
}
|
||||
|
||||
function AnimalRow(props: {
|
||||
animal: AnimalListItem
|
||||
labels: readonly SpeciesLabel[]
|
||||
locale: Locale
|
||||
t: Translate
|
||||
}) {
|
||||
const { animal, t } = props
|
||||
const details = [
|
||||
speciesName(
|
||||
props.labels,
|
||||
animal.species_id,
|
||||
animal.species_detail,
|
||||
props.locale,
|
||||
),
|
||||
animal.breed,
|
||||
t(`animals.sex.${animal.sex}`),
|
||||
].filter(Boolean)
|
||||
return (
|
||||
<li>
|
||||
<Link
|
||||
to={`/app/animals/${animal.id}`}
|
||||
className="flex min-h-11 flex-col gap-1 rounded-xl px-4 py-3 hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="min-w-0 truncate font-medium text-[var(--color-ink)]">
|
||||
{animal.name}
|
||||
</span>
|
||||
{animal.archived_at && (
|
||||
<Badge tone="warn">{t('animals.archived_badge')}</Badge>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--color-ink-muted)]">
|
||||
{details.join(' · ')}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--color-ink)]">
|
||||
{ownersText(animal, t)}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** /app/animals: search, species filter, the archived toggle (U2) and « Afficher plus » pages (U1). */
|
||||
export default function AnimalsListRoute() {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const heading = usePageHeading()
|
||||
const workspaceId = useWorkspaceId()
|
||||
const { state: species } = useSpecies()
|
||||
const labels = species.status === 'ready' ? species.labels : []
|
||||
const list = useAnimalList(workspaceId)
|
||||
const { state } = list
|
||||
|
||||
const emptyMessage =
|
||||
list.term || list.speciesId
|
||||
? t('animals.list.no_results')
|
||||
: list.archived
|
||||
? t('animals.list.archived_empty')
|
||||
: t('animals.list.empty')
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('animals.list.title')}
|
||||
</h1>
|
||||
<ButtonLink to="/app/animals/new" className="min-h-11">
|
||||
{t('animals.list.new')}
|
||||
</ButtonLink>
|
||||
</header>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_12rem] lg:grid-cols-[1fr_12rem_auto] lg:items-end">
|
||||
<FormField
|
||||
id="animal-search"
|
||||
label={t('animals.list.search_label')}
|
||||
hint={t('animals.list.search_hint')}
|
||||
>
|
||||
<Input
|
||||
id="animal-search"
|
||||
type="search"
|
||||
value={list.query}
|
||||
onChange={(e) => list.setQuery(e.target.value)}
|
||||
maxLength={100}
|
||||
autoComplete="off"
|
||||
aria-describedby="animal-search-hint"
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id="animal-species-filter"
|
||||
label={t('animals.list.species_filter')}
|
||||
>
|
||||
<Select
|
||||
id="animal-species-filter"
|
||||
value={list.speciesId ?? ''}
|
||||
onChange={(e) => list.setSpeciesId(e.target.value || null)}
|
||||
>
|
||||
<option value="">{t('animals.list.species_all')}</option>
|
||||
{labels.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{pickLocaleLabel(s.name_fr, s.name_en, locale, s.id)}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-3 text-sm text-[var(--color-ink)]">
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={list.archived}
|
||||
onChange={(e) => list.setArchived(e.target.checked)}
|
||||
className="h-5 w-5 accent-[var(--color-accent)]"
|
||||
/>
|
||||
{t('animals.list.archived_toggle')}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* The number of rows shown is announced; an empty result announces itself below. */}
|
||||
<div aria-live="polite" className="sr-only">
|
||||
{state.status === 'ready' &&
|
||||
state.rows.length > 0 &&
|
||||
t(
|
||||
state.rows.length === 1
|
||||
? 'animals.list.count_one'
|
||||
: 'animals.list.count_other',
|
||||
).replace('{count}', String(state.rows.length))}
|
||||
</div>
|
||||
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.list.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`animals.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={list.retry}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.rows.length === 0 && (
|
||||
<div
|
||||
role="status"
|
||||
className="space-y-3 rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center"
|
||||
>
|
||||
<p className="text-[var(--color-ink)]">{emptyMessage}</p>
|
||||
{!list.term && !list.speciesId && !list.archived && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.list.empty_hint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.rows.length > 0 && (
|
||||
<>
|
||||
<ul
|
||||
aria-label={t('animals.list.results_label')}
|
||||
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
|
||||
>
|
||||
{state.rows.map((animal) => (
|
||||
<AnimalRow
|
||||
key={animal.id}
|
||||
animal={animal}
|
||||
labels={labels}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
{state.moreFailure && (
|
||||
<Notice tone="error">
|
||||
{t(`animals.failure.${state.moreFailure}`)}
|
||||
</Notice>
|
||||
)}
|
||||
{state.next && (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => void list.loadMore()}
|
||||
aria-disabled={list.loadingMore}
|
||||
>
|
||||
{list.loadingMore
|
||||
? t('animals.list.loading_more')
|
||||
: t('animals.list.more')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="space-y-5">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('clients.form.create_title')}
|
||||
</h1>
|
||||
<ClientForm
|
||||
form={form}
|
||||
submitLabel={t('clients.form.submit_create')}
|
||||
cancelTo="/app/clients"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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'),
|
||||
<a
|
||||
key="phone"
|
||||
href={`tel:${record.phone}`}
|
||||
className={`${linkClass} tabular-nums`}
|
||||
>
|
||||
{record.phone}
|
||||
</a>,
|
||||
])
|
||||
if (record.email)
|
||||
rows.push([
|
||||
t('clients.detail.email'),
|
||||
<a
|
||||
key="email"
|
||||
href={`mailto:${record.email}`}
|
||||
className={`${linkClass} break-all`}
|
||||
>
|
||||
{record.email}
|
||||
</a>,
|
||||
])
|
||||
if (address.length)
|
||||
rows.push([
|
||||
t('clients.detail.address'),
|
||||
address.map((line) => (
|
||||
<span key={line} className="block">
|
||||
{line}
|
||||
</span>
|
||||
)),
|
||||
])
|
||||
if (record.country)
|
||||
rows.push([
|
||||
t('clients.detail.country'),
|
||||
countryName(record.country, locale),
|
||||
])
|
||||
|
||||
return (
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="client-contact-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="client-contact-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('clients.detail.contact')}
|
||||
</h2>
|
||||
{rows.length === 0 ? (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.detail.no_contact')}
|
||||
</p>
|
||||
) : (
|
||||
<dl className="grid gap-x-6 gap-y-3 text-sm sm:grid-cols-[9rem_1fr]">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label} className="contents">
|
||||
<dt className="text-[var(--color-ink-muted)]">{label}</dt>
|
||||
<dd className="min-w-0 text-[var(--color-ink)]">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
/** /app/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<string | null>(
|
||||
flash ? t(`clients.detail.${flash}`) : null,
|
||||
)
|
||||
const [archiveOpen, setArchiveOpen] = useState(false)
|
||||
const [restoring, setRestoring] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(null)
|
||||
|
||||
// The announcement is read once; a reload of the page does not repeat it.
|
||||
useEffect(() => {
|
||||
if (flash) navigate(location.pathname, { replace: true, state: null })
|
||||
}, [flash, navigate, location.pathname])
|
||||
|
||||
async function restore() {
|
||||
const client = getSupabaseClient()
|
||||
if (restoring || !client) return
|
||||
setRestoring(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
await setClientArchived(client, clientId, false)
|
||||
setStatus(t('clients.detail.restored'))
|
||||
refresh()
|
||||
} catch (error) {
|
||||
setFailure(classifyRecordError(error))
|
||||
} finally {
|
||||
setRestoring(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === 'not_found') return <ClientNotFound />
|
||||
if (state.status === 'loading')
|
||||
return (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.detail.loading')}
|
||||
</p>
|
||||
)
|
||||
if (state.status === 'error')
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={refresh}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
|
||||
const record = state.record
|
||||
const archived = record.archived_at !== null
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<Link
|
||||
to="/app/clients"
|
||||
className={`${linkClass} inline-flex min-h-11 items-center text-sm`}
|
||||
>
|
||||
{t('clients.detail.back')}
|
||||
</Link>
|
||||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none break-words font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{record.display_name}
|
||||
</h1>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge>{t(`clients.kind.${record.kind}`)}</Badge>
|
||||
{archived && (
|
||||
<Badge tone="warn">{t('clients.archived_badge')}</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{archived ? (
|
||||
<Button
|
||||
type="button"
|
||||
className="min-h-11"
|
||||
onClick={() => void restore()}
|
||||
aria-disabled={restoring}
|
||||
>
|
||||
{restoring
|
||||
? t('clients.detail.restoring')
|
||||
: t('clients.detail.restore')}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<ButtonLink
|
||||
to={`/app/clients/${record.id}/edit`}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t('clients.detail.edit')}
|
||||
</ButtonLink>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => setArchiveOpen(true)}
|
||||
>
|
||||
{t('clients.detail.archive')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{status && <Notice tone="success">{status}</Notice>}
|
||||
{failure && (
|
||||
<Notice tone="error">{t(`clients.failure.${failure}`)}</Notice>
|
||||
)}
|
||||
{archived && (
|
||||
<Notice tone="info">{t('clients.detail.archived_notice')}</Notice>
|
||||
)}
|
||||
|
||||
<ContactCard record={record} />
|
||||
<ClientAnimals
|
||||
key={`${record.id}:${archived}`}
|
||||
clientId={record.id}
|
||||
workspaceId={workspaceId}
|
||||
archived={archived}
|
||||
onStatus={setStatus}
|
||||
/>
|
||||
|
||||
<ArchiveClientDialog
|
||||
open={archiveOpen}
|
||||
clientId={record.id}
|
||||
onClose={() => setArchiveOpen(false)}
|
||||
onArchived={() => {
|
||||
setArchiveOpen(false)
|
||||
setStatus(t('clients.detail.archived'))
|
||||
refresh()
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<ClientForm
|
||||
form={form}
|
||||
submitLabel={t('clients.form.submit_update')}
|
||||
cancelTo={`/app/clients/${record.id}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** /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 <ClientNotFound />
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('clients.form.edit_title')}
|
||||
</h1>
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.detail.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={refresh}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.record.archived_at && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="info">{t('clients.detail.archived_notice')}</Notice>
|
||||
<Link
|
||||
to={`/app/clients/${state.record.id}`}
|
||||
className="text-sm underline underline-offset-2"
|
||||
>
|
||||
{t('clients.form.back_to_client')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && !state.record.archived_at && (
|
||||
<EditForm key={state.record.id} record={state.record} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<typeof useT>
|
||||
|
||||
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 (
|
||||
<li>
|
||||
<Link
|
||||
to={`/app/clients/${client.id}`}
|
||||
className="flex min-h-11 flex-col gap-1 rounded-xl px-4 py-3 hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<span className="min-w-0 truncate font-medium text-[var(--color-ink)]">
|
||||
{client.display_name}
|
||||
</span>
|
||||
<Badge>{t(`clients.kind.${client.kind}`)}</Badge>
|
||||
{client.archived_at && (
|
||||
<Badge tone="warn">{t('clients.archived_badge')}</Badge>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--color-ink-muted)] tabular-nums">
|
||||
{details.join(' · ')}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
/** /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 (
|
||||
<div className="space-y-5">
|
||||
<header className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)] sm:text-3xl"
|
||||
>
|
||||
{t('clients.list.title')}
|
||||
</h1>
|
||||
<ButtonLink to="/app/clients/new" className="min-h-11">
|
||||
{t('clients.list.new')}
|
||||
</ButtonLink>
|
||||
</header>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-end">
|
||||
<FormField
|
||||
id="client-search"
|
||||
label={t('clients.list.search_label')}
|
||||
hint={t('clients.list.search_hint')}
|
||||
>
|
||||
<Input
|
||||
id="client-search"
|
||||
type="search"
|
||||
value={list.query}
|
||||
onChange={(e) => list.setQuery(e.target.value)}
|
||||
maxLength={100}
|
||||
autoComplete="off"
|
||||
aria-describedby="client-search-hint"
|
||||
/>
|
||||
</FormField>
|
||||
<label className="flex min-h-11 cursor-pointer items-center gap-3 text-sm text-[var(--color-ink)]">
|
||||
<input
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
checked={list.archived}
|
||||
onChange={(e) => list.setArchived(e.target.checked)}
|
||||
className="h-5 w-5 accent-[var(--color-accent)]"
|
||||
/>
|
||||
{t('clients.list.archived_toggle')}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* The number of rows shown is announced; an empty result announces itself below. */}
|
||||
<div aria-live="polite" className="sr-only">
|
||||
{state.status === 'ready' &&
|
||||
state.rows.length > 0 &&
|
||||
t(
|
||||
state.rows.length === 1
|
||||
? 'clients.list.count_one'
|
||||
: 'clients.list.count_other',
|
||||
).replace('{count}', String(state.rows.length))}
|
||||
</div>
|
||||
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.list.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={list.retry}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.rows.length === 0 && (
|
||||
<div
|
||||
role="status"
|
||||
className="space-y-3 rounded-2xl border border-dashed border-[var(--color-border)] p-6 text-center"
|
||||
>
|
||||
<p className="text-[var(--color-ink)]">{emptyMessage}</p>
|
||||
{!list.term && !list.archived && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.list.empty_hint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{state.status === 'ready' && state.rows.length > 0 && (
|
||||
<>
|
||||
<ul
|
||||
aria-label={t('clients.list.results_label')}
|
||||
className="divide-y divide-[var(--color-border)] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)]"
|
||||
>
|
||||
{state.rows.map((client) => (
|
||||
<ClientRow key={client.id} client={client} t={t} />
|
||||
))}
|
||||
</ul>
|
||||
{state.moreFailure && (
|
||||
<Notice tone="error">
|
||||
{t(`clients.failure.${state.moreFailure}`)}
|
||||
</Notice>
|
||||
)}
|
||||
{state.next && (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => void list.loadMore()}
|
||||
aria-disabled={list.loadingMore}
|
||||
>
|
||||
{list.loadingMore
|
||||
? t('clients.list.loading_more')
|
||||
: t('clients.list.more')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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<T extends HTMLElement = HTMLHeadingElement>() {
|
||||
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 },
|
||||
)
|
||||
}, [])
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<ClientFormValues>(initial)
|
||||
const [baseline, setBaseline] = useState<ClientFormValues>(initial)
|
||||
const [errors, setErrors] = useState<ClientFieldErrors>({})
|
||||
const [errorRound, setErrorRound] = useState(0)
|
||||
const [phase, setPhase] = useState<ClientFormPhase>({ kind: 'idle' })
|
||||
const [stored, setStored] = useState<ClientRecord | null>(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<typeof useClientForm>
|
||||
@@ -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<ClientListState>({ 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),
|
||||
}
|
||||
}
|
||||
@@ -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<ClientRecordState>({ status: 'loading' })
|
||||
const [reload, setReload] = useState(0)
|
||||
const shownId = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const client = getSupabaseClient()
|
||||
// A refresh of the same 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 }
|
||||
}
|
||||
@@ -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<Record<keyof ClientFormValues, string>>
|
||||
|
||||
/** 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
|
||||
}
|
||||
@@ -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<HTMLInputElement>(null)
|
||||
const pollRef = useRef<number | null>(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() {
|
||||
<Notice tone="error">{t(`account.avatar.error.${phase.failure}`)}</Notice>
|
||||
)}
|
||||
{rejected && <Notice tone="error">{t(`account.avatar.rejected.${rejected}`)}</Notice>}
|
||||
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>
|
||||
<Dialog
|
||||
open={confirmOpen}
|
||||
onClose={closeConfirm}
|
||||
title={t('account.avatar.remove_title')}
|
||||
description={<p className="text-sm text-[var(--color-ink-muted)]">{t('account.avatar.remove_body')}</p>}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setConfirmOpen(false)}>
|
||||
<Button type="button" variant="ghost" onClick={closeConfirm}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="button" variant="danger" onClick={onRemove}>
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ANIMAL_FIELD_LIMITS } from '@faunosteo/supabase'
|
||||
import Button, { buttonClassName } from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios'
|
||||
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import Select from '@/components/ui/Select'
|
||||
import { ClientPicker } from '@/components/relations/Pickers'
|
||||
import { speciesName, useSpecies } from '@/animals/species'
|
||||
import type { AnimalForm as AnimalFormState } from '@/animals/useAnimalForm'
|
||||
import {
|
||||
ANIMAL_SEXES,
|
||||
OTHER_SPECIES,
|
||||
RELATION_ROLES,
|
||||
animalFormValues,
|
||||
type AnimalFormValues,
|
||||
type RelationFieldErrors,
|
||||
} from '@/animals/validation'
|
||||
import { translateFieldError } from '@/account/validation'
|
||||
import { formatDate, localDateIso } from '@/lib/dates'
|
||||
import { pickLocaleLabel } from '@/i18n/pickLocaleLabel'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Ids of the controls that take focus on an error, in form order. */
|
||||
const FIELD_IDS: Record<
|
||||
keyof AnimalFormValues | keyof RelationFieldErrors,
|
||||
string
|
||||
> = {
|
||||
name: 'animal-name',
|
||||
species_id: 'animal-species',
|
||||
species_detail: 'animal-species-detail',
|
||||
sex: firstChoiceId('animal-sex', 'male'),
|
||||
breed: 'animal-breed',
|
||||
birth_year: 'animal-birth-year',
|
||||
birth_date: 'animal-birth-date',
|
||||
client: 'animal-client-search',
|
||||
relation_role: firstChoiceId('animal-role', 'owner'),
|
||||
started_on: 'animal-started-on',
|
||||
}
|
||||
|
||||
export interface AnimalFormProps {
|
||||
form: AnimalFormState
|
||||
workspaceId: string
|
||||
submitLabel: string
|
||||
/** Where « Annuler » leads; the shell asks first while the form holds changes. */
|
||||
cancelTo: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The animal form, one page on every screen (contract §11.3): identity
|
||||
* (name, species with its detail for « Autre », sex with no default, breed),
|
||||
* birth (a year, or a full date that fills and locks the year: U3), and on
|
||||
* a creation the optional first client with an explicit role. Every field
|
||||
* is labelled, errors sit under their field and the first one takes focus.
|
||||
*/
|
||||
export default function AnimalForm({
|
||||
form,
|
||||
workspaceId,
|
||||
submitLabel,
|
||||
cancelTo,
|
||||
}: AnimalFormProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { state: species, retry: retrySpecies } = useSpecies()
|
||||
const { values, errors, relation, relationErrors, phase, stored } = form
|
||||
const labels = species.status === 'ready' ? species.labels : []
|
||||
const today = localDateIso()
|
||||
const chosenText = useRef<HTMLParagraphElement>(null)
|
||||
const shownClient = useRef(relation.client?.id ?? null)
|
||||
|
||||
// Choosing a client focuses the choice; removing it focuses the search that replaces it.
|
||||
useEffect(() => {
|
||||
const id = relation.client?.id ?? null
|
||||
if (id === shownClient.current) return
|
||||
shownClient.current = id
|
||||
if (id) chosenText.current?.focus()
|
||||
else document.getElementById(FIELD_IDS.client)?.focus()
|
||||
}, [relation.client])
|
||||
|
||||
useEffect(() => {
|
||||
if (form.errorRound === 0) return
|
||||
const all = { ...errors, ...relationErrors } as Record<string, unknown>
|
||||
const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find(
|
||||
(key) => all[key],
|
||||
)
|
||||
if (first) document.getElementById(FIELD_IDS[first])?.focus()
|
||||
}, [form.errorRound, errors, relationErrors])
|
||||
|
||||
const err = (key: keyof AnimalFormValues) =>
|
||||
translateFieldError(t, errors[key])
|
||||
const relErr = (key: keyof RelationFieldErrors) =>
|
||||
translateFieldError(t, relationErrors[key])
|
||||
|
||||
/** After a conflict: the stored value under each field that differs from the typed one. */
|
||||
const storedHint = (key: keyof AnimalFormValues): string | undefined => {
|
||||
if (!stored) return undefined
|
||||
const value = animalFormValues(stored)[key]
|
||||
if (value === values[key]) return undefined
|
||||
const shown =
|
||||
value === ''
|
||||
? ''
|
||||
: key === 'species_id'
|
||||
? speciesName(labels, value, null, locale)
|
||||
: key === 'sex'
|
||||
? t(`animals.sex.${value}`)
|
||||
: key === 'birth_date'
|
||||
? formatDate(value, locale)
|
||||
: value
|
||||
return shown
|
||||
? t('animals.form.stored_value').replace('{value}', shown)
|
||||
: t('animals.form.stored_empty')
|
||||
}
|
||||
const describedBy = (key: keyof AnimalFormValues, hint?: string) =>
|
||||
fieldDescribedBy(FIELD_IDS[key], hint, errors[key])
|
||||
|
||||
function textField(
|
||||
key: 'name' | 'breed' | 'species_detail',
|
||||
label: string,
|
||||
max: number,
|
||||
isRequired: boolean,
|
||||
hint?: string,
|
||||
) {
|
||||
const shownHint = storedHint(key) ?? hint
|
||||
return (
|
||||
<FormField
|
||||
id={FIELD_IDS[key]}
|
||||
label={label}
|
||||
optional={t(
|
||||
isRequired ? 'animals.form.required' : 'animals.form.optional',
|
||||
)}
|
||||
hint={shownHint}
|
||||
error={err(key)}
|
||||
>
|
||||
<Input
|
||||
id={FIELD_IDS[key]}
|
||||
value={values[key]}
|
||||
onChange={(e) => form.setField(key)(e.target.value)}
|
||||
maxLength={max}
|
||||
autoComplete="off"
|
||||
aria-invalid={Boolean(errors[key])}
|
||||
aria-describedby={describedBy(key, shownHint)}
|
||||
required={isRequired}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
const required = t('animals.form.required')
|
||||
const optional = t('animals.form.optional')
|
||||
const saving = phase.kind === 'saving'
|
||||
const yearLocked = /^\d{4}-\d{2}-\d{2}$/.test(values.birth_date)
|
||||
const yearHint =
|
||||
storedHint('birth_year') ??
|
||||
t(
|
||||
yearLocked
|
||||
? 'animals.form.birth_year_locked'
|
||||
: 'animals.form.birth_year_hint',
|
||||
)
|
||||
const speciesHint = storedHint('species_id')
|
||||
|
||||
return (
|
||||
<form onSubmit={form.submit} noValidate className="space-y-6">
|
||||
{stored && (
|
||||
<Notice tone="error">
|
||||
<p className="font-medium">{t('animals.form.conflict_title')}</p>
|
||||
<p>{t('animals.form.conflict_body')}</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={form.takeStored}
|
||||
>
|
||||
{t('animals.form.conflict_take_stored')}
|
||||
</Button>
|
||||
</Notice>
|
||||
)}
|
||||
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="animal-identity-title"
|
||||
className="space-y-5 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="animal-identity-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('animals.form.identity_title')}
|
||||
</h2>
|
||||
{textField(
|
||||
'name',
|
||||
t('animals.form.name'),
|
||||
ANIMAL_FIELD_LIMITS.name,
|
||||
true,
|
||||
)}
|
||||
<FormField
|
||||
id={FIELD_IDS.species_id}
|
||||
label={t('animals.form.species')}
|
||||
optional={required}
|
||||
hint={speciesHint}
|
||||
error={err('species_id')}
|
||||
>
|
||||
<Select
|
||||
id={FIELD_IDS.species_id}
|
||||
value={values.species_id}
|
||||
onChange={(e) => form.setField('species_id')(e.target.value)}
|
||||
aria-invalid={Boolean(errors.species_id)}
|
||||
aria-describedby={describedBy('species_id', speciesHint)}
|
||||
required
|
||||
>
|
||||
<option value="">
|
||||
{species.status === 'ready'
|
||||
? t('animals.form.species_choose')
|
||||
: t('animals.form.species_loading')}
|
||||
</option>
|
||||
{labels.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{pickLocaleLabel(s.name_fr, s.name_en, locale, s.id)}
|
||||
</option>
|
||||
))}
|
||||
{/* A stored species that left the active list stays shown on an edit. */}
|
||||
{values.species_id &&
|
||||
species.status === 'ready' &&
|
||||
!labels.some((s) => s.id === values.species_id) && (
|
||||
<option value={values.species_id}>{values.species_id}</option>
|
||||
)}
|
||||
</Select>
|
||||
</FormField>
|
||||
{species.status === 'error' && (
|
||||
<div className="space-y-2">
|
||||
<Notice tone="error">{t('animals.form.species_failed')}</Notice>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="min-h-11"
|
||||
onClick={retrySpecies}
|
||||
>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{values.species_id === OTHER_SPECIES &&
|
||||
textField(
|
||||
'species_detail',
|
||||
t('animals.form.species_detail'),
|
||||
ANIMAL_FIELD_LIMITS.speciesDetail,
|
||||
true,
|
||||
t('animals.form.species_detail_hint'),
|
||||
)}
|
||||
<ChoiceRadios
|
||||
id="animal-sex"
|
||||
legend={t('animals.form.sex')}
|
||||
marker={required}
|
||||
options={ANIMAL_SEXES.map((value) => ({
|
||||
value,
|
||||
label: t(`animals.sex.${value}`),
|
||||
}))}
|
||||
value={values.sex}
|
||||
onChange={(value) => form.setField('sex')(value)}
|
||||
hint={storedHint('sex') ?? t('animals.form.sex_hint')}
|
||||
error={err('sex')}
|
||||
/>
|
||||
{textField(
|
||||
'breed',
|
||||
t('animals.form.breed'),
|
||||
ANIMAL_FIELD_LIMITS.breed,
|
||||
false,
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="animal-birth-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="animal-birth-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('animals.form.birth_title')}
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-[10rem_1fr]">
|
||||
<FormField
|
||||
id={FIELD_IDS.birth_year}
|
||||
label={t('animals.form.birth_year')}
|
||||
optional={optional}
|
||||
hint={yearHint}
|
||||
error={err('birth_year')}
|
||||
>
|
||||
<Input
|
||||
id={FIELD_IDS.birth_year}
|
||||
inputMode="numeric"
|
||||
autoComplete="off"
|
||||
value={values.birth_year}
|
||||
onChange={(e) => form.setField('birth_year')(e.target.value)}
|
||||
readOnly={yearLocked}
|
||||
maxLength={4}
|
||||
aria-invalid={Boolean(errors.birth_year)}
|
||||
aria-describedby={describedBy('birth_year', yearHint)}
|
||||
className={yearLocked ? 'bg-[var(--color-surface-strong)]' : ''}
|
||||
/>
|
||||
</FormField>
|
||||
<FormField
|
||||
id={FIELD_IDS.birth_date}
|
||||
label={t('animals.form.birth_date')}
|
||||
optional={optional}
|
||||
hint={storedHint('birth_date') ?? t('animals.form.birth_date_hint')}
|
||||
error={err('birth_date')}
|
||||
>
|
||||
<Input
|
||||
id={FIELD_IDS.birth_date}
|
||||
type="date"
|
||||
value={values.birth_date}
|
||||
min="1900-01-01"
|
||||
max={today}
|
||||
onChange={(e) => form.setBirthDate(e.target.value)}
|
||||
aria-invalid={Boolean(errors.birth_date)}
|
||||
aria-describedby={describedBy('birth_date', 'hint')}
|
||||
className="sm:max-w-xs"
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{form.mode === 'create' && (
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="animal-client-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<div className="space-y-1">
|
||||
<h2
|
||||
id="animal-client-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('animals.form.client_title')}
|
||||
</h2>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.form.client_hint')}
|
||||
</p>
|
||||
</div>
|
||||
{relation.client ? (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<p
|
||||
ref={chosenText}
|
||||
tabIndex={-1}
|
||||
className="min-w-0 text-sm text-[var(--color-ink)] outline-none"
|
||||
>
|
||||
{t('relations.panel.client_chosen')}{' '}
|
||||
<span className="font-medium">
|
||||
{relation.client.display_name}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="min-h-11"
|
||||
onClick={() => form.chooseClient(null)}
|
||||
>
|
||||
{t('animals.form.client_remove')}
|
||||
</Button>
|
||||
</div>
|
||||
<ChoiceRadios
|
||||
id="animal-role"
|
||||
legend={t('relations.panel.role')}
|
||||
marker={required}
|
||||
options={RELATION_ROLES.map((value) => ({
|
||||
value,
|
||||
label: t(`clients.role.${value}`),
|
||||
}))}
|
||||
value={relation.relation_role}
|
||||
onChange={form.setRelationRole}
|
||||
error={relErr('relation_role')}
|
||||
/>
|
||||
<FormField
|
||||
id={FIELD_IDS.started_on}
|
||||
label={t('relations.panel.started_on')}
|
||||
optional={optional}
|
||||
hint={t('relations.date_hint')}
|
||||
error={relErr('started_on')}
|
||||
>
|
||||
<Input
|
||||
id={FIELD_IDS.started_on}
|
||||
type="date"
|
||||
value={relation.started_on}
|
||||
min="1900-01-01"
|
||||
max={today}
|
||||
onChange={(e) => form.setStartedOn(e.target.value)}
|
||||
aria-invalid={Boolean(relationErrors.started_on)}
|
||||
aria-describedby={
|
||||
relationErrors.started_on
|
||||
? `${FIELD_IDS.started_on}-error`
|
||||
: `${FIELD_IDS.started_on}-hint`
|
||||
}
|
||||
className="sm:max-w-xs"
|
||||
/>
|
||||
</FormField>
|
||||
</>
|
||||
) : (
|
||||
<ClientPicker
|
||||
id={FIELD_IDS.client}
|
||||
workspaceId={workspaceId}
|
||||
onChoose={(chosen) =>
|
||||
form.chooseClient({ id: chosen.id, display_name: chosen.name })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{phase.kind === 'failed' && !stored && (
|
||||
<Notice tone="error">{t(`animals.failure.${phase.failure}`)}</Notice>
|
||||
)}
|
||||
<div className="sticky bottom-0 -mx-4 flex flex-wrap items-center justify-end gap-3 border-t border-[var(--color-border)] bg-[var(--color-bg)] px-4 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0">
|
||||
<Link
|
||||
to={cancelTo}
|
||||
className={buttonClassName('ghost', 'md', 'min-h-11')}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
aria-disabled={saving}
|
||||
className="min-h-11"
|
||||
>
|
||||
{saving ? t('animals.form.saving') : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import ButtonLink from '@/components/ui/ButtonLink'
|
||||
import Card from '@/components/ui/Card'
|
||||
import { usePageHeading } from '@/app/usePageHeading'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The same screen for an unknown id, a malformed one and an id of another workspace (contract §11.1). */
|
||||
export default function AnimalNotFound() {
|
||||
const t = useT()
|
||||
const heading = usePageHeading()
|
||||
return (
|
||||
<Card as="section" className="space-y-3 p-5 sm:p-6">
|
||||
<h1
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="outline-none font-serif text-2xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('animals.not_found.title')}
|
||||
</h1>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.not_found.body')}
|
||||
</p>
|
||||
<ButtonLink to="/app/animals" variant="secondary">
|
||||
{t('animals.not_found.back')}
|
||||
</ButtonLink>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
setAnimalArchived,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface ArchiveAnimalDialogProps {
|
||||
open: boolean
|
||||
animalId: string
|
||||
onClose: () => void
|
||||
/** Called once the server archived the animal; the page then closes the dialog. */
|
||||
onArchived: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmation before archiving an animal (contract §7.1): its relations are
|
||||
* kept and frozen, no client is archived. Closing it is never a
|
||||
* confirmation, and while the request runs it refuses to close.
|
||||
*/
|
||||
export default function ArchiveAnimalDialog({
|
||||
open,
|
||||
animalId,
|
||||
onClose,
|
||||
onArchived,
|
||||
}: ArchiveAnimalDialogProps) {
|
||||
const t = useT()
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(null)
|
||||
|
||||
const close = () => {
|
||||
if (pending) return
|
||||
setFailure(null)
|
||||
onClose()
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
const client = getSupabaseClient()
|
||||
if (pending) return
|
||||
if (!client) return setFailure('unavailable')
|
||||
setPending(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
await setAnimalArchived(client, animalId, true)
|
||||
onArchived()
|
||||
} catch (error) {
|
||||
setFailure(classifyRecordError(error))
|
||||
} finally {
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
title={t('animals.archive.title')}
|
||||
description={
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('animals.archive.body')}
|
||||
</p>
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
{failure && (
|
||||
<Notice tone="error" className="mt-3">
|
||||
{t(`animals.failure.${failure}`)}
|
||||
</Notice>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
{/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={close}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
onClick={() => void confirm()}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{pending
|
||||
? t('animals.archive.archiving')
|
||||
: t('animals.archive.confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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<Preview>({ status: 'loading' })
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(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 (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={close}
|
||||
title={t('clients.archive.title')}
|
||||
description={
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.archive.body')}
|
||||
</p>
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-3 space-y-3 text-sm">
|
||||
{preview.status === 'loading' && (
|
||||
<p role="status" className="text-[var(--color-ink-muted)]">
|
||||
{t('clients.archive.preview_loading')}
|
||||
</p>
|
||||
)}
|
||||
{preview.status === 'failed' && (
|
||||
<Notice tone="info">{t('clients.archive.preview_failed')}</Notice>
|
||||
)}
|
||||
{sole && sole.count > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p>
|
||||
{sole.count === 1
|
||||
? t('clients.archive.sole_owner_one')
|
||||
: t('clients.archive.sole_owner_other').replace(
|
||||
'{count}',
|
||||
String(sole.count),
|
||||
)}
|
||||
</p>
|
||||
<ul className="list-disc pl-5">
|
||||
{sole.animals.map((animal) => (
|
||||
<li key={animal.id}>{animal.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
{others > 0 && (
|
||||
<p>
|
||||
{t('clients.archive.others').replace('{count}', String(others))}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{failure && (
|
||||
<Notice tone="error">{t(`clients.failure.${failure}`)}</Notice>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
{/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={close}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="danger"
|
||||
onClick={() => void confirm()}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{pending
|
||||
? t('clients.archive.archiving')
|
||||
: t('clients.archive.confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -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<string, AnimalGroup>()
|
||||
for (const row of rows.filter((r) => r.is_current === current)) {
|
||||
const group = groups.get(row.animal_id)
|
||||
if (group) group.rows.push(row)
|
||||
else groups.set(row.animal_id, { animalId: row.animal_id, rows: [row] })
|
||||
}
|
||||
return [...groups.values()]
|
||||
}
|
||||
|
||||
const linkClass =
|
||||
'rounded-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
export interface ClientAnimalsProps {
|
||||
clientId: string
|
||||
workspaceId: string
|
||||
/** An archived client takes no new relation (contract §7.1): no add, no link. */
|
||||
archived: boolean
|
||||
/** A change made here, announced by the page. */
|
||||
onStatus: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The client's animals from list_client_animals, current then former, each
|
||||
* with the client's roles and their dates when known, linked to the animal's
|
||||
* page. On an active client: « Ajouter un animal » opens the animal form
|
||||
* with this client pre-associated, « Associer un animal existant » links an
|
||||
* animal already recorded.
|
||||
*/
|
||||
export default function ClientAnimals({
|
||||
clientId,
|
||||
workspaceId,
|
||||
archived,
|
||||
onStatus,
|
||||
}: ClientAnimalsProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { state: species } = useSpecies()
|
||||
const labels = species.status === 'ready' ? species.labels : []
|
||||
const [state, setState] = useState<State>({ status: 'loading' })
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
const [panelOpen, setPanelOpen] = useState(false)
|
||||
const linkButton = useRef<HTMLButtonElement>(null)
|
||||
const panelWasOpen = useRef(false)
|
||||
const generation = useRef(0)
|
||||
|
||||
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 (
|
||||
<section aria-labelledby={id} className="space-y-2">
|
||||
<h3
|
||||
id={id}
|
||||
className="text-sm font-medium text-[var(--color-ink-muted)]"
|
||||
>
|
||||
{t(current ? 'clients.animals.current' : 'clients.animals.former')}
|
||||
</h3>
|
||||
<ul className="divide-y divide-[var(--color-border)] rounded-xl border border-[var(--color-border)] bg-white">
|
||||
{groups.map(({ animalId, rows }) => {
|
||||
const first = rows[0]
|
||||
return (
|
||||
<li key={animalId} className="space-y-1 px-4 py-3">
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<Link to={`/app/animals/${animalId}`} className={linkClass}>
|
||||
{first.animal_name}
|
||||
</Link>
|
||||
<span className="text-sm text-[var(--color-ink-muted)]">
|
||||
{speciesName(
|
||||
labels,
|
||||
first.species_id,
|
||||
first.species_detail,
|
||||
locale,
|
||||
)}
|
||||
</span>
|
||||
{first.animal_archived_at && (
|
||||
<Badge tone="warn">{t('animals.archived_badge')}</Badge>
|
||||
)}
|
||||
</span>
|
||||
<ul className="text-sm text-[var(--color-ink)]">
|
||||
{rows.map((row) => (
|
||||
<li key={row.relation_id}>{roleText(row)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const empty = state.status === 'ready' && state.rows.length === 0
|
||||
|
||||
return (
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="client-animals-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2
|
||||
id="client-animals-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('clients.animals.title')}
|
||||
</h2>
|
||||
{!archived && !panelOpen && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<ButtonLink
|
||||
to="/app/animals/new"
|
||||
state={{ clientId } satisfies AnimalCreateState}
|
||||
className="min-h-11"
|
||||
>
|
||||
{t(empty ? 'clients.animals.add_first' : 'clients.animals.add')}
|
||||
</ButtonLink>
|
||||
<Button
|
||||
ref={linkButton}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => setPanelOpen(true)}
|
||||
>
|
||||
{t('clients.animals.link_existing')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.animals.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">{t(`clients.failure.${state.failure}`)}</Notice>
|
||||
<Button type="button" variant="secondary" onClick={() => void load()}>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{empty && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('clients.animals.none')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'ready' && (
|
||||
<>
|
||||
{section(byAnimal(state.rows, true), true)}
|
||||
{section(byAnimal(state.rows, false), false)}
|
||||
{state.next && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => void more()}
|
||||
aria-disabled={loadingMore}
|
||||
>
|
||||
{loadingMore
|
||||
? t('clients.list.loading_more')
|
||||
: t('clients.list.more')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{panelOpen && (
|
||||
<RelationPanel
|
||||
pick="animal"
|
||||
clientId={clientId}
|
||||
workspaceId={workspaceId}
|
||||
onCancel={() => setPanelOpen(false)}
|
||||
onSaved={async () => {
|
||||
await load()
|
||||
onStatus(t('relations.added_animal'))
|
||||
setPanelOpen(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,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<string, unknown> = {},
|
||||
) {
|
||||
const hint = storedHint(key)
|
||||
return (
|
||||
<FormField
|
||||
id={fieldId(key)}
|
||||
label={label}
|
||||
optional={t('clients.form.optional')}
|
||||
hint={hint}
|
||||
error={err(key)}
|
||||
>
|
||||
<Input
|
||||
id={fieldId(key)}
|
||||
value={values[key]}
|
||||
onChange={(e) => form.setField(key)(e.target.value)}
|
||||
maxLength={max}
|
||||
aria-invalid={Boolean(errors[key])}
|
||||
aria-describedby={describedBy(key, hint)}
|
||||
{...extra}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<form onSubmit={form.submit} noValidate className="space-y-6">
|
||||
{stored && (
|
||||
<Notice tone="error">
|
||||
<p className="font-medium">{t('clients.form.conflict_title')}</p>
|
||||
<p>{t('clients.form.conflict_body')}</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={form.takeStored}
|
||||
>
|
||||
{t('clients.form.conflict_take_stored')}
|
||||
</Button>
|
||||
</Notice>
|
||||
)}
|
||||
<Card as="section" className="space-y-5 p-5 sm:p-6">
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm font-medium text-[var(--color-ink)]">
|
||||
{t('clients.form.kind_legend')}
|
||||
</legend>
|
||||
<div className="grid grid-cols-2 gap-2 sm:inline-grid sm:w-auto">
|
||||
{(['person', 'organization'] as const).map((kind) => (
|
||||
<label
|
||||
key={kind}
|
||||
className="flex min-h-11 cursor-pointer items-center justify-center gap-2 rounded-lg border border-[var(--color-border)] bg-white px-4 text-sm text-[var(--color-ink)] has-[:checked]:border-[var(--color-accent)] has-[:checked]:bg-[var(--color-accent)]/10 has-[:checked]:font-medium has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-accent)]"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="client-kind"
|
||||
value={kind}
|
||||
checked={values.kind === kind}
|
||||
onChange={() => form.setField('kind')(kind)}
|
||||
className="h-4 w-4 accent-[var(--color-accent)]"
|
||||
/>
|
||||
{t(`clients.kind.${kind}`)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{storedHint('kind') && (
|
||||
<p className="text-xs text-[var(--color-ink-muted)]">
|
||||
{storedHint('kind')}
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
<FormField
|
||||
id={fieldId('display_name')}
|
||||
label={t(`clients.form.display_name.${nameKey}`)}
|
||||
optional={t('clients.form.required')}
|
||||
hint={nameHint}
|
||||
error={err('display_name')}
|
||||
>
|
||||
<Input
|
||||
id={fieldId('display_name')}
|
||||
value={values.display_name}
|
||||
onChange={(e) => 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
|
||||
/>
|
||||
</FormField>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="client-contact-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="client-contact-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('clients.form.contact_title')}
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{textField(
|
||||
'email',
|
||||
t('clients.form.email'),
|
||||
CLIENT_FIELD_LIMITS.email,
|
||||
{
|
||||
type: 'email',
|
||||
inputMode: 'email',
|
||||
autoComplete: 'off',
|
||||
},
|
||||
)}
|
||||
<FormField
|
||||
id={fieldId('phone')}
|
||||
label={t('clients.form.phone')}
|
||||
optional={t('clients.form.optional')}
|
||||
hint={storedHint('phone') ?? t('clients.form.phone_hint')}
|
||||
error={err('phone')}
|
||||
>
|
||||
<Input
|
||||
id={fieldId('phone')}
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="off"
|
||||
value={values.phone}
|
||||
onChange={(e) => form.setField('phone')(e.target.value)}
|
||||
onBlur={form.convertPhone}
|
||||
maxLength={32}
|
||||
aria-invalid={Boolean(errors.phone)}
|
||||
aria-describedby={describedBy('phone', 'hint')}
|
||||
/>
|
||||
</FormField>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="client-address-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<h2
|
||||
id="client-address-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('clients.form.address_title')}
|
||||
</h2>
|
||||
{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',
|
||||
},
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-[10rem_1fr]">
|
||||
{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',
|
||||
})}
|
||||
</div>
|
||||
<FormField
|
||||
id={fieldId('country')}
|
||||
label={t('clients.form.country')}
|
||||
optional={t('clients.form.optional')}
|
||||
hint={storedHint('country')}
|
||||
error={err('country')}
|
||||
>
|
||||
<Select
|
||||
id={fieldId('country')}
|
||||
value={values.country}
|
||||
onChange={(e) => form.setField('country')(e.target.value)}
|
||||
aria-invalid={Boolean(errors.country)}
|
||||
aria-describedby={describedBy('country', storedHint('country'))}
|
||||
>
|
||||
<option value="">{t('clients.form.country_none')}</option>
|
||||
{countries.map((c) => (
|
||||
<option key={c.code} value={c.code}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</FormField>
|
||||
</Card>
|
||||
|
||||
{phase.kind === 'failed' && !stored && (
|
||||
<Notice tone="error">{t(`clients.failure.${phase.failure}`)}</Notice>
|
||||
)}
|
||||
<div className="sticky bottom-0 -mx-4 flex flex-wrap items-center justify-end gap-3 border-t border-[var(--color-border)] bg-[var(--color-bg)] px-4 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0">
|
||||
<Link
|
||||
to={cancelTo}
|
||||
className={buttonClassName('ghost', 'md', 'min-h-11')}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Link>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={saving}
|
||||
aria-disabled={saving}
|
||||
className="min-h-11"
|
||||
>
|
||||
{saving ? t('clients.form.saving') : submitLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<Card as="section" className="space-y-3 p-5 sm:p-6">
|
||||
<h1 ref={heading} tabIndex={-1} className="outline-none font-serif text-2xl text-[var(--color-ink)]">
|
||||
{t('clients.not_found.title')}
|
||||
</h1>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{t('clients.not_found.body')}</p>
|
||||
<ButtonLink to="/app/clients" variant="secondary">
|
||||
{t('clients.not_found.back')}
|
||||
</ButtonLink>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import type {
|
||||
AnimalRecord,
|
||||
AnimalRelationItem,
|
||||
RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import Badge from '@/components/ui/Badge'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Card from '@/components/ui/Card'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import RelationPanel from './RelationPanel'
|
||||
import {
|
||||
EndRelationDialog,
|
||||
RelationDatesDialog,
|
||||
VoidRelationDialog,
|
||||
} from './RelationDialogs'
|
||||
import { groupRelations } from '@/relations/groups'
|
||||
import { useAnimalRelations } from '@/relations/useAnimalRelations'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
type Action = 'end' | 'dates' | 'void'
|
||||
interface Target {
|
||||
action: Action
|
||||
relation: AnimalRelationItem
|
||||
}
|
||||
|
||||
const linkClass =
|
||||
'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]'
|
||||
|
||||
export interface AnimalRelationsProps {
|
||||
animal: AnimalRecord
|
||||
workspaceId: string
|
||||
/** A change made here, announced by the page. */
|
||||
onStatus: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The clients of an animal (contract §11.1): owners, keepers and contacts,
|
||||
* current then former, with their dates when known; « Propriétaire non
|
||||
* renseigné » when no current owner exists (never a placeholder client).
|
||||
* Voided relations are never read. On an active animal: link a client, end
|
||||
* a relation, correct its dates, or void one entered by mistake; on an
|
||||
* archived animal the relations are read-only (§7.1).
|
||||
*/
|
||||
export default function AnimalRelations({
|
||||
animal,
|
||||
workspaceId,
|
||||
onStatus,
|
||||
}: AnimalRelationsProps) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { state, reload } = useAnimalRelations(animal.id)
|
||||
const [panelOpen, setPanelOpen] = useState(false)
|
||||
const [target, setTarget] = useState<Target | null>(null)
|
||||
const [stale, setStale] = useState<RecordFailureKind | null>(null)
|
||||
const addButton = useRef<HTMLButtonElement>(null)
|
||||
const panelWasOpen = useRef(false)
|
||||
const editable = animal.archived_at === null
|
||||
|
||||
// The panel gave focus to its own heading; when it closes, focus goes back to « Ajouter ».
|
||||
useEffect(() => {
|
||||
if (panelWasOpen.current && !panelOpen) addButton.current?.focus()
|
||||
panelWasOpen.current = panelOpen
|
||||
}, [panelOpen])
|
||||
|
||||
const roleLabel = (r: AnimalRelationItem) =>
|
||||
t(`clients.role.${r.ended_at === null ? '' : 'former_'}${r.relation_role}`)
|
||||
const label = (r: AnimalRelationItem) =>
|
||||
`${r.client.display_name} · ${roleLabel(r)}`
|
||||
const period = (r: AnimalRelationItem) =>
|
||||
[
|
||||
r.started_on &&
|
||||
t('relations.since').replace(
|
||||
'{date}',
|
||||
formatDate(r.started_on, locale),
|
||||
),
|
||||
r.ended_on &&
|
||||
t('relations.until').replace('{date}', formatDate(r.ended_on, locale)),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
|
||||
const handlers = {
|
||||
onClose: () => setTarget(null),
|
||||
onDone: async (message: string) => {
|
||||
await reload()
|
||||
setStale(null)
|
||||
onStatus(message)
|
||||
setTarget(null)
|
||||
},
|
||||
onStale: async (failure: RecordFailureKind) => {
|
||||
await reload()
|
||||
setStale(failure)
|
||||
setTarget(null)
|
||||
},
|
||||
}
|
||||
|
||||
function row(r: AnimalRelationItem) {
|
||||
const named = (key: string) =>
|
||||
t('relations.action_named')
|
||||
.replace('{action}', t(key))
|
||||
.replace('{name}', r.client.display_name)
|
||||
.replace('{role}', roleLabel(r).toLowerCase())
|
||||
const action = (kind: Action, key: string) => (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="min-h-11"
|
||||
aria-label={named(key)}
|
||||
onClick={() => setTarget({ action: kind, relation: r })}
|
||||
>
|
||||
{t(key)}
|
||||
</Button>
|
||||
)
|
||||
return (
|
||||
<li key={r.id} className="space-y-2 px-4 py-3">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<Link
|
||||
to={`/app/clients/${r.client.id}`}
|
||||
className={`${linkClass} font-medium break-words`}
|
||||
>
|
||||
{r.client.display_name}
|
||||
</Link>
|
||||
{r.client.archived_at && (
|
||||
<Badge tone="warn">{t('clients.archived_badge')}</Badge>
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-[var(--color-ink-muted)]">
|
||||
{roleLabel(r)}
|
||||
{period(r) && ` · ${period(r)}`}
|
||||
</span>
|
||||
</div>
|
||||
{r.client.phone && (
|
||||
<a
|
||||
href={`tel:${r.client.phone}`}
|
||||
className={`${linkClass} inline-flex min-h-11 items-center text-sm tabular-nums`}
|
||||
>
|
||||
{r.client.phone}
|
||||
</a>
|
||||
)}
|
||||
{editable && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{r.ended_at === null && action('end', 'relations.end.action')}
|
||||
{action('dates', 'relations.dates.action')}
|
||||
{action('void', 'relations.void.action')}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function group(rows: AnimalRelationItem[], key: string, id: string) {
|
||||
if (!rows.length) return null
|
||||
return (
|
||||
<section aria-labelledby={id} className="space-y-2">
|
||||
<h3
|
||||
id={id}
|
||||
className="text-sm font-medium text-[var(--color-ink-muted)]"
|
||||
>
|
||||
{t(key)}
|
||||
</h3>
|
||||
<ul className="divide-y divide-[var(--color-border)] rounded-xl border border-[var(--color-border)] bg-white">
|
||||
{rows.map(row)}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const groups =
|
||||
state.status === 'ready' ? groupRelations(state.relations) : null
|
||||
|
||||
return (
|
||||
<Card
|
||||
as="section"
|
||||
aria-labelledby="animal-relations-title"
|
||||
className="space-y-4 p-5 sm:p-6"
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h2
|
||||
id="animal-relations-title"
|
||||
className="font-serif text-xl text-[var(--color-ink)]"
|
||||
>
|
||||
{t('relations.title')}
|
||||
</h2>
|
||||
{editable && !panelOpen && (
|
||||
<Button
|
||||
ref={addButton}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
className="min-h-11"
|
||||
onClick={() => setPanelOpen(true)}
|
||||
>
|
||||
{t('relations.add_client')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{state.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('relations.loading')}
|
||||
</p>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<div className="space-y-3">
|
||||
<Notice tone="error">
|
||||
{t(`relations.failure.${state.failure}`)}
|
||||
</Notice>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => void reload()}
|
||||
>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{stale && <Notice tone="error">{t(`relations.failure.${stale}`)}</Notice>}
|
||||
{groups && !groups.hasOwner && (
|
||||
<p className="rounded-lg border border-dashed border-[var(--color-border)] px-3 py-2 text-sm text-[var(--color-ink)]">
|
||||
{t('animals.no_owner')}
|
||||
</p>
|
||||
)}
|
||||
{groups && groups.current.length + groups.former.length === 0 && (
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('relations.none')}
|
||||
</p>
|
||||
)}
|
||||
{groups &&
|
||||
group(groups.current, 'relations.current', 'animal-relations-current')}
|
||||
{groups &&
|
||||
group(groups.former, 'relations.former', 'animal-relations-former')}
|
||||
{panelOpen && (
|
||||
<RelationPanel
|
||||
pick="client"
|
||||
animalId={animal.id}
|
||||
workspaceId={workspaceId}
|
||||
onCancel={() => setPanelOpen(false)}
|
||||
onSaved={async () => {
|
||||
await reload()
|
||||
setStale(null)
|
||||
onStatus(t('relations.added_client'))
|
||||
setPanelOpen(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{target?.action === 'end' && (
|
||||
<EndRelationDialog
|
||||
relation={target.relation}
|
||||
relationLabel={label(target.relation)}
|
||||
{...handlers}
|
||||
onDone={() => handlers.onDone(t('relations.end.done'))}
|
||||
/>
|
||||
)}
|
||||
{target?.action === 'dates' && (
|
||||
<RelationDatesDialog
|
||||
relation={target.relation}
|
||||
relationLabel={label(target.relation)}
|
||||
{...handlers}
|
||||
onDone={() => handlers.onDone(t('relations.dates.done'))}
|
||||
/>
|
||||
)}
|
||||
{target?.action === 'void' && (
|
||||
<VoidRelationDialog
|
||||
relation={target.relation}
|
||||
relationLabel={label(target.relation)}
|
||||
{...handlers}
|
||||
onDone={() => handlers.onDone(t('relations.void.done'))}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { AnimalListItem, ClientListItem } from '@faunosteo/supabase'
|
||||
import RecordPicker from './RecordPicker'
|
||||
import { speciesName, useSpecies } from '@/animals/species'
|
||||
import { useAnimalChoices, useClientChoices } from '@/relations/choices'
|
||||
import { useLocaleStore } from '@/state/localeStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** The record a picker handed over: its id and the name to show. */
|
||||
export interface Chosen {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
/** A client of the workspace, active only, found by the server search. */
|
||||
export function ClientPicker(props: {
|
||||
id: string
|
||||
workspaceId: string
|
||||
error?: string
|
||||
onChoose: (chosen: Chosen) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const search = useClientChoices(props.workspaceId)
|
||||
return (
|
||||
<RecordPicker<ClientListItem>
|
||||
id={props.id}
|
||||
label={t('relations.picker.client_label')}
|
||||
hint={t('relations.picker.client_hint')}
|
||||
resultsLabel={t('relations.picker.client_results')}
|
||||
emptyLabel={t('relations.picker.client_none')}
|
||||
search={search}
|
||||
toItem={(row) => ({
|
||||
id: row.id,
|
||||
name: row.display_name,
|
||||
detail: [t(`clients.kind.${row.kind}`), row.city]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
})}
|
||||
onChoose={(row) => props.onChoose({ id: row.id, name: row.display_name })}
|
||||
error={props.error}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** An animal of the workspace, active only, found by the server search. */
|
||||
export function AnimalPicker(props: {
|
||||
id: string
|
||||
workspaceId: string
|
||||
error?: string
|
||||
onChoose: (chosen: Chosen) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
const locale = useLocaleStore((s) => s.locale)
|
||||
const { state: species } = useSpecies()
|
||||
const labels = species.status === 'ready' ? species.labels : []
|
||||
const search = useAnimalChoices(props.workspaceId)
|
||||
return (
|
||||
<RecordPicker<AnimalListItem>
|
||||
id={props.id}
|
||||
label={t('relations.picker.animal_label')}
|
||||
hint={t('relations.picker.animal_hint')}
|
||||
resultsLabel={t('relations.picker.animal_results')}
|
||||
emptyLabel={t('relations.picker.animal_none')}
|
||||
search={search}
|
||||
toItem={(row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
detail: [
|
||||
speciesName(labels, row.species_id, row.species_detail, locale),
|
||||
row.breed,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
})}
|
||||
onChoose={(row) => props.onChoose({ id: row.id, name: row.name })}
|
||||
error={props.error}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import Button from '@/components/ui/Button'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { SEARCH_DELAY_MS } from '@/clients/useClientList'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface PickerItem {
|
||||
id: string
|
||||
name: string
|
||||
/** One muted line under the name: kind and city, or species and breed. */
|
||||
detail: string
|
||||
}
|
||||
|
||||
export interface RecordPickerProps<Row> {
|
||||
id: string
|
||||
label: string
|
||||
hint: string
|
||||
/** Accessible name of the result list. */
|
||||
resultsLabel: string
|
||||
emptyLabel: string
|
||||
/** The server search (POST): the term never reaches a URL. Stable across renders. */
|
||||
search: (term: string) => Promise<Row[]>
|
||||
/** How a row reads, computed at render so a change of language needs no new search. */
|
||||
toItem: (row: Row) => PickerItem
|
||||
onChoose: (row: Row) => void
|
||||
/** The field's own error (« choisissez un client »). */
|
||||
error?: string
|
||||
}
|
||||
|
||||
type Results<Row> =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; items: Row[] }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/**
|
||||
* Finds one record to link through the server search, the active records
|
||||
* only: a search field, then the first matches as buttons named by the
|
||||
* record. No local copy of the records; an answer to an older term is
|
||||
* dropped. Choosing hands the item to the parent, which replaces the picker.
|
||||
*/
|
||||
export default function RecordPicker<Row>({
|
||||
id,
|
||||
label,
|
||||
hint,
|
||||
resultsLabel,
|
||||
emptyLabel,
|
||||
search,
|
||||
toItem,
|
||||
onChoose,
|
||||
error,
|
||||
}: RecordPickerProps<Row>) {
|
||||
const t = useT()
|
||||
const [query, setQuery] = useState('')
|
||||
const [term, setTerm] = useState('')
|
||||
const [results, setResults] = useState<Results<Row>>({ status: 'loading' })
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const generation = useRef(0)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [query])
|
||||
|
||||
useEffect(() => {
|
||||
const current = ++generation.current
|
||||
setResults({ status: 'loading' })
|
||||
search(term)
|
||||
.then((items) => {
|
||||
if (current === generation.current)
|
||||
setResults({ status: 'ready', items })
|
||||
})
|
||||
.catch((failure: unknown) => {
|
||||
if (current === generation.current)
|
||||
setResults({
|
||||
status: 'error',
|
||||
failure: classifyRecordError(failure),
|
||||
})
|
||||
})
|
||||
}, [search, term, attempt])
|
||||
|
||||
const describedBy = error ? `${id}-error` : `${id}-hint`
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<FormField id={id} label={label} hint={hint} error={error}>
|
||||
<Input
|
||||
id={id}
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
maxLength={100}
|
||||
autoComplete="off"
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
</FormField>
|
||||
{results.status === 'loading' && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t('relations.picker.loading')}
|
||||
</p>
|
||||
)}
|
||||
{results.status === 'error' && (
|
||||
<div className="space-y-2">
|
||||
<Notice tone="error">
|
||||
{t(`relations.failure.${results.failure}`)}
|
||||
</Notice>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="min-h-11"
|
||||
onClick={() => setAttempt((n) => n + 1)}
|
||||
>
|
||||
{t('common.retry')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{results.status === 'ready' && results.items.length === 0 && (
|
||||
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
|
||||
{emptyLabel}
|
||||
</p>
|
||||
)}
|
||||
{results.status === 'ready' && results.items.length > 0 && (
|
||||
<ul
|
||||
aria-label={resultsLabel}
|
||||
className="max-h-72 divide-y divide-[var(--color-border)] overflow-y-auto rounded-xl border border-[var(--color-border)] bg-white"
|
||||
>
|
||||
{results.items.map((row) => {
|
||||
const item = toItem(row)
|
||||
return (
|
||||
<li key={item.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChoose(row)}
|
||||
className="flex min-h-11 w-full flex-col items-start gap-0.5 px-4 py-2 text-left hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<span className="font-medium text-[var(--color-ink)]">
|
||||
{item.name}
|
||||
</span>
|
||||
{item.detail && (
|
||||
<span className="text-sm text-[var(--color-ink-muted)]">
|
||||
{item.detail}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface RelationActionHandlers {
|
||||
onClose: () => void
|
||||
/** After a success: the page reloads the relations, announces, then closes the dialog. */
|
||||
onDone: () => Promise<void>
|
||||
/**
|
||||
* The relation changed or left elsewhere (`conflict`, `not_found`): the page
|
||||
* reloads and says so, then closes the dialog; the stale row is never retried.
|
||||
*/
|
||||
onStale: (failure: RecordFailureKind) => Promise<void>
|
||||
}
|
||||
|
||||
export interface RelationActionDialogProps extends RelationActionHandlers {
|
||||
title: string
|
||||
/** Which relation: « Marie Dupont · Propriétaire ». */
|
||||
relationLabel: string
|
||||
body: string
|
||||
confirmLabel: string
|
||||
pendingLabel: string
|
||||
danger?: boolean
|
||||
children?: ReactNode
|
||||
/** Checks the fields; false keeps the dialog open with their errors. */
|
||||
validate?: () => boolean
|
||||
/** The relation RPC; throws a RecordFailure. */
|
||||
action: () => Promise<unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmation of one relation write (end, dates, void) on the shared
|
||||
* ModalDialog: closing is never confirming; while the write and the reload
|
||||
* that shows it run, the dialog refuses to close, so focus returns once,
|
||||
* after the change is on the page (to the opener, or to its container when
|
||||
* the opener left with the row). Other failures stay in the dialog with the
|
||||
* values typed.
|
||||
*/
|
||||
export default function RelationActionDialog({
|
||||
title,
|
||||
relationLabel,
|
||||
body,
|
||||
confirmLabel,
|
||||
pendingLabel,
|
||||
danger = false,
|
||||
children,
|
||||
validate,
|
||||
action,
|
||||
onClose,
|
||||
onDone,
|
||||
onStale,
|
||||
}: RelationActionDialogProps) {
|
||||
const t = useT()
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(null)
|
||||
|
||||
const close = () => {
|
||||
if (!pending) onClose()
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (pending || (validate && !validate())) return
|
||||
setPending(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
await action()
|
||||
await onDone()
|
||||
} catch (error) {
|
||||
const kind = classifyRecordError(error)
|
||||
if (kind === 'conflict' || kind === 'not_found') await onStale(kind)
|
||||
else setFailure(kind)
|
||||
} finally {
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onClose={close}
|
||||
title={title}
|
||||
description={
|
||||
<div className="space-y-2 text-sm">
|
||||
<p className="font-medium text-[var(--color-ink)]">{relationLabel}</p>
|
||||
<p className="text-[var(--color-ink-muted)]">{body}</p>
|
||||
</div>
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-3 space-y-3">
|
||||
{children}
|
||||
{failure && (
|
||||
<Notice tone="error">{t(`relations.failure.${failure}`)}</Notice>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
{/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={close}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={danger ? 'danger' : 'primary'}
|
||||
onClick={() => void confirm()}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{pending ? pendingLabel : confirmLabel}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
endAnimalClientRelation,
|
||||
updateAnimalClientRelation,
|
||||
voidAnimalClientRelation,
|
||||
type AnimalRelationItem,
|
||||
} from '@faunosteo/supabase'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import RelationActionDialog, {
|
||||
type RelationActionHandlers,
|
||||
} from './RelationActionDialog'
|
||||
import { recordDateIssue } from '@/animals/validation'
|
||||
import { localDateIso } from '@/lib/dates'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { translateFieldError } from '@/account/validation'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
interface RelationDialogProps extends RelationActionHandlers {
|
||||
relation: AnimalRelationItem
|
||||
/** « Marie Dupont · Propriétaire ». */
|
||||
relationLabel: string
|
||||
}
|
||||
|
||||
function backend() {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new TypeError('no backend')
|
||||
return client
|
||||
}
|
||||
|
||||
/** The issue of an end date: a record date, and not before a known start. */
|
||||
function endIssue(endedOn: string, startedOn: string, today: string) {
|
||||
const issue = recordDateIssue(endedOn, today)
|
||||
if (issue) return issue
|
||||
return startedOn && endedOn && endedOn < startedOn
|
||||
? 'relations.error.end_before_start'
|
||||
: null
|
||||
}
|
||||
|
||||
function DateField(props: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
error: string | null
|
||||
today: string
|
||||
onChange: (value: string) => void
|
||||
}) {
|
||||
const t = useT()
|
||||
return (
|
||||
<FormField
|
||||
id={props.id}
|
||||
label={props.label}
|
||||
optional={t('animals.form.optional')}
|
||||
hint={t('relations.date_hint')}
|
||||
error={translateFieldError(t, props.error ?? undefined)}
|
||||
>
|
||||
<Input
|
||||
id={props.id}
|
||||
type="date"
|
||||
value={props.value}
|
||||
min="1900-01-01"
|
||||
max={props.today}
|
||||
onChange={(e) => props.onChange(e.target.value)}
|
||||
aria-invalid={Boolean(props.error)}
|
||||
aria-describedby={
|
||||
props.error ? `${props.id}-error` : `${props.id}-hint`
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
)
|
||||
}
|
||||
|
||||
/** Ends a current relation, with its real end date when known (N5: never invented). */
|
||||
export function EndRelationDialog({
|
||||
relation,
|
||||
relationLabel,
|
||||
...handlers
|
||||
}: RelationDialogProps) {
|
||||
const t = useT()
|
||||
const today = localDateIso()
|
||||
const [endedOn, setEndedOn] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
return (
|
||||
<RelationActionDialog
|
||||
{...handlers}
|
||||
title={t('relations.end.title')}
|
||||
relationLabel={relationLabel}
|
||||
body={t('relations.end.body')}
|
||||
confirmLabel={t('relations.end.confirm')}
|
||||
pendingLabel={t('relations.saving')}
|
||||
validate={() => {
|
||||
const issue = endIssue(endedOn, relation.started_on ?? '', today)
|
||||
setError(issue)
|
||||
if (issue) document.getElementById('relation-ended-on')?.focus()
|
||||
return issue === null
|
||||
}}
|
||||
action={() =>
|
||||
endAnimalClientRelation(backend(), {
|
||||
relationId: relation.id,
|
||||
expectedRevision: relation.revision,
|
||||
endedOn: endedOn || null,
|
||||
})
|
||||
}
|
||||
>
|
||||
<DateField
|
||||
id="relation-ended-on"
|
||||
label={t('relations.end.ended_on')}
|
||||
value={endedOn}
|
||||
error={error}
|
||||
today={today}
|
||||
onChange={setEndedOn}
|
||||
/>
|
||||
</RelationActionDialog>
|
||||
)
|
||||
}
|
||||
|
||||
/** Corrects the start date, and the end date of an ended relation; client and role never change. */
|
||||
export function RelationDatesDialog({
|
||||
relation,
|
||||
relationLabel,
|
||||
...handlers
|
||||
}: RelationDialogProps) {
|
||||
const t = useT()
|
||||
const today = localDateIso()
|
||||
const ended = relation.ended_at !== null
|
||||
const [startedOn, setStartedOn] = useState(relation.started_on ?? '')
|
||||
const [endedOn, setEndedOn] = useState(relation.ended_on ?? '')
|
||||
const [errors, setErrors] = useState<{
|
||||
start: string | null
|
||||
end: string | null
|
||||
}>({ start: null, end: null })
|
||||
return (
|
||||
<RelationActionDialog
|
||||
{...handlers}
|
||||
title={t('relations.dates.title')}
|
||||
relationLabel={relationLabel}
|
||||
body={t('relations.dates.body')}
|
||||
confirmLabel={t('relations.dates.confirm')}
|
||||
pendingLabel={t('relations.saving')}
|
||||
validate={() => {
|
||||
const start = recordDateIssue(startedOn, today)
|
||||
const end = ended ? endIssue(endedOn, startedOn, today) : null
|
||||
setErrors({ start, end })
|
||||
const first = start
|
||||
? 'relation-started-on'
|
||||
: end
|
||||
? 'relation-ended-on'
|
||||
: null
|
||||
if (first) document.getElementById(first)?.focus()
|
||||
return !start && !end
|
||||
}}
|
||||
action={() =>
|
||||
updateAnimalClientRelation(backend(), {
|
||||
relationId: relation.id,
|
||||
expectedRevision: relation.revision,
|
||||
startedOn: startedOn || null,
|
||||
endedOn: ended ? endedOn || null : null,
|
||||
})
|
||||
}
|
||||
>
|
||||
<DateField
|
||||
id="relation-started-on"
|
||||
label={t('relations.dates.started_on')}
|
||||
value={startedOn}
|
||||
error={errors.start}
|
||||
today={today}
|
||||
onChange={setStartedOn}
|
||||
/>
|
||||
{ended && (
|
||||
<DateField
|
||||
id="relation-ended-on"
|
||||
label={t('relations.dates.ended_on')}
|
||||
value={endedOn}
|
||||
error={errors.end}
|
||||
today={today}
|
||||
onChange={setEndedOn}
|
||||
/>
|
||||
)}
|
||||
</RelationActionDialog>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Voids a relation entered by mistake (N4): it disappears from every page
|
||||
* and list, is kept frozen for the record lifecycle, and cannot come back.
|
||||
* The text says when to use « Terminer » instead.
|
||||
*/
|
||||
export function VoidRelationDialog({
|
||||
relation,
|
||||
relationLabel,
|
||||
...handlers
|
||||
}: RelationDialogProps) {
|
||||
const t = useT()
|
||||
return (
|
||||
<RelationActionDialog
|
||||
{...handlers}
|
||||
title={t('relations.void.title')}
|
||||
relationLabel={relationLabel}
|
||||
body={t('relations.void.body')}
|
||||
confirmLabel={t('relations.void.confirm')}
|
||||
pendingLabel={t('relations.saving')}
|
||||
danger
|
||||
action={() =>
|
||||
voidAnimalClientRelation(backend(), {
|
||||
relationId: relation.id,
|
||||
expectedRevision: relation.revision,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
createAnimalClientRelation,
|
||||
type AnimalRelationRole,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import Button from '@/components/ui/Button'
|
||||
import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios'
|
||||
import FormField from '@/components/ui/FormField'
|
||||
import Input from '@/components/ui/Input'
|
||||
import Notice from '@/components/ui/Notice'
|
||||
import { AnimalPicker, ClientPicker, type Chosen } from './Pickers'
|
||||
import { useLeaveGuard } from '@/app/useLeaveGuard'
|
||||
import {
|
||||
RELATION_ROLES,
|
||||
relationIssues,
|
||||
type RelationFieldErrors,
|
||||
} from '@/animals/validation'
|
||||
import { generateUuid } from '@/lib/id'
|
||||
import { localDateIso } from '@/lib/dates'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
import { useT } from '@/i18n/useT'
|
||||
import { translateFieldError } from '@/account/validation'
|
||||
|
||||
export type RelationPanelProps = {
|
||||
workspaceId: string
|
||||
/** Called once the server made the relation; the page reloads, then closes the panel. */
|
||||
onSaved: () => Promise<void>
|
||||
onCancel: () => void
|
||||
} & (
|
||||
| { pick: 'client'; animalId: string }
|
||||
| { pick: 'animal'; clientId: string }
|
||||
)
|
||||
|
||||
const PANEL = 'relation-panel'
|
||||
const FIELD_IDS = {
|
||||
client: `${PANEL}-search`,
|
||||
relation_role: firstChoiceId(`${PANEL}-role`, 'owner'),
|
||||
started_on: `${PANEL}-started-on`,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Links a client and an animal from one of their pages, inside the page (no
|
||||
* modal form, contract §11.4): find the other record, pick the role (none
|
||||
* preselected), the start date when known. One request id per opening of
|
||||
* the panel, sent again on a retry, so a lost answer never makes a second
|
||||
* relation. Both records must be active; the server says so otherwise.
|
||||
*/
|
||||
export default function RelationPanel(props: RelationPanelProps) {
|
||||
const t = useT()
|
||||
const heading = useRef<HTMLHeadingElement>(null)
|
||||
const chosenText = useRef<HTMLParagraphElement>(null)
|
||||
const [chosen, setChosen] = useState<Chosen | null>(null)
|
||||
const [role, setRole] = useState<AnimalRelationRole | ''>('')
|
||||
const [startedOn, setStartedOn] = useState('')
|
||||
const [errors, setErrors] = useState<RelationFieldErrors>({})
|
||||
const [errorRound, setErrorRound] = useState(0)
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<RecordFailureKind | null>(null)
|
||||
const [requestId] = useState(generateUuid)
|
||||
const inFlight = useRef(false)
|
||||
const today = localDateIso()
|
||||
useLeaveGuard(Boolean(chosen || role || startedOn))
|
||||
|
||||
useEffect(() => heading.current?.focus(), [])
|
||||
useEffect(() => {
|
||||
if (chosen) chosenText.current?.focus()
|
||||
}, [chosen])
|
||||
useEffect(() => {
|
||||
if (errorRound === 0) return
|
||||
const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find(
|
||||
(key) => errors[key],
|
||||
)
|
||||
if (first) document.getElementById(FIELD_IDS[first])?.focus()
|
||||
}, [errorRound, errors])
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (inFlight.current) return
|
||||
const issues = relationIssues(
|
||||
{
|
||||
client: chosen && { id: chosen.id, display_name: chosen.name },
|
||||
relation_role: role,
|
||||
started_on: startedOn,
|
||||
},
|
||||
localDateIso(),
|
||||
true,
|
||||
)
|
||||
setErrors(issues)
|
||||
if (Object.keys(issues).length > 0 || !chosen || role === '') {
|
||||
setErrorRound((n) => n + 1)
|
||||
return
|
||||
}
|
||||
const client = getSupabaseClient()
|
||||
if (!client) return setFailure('unavailable')
|
||||
inFlight.current = true
|
||||
setPending(true)
|
||||
setFailure(null)
|
||||
try {
|
||||
await createAnimalClientRelation(client, {
|
||||
animalId: props.pick === 'client' ? props.animalId : chosen.id,
|
||||
clientId: props.pick === 'client' ? chosen.id : props.clientId,
|
||||
requestId,
|
||||
relationRole: role,
|
||||
startedOn: startedOn || null,
|
||||
})
|
||||
await props.onSaved()
|
||||
} catch (error) {
|
||||
setFailure(classifyRecordError(error))
|
||||
} finally {
|
||||
inFlight.current = false
|
||||
setPending(false)
|
||||
}
|
||||
}
|
||||
|
||||
const err = (key: keyof RelationFieldErrors) =>
|
||||
translateFieldError(t, errors[key])
|
||||
const pickLabel =
|
||||
props.pick === 'client'
|
||||
? 'relations.panel.client_chosen'
|
||||
: 'relations.panel.animal_chosen'
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={submit}
|
||||
noValidate
|
||||
aria-labelledby={`${PANEL}-title`}
|
||||
className="space-y-4 border-t border-[var(--color-border)] pt-4"
|
||||
>
|
||||
<h3
|
||||
id={`${PANEL}-title`}
|
||||
ref={heading}
|
||||
tabIndex={-1}
|
||||
className="text-base font-medium text-[var(--color-ink)] outline-none"
|
||||
>
|
||||
{t(
|
||||
props.pick === 'client'
|
||||
? 'relations.panel.title_client'
|
||||
: 'relations.panel.title_animal',
|
||||
)}
|
||||
</h3>
|
||||
{chosen ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<p
|
||||
ref={chosenText}
|
||||
tabIndex={-1}
|
||||
className="min-w-0 text-sm text-[var(--color-ink)] outline-none"
|
||||
>
|
||||
{t(pickLabel)} <span className="font-medium">{chosen.name}</span>
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="min-h-11"
|
||||
onClick={() => setChosen(null)}
|
||||
>
|
||||
{t('relations.panel.change')}
|
||||
</Button>
|
||||
</div>
|
||||
) : props.pick === 'client' ? (
|
||||
<ClientPicker
|
||||
id={FIELD_IDS.client}
|
||||
workspaceId={props.workspaceId}
|
||||
error={err('client')}
|
||||
onChoose={setChosen}
|
||||
/>
|
||||
) : (
|
||||
<AnimalPicker
|
||||
id={FIELD_IDS.client}
|
||||
workspaceId={props.workspaceId}
|
||||
error={err('client')}
|
||||
onChoose={setChosen}
|
||||
/>
|
||||
)}
|
||||
<ChoiceRadios
|
||||
id={`${PANEL}-role`}
|
||||
legend={t('relations.panel.role')}
|
||||
marker={t('animals.form.required')}
|
||||
options={RELATION_ROLES.map((value) => ({
|
||||
value,
|
||||
label: t(`clients.role.${value}`),
|
||||
}))}
|
||||
value={role}
|
||||
onChange={setRole}
|
||||
error={err('relation_role')}
|
||||
/>
|
||||
<FormField
|
||||
id={FIELD_IDS.started_on}
|
||||
label={t('relations.panel.started_on')}
|
||||
optional={t('animals.form.optional')}
|
||||
hint={t('relations.date_hint')}
|
||||
error={err('started_on')}
|
||||
>
|
||||
<Input
|
||||
id={FIELD_IDS.started_on}
|
||||
type="date"
|
||||
value={startedOn}
|
||||
min="1900-01-01"
|
||||
max={today}
|
||||
onChange={(e) => setStartedOn(e.target.value)}
|
||||
aria-invalid={Boolean(errors.started_on)}
|
||||
aria-describedby={
|
||||
errors.started_on
|
||||
? `${FIELD_IDS.started_on}-error`
|
||||
: `${FIELD_IDS.started_on}-hint`
|
||||
}
|
||||
className="sm:max-w-xs"
|
||||
/>
|
||||
</FormField>
|
||||
{failure && (
|
||||
<Notice tone="error">{t(`relations.failure.${failure}`)}</Notice>
|
||||
)}
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="min-h-11"
|
||||
onClick={() => !pending && props.onCancel()}
|
||||
aria-disabled={pending}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button type="submit" className="min-h-11" aria-disabled={pending}>
|
||||
{pending
|
||||
? t('relations.panel.saving')
|
||||
: t(
|
||||
props.pick === 'client'
|
||||
? 'relations.panel.save_client'
|
||||
: 'relations.panel.save_animal',
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -18,13 +18,11 @@ export default function DisclaimerDialog({
|
||||
open
|
||||
onClose={onAcknowledge}
|
||||
title={t('editor.disclaimer_title')}
|
||||
description={<p className="text-sm text-[var(--color-ink)]">{text}</p>}
|
||||
size="md"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-[var(--color-ink)]">{text}</p>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
|
||||
</div>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button onClick={onAcknowledge}>{t('common.understood')}</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
|
||||
@@ -114,15 +114,17 @@ export default function HeldSessionPanel({
|
||||
? 'session.held.open_title'
|
||||
: `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`,
|
||||
)}
|
||||
description={
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t(
|
||||
pending?.action === 'open'
|
||||
? 'session.held.open_body'
|
||||
: 'session.held.discard_body',
|
||||
)}
|
||||
</p>
|
||||
}
|
||||
size="sm"
|
||||
>
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">
|
||||
{t(
|
||||
pending?.action === 'open'
|
||||
? 'session.held.open_body'
|
||||
: 'session.held.discard_body',
|
||||
)}
|
||||
</p>
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setPending(null)}>
|
||||
{t('common.cancel')}
|
||||
|
||||
@@ -30,8 +30,13 @@ export default function ReplaceSessionDialog({
|
||||
? t('session.replace.body').replace(/\{animal\}/, () => report.animal.name)
|
||||
: t('session.replace.body_unloaded')
|
||||
return (
|
||||
<Dialog open={open} onClose={onCancel} title={t('session.replace.title')} size="sm">
|
||||
<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onCancel}
|
||||
title={t('session.replace.title')}
|
||||
description={<p className="text-sm text-[var(--color-ink-muted)]">{body}</p>}
|
||||
size="sm"
|
||||
>
|
||||
{unsaved && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<p className="text-sm">{t('session.replace.unsaved')}</p>
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { useState } from 'react'
|
||||
import { Link, Outlet, useLocation } from 'react-router-dom'
|
||||
import { useState, type MouseEvent } from 'react'
|
||||
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
|
||||
import Brand from '@/components/brand/Brand'
|
||||
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
|
||||
import Button from '@/components/ui/Button'
|
||||
import Dialog from '@/components/ui/Dialog'
|
||||
import Icon from '@/components/ui/Icon'
|
||||
import MobileDrawer from './MobileDrawer'
|
||||
import SidebarNav, { NAV_ITEMS } from './SidebarNav'
|
||||
import SignOutButton from './SignOutButton'
|
||||
import UserBadge, { AvatarCircle } from './UserBadge'
|
||||
import { useAuthStore } from '@/state/authStore'
|
||||
import { useLeaveGuardStore } from '@/state/leaveGuardStore'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
/** Title of the current /app page for the top bar, from the nav table. */
|
||||
@@ -18,20 +21,53 @@ function pageTitleKey(pathname: string): string {
|
||||
return match?.labelKey ?? 'shell.nav.dashboard'
|
||||
}
|
||||
|
||||
/** An in-app link a plain click would follow: same origin, same tab, no modifier key. */
|
||||
function followedLink(event: MouseEvent): HTMLAnchorElement | null {
|
||||
if (event.defaultPrevented || event.button !== 0) return null
|
||||
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null
|
||||
const anchor = (event.target as Element).closest('a[href]') as HTMLAnchorElement | null
|
||||
if (!anchor || anchor.target === '_blank' || anchor.origin !== window.location.origin) return null
|
||||
return anchor
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticated shell: fixed sidebar on large screens, light top bar with a
|
||||
* drawer button below. The page content scrolls on its own.
|
||||
* drawer button below. The page content scrolls on its own. While a page
|
||||
* holds unsaved changes (useLeaveGuard), following any link of the shell or
|
||||
* of the page asks first; staying is the default.
|
||||
*/
|
||||
export default function AppLayout() {
|
||||
const t = useT()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [drawerOpen, setDrawerOpen] = useState(false)
|
||||
const guarded = useLeaveGuardStore((s) => s.armed)
|
||||
const arm = useLeaveGuardStore((s) => s.arm)
|
||||
const [leaveTo, setLeaveTo] = useState<string | null>(null)
|
||||
|
||||
function askBeforeLeaving(event: MouseEvent) {
|
||||
if (!guarded) return
|
||||
const anchor = followedLink(event)
|
||||
if (!anchor) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setLeaveTo(anchor.pathname + anchor.search + anchor.hash)
|
||||
}
|
||||
|
||||
function leave() {
|
||||
const to = leaveTo
|
||||
if (!to) return
|
||||
arm(false)
|
||||
setLeaveTo(null)
|
||||
setDrawerOpen(false)
|
||||
navigate(to)
|
||||
}
|
||||
const profile = useAuthStore((s) => s.profile)
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const displayName = profile?.display_name ?? user?.email ?? ''
|
||||
|
||||
return (
|
||||
<div className="flex min-h-dvh bg-[var(--color-bg)]">
|
||||
<div className="flex min-h-dvh bg-[var(--color-bg)]" onClickCapture={askBeforeLeaving}>
|
||||
<aside className="hidden lg:flex lg:w-64 lg:shrink-0 lg:flex-col border-r border-[var(--color-border)] bg-[var(--color-surface)]">
|
||||
<div className="px-5 py-5">
|
||||
<Link to="/app" aria-label={t('shell.nav.dashboard')} className="inline-block">
|
||||
@@ -85,6 +121,22 @@ export default function AppLayout() {
|
||||
</div>
|
||||
|
||||
<MobileDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
|
||||
<Dialog
|
||||
open={leaveTo !== null}
|
||||
onClose={() => setLeaveTo(null)}
|
||||
title={t('leave.title')}
|
||||
description={<p className="text-sm text-[var(--color-ink-muted)]">{t('leave.body')}</p>}
|
||||
size="sm"
|
||||
>
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => setLeaveTo(null)}>
|
||||
{t('leave.stay')}
|
||||
</Button>
|
||||
<Button type="button" variant="danger" onClick={leave}>
|
||||
{t('leave.confirm')}
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 <AnimatePresence>{open && <DrawerSurface onClose={onClose} />}</AnimatePresence>
|
||||
}
|
||||
|
||||
function DrawerSurface({ onClose }: Pick<MobileDrawerProps, 'onClose'>) {
|
||||
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 (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 lg:hidden">
|
||||
<motion.div
|
||||
data-testid="drawer-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
<ModalDialog onClose={onClose} label={t('shell.nav_label')} className="open:block">
|
||||
<motion.div
|
||||
data-testid="drawer-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.aside
|
||||
initial={slide}
|
||||
animate={{ x: 0 }}
|
||||
exit={slide}
|
||||
transition={{ duration: reduced ? 0 : 0.2, ease: 'easeOut' }}
|
||||
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
|
||||
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.aside
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t('shell.nav_label')}
|
||||
initial={slide}
|
||||
animate={{ x: 0 }}
|
||||
exit={slide}
|
||||
transition={{ duration: reduced ? 0 : 0.2, ease: 'easeOut' }}
|
||||
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
|
||||
aria-label={t('shell.close_menu')}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
|
||||
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
|
||||
<Brand size="md" />
|
||||
</Link>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('shell.close_menu')}
|
||||
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
|
||||
>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-4">
|
||||
<SidebarNav onNavigate={onClose} />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</motion.aside>
|
||||
<Icon name="close" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-4">
|
||||
<SidebarNav onNavigate={onClose} />
|
||||
</div>
|
||||
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
|
||||
<UserBadge />
|
||||
<SignOutButton className="w-full" />
|
||||
</div>
|
||||
</motion.aside>
|
||||
</ModalDialog>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ButtonHTMLAttributes, ReactNode } from 'react'
|
||||
import type { ButtonHTMLAttributes, ReactNode, Ref } from 'react'
|
||||
|
||||
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary' | 'ghost' | 'danger'
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
children?: ReactNode
|
||||
/** React 19 passes it as a prop; it reaches the <button> with the rest. */
|
||||
ref?: Ref<HTMLButtonElement>
|
||||
}
|
||||
|
||||
const VARIANTS: Record<NonNullable<ButtonProps['variant']>, string> = {
|
||||
|
||||
@@ -4,15 +4,19 @@ export interface CardProps {
|
||||
children: ReactNode
|
||||
className?: string
|
||||
as?: 'div' | 'section' | 'article'
|
||||
/** Names a section card by its heading, so it reads as a named region. */
|
||||
'aria-labelledby'?: string
|
||||
}
|
||||
|
||||
export default function Card({
|
||||
children,
|
||||
className = '',
|
||||
as: Tag = 'div',
|
||||
'aria-labelledby': labelledBy,
|
||||
}: CardProps) {
|
||||
return (
|
||||
<Tag
|
||||
aria-labelledby={labelledBy}
|
||||
className={[
|
||||
'rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] shadow-sm',
|
||||
className,
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
export interface ChoiceRadiosProps<V extends string> {
|
||||
/** Prefix of the radio ids: the first one is `${id}-${options[0].value}`. */
|
||||
id: string
|
||||
legend: string
|
||||
/** « obligatoire » or « facultatif », shown beside the legend like FormField. */
|
||||
marker?: string
|
||||
options: readonly { value: V; label: string }[]
|
||||
/** '' when nothing is chosen: no option is preselected. */
|
||||
value: V | ''
|
||||
onChange: (value: V) => void
|
||||
hint?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
/** The id of the radio that takes focus when the group is in error. */
|
||||
export const firstChoiceId = (id: string, first: string) => `${id}-${first}`
|
||||
|
||||
/**
|
||||
* A required choice among a few explicit options, as large touch targets
|
||||
* (the client kind's look): a fieldset named by its legend, the error under
|
||||
* it and linked from every radio, nothing checked until the user picks.
|
||||
*/
|
||||
export default function ChoiceRadios<V extends string>({
|
||||
id,
|
||||
legend,
|
||||
marker,
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
hint,
|
||||
error,
|
||||
}: ChoiceRadiosProps<V>) {
|
||||
const describedBy = error ? `${id}-error` : hint ? `${id}-hint` : undefined
|
||||
return (
|
||||
<fieldset className="space-y-2">
|
||||
{/* The look of Label (FormField), on the element that names the group. */}
|
||||
<legend className="mb-1 flex w-full items-baseline justify-between text-sm font-medium text-[var(--color-ink)]">
|
||||
<span>{legend}</span>
|
||||
{marker && (
|
||||
<span className="text-xs font-normal text-[var(--color-ink-muted)]">
|
||||
{marker}
|
||||
</span>
|
||||
)}
|
||||
</legend>
|
||||
<div className="grid grid-cols-1 gap-2 min-[400px]:grid-cols-3">
|
||||
{options.map((option) => (
|
||||
<label
|
||||
key={option.value}
|
||||
className="flex min-h-11 cursor-pointer items-center gap-2 rounded-lg border border-[var(--color-border)] bg-white px-4 text-sm text-[var(--color-ink)] has-[:checked]:border-[var(--color-accent)] has-[:checked]:bg-[var(--color-accent)]/10 has-[:checked]:font-medium has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-[var(--color-accent)]"
|
||||
>
|
||||
<input
|
||||
id={`${id}-${option.value}`}
|
||||
type="radio"
|
||||
name={id}
|
||||
value={option.value}
|
||||
checked={value === option.value}
|
||||
onChange={() => onChange(option.value)}
|
||||
aria-invalid={Boolean(error)}
|
||||
aria-describedby={describedBy}
|
||||
className="h-4 w-4 accent-[var(--color-accent)]"
|
||||
/>
|
||||
{option.label}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{error ? (
|
||||
<p
|
||||
id={`${id}-error`}
|
||||
role="alert"
|
||||
className="text-sm text-[var(--color-danger)]"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : (
|
||||
hint && (
|
||||
<p
|
||||
id={`${id}-hint`}
|
||||
className="text-xs text-[var(--color-ink-muted)]"
|
||||
>
|
||||
{hint}
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
</fieldset>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
import { useId, type ReactNode } from 'react'
|
||||
import { AnimatePresence, motion } from 'motion/react'
|
||||
import ModalDialog from './ModalDialog'
|
||||
import { useT } from '@/i18n/useT'
|
||||
|
||||
export interface DialogProps {
|
||||
open: boolean
|
||||
/** Asked on Escape, the close button and a backdrop click; the dialog leaves when `open` turns false. */
|
||||
onClose: () => void
|
||||
title: string
|
||||
/** The dialog's message, announced with its name (aria-describedby). */
|
||||
description?: ReactNode
|
||||
children: ReactNode
|
||||
size?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
}
|
||||
@@ -17,61 +21,66 @@ const SIZE: Record<NonNullable<DialogProps['size']>, string> = {
|
||||
xl: 'max-w-4xl',
|
||||
}
|
||||
|
||||
export default function Dialog({
|
||||
open,
|
||||
onClose,
|
||||
title,
|
||||
children,
|
||||
size = 'md',
|
||||
}: DialogProps) {
|
||||
const t = useT()
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
export default function Dialog({ open, ...surface }: DialogProps) {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-4">
|
||||
<motion.div
|
||||
data-testid="dialog-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
<AnimatePresence>{open && <DialogSurface {...surface} />}</AnimatePresence>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogSurface({
|
||||
onClose,
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
size = 'md',
|
||||
}: Omit<DialogProps, 'open'>) {
|
||||
const t = useT()
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
return (
|
||||
<ModalDialog
|
||||
onClose={onClose}
|
||||
labelledBy={titleId}
|
||||
describedBy={description ? descriptionId : undefined}
|
||||
className="open:flex items-center justify-center p-3 sm:p-4"
|
||||
>
|
||||
<motion.div
|
||||
data-testid="dialog-backdrop"
|
||||
className="absolute inset-0 bg-black/40"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.96 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto overscroll-contain rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
||||
>
|
||||
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
|
||||
<h2
|
||||
id={titleId}
|
||||
className="text-lg font-semibold text-[var(--color-ink)]"
|
||||
>
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClose}
|
||||
/>
|
||||
<motion.div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
initial={{ opacity: 0, scale: 0.96 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.96 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className={`relative w-full ${SIZE[size]} max-h-[85vh] overflow-y-auto rounded-2xl bg-[var(--color-surface)] shadow-xl`}
|
||||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||||
>
|
||||
<header className="flex items-center justify-between px-4 sm:px-6 py-3 sm:py-4 border-b border-[var(--color-border)]">
|
||||
<h2 className="text-lg font-semibold text-[var(--color-ink)]">
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
onClick={onClose}
|
||||
className="rounded-md p-1 text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)]"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4">{children}</div>
|
||||
</motion.div>
|
||||
✕
|
||||
</button>
|
||||
</header>
|
||||
<div className="px-4 sm:px-6 py-3 sm:py-4">
|
||||
{description && <div id={descriptionId}>{description}</div>}
|
||||
{children}
|
||||
</div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
</ModalDialog>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,8 @@ export type IconName =
|
||||
| 'close'
|
||||
| 'dashboard'
|
||||
| 'user'
|
||||
| 'users'
|
||||
| 'paw'
|
||||
| 'tool'
|
||||
| 'logout'
|
||||
| 'eye'
|
||||
@@ -20,6 +22,8 @@ const PATHS: Record<IconName, string> = {
|
||||
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',
|
||||
|
||||
@@ -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<HTMLElement>(FOCUSABLE),
|
||||
)
|
||||
if (controls.some(tryFocus)) return
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Native modal `<dialog>` 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<HTMLDialogElement>(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<HTMLElement>(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<HTMLDialogElement>) => {
|
||||
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<HTMLDialogElement>) => {
|
||||
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 (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-labelledby={labelledBy}
|
||||
aria-label={label}
|
||||
aria-describedby={describedBy}
|
||||
onKeyDown={onKeyDown}
|
||||
onCancel={onCancel}
|
||||
onClose={onClosed}
|
||||
className={`${SURFACE} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -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.',
|
||||
}
|
||||
@@ -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.',
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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)}`
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useCallback } from 'react'
|
||||
import {
|
||||
searchAnimals,
|
||||
searchClients,
|
||||
type AnimalListItem,
|
||||
type ClientListItem,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
/** Matches shown at once: enough to pick from, the term narrows the rest. */
|
||||
const CHOICES = 8
|
||||
|
||||
function backend() {
|
||||
const client = getSupabaseClient()
|
||||
if (!client) throw new TypeError('no backend')
|
||||
return client
|
||||
}
|
||||
|
||||
/** Active clients of the workspace for a term; only an active client can be linked (§7.1). */
|
||||
export function useClientChoices(workspaceId: string) {
|
||||
return useCallback(
|
||||
async (term: string): Promise<ClientListItem[]> =>
|
||||
(
|
||||
await searchClients(backend(), {
|
||||
workspaceId,
|
||||
query: term,
|
||||
archived: false,
|
||||
pageSize: CHOICES,
|
||||
})
|
||||
).rows,
|
||||
[workspaceId],
|
||||
)
|
||||
}
|
||||
|
||||
/** Active animals of the workspace for a term, every species. */
|
||||
export function useAnimalChoices(workspaceId: string) {
|
||||
return useCallback(
|
||||
async (term: string): Promise<AnimalListItem[]> =>
|
||||
(
|
||||
await searchAnimals(backend(), {
|
||||
workspaceId,
|
||||
query: term,
|
||||
speciesId: null,
|
||||
archived: false,
|
||||
pageSize: CHOICES,
|
||||
})
|
||||
).rows,
|
||||
[workspaceId],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AnimalRelationItem } from '@faunosteo/supabase'
|
||||
|
||||
const ROLE_ORDER = { owner: 0, keeper: 1, contact: 2 } as const
|
||||
|
||||
const byName = (a: AnimalRelationItem, b: AnimalRelationItem) =>
|
||||
a.client.display_name.localeCompare(b.client.display_name) ||
|
||||
a.id.localeCompare(b.id)
|
||||
|
||||
/**
|
||||
* An animal's relations for its page: the current ones by role (owners
|
||||
* first) then client name; the former ones, most recently ended first.
|
||||
* `ended_at` orders the history only; the end date shown is `ended_on`.
|
||||
*/
|
||||
export function groupRelations(relations: readonly AnimalRelationItem[]) {
|
||||
const current = relations
|
||||
.filter((r) => r.ended_at === null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
ROLE_ORDER[a.relation_role] - ROLE_ORDER[b.relation_role] ||
|
||||
byName(a, b),
|
||||
)
|
||||
const former = relations
|
||||
.filter((r) => r.ended_at !== null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
(b.ended_at ?? '').localeCompare(a.ended_at ?? '') || byName(a, b),
|
||||
)
|
||||
return {
|
||||
current,
|
||||
former,
|
||||
/** No current owner: the page says « Propriétaire non renseigné », never a placeholder client. */
|
||||
hasOwner: current.some((r) => r.relation_role === 'owner'),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
classifyRecordError,
|
||||
fetchAnimalRelations,
|
||||
type AnimalRelationItem,
|
||||
type RecordFailureKind,
|
||||
} from '@faunosteo/supabase'
|
||||
import { getSupabaseClient } from '@/lib/supabase'
|
||||
|
||||
export type AnimalRelationsState =
|
||||
| { status: 'loading' }
|
||||
| { status: 'ready'; relations: AnimalRelationItem[] }
|
||||
| { status: 'error'; failure: RecordFailureKind }
|
||||
|
||||
/**
|
||||
* The relations of one animal (voided ones never come back). `reload`
|
||||
* resolves once the new answer is on screen, so a confirmation can stay open
|
||||
* until the change it made is shown; the rows stay visible meanwhile. An
|
||||
* answer older than the last request, or arriving after unmount, is dropped.
|
||||
*/
|
||||
export function useAnimalRelations(animalId: string) {
|
||||
const [state, setState] = useState<AnimalRelationsState>({
|
||||
status: 'loading',
|
||||
})
|
||||
const generation = useRef(0)
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
const current = ++generation.current
|
||||
const client = getSupabaseClient()
|
||||
if (!client) {
|
||||
setState({ status: 'error', failure: 'unavailable' })
|
||||
return
|
||||
}
|
||||
try {
|
||||
const relations = await fetchAnimalRelations(client, animalId)
|
||||
if (current === generation.current)
|
||||
setState({ status: 'ready', relations })
|
||||
} catch (error) {
|
||||
if (current === generation.current)
|
||||
setState({ status: 'error', failure: classifyRecordError(error) })
|
||||
}
|
||||
}, [animalId])
|
||||
|
||||
useEffect(() => {
|
||||
// The ref object is stable: bumping it on unmount drops the answer in flight.
|
||||
const requests = generation
|
||||
void reload()
|
||||
return () => {
|
||||
requests.current++
|
||||
}
|
||||
}, [reload])
|
||||
|
||||
return { state, reload }
|
||||
}
|
||||
@@ -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<void>
|
||||
/** Reads the personal workspace again (after a failure). */
|
||||
refreshWorkspace: () => Promise<void>
|
||||
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
|
||||
/** Re-reads the own rows; downloads the clean photo when it changed. */
|
||||
refreshAvatar: () => Promise<AvatarState>
|
||||
@@ -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<AuthState> {
|
||||
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<AuthState> = {
|
||||
// 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<AuthState>((set, get) => ({
|
||||
urlFailure: null,
|
||||
avatar: null,
|
||||
avatarUrl: null,
|
||||
workspace: { status: 'idle' },
|
||||
|
||||
start: () => {
|
||||
const client = getSupabaseClient()
|
||||
@@ -175,6 +243,11 @@ export const useAuthStore = create<AuthState>((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<AuthState>((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 {
|
||||
|
||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user