From a6346105f16250a1ff9dde4b32b5b20e5236612b Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 19:15:35 +0100 Subject: [PATCH 01/60] docs(docs): V1-1 contract approved, technical design for review Owner ratified the V1-1 business decisions. The contract now records them as approved, adds the nomenclature, the proposed SQL schema, RLS, RPCs, technical limits, journeys and test plan, and lists the choices left for the owner. OPEN_QUESTIONS, plan, DOMAIN_MAP, README and CLAUDE.md follow. --- CLAUDE.md | 3 +- README.md | 12 +- docs/development/DOMAIN_MAP.md | 3 +- docs/development/IMPLEMENTATION_PLAN.md | 23 +- docs/development/OPEN_QUESTIONS.md | 10 +- docs/development/TEST_STRATEGY.md | 4 +- docs/development/V1-1_OWNERS_ANIMALS.md | 1387 +++++++++++++++++------ 7 files changed, 1061 insertions(+), 381 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4c137f25..d737e62b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,7 +49,8 @@ MVP species: equine only. 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; SQL/RLS/RPC design awaiting owner validation on +`feature/v1-1-clients-animals`; nothing built). --- diff --git a/README.md b/README.md index edd3c01c..b82a902b 100644 --- a/README.md +++ b/README.md @@ -39,12 +39,12 @@ Q2): Planned, not implemented (roadmap in `docs/development/IMPLEMENTATION_PLAN.md` §0): V1-1 clients and animals (its -contract awaits the owner's ratification), V1-2 sheets served from Supabase, -V1-3 bilans stored in the cloud with history, V1-4 stored PDFs and authorised -sharing, V1-5 mobile and accessibility pass; then professional verification, -cabinets, entitlements, agenda, public site and the rest of the plan. Nothing -on `develop` authorises a release: the release readiness track (TODO RR-1 to -RR-10) comes first. +business decisions ratified, technical design awaiting validation), V1-2 +sheets served from Supabase, V1-3 bilans stored in the cloud with history, +V1-4 stored PDFs and authorised sharing, V1-5 mobile and accessibility pass; +then professional verification, cabinets, entitlements, agenda, public site and +the rest of the plan. Nothing on `develop` authorises a release: the release +readiness track (TODO RR-1 to RR-10) comes first. --- diff --git a/docs/development/DOMAIN_MAP.md b/docs/development/DOMAIN_MAP.md index 63b830cc..52e7028b 100644 --- a/docs/development/DOMAIN_MAP.md +++ b/docs/development/DOMAIN_MAP.md @@ -11,7 +11,8 @@ the code of 2026-10-08: the TypeScript modules they name have since moved into `crates/core` or been deleted (Steps 5 to 8, R2 to R5); `CLAUDE.md` holds the current map. Clients and Animals (§4, §5) are being reframed by the V1-1 contract (`V1-1_OWNERS_ANIMALS.md`): workspaces, no global client record, -client-animal links with roles; owner orientations awaiting ratification. +client-animal links with roles; business decisions ratified by the owner on +2026-10-25 (BDR-073); where this map differs, the contract governs V1-1. Conventions used below: diff --git a/docs/development/IMPLEMENTATION_PLAN.md b/docs/development/IMPLEMENTATION_PLAN.md index f212f60e..32c24c64 100644 --- a/docs/development/IMPLEMENTATION_PLAN.md +++ b/docs/development/IMPLEMENTATION_PLAN.md @@ -314,6 +314,13 @@ Definition of Done: architecture Sprint 2 minus seats billing. Risks: context leakage into later queries (every report/client query must take the context explicitly; enforce by a service-layer signature, not a global). ``` +Step 10 note (2026-10-25): with C4 ratified (BDR-073), cabinets are built as +workspaces of kind `cabinet` on the `workspaces` / `workspace_members` tables +that V1-1 creates, not as separate `organizations` / `organization_members` +tables; cabinet roles extend `workspace_member_role` and plug into the V1-1 +workspace helpers (`V1-1_OWNERS_ANIMALS.md` §3, §4, §9.1). The rest of the +step (member management, context switcher, seats) is unchanged. + ```text Step 11 Name: Entitlement engine skeleton (no Stripe) @@ -342,13 +349,15 @@ Definition of Done: architecture Sprint 3; rule 1 (animal ≠ sheet) visible in Risks: the global-client design (C4) if confirmed as plain shared rows; GDPR consent texts not final (version column from day one). ``` -Step 12 note (2026-10-25): roadmap item V1-1 proposes a reduced Step 12 under -the owner's orientation C4 (records attached to a workspace, one personal -workspace per practitioner, cabinets later, no global client record shared -between practitioners), without consents, grants, sharing, files or candidate -matching: `V1-1_OWNERS_ANIMALS.md`. The text above stands until the owner -ratifies the contract's orientations (§9.1) and answers its sub-choices -(§9.2). +Step 12 note (2026-10-25): roadmap item V1-1 is a reduced Step 12 under C4, +ratified by the owner on 2026-10-25 (BDR-073): records attached to a +workspace, one personal workspace per practitioner, cabinets later, no global +client record shared between practitioners, no consents, grants, sharing, +files or candidate matching. Contract and technical design: +`V1-1_OWNERS_ANIMALS.md` (business decisions approved; the SQL, RLS and RPC +design awaits the owner's validation before the first migration). Where the +text above differs (global clients, consents, grants, photo, files, deceased +flow), the contract governs V1-1. ```text Step 13 (∥ Steps 9–12) diff --git a/docs/development/OPEN_QUESTIONS.md b/docs/development/OPEN_QUESTIONS.md index b147c7e8..90004d6a 100644 --- a/docs/development/OPEN_QUESTIONS.md +++ b/docs/development/OPEN_QUESTIONS.md @@ -6,7 +6,7 @@ ambiguities or technically risky points found when confronting questions for the developer that change architecture or development order. Items that are merely interesting are left out. -## Status (revised 2026-10-25, P0) +## Status (revised 2026-10-25, P0 and V1-1 ratification) The analysis below is the 2026-10-08 text, kept as written; this table says what has been settled since and by which record (BDR = `.claude/memory/decisions.md`, @@ -19,9 +19,9 @@ Step 5). | C1 vertebral formula | settled | ordered `vertebral_config.regions`, free codes (BDR-031) | | C2 report-only points | open | `localAnnotations` reserved empty in Report v3 (BDR-038); promotion semantics undecided (Q6a); defining it later is a report version bump | | C3 worker on day one | settled | Rust worker built at Step 8 / R1 (BDR-044, BDR-048) | -| C4 global client record | owner orientation, awaiting ratification | records belong to a workspace (one personal workspace per practitioner in V1-1, cabinets later); no global directory shared between practitioners (owner, 2026-10-25); contract `V1-1_OWNERS_ANIMALS.md` §3, D2 | -| C5 animal update rights | owner orientation, awaiting ratification | writes reserved to workspace members with a write right, in V1-1 the practitioner in their personal workspace; no retroactive silent change of a finished bilan (owner, 2026-10-25); V1-1 contract §5.1, §5.3 | -| C6 unverified accounts | owner orientation, awaiting ratification | email confirmation ≠ professional verification; private use for confirmed-email accounts, verification (Step 9) required for public features presenting a verified professional; statuses are not platform roles (BDR-026) (owner, 2026-10-25); V1-1 contract §5.2. Replaces the 2026-10-08 assumption below (no clients or reports before verification) once ratified | +| C4 global client record | settled (owner ratification 2026-10-25, BDR-073) | records belong to a workspace (`workspaces`, `workspace_members`; one personal workspace per practitioner in V1-1, cabinet workspaces later without destructive transfer); no global directory shared between practitioners, no data visible between them; contract `V1-1_OWNERS_ANIMALS.md` §4, D2 | +| C5 animal update rights | settled (owner ratification 2026-10-25, BDR-073) | writes reserved to workspace members with a write right, in V1-1 the practitioner in their personal workspace; no retroactive silent change of a finished bilan; V1-1 contract §6.1, §6.4 | +| C6 unverified accounts | settled (owner ratification 2026-10-25, BDR-073) | email confirmed, professional status verified and platform role are three distinct notions; a confirmed email gives private use of the workspace; verification (Step 9) required later for public features presenting a verified professional; no verified status by default; statuses are not platform roles (BDR-026); V1-1 contract §6.2. Replaces the 2026-10-08 assumption below (no clients or reports before verification) | | C7 « Observation » vocabulary | settled | finding category kind `observation` renamed `consultation_reason` (BDR-033 point 5); *Observation* stays the report block | | C8 drafts per sheet | settled | one draft per sheet, partial unique index (BDR-032) | | C9 detail view asset | settled | nullable `svg_asset_id`, crop by `view_box`; the equine head is a crop of one cleaned drawing (BDR-031, BDR-036, BDR-037) | @@ -35,7 +35,7 @@ Step 5). | Q3 non-mammal layouts | settled | free region codes (BDR-031) | | Q4 external use of the pathology editor | moot | the tool was deleted at Step 5 (BDR-038); content changes go through `curation/changes.json` until the Step 17 editor (owner confirmed 2026-10-25) | | Q5 one or two equine assets | settled | one cleaned drawing, head as crop (BDR-036, BDR-037) | -| Q6 manual points, shared client records | open (a); (b) reframed by C4 | (a) as C2; (b) no shared record if C4 is confirmed, so the edit-rights question moves inside a data space (V1-1 contract §5) | +| Q6 manual points, shared client records | open (a); (b) settled by C4 | (a) as C2; (b) no shared record (C4 ratified), so edit rights live inside a workspace (V1-1 contract §6) | | Q7 phone and email providers | open | Step 7 shipped email only; needed before production SMTP and phone verification | | Q8 public site framework | settled | Astro (D-R8, validated with BDR-045), Rust exception recorded | | Q9 catalog anomalies | settled, against the 2026-10-08 recommendation | no medical correction at import, anomalies reported, degraded slugs normalised (BDR-034); later corrections through curation changes (BDR-036, BDR-037) | diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md index 087d7cc9..2097c86e 100644 --- a/docs/development/TEST_STRATEGY.md +++ b/docs/development/TEST_STRATEGY.md @@ -9,8 +9,8 @@ Docker sandbox; 11 pgTAP files under the flat `supabase/tests/`. The locations `apps/app/tests/components`, `apps/app/tests/integration`, `apps/app/e2e`, `supabase/tests/{db,rls}` and `supabase/seed/test/` in §1 and §3 are planned, not created; the real-stack e2e lives in `packages/supabase/tests/e2e`. No -real-browser suite exists yet (TODO RR-8; V1-1 contract §8.4 proposes the -first one). No CI has ever run (BDR-047): "CI" in the tables means the +real-browser suite exists yet (TODO RR-8; V1-1 contract §12.5 proposes the +first one, decision D14). No CI has ever run (BDR-047): "CI" in the tables means the prepared workflow. ## 1. Layers diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index 817d7d0f..c5a9db44 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -1,35 +1,38 @@ -# V1-1 Clients and animals: functional contract +# V1-1 Clients and animals: contract -Status: proposal, 2026-10-25, revised the same day with the owner's -orientations (brief « P0 : arbitrages documentaires et finalisation du contrat -V1-1 »). Nothing is implemented and nothing is authorised: no migration, -table, RPC, RLS policy, component or route exists or may be created for this -step until the owner ratifies the orientations of §9.1 and answers §9.2. The -orientations are recorded as proposed, not ratified. Roadmap position: -`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also -lays the permission frame of Step 10. The file name keeps "OWNERS" so the -documents that cite it keep working. +Status: business decisions approved by the owner on 2026-10-25 (brief « V1-1 : +ratification des décisions métier et préparation de l'implémentation », +BDR-073). The technical design of Parts 8 to 10 and the choices of §13.2 and +§13.3 are proposals awaiting the owner's validation at the V1-1 preparation +checkpoint. Until that validation nothing is implemented: no migration, table, +RPC, policy, component, route or dependency, and Supabase DEV is untouched. +Branch: `feature/v1-1-clients-animals`. Roadmap position: +`IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays +the permission frame of Step 10. The file name keeps "OWNERS" so the documents +that cite it keep working. -Part 1 states the facts. Parts 2 to 7 are the proposed contract. Part 8 lists -the tests and the Definition of Done. Part 9 lists the orientations, the -sub-choices they leave, and the decisions still open. +Parts: 1 facts, 2 scope, 3 nomenclature, 4 workspaces, 5 entities, +6 permissions, 7 archive, deletion and data protection, 8 SQL schema, +9 policies, helpers and RPCs, 10 technical limits, 11 screens and journeys, +12 tests and Definition of Done, 13 decisions, 14 implementation steps and +risks. --- ## 1. Facts the contract rests on -| Area | State on `develop` (0c54e4b) | +| Area | State on `develop` (5502617) | |---|---| | Client and animal data | Text inside a bilan only: report v3 `owner = { name }`, `animal = { speciesId, name, breed?, age? }` (`crates/core/src/domain/report/identity.rs`). No table. | -| Species | `public.species` (`id` slug, `name_fr`, `name_en`, `sort_order`, `active`), one row `equine` / Cheval / Horse; SELECT for `authenticated` on active rows; no API write path. | -| Anatomical sheets | Only the equine DRAFT exists, unpublished until business review (BDR-034, BDR-037). Its content changes only through `curation/changes.json` and the Rust pipeline until plan Step 17 (owner, 2026-10-25). | -| Accounts | Email/password sign-up, `enable_confirmations = true` (no session before the email is confirmed), `profiles.active` switched by staff only, `private.require_actor()` refuses a missing or deactivated actor. | +| Species | `public.species` (`id` slug, `name_fr`, `name_en`, `sort_order`, `active`), one row `equine` / Cheval / Horse; SELECT for `authenticated` on active rows; no API write path. The application never reads this table (the editor uses the bundled sheet). | +| Anatomical sheets | Only the equine DRAFT exists, unpublished until business review (BDR-034, BDR-037). Its content changes only through `curation/changes.json` and the Rust pipeline until plan Step 17. | +| Accounts | Email/password sign-up, `enable_confirmations = true` (no session before the email is confirmed, `auth.users.email_confirmed_at`), anonymous sign-in disabled, `profiles.active` switched by staff only, `private.require_actor()` refuses a missing or deactivated actor. | | Roles | `platform_role` = owner, admin, moderator, support (BDR-026). No professional status and no cabinet table exist. | -| Audit | `audit.audit_logs` append-only, written by `private.log_event()`, action format `domain.verb`. | -| Files | `client-files` and `animal-files` buckets exist, closed (row only, no policy). | +| Audit | `audit.audit_logs` append-only, written by `private.log_event()`, action format `domain.verb`; platform owners and admins read every row (`audit_logs_select_admin`). | +| Files | `client-files` and `animal-files` buckets exist, closed (row only, no policy). `assets.owner_id` is the account that owns a file (Step 8). | | UI | `/app` shell (sidebar, drawer, top bar), `Dashboard`, `Account`. The validated mockup (`docs/design/`) shows Clients and Animaux sidebar entries and a mobile tab bar Accueil / Bilans / Agenda / Profil. The shared `Dialog` has no focus trap or focus restore (RR-7). | -| Form validation | D-R7: form constraints stay TypeScript (Zod schemas returning i18n keys); a constants module is checked against `pg_constraint` by a PGlite test. The SQL CHECK is the server boundary. The 2026-10-25 inventory put V1-1 validation in `crates/core`: that contradicted D-R7 and is withdrawn here (EVAL-034). | -| Tests | pgTAP on PGlite and on the real stack; real-stack e2e pattern in `packages/supabase/tests/e2e`; no real-browser test runner in the repository (RR-8). | +| Form validation | D-R7: form constraints stay TypeScript (Zod schemas returning i18n keys); the SQL CHECK is the server boundary; a constants module checked against `pg_constraint` by a PGlite test is planned (TODO chore D-R7), none exists yet. | +| Tests | pgTAP on PGlite (0.3.16, which ships `unaccent` and `pg_trgm` as contrib; the harness loads only pgTAP today) and on the real stack; real-stack e2e pattern in `packages/supabase/tests/e2e`; no real-browser test runner (RR-8). | --- @@ -37,460 +40,1126 @@ sub-choices they leave, and the decisions still open. In V1-1, a signed-in practitioner with a confirmed email: -1. creates, edits, lists, searches, archives and restores clients, persons - and organisations; -2. creates, edits, lists, searches, archives and restores animals, each - linked to zero, one or several clients with a role per link; -3. sees a client's animals and an animal's clients, current and former; +1. creates, edits, lists, searches, archives and restores clients, persons and + structures; +2. creates, edits, lists, searches, archives and restores animals, each linked + to zero, one or several clients with a role per link; +3. sees a client's animals and an animal's clients, current and former, and + records a change of owner or keeper without losing the history; 4. does all of it on a phone (375 px wide) and on a computer, in French and English, with the keyboard alone and with a screen reader. -Out of scope, each named so nobody builds it early: cabinet creation and -membership management, sharing between practitioners, client portal and -client accounts, any directory or matching across practitioners, consent -records, photos, weight and files, imports (CSV, PDF), notifications, any -link with bilans (V1-3), account closure, deletion, anonymisation and export -(D9), quotas and billing, the professional verification process (plan Step -9), any staff access to the records (D16), any editing of the anatomical -reference. The local tool and the bilan format do not change; annotating a -bilan never changes `curation/changes.json`. +Out of scope, each named so nobody builds it early: cabinet creation, +membership management and invitations, sharing between practitioners, client +portal and client accounts, any directory or matching across practitioners, +consent records, animal weight, photo, detailed identification, coat colour, +neutering status, date of death and notes (D6, deferred), client notes +(§13.2 N3), files, imports (CSV, PDF), notifications, any link with bilans +(V1-3), account closure, deletion, anonymisation and export (D9), quotas and +billing, the professional verification process (plan Step 9), any staff +access to the records (D16), any editing of the anatomical reference. The local +tool and the bilan format do not change; annotating a bilan never changes +`curation/changes.json`. --- -## 3. Workspaces and the future cabinets (D2, C4) +## 3. Nomenclature -Orientation D2 / C4: records belong to a workspace. In V1-1 each practitioner -has one personal workspace. There is no global directory of clients shared -between practitioners. Multi-practitioner cabinets come later and are not -built in V1-1. +Owner requirement: one explicit name per concept, the same in SQL, in the +generated TypeScript types and in the documents. The generated types carry the +SQL names unchanged; TypeScript variables follow them (`relationRole`, +`memberRole`, `platformRole`, never a bare `role` or `owner`). -| Table | V1-1 content | Later | +| Concept | SQL | UI (FR / EN) | |---|---|---| -| `workspaces` | `id`, `kind` (`personal` only), `created_at`; one personal workspace per profile, created with the profile (trigger + backfill of existing profiles) | `kind = cabinet`, name, logo: the plan's Step 10 builds cabinets as workspaces instead of a separate `organizations` table | -| `workspace_members` | `workspace_id`, `user_id`, `role` (`owner` only) | roles `manager`, `practitioner`, `secretary` added with the cabinet step | +| Perimeter that owns and isolates records | table `workspaces`; column `workspace_id` on every record table | not shown in V1-1 | +| Kind of workspace | `workspaces.kind`, enum `workspace_kind`: `personal` (`cabinet` added by the cabinet step) | espace personnel / personal workspace | +| Account whose personal workspace it is | `workspaces.personal_user_id` (unique, null for a future cabinet) | not shown | +| Membership and rights of a member | table `workspace_members` (`workspace_id`, `user_id`, `member_role`), enum `workspace_member_role`: `holder` in V1-1 | titulaire / holder | +| Responsible of a workspace | personal workspace: the account of `personal_user_id`, its only member, with `member_role = holder`; cabinet: defined by the cabinet step (Step 10) | not shown | +| Technical platform role | enum `platform_role` (`owner`, `admin`, `moderator`, `support`), table `profile_roles` (existing, BDR-026) | not shown | +| Client | table `clients`, `client_id`; enum `client_kind`: `person`, `organization` | client: personne, structure / client: person, organization | +| Animal | table `animals`, `animal_id`; enum `animal_sex`: `male`, `female`, `unknown` | animal: mâle, femelle, inconnu / animal: male, female, unknown | +| Relation between a client and an animal | table `animal_client_relations`; column `relation_role`, enum `animal_relation_role`: `owner`, `keeper`, `contact` | propriétaire, détenteur, contact / owner, keeper, contact | +| File owner (existing, Step 8) | `assets.owner_id` | not reused by V1-1 | -One helper answers every access question: the caller's role in a workspace, -null when the caller is not a member or the profile is inactive. Policies and -RPCs never test `user_id = auth.uid()` on the record itself, so the cabinet step -adds members, not new policies on every table. +Rules: -Why not a plain `owner_user_id` column: it is simpler today, but every policy -and helper of clients, animals and later bilans would need a second branch for -cabinets, and moving a practitioner's records into a cabinet would rewrite -ownership columns. The workspace costs two small tables now. - -Record placement is explicit: the browser sends the target workspace on -create and the server checks the caller's role in it. In V1-1 the app always -sends the personal workspace. +- `owner` exists as `platform_role.owner` (the Faunosteo platform owner) and as + `animal_relation_role.owner` (the owner of an animal). It is never a + workspace member role: the person responsible for a personal workspace is its + `holder`. +- No record table (`clients`, `animals`, `animal_client_relations`) has an + `owner_id`, `user_id` or `created_by` column. Placement is `workspace_id`; + authorship lives in the audit log. +- Future client or animal files are placed by workspace, never by + `assets.owner_id`. +- The schema↔types test pins every name of this table. --- -## 4. Entities and fields +## 4. Workspaces (D2 / C4, approved) -Vocabulary (orientation D1): the interface says « Clients » (English -"Clients") and the code entity is `clients`. A client is the person or the -structure the practitioner deals with. Its relation to an animal carries a -role: `owner` (Propriétaire), `keeper` (Détenteur, for example the stable that -boards the horse) or `contact` (Contact). The entity and the role are never -merged: the same client can own one horse and keep another. +Clients and animals belong to a workspace. In V1-1 each account has exactly one +personal workspace, created automatically. There is no global directory of +clients shared between practitioners, no data visible from one practitioner to +another, and no sharing between practitioners of a cabinet. Invitations and +cabinet permissions are not built. -### 4.1 Client +- Creation: a trigger after insert on `profiles` creates the personal workspace + and its `holder` membership; the migration backfills existing profiles. +- Uniqueness: `personal_user_id` is unique, so an account never has two + personal workspaces. +- Context: every read and write names its workspace (RPC parameter or filter). + The app reads its personal workspace once after sign-in and passes its id + explicitly to the access layer; nothing reads a global "current workspace" + (plan Step 10 risk: context leakage). +- Policies and RPCs never compare `auth.uid()` with a column of the record: + they ask the workspace helpers (§9.1). The cabinet step adds members and + roles, not new policies on every table. +- Evolution without destructive transfer: a cabinet is a workspace of kind + `cabinet`. Either a practitioner's workspace gains members and changes kind + (no record moves), or a later step moves the records of one workspace to + another in one transaction (the composite keys of §8 can then be made + deferrable with `ALTER CONSTRAINT`). Records never belong to a user column, + so neither path rewrites ownership. The first path leaves the practitioner + without a personal workspace (`personal_user_id` is null on a cabinet), so + it must also create a new one for them; the cabinet step chooses. + +Why not an `owner_user_id` column: every policy of clients, animals and later +bilans would need a second branch for cabinets, and attaching a practitioner's +records to a cabinet would rewrite ownership columns. The workspace costs two +small tables now. + +--- + +## 5. Entities and fields + +Text rule for every text column: no leading or trailing space, no control +character, never an empty string (an absent value is `null`). The control set +is written as explicit ranges, the same literal in SQL and in TypeScript +(U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029), because `[[:cntrl:]]` +differs between the C libraries of PGlite and of the real stack. SQL checks +U+0020 at both ends (`btrim`); the form trims all Unicode whitespace before +sending, which only ever sends values SQL accepts. Lengths count characters +as PostgreSQL's `char_length` does (code points); §12.2 states how TypeScript +counts the same. Email pattern, shared by SQL and TypeScript: +`^[^@\s]+@[^@\s]+\.[^@\s]+$` on the lower-cased value. Country codes come from +a committed ISO 3166-1 alpha-2 list; their FR and EN labels from +`Intl.DisplayNames` (no dependency). + +### 5.1 Client (D3, D4, D4a, approved) | Field | Rule | Required | |---|---|---| -| `kind` | `person` (personne physique) or `organisation` (structure: écurie, haras, association, entreprise or another legal entity); defaults to `person` | column always set, nothing to type (D3) | -| `display_name` | person: the name as the practitioner writes it (« Marie Dupont »); organisation: its name (« Écurie du Lac »); 1 to 120 characters | yes, the only required input (D4) | -| `email` | practical address format, at most 254 characters, stored lower-case | no | -| `phone` | E.164 like `profiles.phone`; French national input (`06 12 34 56 78`) normalised to `+33…` on submit | no | -| `address_line1`, `address_line2`, `postal_code`, `city` | at most 120 / 120 / 16 / 80 characters, no postal format check (Belgium, Switzerland) | no | -| `country` | ISO 3166-1 alpha-2; no SQL default, the form proposes France | no | -| `notes` | private to the workspace, at most 4 000 characters | no | -| `archived_at`, `archived_by` | set by the archive RPC only | n/a | +| `kind` | `person` (personne physique) or `organization` (structure: écurie, haras, association, entreprise, other legal entity); the form shows both with « Personne » visibly selected | yes | +| `display_name` | person: the name as the practitioner writes it (« Marie Dupont », « Mme Dupont »); organization: its name (« Écurie du Lac »); the label follows the kind: « Nom affiché » or « Dénomination »; 1 to 120 characters | yes, the only required text | +| `email` | practical format, at most 254 characters, stored lower-case, not unique | no | +| `phone` | E.164 like `profiles.phone`; entry rule §11.3 | no | +| `address_line1`, `address_line2` | at most 120 characters each | no | +| `postal_code` | at most 16 characters, no format check (Belgium, Switzerland) | no | +| `city` | at most 80 characters | no | +| `country` | ISO 3166-1 alpha-2, upper-case; no default in SQL or in the form: empty until the practitioner picks one | no | +| `revision`, `archived_at`, `created_at`, `updated_at` | server-maintained | n/a | -Every text field is trimmed, refuses control characters and is never empty -when present. No uniqueness on email or phone: two clients may share a -household address or phone. Contact details are optional at creation (D4): -what a booking, an invoice or a regulated document requires is set by the -step that introduces it, never by a NOT NULL here. +No uniqueness on email or phone: two clients may share a household address or +phone. Contact details are optional at creation; what a booking, an invoice or +a regulated document requires is set by the step that introduces it, never by +a NOT NULL here. Changed from the proposal: `notes` is not in V1-1 (§13.2 N3) +and `archived_by` is dropped (the audit log records who archived; a cabinet +step adds the column if a screen shows it). -### 4.2 Animal +Name rule (D4a): `display_name` is the single reference for display, search, +sorting and documents. V1-1 stores no separate first and last name +(recommendation §13.2 N2). If a later step adds optional `given_name` and +`family_name` for persons, the rule is priority, not synchronisation: +`display_name` stays required and wins wherever a name is shown; the parts are +optional complements read only where a step requires them (a formal invoice +heading, a sort by family name); an organization never carries them (CHECK); +the server never derives one representation from the other; the form proposes +`display_name` from the parts only while `display_name` is empty and never +rewrites it afterwards. + +### 5.2 Animal (D5, D6, D6a, D6b, approved) | Field | Rule | Required | |---|---|---| -| `species_id` | an active row of `species` (§4.4) | yes (D5) | -| `species_detail` | free text, 1 to 80 characters, required with `other` and refused with any other species | if `other` (D5) | -| `name` | 1 to 80 characters | yes (D6) | -| `sex` | `male`, `female`, `unknown`; defaults to `unknown` | column always set, nothing to type (D6) | -| `breed` | free text, at most 80 characters (no breed list in V1-1) | no | -| `birth_year` | four-digit year, not in the future | no | -| `birth_date` | the full date, only when it is known; not in the future; when present, `birth_year` equals its year (CHECK) | no | -| `neutered` | `yes`, `no`, `unknown`; together with `sex` it gives stallion, gelding, mare in the equine UI | no, proposal (D6a) | -| `identification` | microchip, UELN, tattoo: at most 64 characters, letters, digits, spaces and hyphens, stored upper-case; no per-species format check | no, proposal (D6a) | -| `colour` | at most 80 characters | no, proposal (D6a) | -| `notes` | private to the workspace, at most 4 000 characters | no, proposal (D6a) | -| `deceased_on` | date not in the future; a deceased animal stays readable and is never archived implicitly | no, proposal (D6a) | -| `archived_at`, `archived_by` | archive RPC only | n/a | +| `name` | 1 to 80 characters | yes | +| `species_id` | an active row of `species` (§5.4) | yes | +| `species_detail` | 1 to 80 characters; required when `species_id = 'other'`, refused with any other species | with « Autre » | +| `sex` | `male`, `female` or `unknown`; no default: the practitioner picks one, « Inconnu » included (§13.2 N8) | yes | +| `breed` | free text, at most 80 characters (no breed list) | no | +| `birth_year` | 1900 to the year of tomorrow's UTC date (same tolerance as the dates, §9.3) | no | +| `birth_date` | the full date, only when known; not in the future; requires `birth_year` equal to its year | no | +| `revision`, `archived_at`, `created_at`, `updated_at` | server-maintained | n/a | -A year alone never becomes a date: an animal born « in 2015 » has -`birth_year = 2015` and no `birth_date`, never a stored 1 January (D6, D6b). -Deferred to a later step (D6): weight (it belongs to a visit, not to the -animal) and photo (it needs the `animal-files` rules and a worker job). The -fields marked « proposal » go beyond the owner's list of 2026-10-25; the -owner keeps or drops each before the migration (D6a). +Birth representation (D6b): each state has one meaning, and a year never +becomes a date. -### 4.3 Client and animal relation +| `birth_year` | `birth_date` | Meaning | +|---|---|---| +| null | null | birth unknown | +| 2015 | null | born in 2015, day unknown | +| 2015 | 2015-04-12 | born on 12 April 2015 | +| null | 2015-04-12 | refused (CHECK) | +| 2016 | 2015-04-12 | refused (CHECK) | -Table `animal_clients` (orientation D7): `animal_id`, `client_id`, `role` -(`owner`, `keeper`, `contact`), `created_at`, `ended_at`. Rules: +The year of a full date is stored again in `birth_year`, so sorting and +filtering by year read one column. The age shown is computed for display only: +from the date when present, else « environ N ans » from the year. -- many-to-many: an animal links to several clients and a client to several - animals, each link with its role; co-ownership is several `owner` links, - and owner and keeper are distinct links; -- client and animal belong to the same workspace (composite foreign keys on - `(workspace_id, id)`); -- one current row per (animal, client, role) (partial unique index on rows - with no `ended_at`); -- no owner is required: an animal may have no current `owner` link, because - the owner is unknown or not entered yet. No SQL constraint and no RPC - refuses it, and the app never creates a placeholder client; it shows - « Propriétaire non renseigné ». Whether a business operation (bilan, - invoice, sharing) later requires an owner is decided by the step that - introduces the operation; -- ending a relation (horse sold, keeper changed) sets `ended_at`; the row - stays as history and the former owner or keeper is shown as such (D7a, - historical relations kept under D8). +Deferred to a later step (D6), each one an additive nullable column when its +step needs it: weight (it belongs to a visit), photo (it needs the +`animal-files` rules and a worker job), detailed identification (microchip, +UELN, tattoo), coat colour, neutering status, date of death, general notes. No +complete veterinary record is created. -### 4.4 Species +### 5.3 Client and animal relation (D7, D7a, approved) -The species list is reference data written by migration (orientation D5): -the nine species of this contract's first version, horse (the existing row -`equine`), donkey, dog, cat, cattle, goat, sheep, pig and rabbit, plus -« Autre » (`other`) with its required `species_detail`. No other species is -added. The slugs of the new rows follow the format of the `equine` row and are -fixed with the migration. +Table `animal_client_relations`: -A species carries no anatomical sheet by itself: an animal of any listed -species can be recorded while no usable sheet exists for it (today only the -equine draft exists), and nothing links a species to a sheet automatically. -V1-1 shows no sheet information; V1-3 decides what a bilan does for an animal -whose species has no sheet. +| Field | Rule | +|---|---| +| `animal_id`, `client_id` | same workspace, enforced by composite foreign keys | +| `relation_role` | `owner`, `keeper` or `contact` | +| `started_on` | date the relation began, when known; null when unknown | +| `ended_at` | null while the relation is current; set when the end is recorded (§13.2 N5) | +| `ended_on` | date the relation ended, when known; only on an ended relation; not before `started_on` | +| `revision`, `created_at`, `updated_at` | server-maintained | + +Rules: + +- many-to-many, one role per relation: co-ownership is several current `owner` + relations; owner and keeper are separate relations; the same client may hold + two roles for one animal (an owner who keeps the horse at home); +- an animal may have no owner because the owner is unknown or not entered yet; + no SQL constraint and no RPC refuses it, the app never creates a placeholder + client and shows « Propriétaire non renseigné »; whether a later business + operation (bilan, invoice, sharing) needs an owner is decided by the step + that introduces it; +- an animal always belongs to one valid workspace, with or without relations; +- client and animal of a relation are always in the same workspace: the + composite foreign keys make any other row impossible, whatever writes it; +- at most one current relation per (animal, client, role): a partial unique + index on rows with no `ended_at`; successive relations of the same triple are + allowed once the previous one has ended; +- historical periods may overlap (dates are optional and approximate): no + constraint on overlaps; +- `animal_id`, `client_id` and `relation_role` never change after creation; + dates can be corrected; +- change of owner or keeper: add the relation of the new client, then end the + previous one with its end date when known. Both rows stay; the former owner + keeps their other animals and appears as « ancien propriétaire » on the + animal's page. Between the two actions the animal has two current owners or + none, two valid states, so no atomic transfer operation is needed; +- ending is not deleting: an ended relation stays readable. Removing a + relation entered by mistake is §13.2 N4; a relation ended by mistake is + corrected the same way: removed, then created again as current. + +### 5.4 Species (D5, approved) + +Reference data written by migration: the nine species of the contract (the +existing `equine` row plus eight) and « Autre ». No other species is added. +Slugs, names and order are proposal §13.2 N1: + +| `id` | `name_fr` | `name_en` | `sort_order` | +|---|---|---|---| +| `equine` (existing) | Cheval | Horse | 10 | +| `asinine` | Âne | Donkey | 20 | +| `canine` | Chien | Dog | 30 | +| `feline` | Chat | Cat | 40 | +| `bovine` | Bovin | Cattle | 50 | +| `caprine` | Chèvre | Goat | 60 | +| `ovine` | Mouton | Sheep | 70 | +| `porcine` | Porc | Pig | 80 | +| `leporine` | Lapin | Rabbit | 90 | +| `other` | Autre | Other | 1000 | + +A recordable species does not mean an anatomical sheet exists. Only the equine +content exists, as an unpublished draft, and nothing in V1-1 publishes it or +links a species to a sheet. V1-1 shows no sheet information; V1-3 decides what +a bilan does for an animal whose species has no sheet. The migration updates +the table comment (« species of animals and of anatomical sheets »). A sheet +for `other` makes no sense; the sheet RPCs are platform-admin only and V1-2 +adds the refusal if it opens sheet creation. --- -## 5. Permissions +## 6. Permissions -### 5.1 Matrix +### 6.1 Matrix (C5, D16, approved) | Actor | Read | Create | Edit | Archive / restore | Delete | |---|---|---|---|---|---| -| Workspace member with role `owner` (V1-1: the practitioner in their personal workspace) | yes | yes | yes, active records only | yes | no (§6) | -| Future cabinet roles `manager`, `practitioner`, `secretary` | per the cabinet step | per the cabinet step | per the cabinet step | per the cabinet step | no | +| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no, except a relation entered by mistake if §13.2 N4 is approved | +| Future cabinet roles | defined by the cabinet step | | | | | +| The same account with an unconfirmed email | no | no | no | no | no | | Another signed-in account | no | no | no | no | no | | Platform owner, admin, moderator, support | no | no | no | no | no | | Deactivated profile | no | no | no | no | no | | Anonymous | no | no | no | no | no | +| Service key (`service_role`: worker, operator scripts) | no table privilege (§13.2 N7) | no | no | no | no | -Orientation C5: writes belong to the members who hold a write right in the -workspace concerned. In V1-1 that is only the practitioner who owns the -personal workspace. Future cabinets may add permissions (business -architecture §2.2: a secretary manages customers and animals); the helper's -shape allows them, and they are built with the cabinet step. +C5: writes belong to the members who hold a write right in the workspace +concerned; in V1-1 that is only the holder of the personal workspace. Future +cabinet roles (business architecture §2.2: a secretary manages customers and +animals) plug into the helpers of §9.1 and are built with the cabinet step. -Orientation D16: Faunosteo staff have no ordinary business access to private -records. No platform role (owner, admin, moderator, support) reads or writes -clients, animals or bilans through a policy or an RPC, and no admin screen -lists or opens them. That rule is distinct from exceptional privileged -technical operations (database maintenance, backup restore, incident response -through the service key or a database superuser): those exist by construction -of the hosting, and before any publication a separate contract frames, -justifies and audits them. V1-1 creates no exceptional access mechanism (no -impersonation, no break-glass RPC), and no worker job reads these tables. +### 6.2 Email, verification and platform roles (C6, approved) -### 5.2 Verification (C6) +| Notion | Where it lives | Effect in V1-1 | +|---|---|---| +| Email confirmed | `auth.users.email_confirmed_at`, set by GoTrue | required for every V1-1 read and write. GoTrue gives no session before confirmation, and the workspace helpers check the column again in SQL. Limit: with `enable_confirmations` off, GoTrue stamps the column at sign-up, so the SQL check proves only that GoTrue considers the address confirmed; a config test pins `enable_confirmations = true`. A GoTrue ban (`banned_until`) does not end an issued token before it expires (`jwt_expiry` 3 600 s); `profiles.active = false` cuts access at the next request | +| Professional status verified | plan Step 9, not built; no column exists | none; never granted by default; required later by public features that present an account as a verified practitioner (public profile, community publication, booking) | +| Platform role | `profile_roles`, `platform_role` | none: it grants no access to clients, animals or bilans (D16) | -Orientation C6: email confirmation and professional verification are two -distinct things. An account with a confirmed email has private use of the -application, within the permissions and features available: V1-1 is open to -any active account with a session (GoTrue gives no session before -confirmation). Professional verification (plan Step 9; BDR-041 said Step 11, -corrected by BDR-072) is required for the public features that present a -practitioner as a verified professional (public profile, community -publication, booking); it is not built in V1-1 and does not gate it. Professional statuses (practitioner, student, professor) come from -verification and are never platform roles (BDR-026). +verification and are never platform roles (BDR-026). BDR-041 said Step 11 for +verification; BDR-072 corrects it to Step 9. -### 5.3 Edits and finished bilans (C5) +### 6.3 Platform staff (D16, approved) + +Faunosteo staff have no ordinary right to read clients, animals or bilans. No +policy or RPC has a platform-role branch, no admin screen lists or opens these +records, and V1-1 builds no impersonation, support access or break-glass +mechanism. No worker job reads these tables. + +Residual technical paths, named so nobody believes them closed: + +- the service key gets no table or RPC privilege on V1-1 (§13.2 N7), but it is + also the GoTrue admin key: its holder can generate a magic link or set a + password for any account and then read that workspace as its practitioner, + leaving no trace in the application. The worker and the operator scripts + hold it. The service key and the JWT secret are therefore full-access + credentials, bounded only by their custody; the exceptional-access contract + covers them, with two follow-ups in §14 (a narrower worker credential, + monitoring of GoTrue admin actions in `auth.audit_log_entries`); +- the table owner (`postgres`, not a superuser on Supabase) and any database + superuser read past RLS: maintenance, backup restore and incident response + are exceptional privileged operations that the separate contract frames, + justifies and audits before any publication. + +The existing audit policy lets platform owners and admins read audit rows. The +V1-1 rows carry the actor, resource ids, the action and the workspace id. Read +with the staff policy on profiles, that reveals per-practitioner volumes, +working hours and events such as « relation ended »: activity metadata, never +names or contacts. §13.2 N9 decides whether that stays visible. + +### 6.4 Edits and finished bilans (C5, approved) V1-1 holds no bilan. The rule binds V1-3: a bilan keeps its own identity snapshot (already true of the report v3 format); editing an animal or a client never rewrites a finished bilan, retroactively or silently. Any refresh of a draft bilan from the animal record is an explicit user action. -### 5.4 Server rules +--- -- Reads: SELECT policies on `clients`, `animals`, `animal_clients`, - `workspaces`, `workspace_members` through the workspace helper, explicit - column lists in the app (no `select=*`). -- Writes: security-definer RPCs only (create, update, archive, restore, link, - end a link). No INSERT, UPDATE or DELETE grant on these tables for API roles. - Each RPC calls `private.require_actor()`, checks the role in the target - workspace, answers the same 42501 for an unknown id and a forbidden id, and - writes one `log_event` row with ids and changed field names, never names, - contacts or notes. -- Concurrency: update RPCs take the `updated_at` the form loaded and refuse a - stale write with a closed `conflict` kind, so two tabs never overwrite each - other silently. -- Archived records are read-only until restored. -- Helpers in `private` follow the project rule: security definer, - `set search_path = ''`, EXECUTE revoked from public, granted only where - evaluated; census tests updated. +## 7. Archive, deletion and data protection + +### 7.1 Archive (D8, approved) + +Archiving is a functional state, read-only and reversible. + +- An archived record is hidden from default lists and search, stays readable + from its page and under the « archivés » filter, and refuses every edit + (`archived` failure) until it is restored. Restore is always possible. +- Relations are kept. Archiving a client archives none of its animals; + archiving an animal ends none of its relations. An archived client stays on + its animals' pages, marked archived. +- Relation writes: creating a relation needs both the animal and the client + active; ending a relation, correcting its dates or removing it needs the + animal active (the client may be archived, so the history of an active + animal stays maintainable); the relations of an archived animal are frozen. +- The confirmation before archiving a client lists the active animals for + which it is the only current owner. +- Archiving erases nothing. It is not the deletion or anonymisation of + personal data, and no retention duration is attached to it. + +### 7.2 Account deletion and the data lifecycle (D9, D9a, approved) + +V1-1 implements no account closure, deletion, anonymisation or export, and sets +no retention duration. + +Temporary DEV protection (D9a): the records reference their workspace with +`on delete restrict`, and the personal workspace follows its account. Deleting +an account whose workspace holds at least one client or animal is therefore +refused by the database; an account whose workspace holds nothing is deleted +as today, its workspace with it. In DEV a test account with records is removed +by deleting its records first from a privileged SQL session, or by +`pnpm db:reset`. The protection is not a ban: the lifecycle contract (plan +Step 26) will process the records first (export, erasure or anonymisation, +retention where justified, reassignment inside a cabinet) and the deletion then +passes. It forbids one thing permanently: records disappearing as a side +effect of deleting an account. + +The future lifecycle distinguishes closing an account, deleting or anonymising +data, legally justified retention, records of a workspace shared by a cabinet, +and reassignment of responsibilities in a cabinet. What V1-1 does so that it +stays possible: + +- records belong to a workspace, never to a user column, so a cabinet's records + survive a member leaving and a personal workspace can be exported, anonymised + or erased as one unit; +- authorship is ids in the audit log only, so anonymising a profile rewrites no + record; +- a client's personal data sits in identified columns of one table; the folded + keys and phone digits (§8) derive from the same row and follow any rewrite; no copy goes + into audit rows, logs, error messages or URLs, so erasure or anonymisation is + a bounded update. + +### 7.3 Data protection (principles approved; legal framing before exposure) + +Nothing here is a legal policy. The owner frames the legal basis, the +information texts, the retention durations and the rights procedures with +counsel before any public exposure (§13.4). + +| Category | V1-1 data | Whom it concerns | Stored in | Read by | +|---|---|---|---|---| +| Practitioner's professional data | profile (existing): name, practice name, title, SIRET, email | the practitioner, as a user | `profiles`, `auth.users` | the practitioner; staff per the existing policies | +| Clients' personal data | display name, email, phone, postal address | clients who are natural persons, and in practice structures too (a sole trader, an écurie named after a person, a named contact) | `clients` | members of the workspace only | +| Animal information | name, species, sex, breed, birth | the animal, and through its link the client | `animals` | members of the workspace only | +| Relations | owner, keeper or contact, dates | links a person to animals | `animal_client_relations` | members of the workspace only | +| Technical traces | audit rows (actor, ids, actions), server logs | pseudonymised data, still personal data | `audit.audit_logs`, logs | platform owner and admin for audit rows (§6.3) | + +Design rule: the lifecycle contract treats every client row, organizations +included, every relation and every audit row as personal data, whatever counsel +later concludes about each category. + +Elements to prepare for the information of the persons concerned (GDPR +articles 13 and 14), to be written with counsel (D10): identity of the +controller, purposes, legal basis per purpose, recipients (Faunosteo as host), +retention, rights and how to exercise them, and, under article 14, the source +of the data when the practitioner records a person's details received from +someone else (a keeper giving the owner's phone). + +Hypotheses to submit to counsel, not decisions: the practitioner or the cabinet +is the controller of client and animal records and Faunosteo its processor +(processor terms in the conditions of use); consent is not presumed to be the +legal basis; the care relationship and the practitioner's legal obligations are +the likely bases for identity and contact data; consent would cover optional +purposes only (marketing, sharing with another practitioner), none of which +V1-1 implements; data of a structure without a named person may fall outside +personal data, and animal data may be personal data only through its link to +a client. + +Rights in V1-1: rectification is the edit form. Access, export, erasure, +restriction and portability come with the lifecycle contract. Until the legal +framing exists, DEV holds fictitious data only: no real client is entered in +V1-1 before the framing (recommendation, §14 risks). + +Minimisation: the field list of §5 is closed; no free-text notes in V1-1; the +fields of D6 are deferred. No personal data in URLs (ids are uuids, the search +term travels in a POST body), audit rows, application logs or error messages +(§10.6). --- -## 6. Archive, deletion and privacy +## 8. SQL schema (proposed, not a migration) -### 6.1 Archive (D8) +Three forward-only migrations, one per data step, each with its pgTAP files, +the regenerated `database.types.ts` and the census updates in the same branch +(plan principle 2). Timestamps are set when written. -Archiving is a functional state, read-only and reversible. It hides a record -from default lists and search, keeps it readable from its page and from the -« archived » filter, and refuses edits until the record is restored. Restore -is always possible. Relations are kept: an archived client stays on its -animals' pages, marked archived. Archiving a client never archives its animals; -the confirmation lists the active animals for which it is the only current -owner. +| Migration | Step | Content | +|---|---|---| +| M1 `_workspaces.sql` | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS | +| M2 `_clients.sql` | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS | +| M3 `_animals_relations.sql` | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS | -Archiving erases nothing. It is not the deletion or anonymisation of personal -data (§6.2), and no retention duration is attached to it. +Why the correlation header in M1: `private.log_event` copies that request +header verbatim today (foundation migration), the app never sends it, and +PostgREST exposes every header, so a caller chooses the size of each +append-only audit row. V1-1 raises the audited write rate from 10 to 1 000 an +hour per account, which turns that into a storage risk. The change keeps the +function's signature and callers. -### 6.2 Account deletion and the data lifecycle (D9) +Sketch of the tables. `(c)` abbreviates the text rule of §5: +`c = btrim(c)` and no character of the explicit control ranges. Constraint +names follow the existing `__` form. -V1-1 implements no account closure, deletion, anonymisation or export, and -sets no retention duration. Orientation D9: no rule may block the deletion of -an account for good because it holds data. A later lifecycle contract (plan -Step 26, BDR-033 point 7) will distinguish closing the account, deleting or -anonymising personal data, keeping some data where a justification exists, -the records of a workspace shared by a cabinet, and the legal obligations -that apply. The owner sets the retention durations and the erasure policy; -nothing here presumes them. +```sql +-- M1 +create type public.workspace_kind as enum ('personal'); +create type public.workspace_member_role as enum ('holder'); -What V1-1 does so that contract stays possible: +create table public.workspaces ( + id uuid primary key default gen_random_uuid(), + kind public.workspace_kind not null, + personal_user_id uuid unique references public.profiles (id) on delete cascade, + created_at timestamptz not null default now(), + constraint workspaces_personal_user_iff_personal + check ((kind = 'personal') = (personal_user_id is not null)) +); -- records belong to a workspace, never to a user column, so a cabinet's - records survive a member leaving, and a personal workspace can be exported, - anonymised or erased as one unit; -- authorship columns (`archived_by`, audit rows) hold ids only, never names, - so anonymising a profile rewrites no record; -- a client's personal data sits in the identified columns of one table, with - no copy in audit rows, logs or URLs, so erasure or anonymisation is a - bounded update. +create table public.workspace_members ( + workspace_id uuid not null references public.workspaces (id) on delete cascade, + user_id uuid not null references public.profiles (id) on delete cascade, + member_role public.workspace_member_role not null, + created_at timestamptz not null default now(), + primary key (workspace_id, user_id) +); +create index workspace_members_user_idx on public.workspace_members (user_id); -The one technical choice before the migration is how the database behaves -when an auth user whose personal workspace holds records is deleted in DEV -(D9a, §9.2). +-- M2 +create extension if not exists unaccent with schema extensions; +-- lower + unaccent with an explicit dictionary, declared immutable so a +-- generated column can use it. +-- private.fold_text(p_value text) returns text -### 6.3 Privacy, legal basis, information +create type public.client_kind as enum ('person', 'organization'); -To frame with legal counsel before any public exposure (business -architecture §28); nothing here decides it: +create table public.clients ( + id uuid primary key default gen_random_uuid(), + workspace_id uuid not null references public.workspaces (id) on delete restrict, + kind public.client_kind not null, + display_name text not null, -- 1..120, + email text, -- <= 254, = lower(email), practical format + phone text, -- '^\+[1-9][0-9]{6,14}$' + address_line1 text, -- 1..120, + address_line2 text, -- 1..120, + postal_code text, -- 1..16, + city text, -- 1..80, + country text, -- '^[A-Z]{2}$' + name_key text collate "C" + generated always as (private.fold_text(display_name)) stored, + search_key text generated always as + (private.fold_text(concat_ws(' ', display_name, city, email))) stored, + phone_digits text generated always as (ltrim(phone, '+')) stored, + create_request_id uuid not null, -- idempotency key sent by the form + revision integer not null default 1, + archived_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint clients_workspace_id_unique unique (workspace_id, id), + constraint clients_create_request_unique unique (workspace_id, create_request_id) +); +create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id); -- likely roles: the practitioner or cabinet is the controller of client and - animal records, Faunosteo its processor, which needs processor terms in the - conditions of use; -- the legal basis is not presumed to be consent. The likely basis for client - identity and contact data is the care contract between practitioner and - client and the practitioner's legal obligations (invoicing). Consent would - apply to optional purposes only (marketing, sharing with another - practitioner), none of which V1-1 implements; -- clients must be informed (GDPR articles 13 and 14): the information text, - and whether the app records that it was given, is decision D10. V1-1 shows - nothing to clients; -- retention durations belong to the lifecycle contract (§6.2); -- minimisation: the field list of §4 is closed; the notes fields carry a hint - to record only what the care needs; -- no personal data in URLs (ids are uuids; the search term is never put in the - query string), in audit rows or in application logs; search goes through a - POST RPC so the term stays out of access logs. +-- M3 +create type public.animal_sex as enum ('male', 'female', 'unknown'); + +create table public.animals ( + id uuid primary key default gen_random_uuid(), + workspace_id uuid not null references public.workspaces (id) on delete restrict, + name text not null, -- 1..80, + species_id text not null references public.species (id) on delete restrict, + species_detail text, -- 1..80, + sex public.animal_sex not null, -- no default + breed text, -- 1..80, + birth_year smallint, -- 1900..2100 (CHECK); <= current year (RPC) + birth_date date, -- >= 1900-01-01 (CHECK); not in the future (RPC) + name_key text collate "C" + generated always as (private.fold_text(name)) stored, + search_key text generated always as + (private.fold_text(concat_ws(' ', name, breed, species_detail))) stored, + create_request_id uuid not null, + revision integer not null default 1, + archived_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint animals_workspace_id_unique unique (workspace_id, id), + constraint animals_create_request_unique unique (workspace_id, create_request_id), + constraint animals_species_detail_iff_other + check ((species_id = 'other') = (species_detail is not null)), + constraint animals_birth_date_year + check (birth_date is null + or (birth_year is not null + and birth_year = extract(year from birth_date)::integer)) +); +create index animals_workspace_name_idx on public.animals (workspace_id, name_key, id); + +-- M3 (continued) +create type public.animal_relation_role as enum ('owner', 'keeper', 'contact'); + +create table public.animal_client_relations ( + id uuid primary key default gen_random_uuid(), + workspace_id uuid not null, + animal_id uuid not null, + client_id uuid not null, + relation_role public.animal_relation_role not null, + started_on date, -- >= 1900-01-01 (CHECK); not in the future (RPC) + ended_on date, -- idem + ended_at timestamptz, + create_request_id uuid not null, + revision integer not null default 1, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint animal_client_relations_animal_fk foreign key (workspace_id, animal_id) + references public.animals (workspace_id, id) on delete restrict, + constraint animal_client_relations_client_fk foreign key (workspace_id, client_id) + references public.clients (workspace_id, id) on delete restrict, + constraint animal_client_relations_ended_on_needs_end + check (ended_on is null or ended_at is not null), + constraint animal_client_relations_dates_order + check (started_on is null or ended_on is null or started_on <= ended_on), + constraint animal_client_relations_create_request_unique + unique (workspace_id, create_request_id) +); +create unique index animal_client_relations_current_unique + on public.animal_client_relations (animal_id, client_id, relation_role) + where ended_at is null; +create index animal_client_relations_animal_idx + on public.animal_client_relations (workspace_id, animal_id); +create index animal_client_relations_client_idx + on public.animal_client_relations (workspace_id, client_id); +``` + +Every table with `updated_at` gets the existing `private.set_updated_at()` +trigger. `revision` changes only through the RPCs: every successful +state-changing write (update, archive, restore, end, date correction) adds one; +a call that changes nothing does not. + +`create_request_id` makes creation idempotent: the form generates one uuid per +create attempt and resends the same one on retry; a replay returns the ids of +the row already created instead of a duplicate (clients and animals can be +archived, never deleted, so a duplicate would stay forever and block the +account's deletion under D9a). + +The backfill of M1 is a private function the migration calls once +(`private.backfill_personal_workspaces()`, idempotent), so pgTAP can prove it +on data: the migrations run on an empty `profiles` table in both test runners. + +Indexes and why: + +| Index | Serves | +|---|---| +| `workspace_members_user_idx` | the membership lookup of every policy | +| `clients_workspace_name_idx`, `animals_workspace_name_idx` | workspace filter, keyset pagination in name order, search within one workspace | +| unique `(workspace_id, id)` on clients and animals | targets of the composite foreign keys | +| `animal_client_relations_current_unique` | one current relation per (animal, client, role) | +| unique `(workspace_id, create_request_id)` on the three tables | idempotent creation | +| `animal_client_relations_animal_idx`, `_client_idx` | an animal's relations, a client's relations, foreign key checks | + +Search reads stored columns only: `search_key` (folded name, city and email +of a client; folded name, breed and species detail of an animal) and +`phone_digits`. Nothing is folded per row at query time. No trigram index in +V1-1: a workspace holds at most 20 000 rows per table (§10) and the search +scans one workspace through the name index. The measurement of step V1-1.2 +decides: above 100 ms at p95 on 20 000 rows, a `pg_trgm` GIN index on +`search_key` is added (PGlite ships `pg_trgm`). + +`name_key` is stored with `collate "C"`, so the order is the same on PGlite and +on the real stack (rule of the pgTAP files) and, accents and case being folded, +follows French alphabetical order closely enough for a list. If the dictionary +of `unaccent` ever changed, stored keys would differ from new ones until their +rows are rewritten: recorded, low risk. --- -## 7. Screens and journeys +## 9. Policies, helpers and RPCs -Routes (English, like the existing `/app/dashboard` and `/app/account`): +### 9.1 Helpers (schema `private`) + +| Helper | Returns | Rule | EXECUTE | +|---|---|---|---| +| `private.caller_workspace_ids()` | `setof uuid` | the single source of the access rule: workspaces where `auth.uid()` is a member, with an active profile and a confirmed email | `authenticated` (policies evaluate it) | +| `private.writable_workspace_ids()` | `setof uuid` | `caller_workspace_ids()` restricted to a write role (V1-1: `holder`) | none (called inside RPCs) | +| `private.require_write_budget(p_actor uuid)` | `void` | raises P0001 `rate_limited` when the actor has 1 000 audit rows within the past hour or 5 000 within the past day (every audit row of the actor counts, on the existing `audit_logs_actor_idx`) | none | +| `private.fold_text(p_value text)` | `text` | lower case without accents (`unaccent` with an explicit dictionary), declared immutable for the generated columns | `authenticated` (the invoker search folds the term) | +| `private.create_personal_workspace()` | trigger | after insert on `profiles`: workspace + `holder` membership | none | +| `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none | + +All are `security definer` (except `fold_text`, a pure SQL function), +`set search_path = ''`, `revoke all ... from public, anon, authenticated, +service_role` then the grants of the table, and listed in the census of +`001_schema.sql`. The write RPCs do not call `private.require_actor()`: its +two messages differ, and V1-1 refusals must be identical (§9.4). + +### 9.2 Row-level security and grants + +| Table | SELECT policy (role `authenticated`) | Write policies | Column grants to `authenticated` | +|---|---|---|---| +| `workspaces` | `id in (select private.caller_workspace_ids())` | none | `id`, `kind`, `personal_user_id`, `created_at` | +| `workspace_members` | `workspace_id in (select private.caller_workspace_ids())` | none | all columns | +| `clients` | `workspace_id in (select private.caller_workspace_ids())` | none | all columns | +| `animals` | same | none | all columns | +| `animal_client_relations` | same | none | all columns | + +- RLS enabled on every table in the migration that creates it. +- `revoke all ... from public, anon, authenticated, service_role`, then the + column grants above. `anon` and `service_role` hold nothing (§13.2 N7). +- No INSERT, UPDATE or DELETE grant or policy for any API role: every write is + an RPC. +- No policy names a platform role (D16); no `using (true)` (census test). +- The `in (select ...)` form evaluates the helper once per query, not per row. +- The app selects explicit column lists, never `select=*`, and never filters a + text column in a GET URL (`ilike`, `eq` on a name, a keyset cursor on + `name_key`): API URLs land in access logs. Text filters and name-ordered + pages go through the POST RPCs below; GET reads filter by id only. + +### 9.3 RPCs + +Write RPCs: `language plpgsql`, `security definer`, volatile, +`#variable_conflict use_column`, parameters referenced as +`.`. Each one, in this order: + +1. authorises and locks in one statement: the target row or the workspace is + selected `where id = ... and workspace_id in (select + private.writable_workspace_ids())` with its lock, so a caller outside the + workspace never takes a lock and never waits on one; no row found raises + 42501 `not_found`; +2. calls `private.require_write_budget`; +3. checks, in this order, archived (`archived`), then revision (`conflict`), + then the rules of the table below; +4. writes, inside a block that turns `check_violation`, `not_null_violation`, + `string_data_right_truncation` and `invalid_text_representation` into + `invalid_input`, `unique_violation` on the current-relation index into + `duplicate_relation` and `foreign_key_violation` into `not_found`; +5. writes one audit row and returns ids and the new revision only. + +Locks: create RPCs of clients and animals lock the workspace row (cap and +insert serialised per workspace); every relation RPC locks the animal row +`for update` then the client row `for share`, in that order; the archive RPCs +lock their row `for update`. So caps, « both active » and « animal active » +cannot be passed by a concurrent call. + +Parameters: dates, years and enum values arrive as `text` and are parsed inside +the body, so a malformed value (« 2015-02-30 ») is answered `invalid_input` +without being echoed in the error or the server log. Create RPCs give optional +fields a `null` default, after the required ones; update RPCs have no +defaults, so an omitted field is an error and never a silent erasure. An +update that changes nothing writes nothing and returns the current revision. + +| RPC | Parameters | Returns | Specific rules | Audit action | +|---|---|---|---|---| +| `create_client` | `workspace_id`, `create_request_id`, `kind`, `display_name`, then optional `email`, `phone`, `address_line1`, `address_line2`, `postal_code`, `city`, `country` | `{id, revision}` | replay of a known `create_request_id` returns the existing row; cap 20 000 clients | `client.created` | +| `update_client` | `client_id`, `expected_revision`, the nine fields | `{revision}` | | `client.updated` | +| `set_client_archived` | `client_id`, `archived` | `{revision}` | same state: no write | `client.archived` / `client.restored` | +| `create_animal` | `workspace_id`, `create_request_id`, `name`, `species_id`, `sex`, then optional `species_detail`, `breed`, `birth_year`, `birth_date`, and optional initial relation `client_id`, `relation_role`, `started_on` | `{id, revision, relation_id}` | replay returns the existing row; cap 20 000 animals; species active; birth not in the future; the optional relation follows the rules of `create_animal_client_relation` in the same transaction | `animal.created` (+ `animal_client_relation.created`) | +| `update_animal` | `animal_id`, `expected_revision`, the seven fields | `{revision}` | species active or unchanged; birth not in the future | `animal.updated` | +| `set_animal_archived` | `animal_id`, `archived` | `{revision}` | same state: no write | `animal.archived` / `animal.restored` | +| `create_animal_client_relation` | `animal_id`, `client_id`, `create_request_id`, `relation_role`, optional `started_on` | `{id, revision}` | both in one writable workspace (else 42501); both active; no current duplicate; at most 20 current and 200 total relations per animal and 100 000 per workspace (`limit_reached`); `started_on` not in the future | `animal_client_relation.created` | +| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` | +| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` | +| `delete_animal_client_relation` | `relation_id`, `expected_revision` | `void` | only if §13.2 N4 is approved; animal active; explicit confirmation in the UI | `animal_client_relation.deleted` | + +The combined journeys use the atomic `create_animal` with its optional +relation. « New client with a first animal » is two calls (`create_client`, +then `create_animal` with the relation); each carries its own +`create_request_id`, the form keeps the ids it has received, and a retry +after a failure resumes at the missing call and never creates a second client. + +"Not in the future" allows up to the UTC date of tomorrow (and its year for +`birth_year`), so a date that is today in any time zone is accepted; the form +checks against the device's local date. Audit metadata is `{workspace_id}`, +plus `{relation_role}` on relation actions: no changed-field list, no name, +contact, date or search term. + +Read RPCs: `language plpgsql`, `security invoker` (RLS applies), stable, +`set search_path = ''`, `#variable_conflict use_column`, parameters referenced +as `.`, EXECUTE for `authenticated`. The app calls them +with POST, so terms and cursors stay out of URLs and access logs. + +| RPC | Parameters | Returns (one row per record) | Rules | +|---|---|---|---| +| `search_clients` | `workspace_id`, `query`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `kind`, `display_name`, `city`, `phone`, `email`, `archived_at`, `name_key`, `current_animal_count` | see below; also serves the client picker of the relation forms | +| `search_animals` | `workspace_id`, `query`, `species_id`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `archived_at`, `name_key`, `current_owners`, `current_owner_count` | see below; optional species filter | +| `list_client_animals` | `client_id`, `page_size`, `after_sort`, `after_id` | relation and animal columns | a client's relations with their animals, current first then former, each group by animal `name_key`, then `id`; keyset on that order; 50 by default, 100 at most | +| `client_archive_preview` | `client_id` | `{count, animals}` | active animals for which this client holds the only current `owner` relation: their count and the first 10 by name | + +Search rules: `query` trimmed, 0 to 100 characters, empty lists everything. The +term is folded, then `\`, `%` and `_` are escaped (backslash first), and it +must appear inside `search_key`. Phone: when the term holds at least four +digits and only digits, spaces, dots, hyphens and `+`, its digits are also +looked for inside `phone_digits`, after dropping one leading `0` (so +« 06 12 », « 0612345678 » and « +33 6 12 » all find `+33612345678`). +`archived = false` lists active records, `true` archived ones. `page_size` 1 to +100, 25 by default; keyset on `(name_key, id)`. + +Derived values: + +| Value | Exact rule | +|---|---| +| `current_animal_count` | `count(distinct animal_id)` over the client's relations with `ended_at is null`, any role, animals not archived | +| `current_owners` | the animal's relations with `relation_role = 'owner'` and `ended_at is null`, archived clients included and flagged, ordered by client `name_key` then `id`, first three as `{client_id, display_name, archived}` | +| `current_owner_count` | the count of those relations | +| « only current owner » (archive preview) | the animal is active, this client has a current `owner` relation, and no other client, archived or not, has one | + +The animal page reads its relations with one select by animal id (at most 200 +by the cap, ids in the URL only). Dashboard counts (D12) use `count=exact` with +`head=true` filtered by workspace id and `archived_at`. The app finds its +personal workspace with `workspaces?personal_user_id=eq.`. Nested selects +are bounded by the per-animal cap and by the role's `statement_timeout`, +pinned by a test. + +### 9.4 Failures + +Closed kinds, mapped by the access layer (`packages/supabase`), phrased by i18n +in FR and EN, like the auth and asset failures: + +| From the server | Kind | When | +|---|---|---| +| 42501 `not_found` | `not_found` | inactive account, unconfirmed email, not a member, unknown id, id of another workspace: one SQLSTATE and one message for all of them (`anon` gets PostgREST's « permission denied », having no EXECUTE) | +| P0001 `archived` | `archived` | write on an archived record (checked before the revision) | +| P0001 `conflict` | `conflict` | `expected_revision` differs: the form shows the saved values beside the typed ones and keeps the typed ones | +| P0001 `limit_reached` | `limit_reached` | a cap of §10 | +| P0001 `rate_limited` | `rate_limited` | the write budget of §10 | +| P0001 `duplicate_relation` | `duplicate_relation` | same current (animal, client, role), including the loser of a race | +| P0001 `already_ended` | `already_ended` | ending an ended relation | +| P0001 `invalid_input` | `invalid_input` | an RPC rule or a constraint or parse error caught inside the RPC | +| anything else | `unavailable` | network, server | + +pgTAP compares the whole error (SQLSTATE, message, detail, hint) of a foreign id +and of a random uuid. An `invalid_input` from a CHECK means the TypeScript +rules drifted from the SQL: the parity test of §12.2 exists to catch it first. + +### 9.5 SECURITY DEFINER functions: owner, path, privileges, trust + +- Owner: the role that runs the migrations and owns the tables (`postgres` on + the CLI stack, the same on any Supabase project; a table owner, not a + superuser on Supabase), like every existing function; no + `alter function ... owner to`. RLS is not forced on these tables, so the + owner reads past the policies: the function body is the only authorisation + and checks the workspace role before reading, locking or writing any record. +- `set search_path = ''`; every object is schema-qualified; no dynamic SQL, no + `execute`, no `format()`. +- EXECUTE: `revoke all ... from public, anon, authenticated, service_role`, + then granted to `authenticated` for the RPCs and for the two helpers that + policies or the invoker searches evaluate, to nobody for the internal + helpers. `service_role` gets no EXECUTE. +- Trust boundary: the function trusts `auth.uid()` (a JWT verified by + PostgREST) and its own checks, nothing else from the caller; every parameter + is untrusted. It returns ids, revisions and closed codes, never a record of + another workspace, and has no platform-role branch. +- pgTAP pins `prosecdef`, the `search_path` setting and the ACL of each one. + +--- + +## 10. Technical limits (D15, principle approved, thresholds proposed) + +These caps protect the service. They are not commercial quotas: any quota +comes from the entitlement step (plan Step 11), and changing a cap here is a +migration. + +| Limit | Proposed value | Justification | Enforced by | +|---|---|---|---| +| Text fields | display name 120, email 254, phone E.164, address lines 120, postal code 16, city 80, country 2; animal name 80, breed 80, species detail 80; years 1900 to tomorrow's UTC year | long structure names fit in 120; 254 is the SMTP path limit; the rest bounds a record to about 3 KB | SQL CHECK; same constants in the forms (§12.2); years and dates also in the RPC | +| Request size | one record per call (plus one optional relation in `create_animal`), about 3 KB of text at most by the field caps | no bulk operation in V1-1 | SQL; reverse proxy body cap of 64 KiB on `/rest/v1` in production (deploy notes, RR-5) | +| Items per operation | one record and its audit row per write RPC; two in `create_animal` with a relation | imports are out of scope | RPC design | +| Pagination | search pages of 25 by default, 100 at most; a client's animals 50 by default, 100 at most; an animal's relations at most 200 by the cap; PostgREST `max_rows = 1000` limits the top level of a direct select, and `statement_timeout` bounds nested ones | a phone list needs 25; 100 bounds the work of one call | RPC; `config.toml`; role setting | +| Search term | 0 to 100 characters after trimming | a name or a phone fits; longer is noise | RPC | +| Records per workspace | 20 000 clients, 20 000 animals, 100 000 relations | a full-time practitioner sees roughly 1 000 to 2 000 visits a year, so 20 000 animals is more than a decade of distinct animals for one person | RPC, under the workspace or animal row lock | +| Relations per animal | 20 current, 200 in total | co-owners, keeper and contacts fit in 20; 200 covers decades of sales; the animal page reads them in one select | RPC | +| Write rate | 1 000 audited writes per actor per rolling hour and 5 000 per rolling day, every audit row of the actor counted on the existing `audit_logs_actor_idx` | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) | +| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to ids and the relation role | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) | +| Concurrent writes | optimistic `revision` on every update; locks of §9.3 (workspace row for creates, animal then client row for relations, the row itself for archive); idempotent creates through `create_request_id` | no silent overwrite between two tabs or devices, no cap overshoot, no duplicate on retry | SQL and RPC | +| Enumeration | random uuid ids; one 42501 `not_found` for an unknown and a forbidden id in every RPC, with no lock taken outside the caller's workspaces; reads filtered by RLS return empty, never an error that says "exists"; searches limited to one workspace of the caller; closed codes, never values, in errors | | RLS, RPC | +| Login, sign-up, email sending | existing GoTrue limits (`[auth.rate_limit]` in `config.toml`); per-IP limits on `/rest/v1` at the production reverse proxy | | GoTrue; infrastructure (deploy notes) | + +Growth bound of one misused confirmed account, from the figures above: at most +20 000 clients, 20 000 animals and 100 000 relations (about 150 MB with their +indexes at the field caps), and at most 5 000 audit rows a day of a few hundred +bytes each (about 0.5 GB a year). The audit log is append-only and never +cleaned today: its retention belongs to the lifecycle contract. GoTrue's +sign-up limits bound the number of accounts. + +§10.6 Logs and errors: inside the write RPCs, constraint and parse errors +become `invalid_input` (§9.3), so PostgreSQL never logs a failing row, whose +detail would contain names, and no submitted value is echoed. PostgreSQL does +not log statement parameters on error by default +(`log_parameter_max_length_on_error = 0`). Residual: a value PostgREST cannot +cast before the function runs (a non-uuid id) is echoed in the response; ids +are not personal data. The production log settings go to the deploy notes with +RR-5. The app logs no record content. + +--- + +## 11. Screens and journeys + +### 11.1 Routes + +English, like the existing `/app/dashboard` and `/app/account`; identifiers +only, never a name or a search term. | Route | Content | |---|---| -| `/app/clients` | list (name, kind, city, phone, animal count), search, archived filter, « new client » | -| `/app/clients/new` | form; optional « add a first animal » section in the same flow | -| `/app/clients/:clientId` | identity and contact, animals with their role (current and former), edit, archive or restore, add an animal | -| `/app/animals` | list (name, species, breed, sex, owners or « Propriétaire non renseigné »), search, species and archived filters, « new animal » | -| `/app/animals/new` | form with optional client selection or inline client creation; prefilled when opened from a client | -| `/app/animals/:animalId` | identity, owners, keepers and contacts (current and former), edit, archive or restore | +| `/app/clients` | list (name, kind, city, phone, number of animals), search, « archivés » filter, « Nouveau client » | +| `/app/clients/new` | client form; optional « Ajouter un premier animal » section in the same flow | +| `/app/clients/:clientId` | identity and contact (phone as a `tel:` link, email as `mailto:`), animals with their role, current then former, edit, archive or restore, add an animal | +| `/app/clients/:clientId/edit` | client form | +| `/app/animals` | list (name, species, breed, sex, current owners or « Propriétaire non renseigné »), search, species filter, « archivés » filter, « Nouvel animal » | +| `/app/animals/new` | animal form with optional client selection or inline client creation; prefilled when opened from a client | +| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct (and remove per N4) a relation; edit, archive or restore | +| `/app/animals/:animalId/edit` | animal form | -An unknown id and a forbidden id show the same « not found » screen. +An unknown id and a forbidden id show the same « introuvable » screen. -Journeys: +### 11.2 Journeys -1. New client calling about a horse: Clients → new client → type the name, - add the first animal in the same form → save → client page with the animal. -2. Find an animal from a phone in a stable: Animaux → type part of the name or - the identification → open the animal → see owners and keeper with the phone - as a `tel:` link. -3. Horse sold: animal page → add the new owner → end the old owner's relation - → the old client stays, with its other animals, and appears as former owner - on the horse's page. -4. Owner unknown: a rider brings a horse without its owner's details → the - animal is created with no client → its page and the list show - « Propriétaire non renseigné », no placeholder client exists → the owner - is added later. +1. New client calling about a horse: Clients → Nouveau client → type the name, + add the first animal in the same flow → save → client page with the animal + linked as owner. +2. Find an animal from a phone in a stable: Animaux → type part of the name → + open the animal → owners and keeper with their phone as a `tel:` link. +3. Horse sold: animal page → add the new owner → end the former owner's + relation with the sale date if known → the former owner keeps their other + animals and appears as « ancien propriétaire ». +4. Owner unknown: a rider brings a horse without the owner's details → animal + created with no client → its page and the list show « Propriétaire non + renseigné », no placeholder exists → the owner is added later. 5. Client archived: the confirmation lists the animals for which it is the only current owner → archived → hidden from lists, visible under the - archived filter, still shown on its animals' pages, restorable. -6. Animal deceased, if `deceased_on` is kept (D6a): mark deceased with a date - → the animal stays in lists with a « deceased » badge. + « archivés » filter, still shown on its animals' pages, restorable. +6. A stable as keeper: create the structure « Écurie du Lac », link it as + keeper of a horse whose owner is a person. +7. Species « Autre »: create a ferret as « Autre » with the detail « Furet ». + +Journeys run on desktop and phone, in FR and EN, and journey 1 also with the +keyboard only. + +### 11.3 Forms + +- Client: « Personne / Structure » control at the top (« Personne » visibly + selected), then the name field whose label follows the kind, then contact + and address. Phone: international entry (`+32…`) accepted as typed; a + French national entry (`06 12 34 56 78`) is converted to `+33…` only when + the country is empty or France, and the converted value is shown in the + field before saving; with another country a national entry is refused with + « Indiquez le numéro avec son indicatif (+32…) ». Country: empty select, + never prefilled. +- Animal: name, species (with the detail field shown and required for + « Autre »), sex as three explicit choices with none preselected (N8), breed, + birth as a year field plus an optional full date: entering the date fills + and locks the year, clearing it unlocks the year. +- Relation: client picker with search, role, start date (optional); ending + asks for an optional end date. +- Every form: labels on every field, required fields marked in the label, + errors under the field linked with `aria-describedby` and announced, focus + on the first error on submit; unsaved changes protected by a + `beforeunload` guard and by a confirmation on the form's own Cancel and + back actions (the app's declarative router has no navigation blocker, and a + data-router migration is out of scope); `conflict` shows the saved values + beside the typed ones and keeps the typed ones; after a partial failure of a + two-call creation the form keeps what was saved and retries the missing call + with the same request ids (§9.3). + +### 11.4 Layout and navigation Desktop: the sidebar entries Clients and Animaux of the validated mockup become -active; list and detail use the existing `Card`, `FormField` and `Button` -components; no new visual direction. Mobile: single column, rows as cards with -44 px targets, forms as full pages (no modal form), save bar reachable with -the keyboard open. The tab bar question is decision D11; dashboard tiles are -decision D12. +active, in the mockup's order; list and detail use the existing `Card`, +`FormField`, `Button` and `Badge` components; no new visual direction. Mobile: +single column, list rows as cards with 44 px targets, forms as full pages (no +modal form), the save action reachable with the keyboard open, « Afficher +plus » at the end of a list (keyset pages), the drawer as navigation (D11). +Dashboard tiles: D12. The screens follow `docs/design/` and are built with the +project's design workflow. -Accessibility applied in V1-1, not deferred to V1-5: every field labelled, -errors linked with `aria-describedby` and announced, focus moved to the first -error on submit and to the page heading on navigation, visible focus, no -action reachable only by pointer, confirmation dialogs with focus trap and -focus restore (decision D13), an axe check per screen in the browser tests. -Unsaved form changes ask before leaving. Failure kinds are closed and phrased -by i18n (FR and EN), like the auth and asset failures. +### 11.5 Accessibility, applied in V1-1 + +Every field labelled; errors announced; focus to the page heading on +navigation and to the first error on submit; visible focus; nothing reachable +only by pointer; confirmation dialogs with focus containment (the `inert` +attribute on the rest of the page while open) and focus restored to the +opener, no new dependency (D13); +status changes (saved, archived) announced through a live region; an axe check +per screen in the browser tests. --- -## 8. Tests and Definition of Done +## 12. Tests and Definition of Done -### 8.1 SQL (pgTAP, PGlite and real stack) +### 12.1 SQL (pgTAP, on PGlite and on the real stack) -- RLS enabled, no API write grant, explicit column grants; census tests - (`001`, schema↔types) updated. -- Allowed and denied per actor of §5.1: member reads and writes; second - account, anonymous, deactivated account and each platform role read - nothing and every RPC refuses with 42501; unknown id and forbidden id give - the same error. -- Every CHECK of §4 accepted at its bound and refused one step past it; a - client with only a display name accepted; `species_detail` required with - `other` and refused otherwise; a `birth_date` whose year differs from - `birth_year` refused, a `birth_year` alone accepted. -- Same-workspace link rule; an animal with no owner link accepted; a second - current (animal, client, role) row refused; an ended relation kept and - readable; archived records refuse edits; archiving a client leaves its - animals and links unchanged; stale `updated_at` refused. -- Audit rows written for each RPC, with no name, contact or note in them. -- Personal workspace created for a new profile and backfilled for existing - ones; the D9a behaviour as decided. +Files: `012_workspaces.sql`, `013_clients.sql`, +`014_animals_relations.sql`; updates to `001_schema.sql` (tables, RLS, +privileges, helper census) and to `packages/supabase/tests/db/schema-types.test.ts`; +the PGlite harness loads `unaccent`. -### 8.2 Cross-account on the real stack +Actors: A and B, two confirmed active accounts with their workspaces WA and +WB; C, an account with an unconfirmed email; D, an account deactivated after +creating records; S, a platform owner and admin; `anon`; `service_role`. -An e2e file beside `avatar-flow.e2e.ts`: two users created through the admin -API on the local stack; A creates a client and an animal; B lists (empty), -reads by id (nothing), updates, archives, links (42501); the anon key reads -nothing; A deactivated by SQL loses access. Run by `pnpm` script on the DEV -origin. +| Owner's case | Proof | +|---|---| +| Two accounts, two workspaces | A and B each get exactly one personal workspace with a `holder` membership (trigger); the backfill function, called on a profile inserted with the trigger disabled inside the test transaction, creates one and is idempotent on a second call; a second personal workspace for A is refused | +| Read allowed | A reads its workspace, membership, clients, animals and relations | +| Read forbidden | B, C, D and S read zero rows of WA in every table, through `search_clients`, `search_animals`, `list_client_animals` and `client_archive_preview` with WA's ids, and through a `count` query; `anon` and `service_role` get `permission denied` | +| Write allowed | A runs every RPC on WA records | +| Write forbidden | B, C, D and S calling every RPC on WA ids get the same whole error (SQLSTATE, message, detail, hint) as with a random uuid, and take no lock on WA rows; `anon` cannot execute any RPC | +| Reference between workspaces refused | B linking its animal to A's client gets 42501; a direct insert as `postgres` with mismatched workspaces fails on the composite foreign key | +| Archive and restore | an archived client or animal refuses updates (`archived`), keeps its relations, leaves search by default and appears with the archived filter; restore re-enables edits; archiving a client changes none of its animals | +| Historical relations | ending keeps the row with `ended_at`; a second current identical relation is refused; a successive one after the end is accepted; `ended_on` refused on a current relation and before `started_on`; ending an ended relation gives `already_ended`; relations of an archived animal are frozen | -### 8.3 Application +Also: a client with only a name and a kind accepted; the five birth states +of §5.2 (bounds of the fields with a TypeScript twin are proven by §12.2); +`species_detail` with and without `other`; an inactive species refused; dates +in the future refused, and 1 January accepted on 31 December UTC; a malformed +date answered `invalid_input` without its value; stale revision refused, and +`archived` reported before `conflict`; a replayed `create_request_id` returns +the first row; caps reached with rows inserted by `generate_series`; the write +budget (hour and day) reached with audit rows inserted as `postgres`; one audit +row per write with no name, contact or date in it; an oversized or malformed +`x-correlation-id` stored as null; search folding accents and case, escaping +`\`, `%` and `_`, matching « 06 12 », « 0612345678 » and « +33 6 12 », +the species filter excluding a row, keyset pages without gaps or duplicates; +derived values of §9.3 (two roles on one animal counted once, archived owner +shown); two concurrent identical relations giving one row and one +`duplicate_relation`; D9a (an account with records cannot be deleted, an empty +one is, with its workspace); each definer function pinned (owner context, +search path, ACL); a config test pinning `enable_confirmations = true`. -- Unit and component tests: form schemas (each rule, i18n keys), list and - search states (empty, results, error), archive and restore flow, conflict - message, « Propriétaire non renseigné » state, route guard, i18n key parity. -- Constraint parity test (D-R7): the TypeScript constants equal the SQL CHECK - bounds read from `pg_constraint` on PGlite. +### 12.2 Constraint parity (D-R7) -### 8.4 Real browsers +`packages/supabase/src/field-limits.ts` holds the V1-1 bounds and patterns +(lengths, years, email and phone patterns, control ranges), read by the app's +Zod schemas. `packages/supabase/tests/db/field-limits.test.ts` proves them by +behaviour on PGlite: for each constant it inserts a value at the bound and one +step past it and expects acceptance then refusal, so no SQL text is parsed. +Counting rule: `char_length` counts code points, so the TypeScript check counts +`[...value].length`; Zod's `.max()` counts UTF-16 units and is not used alone +on these fields. The existing auth and account forms stay with the separate +D-R7 chore. -A Playwright suite under `apps/app/e2e` (decision D14: `@playwright/test` -and `@axe-core/playwright` as dev dependencies), run against `pnpm dev` and -the local stack on the DEV origin: +### 12.3 Real stack (integration) -- desktop Chromium, Firefox and WebKit; phone viewports 375 × 667 and - 412 × 915; -- journeys 1 to 6 of §7; -- the creation journey with the keyboard only; -- two browser contexts: B opens A's client URL and gets « not found »; -- no client or animal name in any URL; -- an axe scan on each screen, zero serious or critical violation. +`packages/supabase/tests/e2e/clients-animals.e2e.ts`, beside +`avatar-flow.e2e.ts`, run by a root script on the DEV origin: A and B created +through the admin API; A creates a client, an animal and a relation; B lists +nothing, reads nothing by id, and every RPC answers 42501; the anon key reads +nothing; the service key's select on `clients` is refused; an unconfirmed user +cannot obtain a session; A deactivated by SQL loses access; deleting A +through the GoTrue admin API while A holds records fails and leaves user, +profile and records intact. Seeding (20 000 clients for the measurement) and +teardown go through the privileged SQL helper the avatar e2e already uses +(`docker exec ... psql`): `afterAll` deletes the run's records, then its users. +The search time on 20 000 clients is a recorded measurement, not a pass/fail +assertion. -Then the owner's manual check on a real phone and a computer over the LAN. +### 12.4 Application -### 8.5 Definition of Done +Unit and component tests: form schemas per rule with i18n keys and the code +point count; phone conversion rule; birth input states; list and search states +(empty, results, error, more pages); archive and restore flow with the dialog +focus trap; conflict message; archived read-only state; « Propriétaire non +renseigné »; not-found screen for unknown and forbidden ids; route guard; i18n +key parity. + +### 12.5 Real browsers (Playwright and axe, D14) + +A suite under `apps/app/e2e`, run against `pnpm dev` and the local stack on the +DEV origin. In V1-1: Chromium, desktop and a 375 × 667 phone viewport (Firefox, +WebKit and 412 × 915 join at V1-5: WebKit's system libraries need `sudo`, a +user action, and desktop WebKit is not iOS Safari, which the owner's real +phone covers); journeys 1 to 7 of §11.2; the creation journey with the +keyboard only; two browser contexts where B opens A's client URL and gets +« introuvable »; every request the page sends (`page.on('request')`) checked +to hold no fixture name or search term in its URL; an axe scan on each screen +with zero serious or critical violation. Then the owner's manual check on a +real phone and a computer over the LAN. + +### 12.6 Definition of Done All tests above green; `pnpm check:all`; `pnpm db:reset && pnpm db:test`; -regenerated `database.types.ts`; fresh verifier and security gates; docs -(a domain document for clients and animals, CLAUDE.md folder map and -architecture, `docs/design/README.md` owners table); report format, PDF, -sheets and local tool unchanged; nothing deployed, Supabase DEV untouched -outside `db:reset` of the local stack. +`pnpm db:types:check`; fresh verifier and security gates; documents updated +(this contract's "as built" notes, `CLAUDE.md` folder map and architecture, +`docs/design/README.md` owners table, `SUPABASE.md`); report format, PDF, +sheets and local tool unchanged; nothing deployed; no merge into `develop` +without the owner's go. --- -## 9. Orientations and decisions +## 13. Decisions -### 9.1 Owner orientations of 2026-10-25 (proposed, awaiting ratification) +### 13.1 Approved by the owner on 2026-10-25 (BDR-073) -All are needed before the first migration. « SQL » marks an orientation that -fixes a table shape or a constraint, « permissions » one that fixes a policy -or an RPC check. +| Id | Decision | +|---|---| +| D1 | Interface term « Clients » (EN "Clients"); a client is a natural person or a professional or associative structure; Propriétaire, Détenteur and Contact are roles of its relation to an animal, distinct from its identity; consistent FR and EN terms; no platform role reused as the owner of an animal | +| D2 / C4 | `workspaces` and `workspace_members`; one personal workspace per practitioner in V1-1; cabinet workspaces possible later without destructive transfer; no global client directory; no data visible between practitioners; no sharing, invitations or cabinet permissions in V1-1 | +| D3 | Two client kinds: natural person, structure | +| D4 | Required: a display name for a person, a name (dénomination) for a structure; every other detail optional at creation; no country imposed silently; no email or phone imposed; billing, booking and regulatory needs belong to their steps | +| D4a | Optional separate first and last names allowed for persons; the display name stays the required reference; the contract defines the rule between them (§5.1) | +| D5 | Exactly the nine species of the contract plus « Autre » with a required detail; no invented species; a recordable species does not mean a sheet exists; the equine draft is never published automatically | +| D6 | Required: name, species, sex with an explicit `unknown`; optional: breed, full birth date when known, birth year alone when only the year is known; weight, photo, detailed identification, coat colour, neutering status, date of death and further notes deferred; no complete veterinary record | +| D6a | The fields beyond the owner's list (neutering, identification, colour, notes, date of death) are deferred, not built in V1-1 | +| D6b | A year is never turned into a date; the representation keeps the precision given, with coherence constraints and tests (§5.2) | +| D7 | Many-to-many relation with an explicit role (owner, keeper, contact); co-ownership allowed; an animal may have no identified owner and always belongs to a valid workspace; no fictitious client to satisfy a constraint; never a relation across workspaces | +| D7a | Relation history with a start date when known and a nullable end (`ended_at`); no incoherent current duplicates, successive relations allowed; a change of owner or keeper never deletes history silently | +| D8 | Functional archive, read-only, reversible; historical relations kept; archiving a client does not archive its animals; archiving an animal does not delete its relations; archive is not erasure; no retention duration | +| D9 / D9a | A temporary DEV protection may block an account deletion that would leave incoherent data, never a permanent ban; the future lifecycle distinguishes closure, deletion or anonymisation, justified retention, shared records and reassignment in cabinets; V1-1 implements none of it and makes none of it impossible; no legal retention invented | +| C5 | V1-1 writes only by the authorised practitioner in their personal workspace; data isolated between workspaces; model ready for cabinet permissions; current-data edits never change finished bilans silently | +| C6 | Email confirmed, professional status verified and platform role are three distinct notions; a confirmed email gives private use of the workspace; verification required later for public features; no verified status by default; verification stays plan Step 9 | +| D16 | No ordinary staff access to clients, animals or private bilans; no general admin screen on them; exceptional privileged access framed and audited by a separate policy before publication; no impersonation or exceptional support access in V1-1 | +| D15 | Principle of technical caps protecting the service, distinct from commercial quotas; thresholds proposed in §10 for validation before the RPCs | +| Naming | Explicit nomenclature (§3); no generic `owner_id` | -| Id | Orientation | Impact | -|---|---|---| -| D1 | Interface term « Clients »; Propriétaire, Détenteur and Contact are roles of the relation to an animal; the client entity is never confused with its role | SQL: table `clients`, link roles `owner` / `keeper` / `contact` | -| D2 / C4 | `workspaces` and `workspace_members`; one personal workspace per practitioner in V1-1; records attached to a workspace; no global client directory; cabinets later, not built in V1-1 | SQL and permissions: every policy and RPC goes through the workspace helper | -| D3 | Persons and structures (écuries, haras, associations, entreprises, other legal entities), with an explicit distinction in the model | SQL: `kind` column and CHECK | -| D4 | The display name or company name is the only required field; contact details optional at creation; later steps set their own requirements | SQL: one required column; no NOT NULL on contact columns | -| D5 | The nine species of this contract plus « Autre » with a detail; no new species; no automatic sheet per species; a species may exist with no usable sheet | SQL: reference rows by migration; `species_detail` CHECK | -| D6 | Name and species required; sex with `unknown`; breed optional; birth year optional; a full date when known, never invented from a year; weight and photo deferred | SQL: `sex` CHECK and default; `birth_year` / `birth_date` coherence CHECK | -| D7 | Many-to-many relation with an explicit role per link; co-ownership; owner unknown or not entered allowed with no fake client; no SQL rule forcing an owner while that is undecided | SQL: link table with no minimum-owner constraint | -| D8 | Archive read-only and reversible; historical relations kept; no cascade from a client to its animals; no retention duration; archive is not erasure | SQL and permissions: `archived_at` columns, RPCs refuse edits on archived rows | -| D9 | No rule blocking an account's deletion for good; a later lifecycle contract (closure, deletion or anonymisation, justified retention, cabinet records, legal obligations); nothing implemented in V1-1, nothing in the model preventing it | SQL: delete behaviour of the keys to the profile (D9a) | -| D16 | No ordinary staff access to private records; no admin screen on clients, animals or bilans; exceptional technical operations framed, justified and audited before publication; no exceptional access mechanism in V1-1 | permissions: no platform-role branch in any policy or RPC | -| C5 | Writes reserved to workspace members with a write right; in V1-1 only the practitioner in their personal workspace; finished bilans never changed retroactively or silently | permissions | -| C6 | Email confirmation distinct from professional verification; a confirmed email gives private use; verification required for public professional features; statuses are not platform roles; verification process not built now | permissions: the V1-1 gate is an active session | - -### 9.2 Sub-choices the orientations leave open (SQL, before the migration) +### 13.2 Technical choices to validate before the first migration | Id | Question | Recommendation | Alternative | |---|---|---|---| -| D4a | Structured first and last name for persons | not in V1-1: one `display_name`; nullable columns can be added later without touching existing rows | a required `last_name` for persons (a second required field, against D4) | -| D6a | Fields beyond the owner's list: `neutered`, `identification`, `colour`, `notes`, `deceased_on` | keep all five, optional | drop any of them; adding one later is an additive column | -| D6b | Birth date model | `birth_year` plus an optional `birth_date`, with the coherence CHECK | one `date` with a precision flag: stores an invented day for a year-only birth, which D6 refuses | -| D7a | Ending a relation | `ended_at` on the link, the row kept as history | delete the row; the history then survives only as ids in the audit log | -| D9a | Deleting, in DEV, an auth user whose personal workspace holds records | a temporary guard refuses it, replaced by the lifecycle contract; an account with no record is deleted as today | cascade (erases the records with the account, deciding the policy early) or keep an orphaned workspace (records nobody can read) | +| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | English nouns (`donkey`, `dog`…), which mixes two schemes since `equine` cannot be renamed (sheets and reports cite it) | +| N2 | First and last names for persons (D4a) | not in V1-1: no V1-1 screen reads them, search and sort use the display name, and adding two nullable columns later touches no row | add `given_name` and `family_name` now with the priority rule of §5.1 | +| N3 | Client notes (not in the ratified list; animal notes deferred) | defer, like animal notes: minimisation, and free text is where sensitive data slips in | keep `notes` (at most 2 000 characters, with a hint to record only what the care needs) | +| N4 | Removing a relation entered by mistake | allow an explicit, confirmed, audited deletion (`delete_animal_client_relation`): ending a wrong relation would record a false « ancien propriétaire », against the accuracy principle; this is an exception to plan principle 4 (no deletion of user data), limited to relations | a `voided_at` flag hidden from every read (keeps the wrong row, adds a filter everywhere), or no correction (end it) | +| N5 | Relation dates | `started_on` and `ended_on` as optional business dates, plus `ended_at` as the owner named it: null while current, the time the end was recorded, so an end with an unknown date never invents one | `ended_at` alone, which stores the recording time as the end date | +| N6 | Thresholds of §10 | as proposed | other values | +| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` (the precedent of the files migration): no direct read path. It does not close the GoTrue admin path (§6.3): the key stays a full-access credential, bounded by its custody | default Supabase privileges for `service_role` (bypasses RLS: one request reads every record) | +| N8 | Sex in the form | three explicit choices, none preselected: one tap more, but « inconnu » then means unknown, not skipped | « Inconnu » preselected | +| N9 | Audit rows read by platform owners and admins | exclude `client.*`, `animal.*` and `animal_client_relation.*` actions from `audit_logs_select_admin` now (a new policy condition in M2): what they reveal (§6.3) is activity of private records, which D16 keeps from staff; incident work reads them through the exceptional-access path | keep the existing policy until the exceptional-access contract | -### 9.3 Decisions still open +### 13.3 Interface decisions still open -Not arbitrated by the owner; status open, recommendation and impact given. - -Before the RPCs are written (they change server behaviour): +Not ratified; recommendation and impact given. | Id | Decision | Recommendation | Impact | |---|---|---|---| -| D15 | Abuse guard | per-workspace caps (20 000 clients, 50 000 animals) refused by the create RPCs | RPC behaviour, no table change | - -Before or during the interface work (no table impact): - -| Id | Decision | Recommendation | Impact | -|---|---|---|---| -| D10 | Client information notice: text, and whether the app records that it was given | decide with the legal texts; nothing recorded in V1-1 | none in V1-1; recording it later adds a column; required before public exposure | -| D11 | Mobile navigation | drawer only in V1-1; the tab bar of the mockup arrives with Bilans (V1-3), since two of its four entries would lead nowhere today | UI | -| D12 | Dashboard tiles | show the two real tiles (clients, animals) now; bilans and appointments when their tables exist | UI | -| D13 | Shared `Dialog` focus trap and restore | fix it in V1-1 (it also improves the editor dialogs; partial RR-7) | UI, shared component | -| D14 | Real-browser test tooling | add `@playwright/test` and `@axe-core/playwright` as dev dependencies | manifest and lockfile change at implementation | +| D10 | Client information notice: text, and whether the app records that it was given | decide with the legal texts; nothing shown or recorded in V1-1 | none in V1-1; recording it later adds a column; required before public exposure | +| D11 | Mobile navigation | drawer only in V1-1; the mockup's tab bar (Accueil, Bilans, Agenda, Profil) arrives with Bilans (V1-3), since two of its four entries would lead nowhere today. `docs/design/README.md` says the tab bar comes "with the first list screens": the README line is updated once D11 is decided | UI | +| D12 | Dashboard tiles | the two real tiles (clients, animals) now, from live counts; bilans and appointments when their tables exist | UI | +| D13 | Shared `Dialog` focus containment and restore | fix it in V1-1 with `inert` and a restore to the opener, no dependency (it also improves the editor's dialogs; partial RR-7) | shared component | +| D14 | Real-browser test tooling | `@playwright/test` and `@axe-core/playwright` as dev dependencies of `apps/app`; Chromium only in V1-1, Firefox and WebKit at V1-5 | manifest and lockfile change at step V1-1.3; a browser download | | D17 | Bridge to the local tool (« start a bilan for this animal », prefill only) | no: V1-3 links bilans to animals properly; a prefill now would be a second path to delete later | none | +| U1 | Long lists | « Afficher plus » (keyset pages of 25), no numbered pages | UI | +| U2 | Archived records | one « archivés » toggle on each list, not a separate tab | UI | +| U3 | Birth input | year field plus optional full date that fills and locks the year (§11.3) | UI | -### 9.4 Never assumed, framed before any public exposure +### 13.4 Never assumed, framed before any public exposure -The legal basis of the processing (consent is not presumed to be required), +The legal basis of each processing (consent is not presumed to be required), the information given to clients, the retention durations, the deletion and -anonymisation rules, the legal qualification of each party. None of them -blocks a DEV implementation once §9.1 is ratified; each blocks any public -exposure. +anonymisation rules, the legal qualification of each party. None of them blocks +a DEV implementation with fictitious data; each blocks any public exposure. -Ratifying §9.1, answering §9.2 and settling D15 unlock the first migration, -on a `feature/` branch off `develop`. +--- + +## 14. Implementation steps and risks + +Each step is a vertical, testable unit on `feature/v1-1-clients-animals`, +detailed in `.claude/tasks/TODO.md` (objective, dependencies, files, +migration, tests, acceptance, security checks, stop conditions). The owner +validates after V1-1.1 and after the first UI step; nothing merges into +`develop` without the owner's go. + +| Step | Content | +|---|---| +| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012` | +| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards, N9 audit policy, field limits and parity test, access layer, real-stack e2e | +| V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13) | +| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof | +| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry | +| V1-1.6 | Animals and relations UI, navigation (D11), dashboard tiles (D12), documents, Definition of Done | + +Recommended first step: V1-1.1. It is SQL only, has no visible choice, and +every later step depends on its helpers. + +Risks and dependencies: + +- the service key and the JWT secret give full access through GoTrue admin + (§6.3); follow-ups outside V1-1, on the release track (RR-4): a narrower + worker credential (a dedicated Postgres role behind a custom-role JWT, which + GoTrue admin refuses) and monitoring of `auth.audit_log_entries`; +- `unaccent` must load on PGlite (the contrib ships with 0.3.16; the harness + needs it) and on the CLI stack; otherwise the fold falls back to + `translate()` over a committed accent table, a decision for the owner; +- the D9a guard makes GoTrue's admin delete fail (« Database error deleting + user ») for an account with records: expected, documented, tested; +- the audit log stays append-only with no retention: its growth is bounded + (§10), its retention belongs to the lifecycle contract; +- DEV holds fictitious data only until the legal framing (§7.3); +- `docs/design/README.md` places the mobile tab bar « with the first list + screens », which D11 contradicts until the owner decides; +- the RPC surface grows by fourteen functions (RR-4 review); +- the D-R7 chore for the existing forms reuses the V1-1 constants module; +- no CI runs on the forge: every gate is local; +- two old R5.6 rehearsal worktrees in an earlier session's scratchpad hold + uncommitted edits; they are not V1-1 work and are left to the owner. From 5d734be512e5c788b0f56af3b1803966479fe27e Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 19:15:35 +0100 Subject: [PATCH 02/60] chore(memory): BDR-073 V1-1 ratification, EVAL-035, V1-1 plan in TODO --- .claude/memory/decisions.md | 7 +++++ .claude/memory/evals.md | 6 ++++ .claude/memory/journal.md | 4 +++ .claude/tasks/TODO.md | 61 +++++++++++++++++++++++++++++++++++-- 4 files changed, 76 insertions(+), 2 deletions(-) diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 59dbad20..0fcf2fa3 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -535,3 +535,10 @@ 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. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index e559e1b8..8fbfff28 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -247,3 +247,9 @@ 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. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 3241d5af..b0c1847d 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -396,3 +396,7 @@ 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. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 07f38948..0fe1dd6a 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -368,7 +368,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo --- ## Product roadmap V1 (owner 2026-10-25 « Validation de l'inventaire et cadrage P0 / V1-1 ») -Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheets served from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 cross-cutting mobile + a11y pass (a11y and security apply at every step). C4/C5/C6 and the V1-1 orientations (owner brief « P0 : arbitrages documentaires et finalisation du contrat V1-1 ») = proposed, awaiting ratification. No migration, component, API or table before the owner ratifies the V1-1 contract; no merge into main, no release/0.2.0 change, no deploy, no Supabase DEV change; equine draft stays unpublished. +Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheets served from Supabase → V1-3 cloud bilans + history → V1-4 stored PDF + authorised sharing → V1-5 cross-cutting mobile + a11y pass (a11y and security apply at every step). C4/C5/C6 and the V1-1 business decisions ratified 2026-10-25 (BDR-073). No migration, component, API, dependency or table before the owner validates the V1-1 technical design at the preparation checkpoint; no merge into main or develop without the owner's go, no release/0.2.0 change, no deploy, no Supabase DEV change; equine draft stays unpublished. - [x] P0 docs realignment (docs only; branch `chore/p0-doc-realignment` created by the owner off develop, the working-tree edits carried over; merge into develop on the owner's go only) - [x] census of stale text in active docs (worker Node / Edge Functions, step numbers, roles, Step 13 "published", deleted tools, OPEN_QUESTIONS statuses) - [x] IMPLEMENTATION_PLAN: roadmap V1 section, step statuses, D-R9 in Steps 8/15/19/21/23/24/26, Step 13 DoD draft-only, deleted tools, Step 22 D-R8 @@ -379,7 +379,64 @@ 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) + - [ ] CHECKPOINT: owner validates the technical design (§8-§10) + N1-N9 + D10-D14, D17, U1-U3 → STOP until then (no migration, no dependency) + - [ ] V1-1.1 Workspaces foundation + - Objective: every account has exactly one personal workspace, readable by itself only, with the helpers every later table uses; audit rows no longer sized by the caller + - Depends: checkpoint + - Files: `supabase/migrations/_workspaces.sql`; `supabase/tests/012_workspaces.sql`; `supabase/tests/001_schema.sql` (tables, RLS, privileges, helper census); `packages/supabase/src/database.types.ts` (regenerated); `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspace`) + `src/index.ts`; `packages/supabase/tests/db/schema-types.test.ts`; config test (`enable_confirmations = true`); `docs/development/SUPABASE.md` + - Migration M1: enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; `private.caller_workspace_ids`, `private.writable_workspace_ids`, trigger `private.create_personal_workspace` after insert on profiles, `private.backfill_personal_workspaces()` called once; `private.log_event` redefined (same signature, `x-correlation-id` kept only if `^[A-Za-z0-9-]{1,64}$`) + NOT VALID CHECK; revoke all (public, anon, authenticated, service_role) + column grants; RLS + - Tests: trigger; backfill function on a profile inserted with the trigger disabled (idempotent); one personal workspace per account; A/B isolation; unconfirmed, deactivated, platform staff, anon, service_role see nothing; empty account deletion removes its workspace; oversized/malformed correlation header stored null; helper census (prosecdef, search_path, ACL); PGlite + real stack + - Acceptance: gates green; every account of `seed.sql` has one workspace + holder row after `pnpm db:reset` + - Security: no platform-role branch; no `using (true)`; helpers `search_path = ''`, EXECUTE only where evaluated; email confirmation checked in SQL; `log_event` callers unchanged + - Stop if: `auth.users` join behaves differently on PGlite and the real stack; the profiles trigger interferes with `handle_new_auth_user` or sign-up; an existing policy would need editing beyond the `log_event` redefinition + - [ ] V1-1.2 Clients data + - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack + - Depends: V1-1.1; N2, N3, N6, N9 decided + - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated + - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget` (1 000/h, 5 000/day); 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 + - 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 + - Objective: animals with the ten species rows and the D6b birth model, relations with history, never across workspaces + - Depends: V1-1.2; N1, N4, N5, N8 decided + - Files: `supabase/migrations/_animals_relations.sql`; `supabase/tests/014_animals_relations.sql`; `field-limits.ts` + parity test; `packages/supabase/src/{animals,relations}.ts`; e2e extended; types regenerated + - Migration M3: species rows (9 + `other`), table comment; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations` (composite FKs, partial unique index, request ids); `create_animal` (optional initial relation), `update_animal`, `set_animal_archived`, `search_animals`, relation create/end/update/(delete if N4); `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 + - 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 + - [ ] V1-1.6 Animals and relations UI, navigation and closure + - 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 - [ ] 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) From 7bf4fb6079e4e5c8d2779a7acbfcabe570ad3aba Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 19:53:16 +0100 Subject: [PATCH 03/60] feat(supabase): workspaces M1, one personal workspace per account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit V1-1.1 (contract V1-1_OWNERS_ANIMALS.md §4, §8, §9). Tables workspaces and workspace_members, created with the profile by trigger through one atomic, idempotent write path; deferred invariant (a personal workspace has exactly its account as holder); backfill of existing profiles; access helpers caller_workspace_ids (active profile, confirmed email) and writable_workspace_ids; RLS select for members only; no privilege for anon or service_role. log_event keeps x-correlation-id only as a short token. pgTAP 012 (85 checks), census and types updated, config test. --- packages/supabase/src/database.types.ts | 71 +++ packages/supabase/tests/db/config.test.ts | 38 ++ .../supabase/tests/db/schema-types.test.ts | 2 + .../migrations/20261025100000_workspaces.sql | 353 ++++++++++++++ supabase/tests/001_schema.sql | 2 +- supabase/tests/012_workspaces.sql | 458 ++++++++++++++++++ 6 files changed, 923 insertions(+), 1 deletion(-) create mode 100644 packages/supabase/tests/db/config.test.ts create mode 100644 supabase/migrations/20261025100000_workspaces.sql create mode 100644 supabase/tests/012_workspaces.sql diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index ad4cdb51..37fab90b 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -444,6 +444,73 @@ export type Database = { } Relationships: [] } + workspace_members: { + Row: { + created_at: string + member_role: Database['public']['Enums']['workspace_member_role'] + user_id: string + workspace_id: string + } + ComputedFields: never + Insert: { + created_at?: string + member_role: Database['public']['Enums']['workspace_member_role'] + user_id: string + workspace_id: string + } + Update: { + created_at?: string + member_role?: Database['public']['Enums']['workspace_member_role'] + user_id?: string + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'workspace_members_user_id_fkey' + columns: ['user_id'] + isOneToOne: false + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + { + foreignKeyName: 'workspace_members_workspace_id_fkey' + columns: ['workspace_id'] + isOneToOne: false + referencedRelation: 'workspaces' + referencedColumns: ['id'] + }, + ] + } + workspaces: { + Row: { + created_at: string + id: string + kind: Database['public']['Enums']['workspace_kind'] + personal_user_id: string | null + } + ComputedFields: never + Insert: { + created_at?: string + id?: string + kind: Database['public']['Enums']['workspace_kind'] + personal_user_id?: string | null + } + Update: { + created_at?: string + id?: string + kind?: Database['public']['Enums']['workspace_kind'] + personal_user_id?: string | null + } + Relationships: [ + { + foreignKeyName: 'workspaces_personal_user_id_fkey' + columns: ['personal_user_id'] + isOneToOne: true + referencedRelation: 'profiles' + referencedColumns: ['id'] + }, + ] + } } Views: { [_ in never]: never @@ -588,6 +655,8 @@ export type Database = { sheet_status: 'active' | 'archived' | 'deleted' sheet_version_status: 'draft' | 'published' | 'deprecated' sheet_visibility: 'private' | 'public' + workspace_kind: 'personal' + workspace_member_role: 'holder' } CompositeTypes: { [_ in never]: never @@ -726,6 +795,8 @@ export const Constants = { sheet_status: ['active', 'archived', 'deleted'], sheet_version_status: ['draft', 'published', 'deprecated'], sheet_visibility: ['private', 'public'], + workspace_kind: ['personal'], + workspace_member_role: ['holder'], }, }, } as const diff --git a/packages/supabase/tests/db/config.test.ts b/packages/supabase/tests/db/config.test.ts new file mode 100644 index 00000000..4ed86b19 --- /dev/null +++ b/packages/supabase/tests/db/config.test.ts @@ -0,0 +1,38 @@ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { supabaseDir } from './harness' + +/** + * Settings the workspace access rule depends on (V1-1 contract §6.2, §9.1). + * private.caller_workspace_ids() requires auth.users.email_confirmed_at, but + * with confirmations off GoTrue stamps that column at sign-up; the helpers + * live in `private`, which must stay out of the PostgREST schemas. + */ +async function readSetting( + section: string, + key: string, +): Promise { + const config = await readFile(join(supabaseDir, 'config.toml'), 'utf8') + let current = '' + for (const line of config.split('\n')) { + const header = line.match(/^\[([^\]]+)\]\s*$/) + if (header) current = header[1] + const setting = line.match(/^(\w+)\s*=\s*(.+?)\s*$/) + if (current === section && setting?.[1] === key) return setting[2] + } + return undefined +} + +describe('config.toml settings the access rules rely on', () => { + it('requires email confirmation before any session', async () => { + expect(await readSetting('auth.email', 'enable_confirmations')).toBe('true') + }) + + it('keeps anonymous sign-ins off (no account without an email)', async () => { + expect(await readSetting('auth', 'enable_anonymous_sign_ins')).toBe('false') + }) + + it('exposes only the public schema through PostgREST', async () => { + expect(await readSetting('api', 'schemas')).toBe('["public"]') + }) +}) diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 84da6653..36aa8f45 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -112,6 +112,8 @@ const expectedColumns = { 'updated_at', ], species: ['active', 'created_at', 'id', 'name_en', 'name_fr', 'sort_order'], + workspace_members: ['created_at', 'member_role', 'user_id', 'workspace_id'], + workspaces: ['created_at', 'id', 'kind', 'personal_user_id'], } as const satisfies ColumnMap // Compile-time: a column present in the type but absent from the list is an error. diff --git a/supabase/migrations/20261025100000_workspaces.sql b/supabase/migrations/20261025100000_workspaces.sql new file mode 100644 index 00000000..fad6a2cd --- /dev/null +++ b/supabase/migrations/20261025100000_workspaces.sql @@ -0,0 +1,353 @@ +-- V1-1.1 Workspaces (M1): the perimeter that will own and isolate clients, +-- animals and later bilans. Contract: docs/development/V1-1_OWNERS_ANIMALS.md +-- §4 (model), §8 (schema), §9 (helpers, RLS), §13.2 N7 / N9 (privileges, audit). +-- +-- In V1-1 every account has exactly one personal workspace, created by the +-- server in the transaction that creates its profile (sign-up), never by a +-- client call. Its only member is the account itself, with member_role +-- holder. Nothing is shared between accounts; cabinets come with plan Step 10. +-- +-- Invariants pinned by supabase/tests/012_workspaces.sql: +-- * one personal workspace per profile (unique personal_user_id), created +-- with its holder membership in one statement, idempotent under retries +-- and concurrent calls (ON CONFLICT on the unique key); +-- * a personal workspace has exactly one member, its account as holder, +-- checked at commit, so neither row ever survives alone; +-- * a workspace is readable only by its members whose profile is active and +-- whose email is confirmed; auth.uid() is the only input of that rule; +-- * no API role writes either table; anon and service_role hold no +-- privilege on them; no policy names a platform role (D16); +-- * the audit correlation id is kept only when it is a short token, so a +-- caller no longer chooses the size of an append-only audit row. + +-- --------------------------------------------------------------------------- +-- Tables +-- --------------------------------------------------------------------------- +-- cabinet joins workspace_kind with the cabinet step; holder is the only +-- member role until then (no unused cabinet role). +create type public.workspace_kind as enum ('personal'); +create type public.workspace_member_role as enum ('holder'); + +create table public.workspaces ( + id uuid primary key default gen_random_uuid(), + kind public.workspace_kind not null, + -- The account whose personal workspace this is; null for a future cabinet. + -- Deleting the account deletes its personal workspace, unless a record + -- table refuses it (D9a, `on delete restrict` from M2 on). + personal_user_id uuid references public.profiles (id) on delete cascade, + created_at timestamptz not null default now(), + constraint workspaces_personal_user_unique unique (personal_user_id), + constraint workspaces_personal_user_iff_personal + check ((kind = 'personal') = (personal_user_id is not null)) +); + +comment on table public.workspaces is + 'Perimeter that owns and isolates records. V1-1: one personal workspace per account, created with its profile; no API write path; no archive (it follows its account).'; +comment on column public.workspaces.personal_user_id is + 'Account of a personal workspace (unique); null for a cabinet.'; + +create table public.workspace_members ( + workspace_id uuid not null references public.workspaces (id) on delete cascade, + user_id uuid not null references public.profiles (id) on delete cascade, + member_role public.workspace_member_role not null, + created_at timestamptz not null default now(), + primary key (workspace_id, user_id) +); + +comment on table public.workspace_members is + 'Membership and rights of an account in a workspace. V1-1: the holder of each personal workspace only; no API write path.'; + +-- The membership lookup of every workspace policy (by caller). +create index workspace_members_user_idx on public.workspace_members (user_id); + +-- --------------------------------------------------------------------------- +-- Invariant: a personal workspace has exactly one member, its account as +-- holder. Deferred to commit so the two rows may be written in either order +-- inside one transaction; a workspace or a membership left alone, or a +-- foreign member added to a personal workspace, fails the commit whatever +-- role writes it. Cabinets are not constrained here. +-- --------------------------------------------------------------------------- +create or replace function private.check_personal_workspace() +returns trigger +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_ids uuid[]; +begin + if tg_table_name = 'workspaces' then + v_ids := array[new.id]; + elsif tg_op = 'INSERT' then + v_ids := array[new.workspace_id]; + elsif tg_op = 'DELETE' then + v_ids := array[old.workspace_id]; + else + v_ids := array[old.workspace_id, new.workspace_id]; + end if; + + -- A deleted workspace has nothing left to check (account deletion cascades). + if exists ( + select 1 + from public.workspaces w + where w.id = any (v_ids) + and w.kind = 'personal' + and ( + not exists ( + select 1 from public.workspace_members m + where m.workspace_id = w.id + and m.user_id = w.personal_user_id + and m.member_role = 'holder' + ) + or exists ( + select 1 from public.workspace_members m + where m.workspace_id = w.id + and m.user_id <> w.personal_user_id + ) + ) + ) then + raise exception 'personal workspace must have exactly its account as holder' + using errcode = '23514', constraint = 'workspaces_personal_holder'; + end if; + return null; +end; +$$; + +comment on function private.check_personal_workspace() is + 'Deferred constraint trigger: a personal workspace has exactly one member, personal_user_id as holder.'; + +create constraint trigger workspaces_personal_holder + after insert or update on public.workspaces + deferrable initially deferred + for each row execute function private.check_personal_workspace(); + +create constraint trigger workspace_members_personal_holder + after insert or update or delete on public.workspace_members + deferrable initially deferred + for each row execute function private.check_personal_workspace(); + +-- --------------------------------------------------------------------------- +-- Creation of the personal workspace +-- --------------------------------------------------------------------------- +-- The single write path: workspace and holder membership in one statement, +-- so both rows exist or neither does. A replay, or a call racing another +-- one, waits on the unique personal_user_id, then writes nothing and +-- returns false. The id comes from the server (a new profile, the backfill), +-- never from an API role: EXECUTE is granted to nobody. +create or replace function private.ensure_personal_workspace(p_user_id uuid) +returns boolean +language sql +volatile +security definer +set search_path = '' +as $$ + with created as ( + insert into public.workspaces (kind, personal_user_id) + values ('personal', p_user_id) + on conflict (personal_user_id) do nothing + returning id, personal_user_id + ), + joined as ( + insert into public.workspace_members (workspace_id, user_id, member_role) + select id, personal_user_id, 'holder' from created + returning workspace_id + ) + select exists (select 1 from joined); +$$; + +comment on function private.ensure_personal_workspace(uuid) is + 'Creates the personal workspace of an existing profile with its holder membership, atomically; idempotent (false when it already exists).'; + +-- Sign-up: GoTrue inserts auth.users, private.handle_new_auth_user inserts the +-- profile, this trigger creates the workspace, all in one transaction. The +-- workspace exists before the email is confirmed but stays unreadable until +-- then (private.caller_workspace_ids). +create or replace function private.create_personal_workspace() +returns trigger +language plpgsql +security definer +set search_path = '' +as $$ +begin + perform private.ensure_personal_workspace(new.id); + return null; +end; +$$; + +comment on function private.create_personal_workspace() is + 'AFTER INSERT on profiles: creates the personal workspace and its holder membership.'; + +create trigger profiles_create_personal_workspace + after insert on public.profiles + for each row execute function private.create_personal_workspace(); + +-- Accounts created before this migration. Called once below; idempotent, so +-- a second call (or a call racing a sign-up) creates nothing twice. +create or replace function private.backfill_personal_workspaces() +returns integer +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_profile_id uuid; + v_created integer := 0; +begin + for v_profile_id in + select p.id + from public.profiles p + where not exists ( + select 1 from public.workspaces w where w.personal_user_id = p.id + ) + order by p.id + loop + if private.ensure_personal_workspace(v_profile_id) then + v_created := v_created + 1; + end if; + end loop; + return v_created; +end; +$$; + +comment on function private.backfill_personal_workspaces() is + 'Creates the missing personal workspaces of existing profiles; returns how many were created. Idempotent.'; + +-- --------------------------------------------------------------------------- +-- Access helpers (contract §9.1) +-- --------------------------------------------------------------------------- +-- The single source of the access rule of every workspace-scoped table: the +-- workspaces where the caller is a member, with an active profile and a +-- confirmed email. No parameter: auth.uid() (a JWT verified by PostgREST) is +-- the only input, so a caller can name nobody else, and a direct call returns +-- what the caller may already read. Definer, so it reads auth.users and +-- workspace_members past their privileges and policies (no RLS recursion). +create or replace function private.caller_workspace_ids() +returns setof uuid +language sql +stable +security definer +set search_path = '' +as $$ + select m.workspace_id + from public.workspace_members m + join public.profiles p on p.id = m.user_id + join auth.users u on u.id = m.user_id + where m.user_id = (select auth.uid()) + and p.active + and u.email_confirmed_at is not null; +$$; + +comment on function private.caller_workspace_ids() is + 'Workspaces of auth.uid() as a member, active profile and confirmed email required. Evaluated by the workspace policies.'; + +-- The same set restricted to the member roles that may write records (V1-1: +-- holder). Called inside the write RPCs of M2 and M3 only. +create or replace function private.writable_workspace_ids() +returns setof uuid +language sql +stable +security definer +set search_path = '' +as $$ + select m.workspace_id + from public.workspace_members m + where m.user_id = (select auth.uid()) + and m.member_role = 'holder' + and m.workspace_id in (select private.caller_workspace_ids()); +$$; + +comment on function private.writable_workspace_ids() is + 'caller_workspace_ids() restricted to a write role (holder). For definer RPCs only.'; + +-- --------------------------------------------------------------------------- +-- Audit: cap the caller-controlled correlation id (contract §8, §10, N9) +-- --------------------------------------------------------------------------- +-- PostgREST exposes every request header, so x-correlation-id is chosen by +-- the caller. Kept only when it is a short token, else stored as null. Same +-- signature, privileges and callers as the foundation version. +create or replace function private.log_event( + p_actor_user_id uuid, + p_action text, + p_resource_type text, + p_resource_id uuid default null, + p_target_user_id uuid default null, + p_organization_id uuid default null, + p_metadata jsonb default '{}'::jsonb +) +returns uuid +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_id uuid; + v_correlation text; +begin + -- PostgREST exposes request headers as a JSON setting; absent elsewhere. + v_correlation := nullif(current_setting('request.headers', true), '')::jsonb ->> 'x-correlation-id'; + if v_correlation !~ '^[A-Za-z0-9-]{1,64}$' then + v_correlation := null; + end if; + + insert into audit.audit_logs ( + actor_user_id, action, resource_type, resource_id, + target_user_id, organization_id, metadata, correlation_id + ) + values ( + p_actor_user_id, p_action, p_resource_type, p_resource_id, + p_target_user_id, p_organization_id, coalesce(p_metadata, '{}'::jsonb), v_correlation + ) + returning id into v_id; + + return v_id; +end; +$$; + +-- New rows only: rows written before this migration keep whatever they hold. +alter table audit.audit_logs + add constraint audit_logs_correlation_id_format + check (correlation_id ~ '^[A-Za-z0-9-]{1,64}$') not valid; + +-- --------------------------------------------------------------------------- +-- Privileges + RLS. Supabase default privileges grant ALL on new public +-- tables to anon, authenticated and service_role: start from zero. The +-- service key reads nothing here (N7); it remains a GoTrue admin credential +-- (contract §6.3), which no table privilege can bound. +-- --------------------------------------------------------------------------- +revoke all on public.workspaces from public, anon, authenticated, service_role; +revoke all on public.workspace_members from public, anon, authenticated, service_role; +grant select (id, kind, personal_user_id, created_at) on public.workspaces to authenticated; +grant select (workspace_id, user_id, member_role, created_at) on public.workspace_members to authenticated; + +alter table public.workspaces enable row level security; +alter table public.workspace_members enable row level security; + +-- Members read their workspaces and the memberships of those workspaces. +-- No write policy: every write is server-side (trigger, backfill, RPCs). +create policy workspaces_select_member + on public.workspaces + for select + to authenticated + using (id in (select private.caller_workspace_ids())); + +create policy workspace_members_select_member + on public.workspace_members + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +revoke all on function private.check_personal_workspace() from public, anon, authenticated, service_role; +revoke all on function private.ensure_personal_workspace(uuid) from public, anon, authenticated, service_role; +revoke all on function private.create_personal_workspace() from public, anon, authenticated, service_role; +revoke all on function private.backfill_personal_workspaces() from public, anon, authenticated, service_role; +revoke all on function private.writable_workspace_ids() from public, anon, authenticated, service_role; +revoke all on function private.caller_workspace_ids() from public, anon, authenticated, service_role; +-- Policies run as the API role: it needs EXECUTE on the predicate. +grant execute on function private.caller_workspace_ids() to authenticated; + +-- --------------------------------------------------------------------------- +-- Existing accounts. Runs after the trigger exists, so a profile created +-- while the migration runs is covered by one or the other; a double pass +-- creates nothing twice (ensure_personal_workspace). +-- --------------------------------------------------------------------------- +select private.backfill_personal_workspaces(); diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index 0f99835a..ce66814d 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -62,7 +62,7 @@ select is( (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), - 'can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', 'authenticated executes only the policy predicates in private' ); diff --git a/supabase/tests/012_workspaces.sql b/supabase/tests/012_workspaces.sql new file mode 100644 index 00000000..a9de24b1 --- /dev/null +++ b/supabase/tests/012_workspaces.sql @@ -0,0 +1,458 @@ +-- V1-1.1 Workspaces (M1): creation with the account, uniqueness, the commit +-- invariant, the backfill, isolation between accounts, refusals for every +-- other actor, privileges and the definer census, the audit correlation cap. +-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8, §9, §12.1. +-- Actors: A and B confirmed and active; C unconfirmed; D deactivated; S a +-- platform owner; E an empty account deleted; F and G profiles created with +-- the trigger disabled (backfill, invariant). +begin; +select plan(85); + +insert into auth.users (id, email, email_confirmed_at) values + ('50000000-0000-0000-0000-00000000000a', 'alice-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000b', 'bob-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000c', 'carol-ws@test.local', null), + ('50000000-0000-0000-0000-00000000000d', 'dave-ws@test.local', now()), + ('50000000-0000-0000-0000-000000000005', 'staff-ws@test.local', now()), + ('50000000-0000-0000-0000-00000000000e', 'empty-ws@test.local', now()); +update public.profiles set active = false where id = '50000000-0000-0000-0000-00000000000d'; +select private.assign_platform_role(null, '50000000-0000-0000-0000-000000000005', 'owner'); + +-- Fixture readers usable from every role (pg_temp objects belong to postgres). +create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer +as $$ select id from public.workspaces where personal_user_id = p_user $$; +create function pg_temp.act_as(p_user uuid) returns text language sql +as $$ select set_config('request.jwt.claims', + json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$; +create function pg_temp.writable() returns setof uuid language sql stable security definer +as $$ select private.writable_workspace_ids() $$; +create table pg_temp.audit_ids (key text primary key, id uuid not null); +grant execute on function pg_temp.ws(uuid) to anon, authenticated, service_role; +grant execute on function pg_temp.act_as(uuid) to anon, authenticated, service_role; +grant execute on function pg_temp.writable() to anon, authenticated, service_role; + +-- --------------------------------------------------------------------------- +-- 1. Schema +-- --------------------------------------------------------------------------- +select has_table('public', 'workspaces', 'table public.workspaces exists'); +select has_table('public', 'workspace_members', 'table public.workspace_members exists'); +select enum_has_labels('public', 'workspace_kind', array['personal'], 'workspace_kind: personal only (cabinet comes with its step)'); +select enum_has_labels('public', 'workspace_member_role', array['holder'], 'workspace_member_role: holder only (no unused cabinet role)'); +select ok((select relrowsecurity from pg_class where oid = 'public.workspaces'::regclass), 'RLS enabled on workspaces'); +select ok((select relrowsecurity from pg_class where oid = 'public.workspace_members'::regclass), 'RLS enabled on workspace_members'); +select is( + (select string_agg(tablename || ':' || tableowner, ',' order by tablename collate "C") + from pg_tables where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')), + 'workspace_members:postgres,workspaces:postgres', 'both tables belong to postgres (the migration role)' +); + +-- --------------------------------------------------------------------------- +-- 2. Creation with the account (sign-up chain auth.users -> profiles -> workspace) +-- --------------------------------------------------------------------------- +select is( + (select count(*) from public.workspaces where personal_user_id::text like '50000000-%'), + 6::bigint, 'every new account got a workspace, confirmed or not' +); +select results_eq( + $$ select kind::text, personal_user_id from public.workspaces + where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$, + $$ values ('personal'::text, '50000000-0000-0000-0000-00000000000a'::uuid) $$, + 'A has one personal workspace of its own' +); +select results_eq( + $$ select user_id, member_role::text from public.workspace_members + where workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000a') $$, + $$ values ('50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$, + 'the workspace of A has exactly A as holder' +); +select is( + (select count(*) from public.workspace_members m join public.workspaces w on w.id = m.workspace_id + where w.personal_user_id::text like '50000000-%' and m.user_id = w.personal_user_id and m.member_role = 'holder'), + 6::bigint, 'every fixture workspace has its account as holder' +); +select isnt( + pg_temp.ws('50000000-0000-0000-0000-00000000000a'), pg_temp.ws('50000000-0000-0000-0000-00000000000b'), + 'A and B have two distinct workspaces' +); + +-- A sign-up that fails after the chain ran leaves no account, profile or workspace. +select throws_ok( + $$ do $b$ begin + insert into auth.users (id, email, email_confirmed_at) + values ('50000000-0000-0000-0000-000000000099', 'boom-ws@test.local', now()); + raise exception 'boom' using errcode = 'P0001'; + end $b$ $$, + 'P0001', 'boom', 'a sign-up transaction that fails after the trigger raises' +); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000099'), + 0::bigint, 'no workspace survives the failed sign-up' +); +select is( + (select count(*) from public.profiles where id = '50000000-0000-0000-0000-000000000099'), + 0::bigint, 'no profile survives the failed sign-up' +); + +-- --------------------------------------------------------------------------- +-- 3. Uniqueness and idempotence +-- --------------------------------------------------------------------------- +select is(private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000a'), false, + 'a replayed creation for A writes nothing and says so'); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000a'), + 1::bigint, 'A still has one workspace after the replay' +); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a'), + 1::bigint, 'A still has one membership after the replay' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$, + '23505', null, 'a second personal workspace for A is refused by the unique key' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', null) $$, + '23514', null, 'a personal workspace without an account is refused' +); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-0000000000ff') $$, + '23503', null, 'a personal workspace for an unknown account is refused' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (gen_random_uuid(), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '23503', null, 'a membership of an unknown workspace is refused' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '23505', null, 'a duplicate membership is refused by the primary key' +); + +-- --------------------------------------------------------------------------- +-- 4. Backfill of accounts created without the trigger (migration path) +-- --------------------------------------------------------------------------- +alter table public.profiles disable trigger profiles_create_personal_workspace; +insert into auth.users (id, email, email_confirmed_at) values + ('50000000-0000-0000-0000-00000000000f', 'backfill-ws@test.local', now()), + ('50000000-0000-0000-0000-000000000010', 'invariant-ws@test.local', now()); +alter table public.profiles enable trigger profiles_create_personal_workspace; +select is(pg_temp.ws('50000000-0000-0000-0000-00000000000f'), null, 'F has no workspace before the backfill'); +select is(private.backfill_personal_workspaces(), 2, 'the backfill creates the two missing workspaces'); +select is(private.backfill_personal_workspaces(), 0, 'a second backfill creates nothing'); +select results_eq( + $$ select m.user_id, m.member_role::text from public.workspace_members m + where m.workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000f') $$, + $$ values ('50000000-0000-0000-0000-00000000000f'::uuid, 'holder'::text) $$, + 'the backfilled workspace of F has F as holder' +); + +-- --------------------------------------------------------------------------- +-- 5. Commit invariant (checked here statement by statement) +-- --------------------------------------------------------------------------- +set constraints workspaces_personal_holder, workspace_members_personal_holder immediate; +delete from public.workspaces where personal_user_id = '50000000-0000-0000-0000-000000000010'; +select is(pg_temp.ws('50000000-0000-0000-0000-000000000010'), null, 'deleting a personal workspace takes its membership along'); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-000000000010') $$, + '23514', 'personal workspace must have exactly its account as holder', + 'a personal workspace without its holder cannot be committed' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$, + '23514', 'personal workspace must have exactly its account as holder', + 'B cannot be added to the personal workspace of A, even by the table owner' +); +select throws_ok( + $$ delete from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000a' $$, + '23514', 'personal workspace must have exactly its account as holder', + 'the holder of a personal workspace cannot be removed alone' +); +select throws_ok( + $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-000000000010' + where personal_user_id = '50000000-0000-0000-0000-00000000000a' $$, + '23514', 'personal workspace must have exactly its account as holder', + 'a personal workspace cannot be handed to another account' +); +select is(private.ensure_personal_workspace('50000000-0000-0000-0000-000000000010'), true, + 'the single write path passes the invariant (both rows in one statement)'); +set constraints all deferred; + +-- --------------------------------------------------------------------------- +-- 6. Reading: each confirmed active account reads its own workspace only +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('50000000-0000-0000-0000-00000000000a'); +select results_eq( + $$ select id, kind::text, personal_user_id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), 'personal'::text, + '50000000-0000-0000-0000-00000000000a'::uuid) $$, + 'A reads exactly its workspace' +); +select results_eq( + $$ select workspace_id, user_id, member_role::text from public.workspace_members $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000a'::uuid, 'holder'::text) $$, + 'A reads exactly its membership (no RLS recursion)' +); +select is( + (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')), + 0::bigint, 'A reads nothing of the workspace of B by id' +); +select is( + (select count(*) from public.workspaces where personal_user_id = '50000000-0000-0000-0000-00000000000b'), + 0::bigint, 'A naming B as personal_user_id reads nothing' +); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000b' + or workspace_id = pg_temp.ws('50000000-0000-0000-0000-00000000000b')), + 0::bigint, 'A reads no membership of B' +); +select results_eq( + $$ select private.caller_workspace_ids() $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$, + 'a direct call of the helper returns only what A may already read' +); +select results_eq( + $$ select pg_temp.writable() $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000a')) $$, + 'A may write in its workspace (holder)' +); + +select pg_temp.act_as('50000000-0000-0000-0000-00000000000b'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000b')) $$, + 'B reads exactly its workspace' +); +select is( + (select count(*) from public.workspaces where id = pg_temp.ws('50000000-0000-0000-0000-00000000000a')), + 0::bigint, 'B reads nothing of the workspace of A' +); + +-- --------------------------------------------------------------------------- +-- 7. Refused readers: unconfirmed, deactivated, platform staff +-- --------------------------------------------------------------------------- +select pg_temp.act_as('50000000-0000-0000-0000-00000000000c'); +select is((select count(*) from public.workspaces), 0::bigint, 'C (email unconfirmed) reads no workspace, not even its own'); +select is((select count(*) from public.workspace_members), 0::bigint, 'C reads no membership'); +select is((select count(*) from private.caller_workspace_ids()), 0::bigint, 'C has no workspace for the helper'); +select is((select count(*) from pg_temp.writable()), 0::bigint, 'C may write nowhere'); + +select pg_temp.act_as('50000000-0000-0000-0000-00000000000d'); +select is((select count(*) from public.workspaces), 0::bigint, 'D (deactivated) reads no workspace, not even its own'); +select is((select count(*) from public.workspace_members), 0::bigint, 'D reads no membership'); +select is((select count(*) from pg_temp.writable()), 0::bigint, 'D may write nowhere'); + +select pg_temp.act_as('50000000-0000-0000-0000-000000000005'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-000000000005')) $$, + 'S (platform owner) reads its own workspace only: no platform-role branch' +); +select is( + (select count(*) from public.workspace_members where user_id <> '50000000-0000-0000-0000-000000000005'), + 0::bigint, 'S reads no membership of another account' +); +reset role; + +-- The confirmation flow: confirming the email opens the existing workspace. +update auth.users set email_confirmed_at = now() where id = '50000000-0000-0000-0000-00000000000c'; +set local role authenticated; +select pg_temp.act_as('50000000-0000-0000-0000-00000000000c'); +select results_eq( + $$ select id from public.workspaces $$, + $$ values (pg_temp.ws('50000000-0000-0000-0000-00000000000c')) $$, + 'once its email is confirmed, C reads the workspace created at sign-up' +); + +-- --------------------------------------------------------------------------- +-- 8. Refused writes and calls for an authenticated caller +-- --------------------------------------------------------------------------- +select pg_temp.act_as('50000000-0000-0000-0000-00000000000a'); +select throws_ok( + $$ insert into public.workspaces (kind, personal_user_id) values ('personal', '50000000-0000-0000-0000-00000000000a') $$, + '42501', 'permission denied for table workspaces', 'A cannot create a workspace' +); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000b'), '50000000-0000-0000-0000-00000000000a', 'holder') $$, + '42501', 'permission denied for table workspace_members', 'A cannot add itself to the workspace of B' +); +select throws_ok( + $$ update public.workspaces set personal_user_id = '50000000-0000-0000-0000-00000000000b' $$, + '42501', 'permission denied for table workspaces', 'A cannot rewrite a workspace' +); +select throws_ok( + $$ update public.workspace_members set member_role = 'holder' $$, + '42501', 'permission denied for table workspace_members', 'A cannot rewrite a membership' +); +select throws_ok( + $$ delete from public.workspaces $$, + '42501', 'permission denied for table workspaces', 'A cannot delete a workspace' +); +select throws_ok( + $$ delete from public.workspace_members $$, + '42501', 'permission denied for table workspace_members', 'A cannot delete a membership' +); +select throws_ok( + $$ select private.ensure_personal_workspace('50000000-0000-0000-0000-00000000000b') $$, + '42501', null, 'A cannot call the creation path, for itself or anyone' +); +select throws_ok( + $$ select private.backfill_personal_workspaces() $$, + '42501', null, 'A cannot run the backfill' +); +select throws_ok( + $$ select private.writable_workspace_ids() $$, + '42501', null, 'A cannot call the write helper directly' +); +reset role; + +-- --------------------------------------------------------------------------- +-- 9. anon and service_role hold no privilege (refused by SQL, not by RLS) +-- --------------------------------------------------------------------------- +set local role anon; +select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'anon cannot read workspaces'); +select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'anon cannot read memberships'); +select throws_ok($$ select private.caller_workspace_ids() $$, '42501', null, 'anon cannot call the access helper'); +reset role; + +set local role service_role; +select throws_ok($$ select id from public.workspaces $$, '42501', 'permission denied for table workspaces', 'service_role cannot read workspaces despite BYPASSRLS'); +select throws_ok($$ select user_id from public.workspace_members $$, '42501', 'permission denied for table workspace_members', 'service_role cannot read memberships'); +select throws_ok( + $$ insert into public.workspace_members (workspace_id, user_id, member_role) + values (pg_temp.ws('50000000-0000-0000-0000-00000000000a'), '50000000-0000-0000-0000-00000000000b', 'holder') $$, + '42501', 'permission denied for table workspace_members', 'service_role cannot add a member' +); +select throws_ok($$ select private.backfill_personal_workspaces() $$, '42501', null, 'service_role cannot run the backfill'); +reset role; + +select is( + (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name) + cross join (values ('anon'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege(r.role, t.name, p.priv)), + 0::bigint, 'anon and service_role hold no table privilege on either table' +); +select is( + (select count(*) from (values ('public.workspaces'), ('public.workspace_members')) t(name) + cross join (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege('authenticated', t.name, p.priv)), + 0::bigint, 'authenticated holds no write privilege on either table' +); +select ok( + has_column_privilege('authenticated', 'public.workspaces', 'personal_user_id', 'select') + and has_column_privilege('authenticated', 'public.workspace_members', 'member_role', 'select'), + 'authenticated selects the granted columns (RLS then filters rows)' +); + +-- --------------------------------------------------------------------------- +-- 10. Policies and definer functions +-- --------------------------------------------------------------------------- +select is( + (select string_agg(tablename || ':' || policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',' + order by tablename collate "C") + from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members')), + 'workspace_members:workspace_members_select_member:SELECT:authenticated,workspaces:workspaces_select_member:SELECT:authenticated', + 'one SELECT policy per table, for authenticated only; no write policy' +); +select is( + (select count(*) from pg_policies where schemaname = 'public' and tablename in ('workspaces', 'workspace_members') + and (qual not like '%caller_workspace_ids()%' or qual like '%platform%' or qual like '%support%')), + 0::bigint, 'both policies go through caller_workspace_ids() and name no platform role (D16)' +); +select is( + (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids', + 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids') + and p.prosecdef and p.proconfig = array['search_path=""'] + and pg_get_userbyid(p.proowner) = 'postgres'), + 'backfill_personal_workspaces,caller_workspace_ids,check_personal_workspace,create_personal_workspace,ensure_personal_workspace,writable_workspace_ids', + 'the six workspace functions are security definer, owned by postgres, search_path empty' +); +select ok( + (select p.prosecdef and p.proconfig = array['search_path=""'] from pg_proc p + where p.oid = 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)'::regprocedure), + 'log_event keeps security definer and its empty search_path' +); +select is( + (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + cross join (values ('anon'), ('authenticated'), ('service_role')) r(role) + where n.nspname = 'private' and p.proname in ('backfill_personal_workspaces', 'caller_workspace_ids', + 'check_personal_workspace', 'create_personal_workspace', 'ensure_personal_workspace', 'writable_workspace_ids') + and has_function_privilege(r.role, p.oid, 'execute')), + 'authenticated:caller_workspace_ids', + 'EXECUTE: authenticated on the policy helper only; anon and service_role on none' +); +select ok( + has_function_privilege('service_role', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute') + and not has_function_privilege('authenticated', 'private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb)', 'execute'), + 'log_event keeps the privileges of the foundation (service_role yes, authenticated no)' +); +select is( + (select count(*) from pg_trigger where not tgisinternal and tgdeferrable and tginitdeferred + and tgname in ('workspaces_personal_holder', 'workspace_members_personal_holder')), + 2::bigint, 'the invariant triggers are deferred to commit' +); + +-- --------------------------------------------------------------------------- +-- 11. Account deletion: an empty account takes its workspace along (D9a) +-- --------------------------------------------------------------------------- +set constraints workspaces_personal_holder, workspace_members_personal_holder immediate; +select lives_ok( + $$ delete from auth.users where id = '50000000-0000-0000-0000-00000000000e' $$, + 'deleting an empty account passes the invariant' +); +select is(pg_temp.ws('50000000-0000-0000-0000-00000000000e'), null, 'its workspace is gone'); +select is( + (select count(*) from public.workspace_members where user_id = '50000000-0000-0000-0000-00000000000e'), + 0::bigint, 'its membership is gone' +); +set constraints all deferred; + +-- --------------------------------------------------------------------------- +-- 12. Audit correlation id: kept only as a short token (contract §10, N9) +-- --------------------------------------------------------------------------- +select set_config('request.headers', '{"x-correlation-id":"req-7f3a-01"}', true); +insert into pg_temp.audit_ids values ('valid', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 64))::text, true); +insert into pg_temp.audit_ids values ('max', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('a', 65))::text, true); +insert into pg_temp.audit_ids values ('long', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', json_build_object('x-correlation-id', repeat('x', 8192))::text, true); +insert into pg_temp.audit_ids values ('huge', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":"a b"}', true); +insert into pg_temp.audit_ids values ('space', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":"abc\n"}', true); +insert into pg_temp.audit_ids values ('newline', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{"x-correlation-id":{"nested":"x"}}', true); +insert into pg_temp.audit_ids values ('object', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '{}', true); +insert into pg_temp.audit_ids values ('absent', private.log_event(null, 'workspace.probed', 'workspace')); +select set_config('request.headers', '', true); + +select is( + (select correlation_id from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'valid')), + 'req-7f3a-01', 'a short token is kept' +); +select is( + (select char_length(correlation_id) from audit.audit_logs where id = (select id from pg_temp.audit_ids where key = 'max')), + 64, 'a 64-character token is kept' +); +select is( + (select string_agg(i.key, ',' order by i.key collate "C") from pg_temp.audit_ids i + join audit.audit_logs a on a.id = i.id where a.correlation_id is null), + 'absent,huge,long,newline,object,space', + 'an oversized, malformed or absent correlation id is stored as null' +); +select throws_ok( + $$ insert into audit.audit_logs (action, resource_type, correlation_id) values ('workspace.probed', 'workspace', repeat('a', 65)) $$, + '23514', null, 'the CHECK refuses an oversized correlation id on a new row, whoever writes it' +); + +select * from finish(); +rollback; From 0f8c9833cc27449831936e42585114387263e738 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:00:06 +0100 Subject: [PATCH 04/60] docs(docs): V1-1 owner decisions N1-N9 and M1 as built MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contract: N4 voiding instead of deletion, N5 date constraints, N6 write budget per workspace under a lock, N7 effective-privilege wording and residual admin paths, N9 audit metadata limited to ids; M1 as-built notes and isolated-stack results (§8.1). SUPABASE.md §3.3 with the owner procedure to apply M1 on DEV without reset; backend architecture, test strategy, plan and CLAUDE.md lines. --- CLAUDE.md | 7 +- docs/development/BACKEND_ARCHITECTURE.md | 15 +- docs/development/IMPLEMENTATION_PLAN.md | 5 +- docs/development/SUPABASE.md | 38 +++- docs/development/TEST_STRATEGY.md | 4 + docs/development/V1-1_OWNERS_ANIMALS.md | 227 ++++++++++++++++++----- 6 files changed, 237 insertions(+), 59 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d737e62b..5753ea05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -49,8 +49,9 @@ MVP species: equine only. 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`: -business decisions ratified 2026-10-25, BDR-073; SQL/RLS/RPC design awaiting owner validation on -`feature/v1-1-clients-animals`; nothing built). +business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on +`feature/v1-1-clients-animals` only V1-1.1 is built: migration `20261025100000_workspaces.sql`, tested on PGlite and an +isolated stack, not applied to Supabase DEV). --- @@ -274,7 +275,7 @@ faunosteo/ │ └─ 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) │ ├─ 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) diff --git a/docs/development/BACKEND_ARCHITECTURE.md b/docs/development/BACKEND_ARCHITECTURE.md index 8f581756..c9ae2ad9 100644 --- a/docs/development/BACKEND_ARCHITECTURE.md +++ b/docs/development/BACKEND_ARCHITECTURE.md @@ -83,12 +83,25 @@ private.has_active_entitlement(uid, capability text) Each helper ships with pgTAP tests in the same migration step: positive case, negative case, expired grant, revoked grant, wrong organization. +As built from V1-1 (contract `V1-1_OWNERS_ANIMALS.md` §9, BDR-073/074): the +perimeter is a workspace, not an organization. `private.caller_workspace_ids()` +(member, active profile, confirmed email; no parameter, `auth.uid()` only; +EXECUTE for `authenticated`) and `private.writable_workspace_ids()` (the same, +restricted to a write role; EXECUTE for nobody, called inside definer RPCs) +replace `is_org_*` and `can_view_client/animal` for V1-1 records. They avoid +RLS recursion by running as the table owner (`security definer`, owner +`postgres`, `search_path = ''`) rather than with `row_security = off`. No +helper or policy has a platform-role branch (D16). Every V1-1 table revokes +all privileges from `anon` and `service_role` (N7); `postgres` keeps +`BYPASSRLS` on the Supabase image and the service key stays a GoTrue admin +credential, residual paths named in the contract §6.3. + ### 4.2 Policy rules per domain (summary of §17.3) | Table family | SELECT | INSERT/UPDATE/DELETE | |---|---|---| | `profiles` | own row; admins via view | own row; roles only through RPC | -| `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place | +| `workspaces`, `workspace_members` (V1-1; cabinets extend them instead of `organizations`) | members, through `caller_workspace_ids()` | none through the API: personal workspace created by trigger; cabinet membership RPCs come with Step 10 | | `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) | | `animals` | `can_view_animal` | practitioner with an active relationship or grant | | `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC | diff --git a/docs/development/IMPLEMENTATION_PLAN.md b/docs/development/IMPLEMENTATION_PLAN.md index 32c24c64..ab07364b 100644 --- a/docs/development/IMPLEMENTATION_PLAN.md +++ b/docs/development/IMPLEMENTATION_PLAN.md @@ -354,8 +354,9 @@ ratified by the owner on 2026-10-25 (BDR-073): records attached to a workspace, one personal workspace per practitioner, cabinets later, no global client record shared between practitioners, no consents, grants, sharing, files or candidate matching. Contract and technical design: -`V1-1_OWNERS_ANIMALS.md` (business decisions approved; the SQL, RLS and RPC -design awaits the owner's validation before the first migration). Where the +`V1-1_OWNERS_ANIMALS.md` (business decisions approved; architecture and N1-N9 +validated 2026-10-25, BDR-074; V1-1.1 workspaces migration written and tested +in isolation, not applied to DEV). Where the text above differs (global clients, consents, grants, photo, files, deceased flow), the contract governs V1-1. diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 1d9bb47e..d14fa979 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -18,7 +18,8 @@ supabase/ │ ├─ 20261009100000_sheet_asset_storage.sql bucket anatomical-sheet-assets + read policy through the sheet │ ├─ 20261010100000_sheet_document_schema_v2.sql document schema 2: references, review_status, count_range checks │ ├─ 20261011100000_profiles_professional.sql practice_name, professional_title, siret -│ └─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md) +│ ├─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md) +│ └─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3) ├─ seed.sql LOCAL dev accounts + first owner (never run in prod) ├─ seed/anatomical-sheets/equine/ official equine sheet as a DRAFT, generated by `pnpm import:equine` │ ├─ legacy-sources/ the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input) @@ -181,11 +182,44 @@ Seed accounts (local only, password `LocalDev-only-password-1`): | `alice@faunosteo.local` | plain user | | `bob@faunosteo.local` | plain user | +### 3.3 Workspaces (V1-1.1, migration M1) + +Contract: `docs/development/V1-1_OWNERS_ANIMALS.md` §4, §8.1, §9. Every +account has exactly one personal workspace, created by the trigger +`profiles_create_personal_workspace` in the sign-up transaction (GoTrue → +`handle_new_auth_user` → profile → workspace + `holder` membership), through +the single write path `private.ensure_personal_workspace(uuid)` (one +statement, idempotent, race-safe). A deferred constraint trigger refuses at +commit a personal workspace without its holder or with any other member. +Reads: RLS through `private.caller_workspace_ids()` (member, active profile, +confirmed email, `auth.uid()` only). No API role writes either table; `anon` +and `service_role` hold no privilege on them. From M2 on, record tables use +the same helpers; the app passes its workspace id explicitly. + +M1 is written and tested on PGlite and on an isolated stack, not applied to +the DEV stack. Applying it there is an owner action, without a reset: + +```bash +pnpm supabase db dump --local -f ~/faunosteo-dev-schema-before-m1.sql # optional safety copy: schema +pnpm supabase db dump --local --data-only -f ~/faunosteo-dev-data-before-m1.sql # and data (DEV accounts are fictitious) +pnpm supabase migration list --local # 20261025100000 listed as local only +pnpm supabase migration up --local # applies the pending migration; its backfill creates the missing workspaces +pnpm db:test # the 12 pgTAP files on the DEV database (each rolled back) +pnpm db:types:check # no diff with the committed types +``` + +Afterwards every existing account has its workspace: in Studio's SQL editor, +`select count(*) from public.profiles p where not exists (select 1 from +public.workspaces w where w.personal_user_id = p.id)` returns 0. The migration is forward-only: undoing it means restoring +the dumps or writing a new migration. `pnpm db:reset` also applies it, but +replays the whole database from zero and loses the DEV accounts and data. + ## 4. Writing a migration 1. `pnpm supabase migration new ` creates `supabase/migrations/_.sql`. 2. A migration that adds a table adds, in the same file: RLS enable, explicit - `revoke all ... from public, anon, authenticated` then the exact grants, + `revoke all ... from public, anon, authenticated` (and `service_role` for + V1-1 record tables, contract N7) then the exact grants, separate SELECT / INSERT / UPDATE / DELETE policies, indexes, comments. 3. Add or extend a pgTAP file under `supabase/tests/`: the allowed path and every denied path (other user, anon, direct write bypassing an RPC). Scope diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md index 2097c86e..7bf1897f 100644 --- a/docs/development/TEST_STRATEGY.md +++ b/docs/development/TEST_STRATEGY.md @@ -12,6 +12,10 @@ not created; the real-stack e2e lives in `packages/supabase/tests/e2e`. No real-browser suite exists yet (TODO RR-8; V1-1 contract §12.5 proposes the first one, decision D14). No CI has ever run (BDR-047): "CI" in the tables means the prepared workflow. +V1-1.1 (2026-10-25): supabase vitest 44 (config test added), 12 pgTAP files +(`012_workspaces.sql`, 85 checks; 531 checks in all), also run on an isolated +real stack because the DEV stack stays untouched until the owner applies M1 +(`V1-1_OWNERS_ANIMALS.md` §8.1). ## 1. Layers diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index c5a9db44..60fcc75f 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -2,10 +2,13 @@ Status: business decisions approved by the owner on 2026-10-25 (brief « V1-1 : ratification des décisions métier et préparation de l'implémentation », -BDR-073). The technical design of Parts 8 to 10 and the choices of §13.2 and -§13.3 are proposals awaiting the owner's validation at the V1-1 preparation -checkpoint. Until that validation nothing is implemented: no migration, table, -RPC, policy, component, route or dependency, and Supabase DEV is untouched. +BDR-073). The architecture of Parts 4 to 9 and the technical choices N1 to N9 +were validated by the owner the same day (brief « Validation du contrat V1-1 +et autorisation de V1-1.1 Workspaces », BDR-074, §13.2), with the precisions +written into §5.3, §9 and §10. The interface choices of §13.3 stay proposals +until their UI steps. Only step V1-1.1 is authorised: migration M1 is written +and tested on an isolated database (§8.1); it is not applied to Supabase DEV, +and nothing of V1-1.2 to V1-1.6 exists. Branch: `feature/v1-1-clients-animals`. Roadmap position: `IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays the permission frame of Step 10. The file name keeps "OWNERS" so the documents @@ -106,10 +109,25 @@ clients shared between practitioners, no data visible from one practitioner to another, and no sharing between practitioners of a cabinet. Invitations and cabinet permissions are not built. -- Creation: a trigger after insert on `profiles` creates the personal workspace - and its `holder` membership; the migration backfills existing profiles. +- Creation: a controlled server initialisation, never a client call. A + trigger after insert on `profiles` creates the personal workspace and its + `holder` membership in the transaction that creates the account (GoTrue + inserts `auth.users`, `private.handle_new_auth_user` inserts the profile, + the trigger creates the workspace): a failure anywhere rolls back the whole + sign-up, so no account exists without its workspace and no workspace + without its account. The workspace exists before the email is confirmed and + stays unreadable until then (§9.1). The migration backfills existing + profiles through the same write path. - Uniqueness: `personal_user_id` is unique, so an account never has two - personal workspaces. + personal workspaces. The single write path inserts with `on conflict do + nothing` on that key: a retry, a replay or two concurrent calls create one + workspace and one membership, never two (§8.1). +- Consistency: a personal workspace has exactly one member, its account, as + `holder`. A deferred constraint trigger checks it at commit, whatever role + writes, so neither row survives alone and no other account can be added. +- Deletion: no archive state for a workspace. A personal workspace follows its + account: deleting an empty account deletes it; from M2 on, records refuse + the deletion (D9a, §7.2). - Context: every read and write names its workspace (RPC parameter or filter). The app reads its personal workspace once after sign-in and passes its id explicitly to the access layer; nothing reads a global "current workspace" @@ -222,9 +240,10 @@ Table `animal_client_relations`: |---|---| | `animal_id`, `client_id` | same workspace, enforced by composite foreign keys | | `relation_role` | `owner`, `keeper` or `contact` | -| `started_on` | date the relation began, when known; null when unknown | -| `ended_at` | null while the relation is current; set when the end is recorded (§13.2 N5) | +| `started_on` | date the relation began, when known; null when unknown; never filled by default | +| `ended_at` | null while the relation is current; set to the recording time when the end is recorded (§13.2 N5); a technical time, never shown as the end date | | `ended_on` | date the relation ended, when known; only on an ended relation; not before `started_on` | +| `voided_at` | null for a relation that existed; set when a relation entered by mistake is voided (§13.2 N4) | | `revision`, `created_at`, `updated_at` | server-maintained | Rules: @@ -252,15 +271,48 @@ Rules: keeps their other animals and appears as « ancien propriétaire » on the animal's page. Between the two actions the animal has two current owners or none, two valid states, so no atomic transfer operation is needed; -- ending is not deleting: an ended relation stays readable. Removing a - relation entered by mistake is §13.2 N4; a relation ended by mistake is - corrected the same way: removed, then created again as current. +- ending is not deleting: an ended relation stays readable as a former + relation, with its dates; +- voiding is not ending (N4): a relation that never existed (wrong client, + wrong animal, wrong role) is voided, never ended, so it never appears as a + former owner or keeper and no end date is invented for a period that never + was. The row keeps every value as entered, gains `voided_at`, and becomes + frozen (no end, no date change, no un-voiding); the audit log records who + voided it and when (§9.3). Voided relations are left out of every list, of + the current-relation index, of the derived values (§9.3) and of the current + cap; they count in the 200 total per animal, so a create-and-void loop + cannot grow a table without bound. No V1-1 screen shows them; the row stays + for the lifecycle contract (export, erasure) and incident work; +- an end recorded on the wrong relation is voided like any wrong relation, + then the right one is created. An end recorded with a wrong date is + corrected by `update_animal_client_relation`. Re-opening a relation whose + end never happened (clearing `ended_at`) is not offered in V1-1: the + relation is voided and created again as current, with the same start date; + the owner may ask for an explicit reopening at V1-1.4. + +Date rules (N5), all enforced by SQL CHECK except « not in the future », +which needs the clock and is checked by the RPCs (tomorrow's UTC date, §9.3): + +| Constraint | SQL | +|---|---| +| dates optional, no default | `started_on date`, `ended_on date`, both nullable, no `default` | +| plausible lower bound | `started_on >= '1900-01-01'`, `ended_on >= '1900-01-01'` | +| an end date only on an ended relation | `ended_on is null or ended_at is not null` | +| order when both are known | `started_on is null or ended_on is null or started_on <= ended_on` | +| a voided relation keeps its state | `voided_at` set only by the void RPC; every other write RPC refuses a voided row (`invalid_input`) | +| one current relation per triple | unique index on `(animal_id, client_id, relation_role) where ended_at is null and voided_at is null` | ### 5.4 Species (D5, approved) Reference data written by migration: the nine species of the contract (the existing `equine` row plus eight) and « Autre ». No other species is added. -Slugs, names and order are proposal §13.2 N1: +Slugs, names and order approved by the owner (§13.2 N1). Compatibility, +checked on 2026-10-25: species are rows of `public.species` (text `id`, +CHECK `^[a-z0-9][a-z0-9_-]{0,63}$`, which every slug below satisfies), never a +SQL enum, so M3 adds rows and freezes no new enumeration; the Rust core +carries `species_id` / `speciesId` as a free string (report identity, sheet +document, snapshot, sheet index) with no species list, and the only existing +id, `equine`, is kept unchanged: | `id` | `name_fr` | `name_en` | `sort_order` | |---|---|---|---| @@ -291,7 +343,7 @@ adds the refusal if it opens sheet creation. | Actor | Read | Create | Edit | Archive / restore | Delete | |---|---|---|---|---|---| -| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no, except a relation entered by mistake if §13.2 N4 is approved | +| Member with role `holder` of the workspace (V1-1: the account of its personal workspace), active profile, confirmed email | yes | yes | yes, active records only | yes | no; a relation entered by mistake is voided, never deleted (§13.2 N4) | | Future cabinet roles | defined by the cabinet step | | | | | | The same account with an unconfirmed email | no | no | no | no | no | | Another signed-in account | no | no | no | no | no | @@ -334,16 +386,26 @@ Residual technical paths, named so nobody believes them closed: credentials, bounded only by their custody; the exceptional-access contract covers them, with two follow-ups in §14 (a narrower worker credential, monitoring of GoTrue admin actions in `auth.audit_log_entries`); -- the table owner (`postgres`, not a superuser on Supabase) and any database +- the table owner (`postgres`, not a superuser on Supabase, but holding + `BYPASSRLS` on the Supabase image, checked on 17.11.0.004) and any database superuser read past RLS: maintenance, backup restore and incident response are exceptional privileged operations that the separate contract frames, justifies and audits before any publication. +Both paths were exercised on the isolated stack of V1-1.1 (§8.1): the service +key reads nothing through PostgREST (`permission denied`), yet it obtains a +session for any account through GoTrue's admin link generation and then reads +that account's workspace like its practitioner. Removing table privileges +narrows the direct path only; the residual risk stays on the security track +before production (RR-4), as the owner required (N7). + The existing audit policy lets platform owners and admins read audit rows. The -V1-1 rows carry the actor, resource ids, the action and the workspace id. Read -with the staff policy on profiles, that reveals per-practitioner volumes, -working hours and events such as « relation ended »: activity metadata, never -names or contacts. §13.2 N9 decides whether that stays visible. +V1-1 rows carry the actor, the resource id, the action, the time and the +workspace id. Read with the staff policy on profiles, that would reveal +per-practitioner volumes, working hours and events such as « relation ended »: +activity metadata, never names or contacts. N9 (§13.2): platform staff get no +general view of the private records, so M2 removes the `client.*`, `animal.*` +and `animal_client_relation.*` actions from `audit_logs_select_admin`. ### 6.4 Edits and finished bilans (C5, approved) @@ -454,23 +516,24 @@ term travels in a POST body), audit rows, application logs or error messages --- -## 8. SQL schema (proposed, not a migration) +## 8. SQL schema (M1 written, M2 and M3 proposed) Three forward-only migrations, one per data step, each with its pgTAP files, the regenerated `database.types.ts` and the census updates in the same branch -(plan principle 2). Timestamps are set when written. +(plan principle 2). Timestamps are set when written. M1 as built, with its +differences from the sketch below: §8.1. | Migration | Step | Content | |---|---|---| -| M1 `_workspaces.sql` | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS | +| M1 `20261025100000_workspaces.sql` (written, V1-1.1) | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS | | M2 `_clients.sql` | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS | | M3 `_animals_relations.sql` | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS | Why the correlation header in M1: `private.log_event` copies that request header verbatim today (foundation migration), the app never sends it, and PostgREST exposes every header, so a caller chooses the size of each -append-only audit row. V1-1 raises the audited write rate from 10 to 1 000 an -hour per account, which turns that into a storage risk. The change keeps the +append-only audit row. V1-1 raises the audited write rate to 1 000 an hour +per workspace (§10), which turns that into a storage risk. The change keeps the function's signature and callers. Sketch of the tables. `(c)` abbreviates the text rule of §5: @@ -580,6 +643,7 @@ create table public.animal_client_relations ( started_on date, -- >= 1900-01-01 (CHECK); not in the future (RPC) ended_on date, -- idem ended_at timestamptz, + voided_at timestamptz, -- set once by the void RPC (N4) create_request_id uuid not null, revision integer not null default 1, created_at timestamptz not null default now(), @@ -592,12 +656,14 @@ create table public.animal_client_relations ( check (ended_on is null or ended_at is not null), constraint animal_client_relations_dates_order check (started_on is null or ended_on is null or started_on <= ended_on), + constraint animal_client_relations_started_on_range check (started_on >= '1900-01-01'), + constraint animal_client_relations_ended_on_range check (ended_on >= '1900-01-01'), constraint animal_client_relations_create_request_unique unique (workspace_id, create_request_id) ); create unique index animal_client_relations_current_unique on public.animal_client_relations (animal_id, client_id, relation_role) - where ended_at is null; + where ended_at is null and voided_at is null; create index animal_client_relations_animal_idx on public.animal_client_relations (workspace_id, animal_id); create index animal_client_relations_client_idx @@ -644,6 +710,51 @@ follows French alphabetical order closely enough for a list. If the dictionary of `unaccent` ever changed, stored keys would differ from new ones until their rows are rewritten: recorded, low risk. +### 8.1 M1 as built (V1-1.1, 2026-10-25) + +`supabase/migrations/20261025100000_workspaces.sql`, tested by +`supabase/tests/012_workspaces.sql` (85 checks) and the census of +`001_schema.sql`. Differences from the sketch and from the plan, each +deliberate: + +| Point | Sketch or plan | As built | Why | +|---|---|---|---| +| Uniqueness of the personal workspace | inline `unique` | named constraint `workspaces_personal_user_unique` | the single write path targets it with `on conflict`, tests name it | +| Write path | trigger and backfill | both call `private.ensure_personal_workspace(uuid)`: workspace and holder membership inserted by one statement, `on conflict (personal_user_id) do nothing`, returns whether it created | one place for atomicity and idempotence; a concurrent call waits for the first commit, then writes nothing | +| Consistency workspace ↔ holder | not in the sketch | deferred constraint triggers `workspaces_personal_holder` and `workspace_members_personal_holder` on `private.check_personal_workspace()`: at commit, a personal workspace has exactly its account as `holder` | the owner asked for a coherence constraint between the workspace's account and its member; it holds for any writer, the table owner included; cabinets are not constrained | +| Trigger name | not named | `profiles_create_personal_workspace` | | +| `private.writable_workspace_ids()` | M1 | created in M1, unused until M2's write RPCs | the helper set of §9.1 ships and is tested once | +| Access layer `packages/supabase/src/workspaces.ts` | planned in V1-1.1 | deferred to V1-1.2 | no consumer before the clients access layer; the brief authorised M1 and its tests | +| `pnpm db:reset && pnpm db:test` | planned gate | not run: the owner kept the DEV stack untouched | replaced by an isolated real stack (below) | + +Not changed by M1: the privileges of existing tables. `service_role` keeps the +Supabase default privileges it holds today on `profiles`, `profile_roles` and +`assets` (only the new tables and `private.object_purge_queue` revoke it); +narrowing them is outside V1-1.1 and needs the owner's decision (N7). + +Isolated real-stack verification. A throwaway stack built from the DEV stack's +images (PostgreSQL 17.11.0.004, GoTrue v2.197.0, Storage v1.79.36, PostgREST +v16.4, Mailpit v1.31.3) on its own Docker network, ports on the loopback +only, no Docker volume, DEV containers untouched. Two runs: from zero (all +migrations then the seeds, as `supabase db reset`), and the DEV path (the +migrations before M1, the seeds and two accounts created through GoTrue, then +M1, whose backfill created the five missing workspaces). In both: the twelve +pgTAP files green (531 checks); real concurrent sessions (two creations of one +account's workspace: the second waited for the first commit and wrote +nothing; two racing backfills created 40 workspaces between them, no +duplicate; commits of a workspace without its holder or with a foreign member +refused at COMMIT; a rolled-back creation left nothing and the retry created +one); ten parallel GoTrue sign-ups each with one workspace; 33 HTTP checks +through GoTrue and PostgREST (sign-up without session, confirmation by the +mailed link, reads limited to the own workspace, `count=exact` of one, +refusals with `permission denied` for writes, for the anon key and for the +service key, `private` functions unreachable, deactivation effective on the +next request with the same token, the correlation header capped through a +real request, an empty account deleted by the GoTrue admin API taking its +workspace along, and the residual admin path of §6.3). The types were +generated from that database: the diff with the committed file is exactly the +M1 additions. + --- ## 9. Policies, helpers and RPCs @@ -654,10 +765,12 @@ rows are rewritten: recorded, low risk. |---|---|---|---| | `private.caller_workspace_ids()` | `setof uuid` | the single source of the access rule: workspaces where `auth.uid()` is a member, with an active profile and a confirmed email | `authenticated` (policies evaluate it) | | `private.writable_workspace_ids()` | `setof uuid` | `caller_workspace_ids()` restricted to a write role (V1-1: `holder`) | none (called inside RPCs) | -| `private.require_write_budget(p_actor uuid)` | `void` | raises P0001 `rate_limited` when the actor has 1 000 audit rows within the past hour or 5 000 within the past day (every audit row of the actor counts, on the existing `audit_logs_actor_idx`) | none | +| `private.require_write_budget(p_workspace_id uuid)` | `void` | raises P0001 `rate_limited` when the workspace has 1 000 audited writes within the past hour or 5 000 within the past day (N6: per workspace); the count and the write are serialised per workspace, never a bare count followed by an unprotected insert; the counter (rows counted by workspace, or a counter row per workspace and window) and its lock are fixed and documented with M2 | none | | `private.fold_text(p_value text)` | `text` | lower case without accents (`unaccent` with an explicit dictionary), declared immutable for the generated columns | `authenticated` (the invoker search folds the term) | -| `private.create_personal_workspace()` | trigger | after insert on `profiles`: workspace + `holder` membership | none | +| `private.ensure_personal_workspace(p_user_id uuid)` | `boolean` | the single write path: workspace and `holder` membership in one statement, `on conflict do nothing` on `personal_user_id`; true when it created (M1, §8.1) | none | +| `private.create_personal_workspace()` | trigger | after insert on `profiles`: calls `ensure_personal_workspace(new.id)` | none | | `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none | +| `private.check_personal_workspace()` | constraint trigger | deferred to commit: a personal workspace has exactly its account as `holder` (M1, §8.1) | none | All are `security definer` (except `fold_text`, a pure SQL function), `set search_path = ''`, `revoke all ... from public, anon, authenticated, @@ -711,7 +824,12 @@ Locks: create RPCs of clients and animals lock the workspace row (cap and insert serialised per workspace); every relation RPC locks the animal row `for update` then the client row `for share`, in that order; the archive RPCs lock their row `for update`. So caps, « both active » and « animal active » -cannot be passed by a concurrent call. +cannot be passed by a concurrent call. The write budget and the 100 000 +relations per workspace count rows that writes on different animals or +clients can add at the same time: they are counted under a lock that +serialises those writes per workspace (owner, N6: never a bare count followed +by an unprotected insert). M2 fixes that lock and the global lock order +(candidate: workspace row, then animal, then client) and documents it here. Parameters: dates, years and enum values arrive as `text` and are parsed inside the body, so a malformed value (« 2015-02-30 ») is answered `invalid_input` @@ -729,9 +847,9 @@ update that changes nothing writes nothing and returns the current revision. | `update_animal` | `animal_id`, `expected_revision`, the seven fields | `{revision}` | species active or unchanged; birth not in the future | `animal.updated` | | `set_animal_archived` | `animal_id`, `archived` | `{revision}` | same state: no write | `animal.archived` / `animal.restored` | | `create_animal_client_relation` | `animal_id`, `client_id`, `create_request_id`, `relation_role`, optional `started_on` | `{id, revision}` | both in one writable workspace (else 42501); both active; no current duplicate; at most 20 current and 200 total relations per animal and 100 000 per workspace (`limit_reached`); `started_on` not in the future | `animal_client_relation.created` | -| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` | -| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` | -| `delete_animal_client_relation` | `relation_id`, `expected_revision` | `void` | only if §13.2 N4 is approved; animal active; explicit confirmation in the UI | `animal_client_relation.deleted` | +| `end_animal_client_relation` | `relation_id`, `expected_revision`, optional `ended_on` | `{revision}` | animal active; not voided; current only (`already_ended`); sets `ended_at = now()`; `ended_on` not in the future and not before `started_on` | `animal_client_relation.ended` | +| `update_animal_client_relation` | `relation_id`, `expected_revision`, `started_on`, `ended_on` | `{revision}` | animal active; not voided; `ended_on` only on an ended relation; same date rules | `animal_client_relation.updated` | +| `void_animal_client_relation` | `relation_id`, `expected_revision` | `{revision}` | N4: a relation entered by mistake, current or ended; animal active; not already voided; sets `voided_at = now()`, changes no other column; explicit confirmation in the UI; no deletion | `animal_client_relation.voided` | The combined journeys use the atomic `create_animal` with its optional relation. « New client with a first animal » is two calls (`create_client`, @@ -741,9 +859,12 @@ after a failure resumes at the missing call and never creates a second client. "Not in the future" allows up to the UTC date of tomorrow (and its year for `birth_year`), so a date that is today in any time zone is accepted; the form -checks against the device's local date. Audit metadata is `{workspace_id}`, -plus `{relation_role}` on relation actions: no changed-field list, no name, -contact, date or search term. +checks against the device's local date. Audit rows (N9) hold the technical +ids (actor, resource, workspace in `metadata` as `{workspace_id}`), the +action and its time: no relation role, no changed-field list, no name, +contact, date or search term. A row exists only for a committed write, so its +presence is the result; refusals write nothing, which keeps a caller from +growing the log by failing on purpose. Read RPCs: `language plpgsql`, `security invoker` (RLS applies), stable, `set search_path = ''`, `#variable_conflict use_column`, parameters referenced @@ -840,8 +961,8 @@ migration. | Search term | 0 to 100 characters after trimming | a name or a phone fits; longer is noise | RPC | | Records per workspace | 20 000 clients, 20 000 animals, 100 000 relations | a full-time practitioner sees roughly 1 000 to 2 000 visits a year, so 20 000 animals is more than a decade of distinct animals for one person | RPC, under the workspace or animal row lock | | Relations per animal | 20 current, 200 in total | co-owners, keeper and contacts fit in 20; 200 covers decades of sales; the animal page reads them in one select | RPC | -| Write rate | 1 000 audited writes per actor per rolling hour and 5 000 per rolling day, every audit row of the actor counted on the existing `audit_logs_actor_idx` | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) | -| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to ids and the relation role | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) | +| Write rate | 1 000 audited writes per workspace per rolling hour and 5 000 per rolling day (owner, N6), counted under a per-workspace lock (§9.3); the counter is fixed with M2 | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) | +| Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to the workspace id (N9) | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) | | Concurrent writes | optimistic `revision` on every update; locks of §9.3 (workspace row for creates, animal then client row for relations, the row itself for archive); idempotent creates through `create_request_id` | no silent overwrite between two tabs or devices, no cap overshoot, no duplicate on retry | SQL and RPC | | Enumeration | random uuid ids; one 42501 `not_found` for an unknown and a forbidden id in every RPC, with no lock taken outside the caller's workspaces; reads filtered by RLS return empty, never an error that says "exists"; searches limited to one workspace of the caller; closed codes, never values, in errors | | RLS, RPC | | Login, sign-up, email sending | existing GoTrue limits (`[auth.rate_limit]` in `config.toml`); per-IP limits on `/rest/v1` at the production reverse proxy | | GoTrue; infrastructure (deploy notes) | @@ -879,7 +1000,7 @@ only, never a name or a search term. | `/app/clients/:clientId/edit` | client form | | `/app/animals` | list (name, species, breed, sex, current owners or « Propriétaire non renseigné »), search, species filter, « archivés » filter, « Nouvel animal » | | `/app/animals/new` | animal form with optional client selection or inline client creation; prefilled when opened from a client | -| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct (and remove per N4) a relation; edit, archive or restore | +| `/app/animals/:animalId` | identity, owners, keepers and contacts, current then former, with dates; add, end, correct the dates of, or void (N4) a relation; edit, archive or restore | | `/app/animals/:animalId/edit` | animal form | An unknown id and a forbidden id show the same « introuvable » screen. @@ -1083,19 +1204,22 @@ without the owner's go. | D15 | Principle of technical caps protecting the service, distinct from commercial quotas; thresholds proposed in §10 for validation before the RPCs | | Naming | Explicit nomenclature (§3); no generic `owner_id` | -### 13.2 Technical choices to validate before the first migration +### 13.2 Technical choices, decided by the owner on 2026-10-25 (BDR-074) -| Id | Question | Recommendation | Alternative | +The owner validated N1 to N9 with the precisions of the last column; they +prevail over the recommendation where they differ (N4, N6, N9). + +| Id | Question | Recommendation (preparation) | Owner decision, 2026-10-25 | |---|---|---|---| -| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | English nouns (`donkey`, `dog`…), which mixes two schemes since `equine` cannot be renamed (sheets and reports cite it) | -| N2 | First and last names for persons (D4a) | not in V1-1: no V1-1 screen reads them, search and sort use the display name, and adding two nullable columns later touches no row | add `given_name` and `family_name` now with the priority rule of §5.1 | -| N3 | Client notes (not in the ratified list; animal notes deferred) | defer, like animal notes: minimisation, and free text is where sensitive data slips in | keep `notes` (at most 2 000 characters, with a hint to record only what the care needs) | -| N4 | Removing a relation entered by mistake | allow an explicit, confirmed, audited deletion (`delete_animal_client_relation`): ending a wrong relation would record a false « ancien propriétaire », against the accuracy principle; this is an exception to plan principle 4 (no deletion of user data), limited to relations | a `voided_at` flag hidden from every read (keeps the wrong row, adds a filter everywhere), or no correction (end it) | -| N5 | Relation dates | `started_on` and `ended_on` as optional business dates, plus `ended_at` as the owner named it: null while current, the time the end was recorded, so an end with an unknown date never invents one | `ended_at` alone, which stores the recording time as the end date | -| N6 | Thresholds of §10 | as proposed | other values | -| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` (the precedent of the files migration): no direct read path. It does not close the GoTrue admin path (§6.3): the key stays a full-access credential, bounded by its custody | default Supabase privileges for `service_role` (bypasses RLS: one request reads every record) | -| N8 | Sex in the form | three explicit choices, none preselected: one tap more, but « inconnu » then means unknown, not skipped | « Inconnu » preselected | -| N9 | Audit rows read by platform owners and admins | exclude `client.*`, `animal.*` and `animal_client_relation.*` actions from `audit_logs_select_admin` now (a new policy condition in M2): what they reveal (§6.3) is activity of private records, which D16 keeps from staff; incident work reads them through the exceptional-access path | keep the existing policy until the exceptional-access contract | +| N1 | Species slugs, names and order (§5.4) | Latin adjectives like the existing `equine` (`asinine`, `canine`, `feline`, `bovine`, `caprine`, `ovine`, `porcine`, `leporine`) plus `other`; names Âne, Chien, Chat, Bovin, Chèvre, Mouton, Porc, Lapin, Autre | approved: exactly the nine species of the contract plus `other` with a required detail, no invented species, no historical anatomical id renamed; compatibility with the Rust model and Supabase checked before freezing anything (§5.4: rows, not an enum) | +| N2 | First and last names for persons (D4a) | not in V1-1 | approved: no separate names in V1-1; `display_name` is the required reference and the single source of truth | +| N3 | Client notes | defer, like animal notes (minimisation) | approved: deferred; no free-text field without an identified business need | +| N4 | Correcting a relation entered by mistake | an explicit, audited deletion | changed: a traceable logical voiding (`voided_at`, `void_animal_client_relation`), distinct from the normal end of a relation; a voided relation stops appearing as current or former without its history being falsified; `ended_on` never represents a period that never existed; minimised audit row (§5.3, §9.3); nothing built before V1-1.4 | +| N5 | Relation dates | optional `started_on` and `ended_on`, plus `ended_at` recording time | approved: both dates optional, never invented, ordered when both are known; an end date is not a deletion; SQL constraints written in §5.3 before V1-1.4 | +| N6 | Thresholds of §10 | as proposed, write budget per actor | approved as technical caps (not commercial quotas), with the write budget per workspace: 1 000 an hour, 5 000 a day; caps enforced consistently under concurrency, never a bare count then an unprotected insert; counters and locks documented when the RPCs are written; no quota system in V1-1.1 | +| N7 | Service key on the V1-1 tables | no table or RPC privilege for `service_role` | approved as minimisation, without claiming it removes every administrative path: effective grants examined, direct privileges removed, EXECUTE limited, definer owners checked, access tested for anon, authenticated and service_role; global Supabase privileges and existing tables unchanged without a specific decision; the GoTrue admin residual risk stays on the pre-production security track (§6.3) | +| N8 | Sex in the form | three explicit choices, none preselected | approved: nothing preselected, « Inconnu » chosen explicitly, a missing answer never turned into a value | +| N9 | Audit rows read by platform owners and admins | exclude the V1-1 actions from `audit_logs_select_admin` (M2) | approved: no general staff view of private client and animal data; audit rows limited to technical id, operation, time, result and bounded validated correlation ids; no name, contact, observation or business data; append-only kept; caller-controlled growth bounded (correlation cap in M1, §8.1) | ### 13.3 Interface decisions still open @@ -1132,8 +1256,8 @@ validates after V1-1.1 and after the first UI step; nothing merges into | Step | Content | |---|---| -| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012` | -| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards, N9 audit policy, field limits and parity test, access layer, real-stack e2e | +| V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), awaiting the owner's checkpoint; not applied to DEV | +| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, access layer (with the personal workspace read deferred from V1-1.1), real-stack e2e | | V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13) | | V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof | | V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry | @@ -1158,7 +1282,8 @@ Risks and dependencies: - DEV holds fictitious data only until the legal framing (§7.3); - `docs/design/README.md` places the mobile tab bar « with the first list screens », which D11 contradicts until the owner decides; -- the RPC surface grows by fourteen functions (RR-4 review); +- the RPC surface grows by fourteen functions (RR-4 review); N4 replaces the + delete RPC by `void_animal_client_relation`, so the count is unchanged; - the D-R7 chore for the existing forms reuses the V1-1 constants module; - no CI runs on the forge: every gate is local; - two old R5.6 rehearsal worktrees in an earlier session's scratchpad hold From 6bf69787cb72d58e4340ca9081ab6bb4ed95ddeb Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:08:33 +0100 Subject: [PATCH 05/60] chore(memory): BDR-074, EVAL-036, V1-1.1 journal, TODO, gate contract --- .claude/memory/decisions.md | 8 +++ .claude/memory/evals.md | 7 +++ .claude/memory/journal.md | 5 ++ .claude/tasks/TODO.md | 16 +++-- .../contracts/2026-10-25-v1-1-1-workspaces.md | 58 +++++++++++++++++++ 5 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 0fcf2fa3..f2a17de9 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -542,3 +542,11 @@ Decision (owner brief « V1-1 : ratification des décisions métier et préparat 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. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 8fbfff28..9994d592 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -253,3 +253,10 @@ Action: V1-1 contract §1 + §8.3 follow D-R7. Check every proposal against Anne 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. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index b0c1847d..6eb7069e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -400,3 +400,8 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp ## 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). diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 0fe1dd6a..7bbc728d 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -382,8 +382,16 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - [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) - - [ ] CHECKPOINT: owner validates the technical design (§8-§10) + N1-N9 + D10-D14, D17, U1-U3 → STOP until then (no migration, no dependency) - - [ ] V1-1.1 Workspaces foundation + - [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 + - [ ] fresh verifier + security audit on M1; `pnpm rust:check`, `pnpm check:all`; commits pushed; checkpoint report + - Deviation from the line below: `packages/supabase/src/workspaces.ts` deferred to V1-1.2 (no consumer before the clients access layer; brief authorises M1 + tests) - Objective: every account has exactly one personal workspace, readable by itself only, with the helpers every later table uses; audit rows no longer sized by the caller - Depends: checkpoint - Files: `supabase/migrations/_workspaces.sql`; `supabase/tests/012_workspaces.sql`; `supabase/tests/001_schema.sql` (tables, RLS, privileges, helper census); `packages/supabase/src/database.types.ts` (regenerated); `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspace`) + `src/index.ts`; `packages/supabase/tests/db/schema-types.test.ts`; config test (`enable_confirmations = true`); `docs/development/SUPABASE.md` @@ -396,7 +404,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack - Depends: V1-1.1; N2, N3, N6, N9 decided - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated - - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget` (1 000/h, 5 000/day); 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 + - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget(p_workspace_id)` (N6: per workspace, 1 000/h, 5 000/day, counted under a per-workspace lock; document counter + lock order in contract §9.3); 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 @@ -414,7 +422,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - Objective: animals with the ten species rows and the D6b birth model, relations with history, never across workspaces - Depends: V1-1.2; N1, N4, N5, N8 decided - Files: `supabase/migrations/_animals_relations.sql`; `supabase/tests/014_animals_relations.sql`; `field-limits.ts` + parity test; `packages/supabase/src/{animals,relations}.ts`; e2e extended; types regenerated - - Migration M3: species rows (9 + `other`), table comment; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations` (composite FKs, partial unique index, request ids); `create_animal` (optional initial relation), `update_animal`, `set_animal_archived`, `search_animals`, relation create/end/update/(delete if N4); `list_client_animals`, `client_archive_preview`; grants; RLS + - 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 diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md new file mode 100644 index 00000000..97fa6607 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-25-v1-1-1-workspaces.md @@ -0,0 +1,58 @@ +# CONTRACT: V1-1.1 Workspaces (M1), owner brief 2026-10-25 « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces » + +- branch `feature/v1-1-clients-animals`, base 5d734be; code commit 7bf4fb6 +- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §3, §4, §8 (M1 sketch), §9.1, §9.2, §9.5, §10, §12.1 +- diff under review: `git diff 5d734be..HEAD -- supabase packages/supabase` +- isolated real-stack evidence: `/tmp/claude-1000/-home-bchanot-Documents-faunosteo/55c1fd3e-1c33-4c77-8509-9cd3ca683a18/scratchpad/sandbox/` + (`RESULTS.md`; scripts `up.sh`, `tap.sh`, `concurrency.sh`, `http.mjs`, `down.sh`; containers `faunosteo_m1sandbox_*` + running, same images as the DEV stack). `tap.sh` and `node http.mjs` may be re-run (rolled back / unique emails); + `concurrency.sh` inserts fixed ids and runs once per sandbox. The DEV stack (`supabase_*_faunosteo`) must not be touched. + +## Clauses + +C1. **Scope.** One migration only, `supabase/migrations/20261025100000_workspaces.sql` (M1). No M2/M3 object (no clients, +animals, relations, species rows, unaccent, fold_text, write budget, write RPC), no React screen, no Playwright, no cabinet +feature, no change to crates/, no change to an existing migration file, no change to existing tables' grants or policies +except the `private.log_event` redefinition and the NOT VALID CHECK on `audit.audit_logs.correlation_id`. + +C2. **Model.** Enums `workspace_kind` = {personal} and `workspace_member_role` = {holder} only (no unused cabinet role); +`workspaces(id, kind, personal_user_id unique → profiles on delete cascade, created_at)` with CHECK personal ⇔ +personal_user_id not null; `workspace_members(workspace_id → workspaces cascade, user_id → profiles cascade, member_role, +created_at, PK (workspace_id, user_id))`, index on user_id. No `owner_id`; names as in contract §3. No archive column: +a workspace follows its account (deletion cascades; M2's `on delete restrict` will block it when records exist, D9a). + +C3. **Creation.** Server-side only: trigger after insert on `profiles` → `private.ensure_personal_workspace(uuid)`, which +writes workspace and holder membership in one statement with ON CONFLICT on the unique key (atomic, idempotent, race-safe); +`private.backfill_personal_workspaces()` covers existing profiles, idempotent, called once by the migration after the +trigger exists. No API role can call either. Works with the existing sign-up chain (GoTrue → `handle_new_auth_user` → +profile → workspace, one transaction); the workspace exists before email confirmation and stays unreadable until then. + +C4. **Integrity.** A deferred constraint trigger refuses at commit, whatever role writes: a personal workspace without its +holder, a foreign member in a personal workspace, the removal of the holder alone, the transfer of a personal workspace to +another account. Cabinets are not constrained. Error messages carry no id or personal data. + +C5. **Access rule.** `private.caller_workspace_ids()`: no parameter, `auth.uid()` only, member + `profiles.active` + +`auth.users.email_confirmed_at is not null`; security definer, `search_path = ''`, owner postgres, EXECUTE for +`authenticated` only. `private.writable_workspace_ids()`: same restricted to holder, EXECUTE for nobody. No platform-role +branch anywhere (D16). The private schema stays out of PostgREST (`config.toml` schemas = public, pinned by a test). + +C6. **RLS and privileges.** RLS enabled on both tables; one SELECT policy each, for `authenticated`, through +`caller_workspace_ids()`, no `using (true)`; no write policy. `revoke all` from public, anon, authenticated, service_role, +then column SELECT grants to authenticated only. Every new function: `revoke all` from public, anon, authenticated, +service_role; security definer; `search_path = ''`; owner postgres. Effective privileges tested for anon, authenticated and +service_role (SQL refusal 42501 distinct from an empty RLS result). + +C7. **Audit (N9).** `private.log_event` keeps its signature, privileges and callers; `x-correlation-id` stored only when it +matches `^[A-Za-z0-9-]{1,64}$`, else null; `audit_logs_correlation_id_format` CHECK NOT VALID on new rows. Append-only kept. + +C8. **Tests.** pgTAP `supabase/tests/012_workspaces.sql` covers: creation with the account, holder membership, failed sign-up +leaves nothing, idempotence, uniqueness, FK/PK refusals, backfill (trigger disabled) and its idempotence, the commit +invariant, A/B isolation, refusal for unconfirmed (then access after confirmation), deactivated, platform staff, anon, +service_role, parameter usurpation (filters by other ids, inserts naming others), direct calls of private functions, the +privilege/definer/owner census, the empty account deletion, the correlation cap. `001_schema.sql` census updated; +`schema-types.test.ts` and `database.types.ts` (regenerated, only M1 additions); `config.test.ts` pins +`enable_confirmations = true`, anonymous sign-ins off, schemas = public. All green on PGlite (`pnpm test:run`) and on the +isolated real stack from zero and on the upgrade path (sandbox `RESULTS.md`), with real concurrency evidence. + +C9. **Limits.** Nothing applied to the DEV stack; no merge into develop; main and release/0.2.0 untouched; no deploy; +no real personal data in fixtures. From 08abe42c48d62718ae61b9de0f7dbb84b4480160 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:57:09 +0100 Subject: [PATCH 06/60] test(supabase): isolated Supabase stack and real-stack suite for M1 scripts/db-sandbox.sh (pnpm db:sandbox): DEV images on an own network, loopback ports distinct from DEV, no volume, secrets generated outside Git; fresh and upgrade modes through the CLI's migration up, test db and gen types with --db-url. packages/supabase/tests/sandbox: M1 sign-up and confirmation, reads and refusals per role, residual GoTrue admin path, correlation cap, concurrent sessions. --- package.json | 1 + packages/supabase/package.json | 3 +- packages/supabase/tests/sandbox/stack.ts | 243 ++++++++++++++ .../tests/sandbox/workspaces.sandbox.ts | 317 ++++++++++++++++++ packages/supabase/vitest.sandbox.config.ts | 18 + scripts/db-sandbox.sh | 210 ++++++++++++ 6 files changed, 791 insertions(+), 1 deletion(-) create mode 100644 packages/supabase/tests/sandbox/stack.ts create mode 100644 packages/supabase/tests/sandbox/workspaces.sandbox.ts create mode 100644 packages/supabase/vitest.sandbox.config.ts create mode 100755 scripts/db-sandbox.sh diff --git a/package.json b/package.json index 17d5e60d..f68f9a2c 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "db:test": "bash scripts/supabase.sh test db", "db:types": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript > packages/supabase/src/database.types.ts", "db:types:check": "bash scripts/supabase.sh gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts", + "db:sandbox": "bash scripts/db-sandbox.sh", "assets:upload": "bash scripts/upload-sheet-assets.sh", "e2e:sheet-assets": "bash scripts/sheet-assets-e2e.sh", "build:preview": "SHEET_BUNDLE=draft pnpm --filter @faunosteo/app build", diff --git a/packages/supabase/package.json b/packages/supabase/package.json index 1f07f8f2..1c496f10 100644 --- a/packages/supabase/package.json +++ b/packages/supabase/package.json @@ -17,7 +17,8 @@ "test:run": "vitest run", "lint": "eslint . --max-warnings 0", "build": "tsc -p tsconfig.json --noEmit", - "test:e2e": "vitest run --config vitest.e2e.config.ts" + "test:e2e": "vitest run --config vitest.e2e.config.ts", + "test:sandbox": "vitest run --config vitest.sandbox.config.ts" }, "dependencies": { "@supabase/supabase-js": "^2.100.0", diff --git a/packages/supabase/tests/sandbox/stack.ts b/packages/supabase/tests/sandbox/stack.ts new file mode 100644 index 00000000..f687aa9a --- /dev/null +++ b/packages/supabase/tests/sandbox/stack.ts @@ -0,0 +1,243 @@ +/** + * Access to the throwaway stack of `pnpm db:sandbox` (scripts/db-sandbox.sh): + * real GoTrue, PostgREST and PostgreSQL sessions, never the DEV stack. The + * script passes the endpoints and the generated keys through the environment; + * the database password reaches `docker exec` through the environment too, + * never through a command argument. + */ +import { execFile } from 'node:child_process' +import { randomUUID } from 'node:crypto' + +const need = (name: string): string => { + const value = process.env[name] + if (!value) + throw new Error(`${name} missing: run through pnpm db:sandbox test`) + return value +} + +export const stack = { + container: need('SANDBOX_DB_CONTAINER'), + authUrl: need('SANDBOX_AUTH_URL'), + restUrl: need('SANDBOX_REST_URL'), + mailUrl: need('SANDBOX_MAIL_URL'), + anonKey: need('SANDBOX_ANON_KEY'), + serviceKey: need('SANDBOX_SERVICE_KEY'), +} +const PG_PASSWORD = need('SANDBOX_PG_PASSWORD') +export const PASSWORD = 'Sandbox-only-pw-1' + +/** One psql session as postgres; resolves with stdout (tuples only) or rejects with stderr. */ +export function sql(script: string): Promise { + return new Promise((resolve, reject) => { + const child = execFile( + 'docker', + [ + 'exec', + '-i', + '-e', + 'PGPASSWORD', + stack.container, + 'psql', + '-X', + '-q', + '-t', + '-A', + '-h', + '127.0.0.1', + '-U', + 'postgres', + '-d', + 'postgres', + '-v', + 'ON_ERROR_STOP=1', + ], + { + env: { ...process.env, PGPASSWORD: PG_PASSWORD }, + maxBuffer: 64 * 1024 * 1024, + }, + (error, stdout, stderr) => + error + ? reject(new Error(stderr || error.message)) + : resolve(stdout.trim()), + ) + child.stdin?.end(script) + }) +} + +/** Same session, but settles with the outcome instead of throwing (for refusal checks). */ +export async function sqlOutcome( + script: string, +): Promise<{ ok: boolean; out: string }> { + try { + return { ok: true, out: await sql(script) } + } catch (error) { + return { ok: false, out: (error as Error).message } + } +} + +export const uniqueEmail = (tag: string) => + `${tag}-${randomUUID().slice(0, 8)}@sandbox.local` + +async function authCall( + path: string, + body: unknown, + key = stack.anonKey, +): Promise { + return fetch(stack.authUrl + path, { + method: 'POST', + headers: { + apikey: stack.anonKey, + Authorization: `Bearer ${key}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + }) +} + +export async function signIn( + email: string, + password = PASSWORD, +): Promise<{ status: number; body: Record }> { + const res = await authCall('/token?grant_type=password', { email, password }) + return { + status: res.status, + body: (await res.json()) as Record, + } +} + +export interface Account { + id: string + email: string + token: string +} + +/** A confirmed account created by the admin API, signed in. */ +export async function confirmedAccount(tag: string): Promise { + const email = uniqueEmail(tag) + const res = await authCall( + '/admin/users', + { email, password: PASSWORD, email_confirm: true }, + stack.serviceKey, + ) + const user = (await res.json()) as { id: string } + const session = await signIn(email) + return { id: user.id, email, token: session.body.access_token as string } +} + +/** Public sign-up (no session until confirmation). */ +export async function signUp( + email: string, +): Promise<{ status: number; body: Record }> { + const res = await authCall('/signup', { email, password: PASSWORD }) + return { + status: res.status, + body: (await res.json()) as Record, + } +} + +/** Opens the confirmation link GoTrue mailed to this address; returns the HTTP status. */ +export async function confirmByMail(email: string): Promise { + const search = (await ( + await fetch( + `${stack.mailUrl}/api/v1/search?query=${encodeURIComponent('to:' + email)}`, + ) + ).json()) as { + messages: { ID: string }[] + } + const message = (await ( + await fetch(`${stack.mailUrl}/api/v1/message/${search.messages[0].ID}`) + ).json()) as { Text: string } + const link = message.Text.match( + new RegExp( + `${stack.authUrl.replace(/[.:/]/g, '\\$&')}/verify\\?[^\\s)\\]]+`, + ), + )?.[0] + if (!link) throw new Error('no confirmation link in the mail') + return (await fetch(link.replace(/&/g, '&'), { redirect: 'manual' })) + .status +} + +/** GoTrue admin link for any account: the residual path of contract §6.3. */ +export async function adminMagicLinkSession( + email: string, +): Promise { + const res = await authCall( + '/admin/generate_link', + { type: 'magiclink', email }, + stack.serviceKey, + ) + const body = (await res.json()) as { + action_link?: string + properties?: { action_link?: string } + } + const link = body.action_link ?? body.properties?.action_link + if (!link) return null + const verify = await fetch(link, { redirect: 'manual' }) + return new URLSearchParams( + (verify.headers.get('location') ?? '').split('#')[1] ?? '', + ).get('access_token') +} + +export async function adminDeleteUser(id: string): Promise { + const res = await fetch(`${stack.authUrl}/admin/users/${id}`, { + method: 'DELETE', + headers: { + apikey: stack.anonKey, + Authorization: `Bearer ${stack.serviceKey}`, + }, + }) + return res.status +} + +export interface RestResult { + status: number + body: unknown + text: string + headers: Headers +} + +/** A PostgREST request with the given bearer token (a user's, or the anon / service key). */ +export async function rest( + path: string, + token: string, + init: RequestInit = {}, +): Promise { + const res = await fetch(stack.restUrl + path, { + ...init, + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + ...(init.headers ?? {}), + }, + }) + const text = await res.text() + let body: unknown = text + try { + body = JSON.parse(text) + } catch { + // not JSON: keep the text + } + return { status: res.status, body, text, headers: res.headers } +} + +/** POST /rpc/: the way the app calls every RPC (terms stay out of URLs). */ +export function rpc( + fn: string, + args: Record, + token: string, + headers: Record = {}, +) { + return rest(`/rpc/${fn}`, token, { + method: 'POST', + body: JSON.stringify(args), + headers, + }) +} + +/** The PostgREST error code of a refusal, or null. */ +export const errorCode = (result: RestResult): string | null => + typeof result.body === 'object' && + result.body !== null && + 'code' in result.body + ? String((result.body as { code: unknown }).code) + : null diff --git a/packages/supabase/tests/sandbox/workspaces.sandbox.ts b/packages/supabase/tests/sandbox/workspaces.sandbox.ts new file mode 100644 index 00000000..6b1ce5df --- /dev/null +++ b/packages/supabase/tests/sandbox/workspaces.sandbox.ts @@ -0,0 +1,317 @@ +/** + * V1-1.1 workspaces (M1) on the real stack of `pnpm db:sandbox`: the sign-up + * chain, reads and refusals through PostgREST per role, the residual GoTrue + * admin path, the audit correlation cap, and concurrent sessions. + * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §4, §8.1, §9. + */ +import { randomUUID } from 'node:crypto' +import { + adminDeleteUser, + adminMagicLinkSession, + confirmByMail, + confirmedAccount, + errorCode, + rest, + rpc, + signIn, + signUp, + sql, + sqlOutcome, + stack, + uniqueEmail, + type Account, +} from './stack' + +const workspaceOf = (userId: string) => + sql(`select id from public.workspaces where personal_user_id = '${userId}'`) +const holderCount = (userId: string) => + sql(`select count(*) from public.workspaces w join public.workspace_members m + on m.workspace_id = w.id and m.user_id = w.personal_user_id and m.member_role = 'holder' + where w.personal_user_id = '${userId}'`) + +describe('sign-up and confirmation', () => { + it('creates the workspace in the sign-up transaction, readable only after confirmation', async () => { + const email = uniqueEmail('ws-signup') + const signup = await signUp(email) + expect(signup.status).toBe(200) + expect(signup.body.access_token).toBeUndefined() + const id = signup.body.id as string + expect(await holderCount(id)).toBe('1') + const early = await signIn(email) + expect(early.body.error_code).toBe('email_not_confirmed') + expect(await confirmByMail(email)).toBe(303) + const session = await signIn(email) + const read = await rest( + '/workspaces?select=id,kind,personal_user_id', + session.body.access_token as string, + ) + expect(read.body).toEqual([ + { id: await workspaceOf(id), kind: 'personal', personal_user_id: id }, + ]) + }) +}) + +describe('reads and refusals per role', () => { + let a: Account + let b: Account + let wA: string + let wB: string + + beforeAll(async () => { + a = await confirmedAccount('ws-a') + b = await confirmedAccount('ws-b') + wA = await workspaceOf(a.id) + wB = await workspaceOf(b.id) + }) + + it('each account reads exactly its workspace and membership', async () => { + expect((await rest('/workspaces?select=id', a.token)).body).toEqual([ + { id: wA }, + ]) + expect( + (await rest('/workspace_members?select=user_id,member_role', a.token)) + .body, + ).toEqual([{ user_id: a.id, member_role: 'holder' }]) + const head = await rest('/workspaces?select=id', b.token, { + method: 'HEAD', + headers: { Prefer: 'count=exact' }, + }) + expect(head.headers.get('content-range')).toBe('0-0/1') + }) + + it('naming another account or workspace returns nothing', async () => { + expect( + (await rest(`/workspaces?select=id&id=eq.${wA}`, b.token)).body, + ).toEqual([]) + expect( + (await rest(`/workspaces?select=id&personal_user_id=eq.${a.id}`, b.token)) + .body, + ).toEqual([]) + expect( + ( + await rest( + `/workspace_members?select=user_id&workspace_id=eq.${wA}`, + b.token, + ) + ).body, + ).toEqual([]) + }) + + it('refuses every write, for a user, the anon key and the service key', async () => { + const attempts: [string, string, RequestInit, number][] = [ + [ + '/workspaces', + b.token, + { + method: 'POST', + body: JSON.stringify({ kind: 'personal', personal_user_id: b.id }), + }, + 403, + ], + [ + '/workspace_members', + b.token, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wA, + user_id: b.id, + member_role: 'holder', + }), + }, + 403, + ], + [ + `/workspaces?id=eq.${wB}`, + b.token, + { method: 'PATCH', body: JSON.stringify({ personal_user_id: a.id }) }, + 403, + ], + [ + `/workspace_members?user_id=eq.${b.id}`, + b.token, + { method: 'DELETE' }, + 403, + ], + ['/workspaces?select=id', stack.anonKey, {}, 401], + ['/workspace_members?select=user_id', stack.anonKey, {}, 401], + ['/workspaces?select=id', stack.serviceKey, {}, 403], + [ + '/workspace_members', + stack.serviceKey, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wA, + user_id: b.id, + member_role: 'holder', + }), + }, + 403, + ], + ] + for (const [path, token, init, status] of attempts) { + const result = await rest(path, token, init) + expect([path, result.status, errorCode(result)]).toEqual([ + path, + status, + '42501', + ]) + expect(result.text).not.toContain(wA) + expect(result.text).not.toContain(a.id) + } + }) + + it('keeps the private helpers out of the API', async () => { + expect((await rpc('caller_workspace_ids', {}, b.token)).status).toBe(404) + expect( + (await rpc('ensure_personal_workspace', { p_user_id: b.id }, b.token)) + .status, + ).toBe(404) + const profile = await rest('/rpc/backfill_personal_workspaces', b.token, { + method: 'POST', + body: '{}', + headers: { 'Content-Profile': 'private' }, + }) + expect([profile.status, errorCode(profile)]).toEqual([406, 'PGRST106']) + }) + + it('cuts a deactivated account at its next request, same token', async () => { + await sql(`update public.profiles set active = false where id = '${b.id}'`) + expect((await rest('/workspaces?select=id', b.token)).body).toEqual([]) + await sql(`update public.profiles set active = true where id = '${b.id}'`) + expect((await rest('/workspaces?select=id', b.token)).body).toEqual([ + { id: wB }, + ]) + }) + + it('RESIDUAL (contract §6.3): the service key mints a session for any account through GoTrue admin', async () => { + const token = await adminMagicLinkSession(a.email) + expect(token).toBeTruthy() + expect((await rest('/workspaces?select=id', token ?? '')).body).toEqual([ + { id: wA }, + ]) + }) + + it('stores an oversized correlation header as null and keeps a short token', async () => { + const owner = await signIn( + 'owner@faunosteo.local', + 'LocalDev-only-password-1', + ) + const token = owner.body.access_token as string + const grant = await rpc( + 'grant_platform_role', + { target_user_id: b.id, role: 'support' }, + token, + { + 'x-correlation-id': 'x'.repeat(6000), + }, + ) + const revoke = await rpc( + 'revoke_platform_role', + { target_user_id: b.id, role: 'support', reason: 'sandbox' }, + token, + { + 'x-correlation-id': 'req-sandbox-01', + }, + ) + expect([grant.status, revoke.status]).toEqual([200, 200]) + expect( + await sql(`select string_agg(coalesce(correlation_id, 'NULL'), '|' order by occurred_at, action) + from audit.audit_logs where target_user_id = '${b.id}'`), + ).toBe('NULL|req-sandbox-01') + }) + + it('deletes an empty account through GoTrue admin with its workspace', async () => { + const e = await confirmedAccount('ws-e') + expect(await adminDeleteUser(e.id)).toBe(200) + expect( + await sql( + `select count(*) from public.workspace_members where user_id = '${e.id}'`, + ), + ).toBe('0') + expect(await workspaceOf(e.id)).toBe('') + }) +}) + +describe('concurrent sessions', () => { + const ids = Array.from({ length: 20 }, () => randomUUID()) + + beforeAll(async () => { + const values = ids + .map( + (id, i) => + `('${id}', 'race-${i}-${id.slice(0, 8)}@sandbox.local', now())`, + ) + .join(',') + await sql(`begin; + alter table public.profiles disable trigger profiles_create_personal_workspace; + insert into auth.users (id, email, email_confirmed_at) values ${values}; + alter table public.profiles enable trigger profiles_create_personal_workspace; + commit;`) + }) + + it('two sessions creating one workspace: the second waits for the commit, then writes nothing', async () => { + const first = sql( + `begin; select private.ensure_personal_workspace('${ids[0]}'); select pg_sleep(1.5); commit;`, + ) + await new Promise((resolve) => setTimeout(resolve, 400)) + const started = Date.now() + const second = await sql( + `select private.ensure_personal_workspace('${ids[0]}')`, + ) + expect(Date.now() - started).toBeGreaterThan(700) + expect(await first).toContain('t') + expect(second).toBe('f') + expect(await holderCount(ids[0])).toBe('1') + }) + + it('refuses at COMMIT a workspace without its holder or with a foreign member', async () => { + const alone = await sqlOutcome( + `begin; insert into public.workspaces (kind, personal_user_id) values ('personal', '${ids[1]}'); commit;`, + ) + expect(alone.ok).toBe(false) + expect(alone.out).toContain( + 'personal workspace must have exactly its account as holder', + ) + expect(await workspaceOf(ids[1])).toBe('') + const foreign = + await sqlOutcome(`begin; insert into public.workspace_members (workspace_id, user_id, member_role) + select id, '${ids[1]}', 'holder' from public.workspaces where personal_user_id = '${ids[0]}'; commit;`) + expect(foreign.ok).toBe(false) + }) + + it('a rolled-back creation leaves nothing; the retry creates once', async () => { + await sql( + `begin; select private.ensure_personal_workspace('${ids[1]}'); rollback;`, + ) + expect(await workspaceOf(ids[1])).toBe('') + expect( + await sql(`select private.ensure_personal_workspace('${ids[1]}')`), + ).toBe('t') + expect( + await sql(`select private.ensure_personal_workspace('${ids[1]}')`), + ).toBe('f') + }) + + it('two racing backfills create each missing workspace once', async () => { + const [x, y] = await Promise.all([ + sql('select private.backfill_personal_workspaces()'), + sql('select private.backfill_personal_workspaces()'), + ]) + expect(Number(x) + Number(y)).toBe(18) + const counts = await Promise.all(ids.map(holderCount)) + expect(counts.every((c) => c === '1')).toBe(true) + }) + + it('parallel GoTrue sign-ups each get one workspace', async () => { + const results = await Promise.all( + Array.from({ length: 8 }, () => signUp(uniqueEmail('ws-par'))), + ) + expect(results.map((r) => r.status)).toEqual(Array(8).fill(200)) + const counts = await Promise.all( + results.map((r) => holderCount(r.body.id as string)), + ) + expect(counts).toEqual(Array(8).fill('1')) + }) +}) diff --git a/packages/supabase/vitest.sandbox.config.ts b/packages/supabase/vitest.sandbox.config.ts new file mode 100644 index 00000000..dab31ea5 --- /dev/null +++ b/packages/supabase/vitest.sandbox.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'vitest/config' + +/** + * Real-stack suite on the throwaway stack of `pnpm db:sandbox` (tests/sandbox): + * HTTP through GoTrue and PostgREST, concurrent SQL sessions. Run only through + * `pnpm db:sandbox test`, which provides the endpoints and the generated keys; + * kept out of the default `test:run` include on purpose. + */ +export default defineConfig({ + test: { + environment: 'node', + globals: true, + include: ['tests/sandbox/**/*.sandbox.ts'], + fileParallelism: false, + testTimeout: 120_000, + hookTimeout: 120_000, + }, +}) diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh new file mode 100755 index 00000000..824e596c --- /dev/null +++ b/scripts/db-sandbox.sh @@ -0,0 +1,210 @@ +#!/usr/bin/env bash +# Throwaway Supabase stack for testing migrations without touching the DEV +# stack (docs/development/SUPABASE.md §5.1). Same images as the CLI stack, +# its own Docker network, ports published on 127.0.0.1 only and distinct from +# DEV, no Docker volume (the images declare none and nothing is mounted), so +# `down` removes only the containers and network named below. +# +# pnpm db:sandbox up fresh all migrations, then the seeds (= db reset) +# pnpm db:sandbox up upgrade migrations before , seeds, two +# GoTrue accounts, then `migration up` (= DEV path) +# pnpm db:sandbox test-db the pgTAP files (`supabase test db`) +# pnpm db:sandbox types [--check] generated types (write, or diff with the committed file) +# pnpm db:sandbox test packages/supabase/tests/sandbox (HTTP, concurrency) +# pnpm db:sandbox sql psql as postgres on stdin +# pnpm db:sandbox down +# +# Secrets are generated at `up` (random password, JWT secret, keys) into a +# 600 file under $FAUNOSTEO_SANDBOX_DIR (default ~/.cache/faunosteo-db-sandbox), +# outside the repository, and never printed. Every Supabase CLI call names the +# sandbox with --db-url: none may fall back to the local DEV database. +set -euo pipefail +cd "$(dirname "$0")/.." +. scripts/dev-env.sh + +PG_IMAGE=public.ecr.aws/supabase/postgres:17.11.0.004 +AUTH_IMAGE=public.ecr.aws/supabase/gotrue:v2.197.0 +REST_IMAGE=public.ecr.aws/supabase/postgrest:v16.4 +STORAGE_IMAGE=public.ecr.aws/supabase/storage-api:v1.79.36 +MAIL_IMAGE=public.ecr.aws/supabase/mailpit:v1.31.3 +NET=faunosteo_dbsandbox_net +DB=faunosteo_dbsandbox_db +AUTH=faunosteo_dbsandbox_auth +REST=faunosteo_dbsandbox_rest +STORAGE=faunosteo_dbsandbox_storage +MAIL=faunosteo_dbsandbox_mail +PORT_DB=57432 PORT_AUTH=57999 PORT_REST=57300 PORT_STORAGE=57500 PORT_MAIL=57025 +STATE="${FAUNOSTEO_SANDBOX_DIR:-$HOME/.cache/faunosteo-db-sandbox}" +SECRETS="$STATE/secrets.sh" +CLI=node_modules/.bin/supabase + +die() { echo "db-sandbox: $*" >&2; exit 1; } +load_secrets() { [ -f "$SECRETS" ] || die "not running (pnpm db:sandbox up fresh)"; . "$SECRETS"; } +db_url() { printf 'postgresql://postgres:%s@127.0.0.1:%s/postgres?sslmode=disable' "$SB_PW" "$PORT_DB"; } +sb_psql() { + docker exec -i -e PGPASSWORD="$SB_PW" "$DB" \ + psql -X -q -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 "$@" +} +wait_for() { + local what="$1"; shift + for _ in $(seq 1 120); do "$@" >/dev/null 2>&1 && return 0; sleep 1; done + die "timeout waiting for $what" +} + +new_secrets() { + mkdir -p "$STATE"; chmod 700 "$STATE" + ( umask 077; node -e ' + const c = require("crypto"); + const secret = c.randomBytes(32).toString("hex"); + const b64 = (o) => Buffer.from(JSON.stringify(o)).toString("base64url"); + const jwt = (p) => { const h = b64({ alg: "HS256", typ: "JWT" }), b = b64(p); + return h + "." + b + "." + c.createHmac("sha256", secret).update(h + "." + b).digest("base64url"); }; + const exp = Math.floor(Date.now() / 1000) + 30 * 86400; + console.log("SB_PW=" + c.randomBytes(24).toString("hex")); + console.log("SB_JWT_SECRET=" + secret); + console.log("SB_ANON_KEY=" + jwt({ role: "anon", iss: "db-sandbox", exp })); + console.log("SB_SERVICE_KEY=" + jwt({ role: "service_role", iss: "db-sandbox", exp })); + ' > "$SECRETS" ) +} + +# The role passwords the CLI sets at db start (its /etc/postgresql.schema.sql), +# reduced to what the sandbox services use. +DB_INIT='cat <<'"'"'EOF'"'"' > /etc/postgresql.schema.sql && exec docker-entrypoint.sh postgres -D /etc/postgresql +\set pgpass `echo "$PGPASSWORD"` +\set jwt_secret `echo "$JWT_SECRET"` +ALTER DATABASE postgres SET "app.settings.jwt_secret" TO :'"'"'jwt_secret'"'"'; +ALTER DATABASE postgres SET "app.settings.jwt_exp" TO '"'"'3600'"'"'; +ALTER USER postgres WITH PASSWORD :'"'"'pgpass'"'"'; +ALTER USER authenticator WITH PASSWORD :'"'"'pgpass'"'"'; +ALTER USER supabase_auth_admin WITH PASSWORD :'"'"'pgpass'"'"'; +ALTER USER supabase_storage_admin WITH PASSWORD :'"'"'pgpass'"'"'; +EOF' + +start_services() { + docker network create "$NET" >/dev/null + docker run -d --name "$DB" --network "$NET" -p 127.0.0.1:$PORT_DB:5432 \ + -e POSTGRES_PASSWORD="$SB_PW" -e PGPASSWORD="$SB_PW" -e POSTGRES_HOST=/var/run/postgresql \ + -e JWT_SECRET="$SB_JWT_SECRET" -e JWT_EXP=3600 \ + -e POSTGRES_INITDB_ARGS="--allow-group-access --locale-provider=icu --encoding=UTF-8 --icu-locale=en_US.UTF-8" \ + --entrypoint sh "$PG_IMAGE" -c "$DB_INIT" >/dev/null + wait_for "database roles" docker exec -e PGPASSWORD="$SB_PW" "$DB" \ + psql -h 127.0.0.1 -U supabase_auth_admin -d postgres -c 'select 1' + wait_for "database" docker exec -e PGPASSWORD="$SB_PW" "$DB" \ + psql -h 127.0.0.1 -U postgres -d postgres -c 'select 1' + + docker run -d --name "$MAIL" --network "$NET" -p 127.0.0.1:$PORT_MAIL:8025 "$MAIL_IMAGE" >/dev/null + docker run -d --name "$AUTH" --network "$NET" -p 127.0.0.1:$PORT_AUTH:9999 \ + -e GOTRUE_API_HOST=0.0.0.0 -e GOTRUE_API_PORT=9999 -e API_EXTERNAL_URL=http://127.0.0.1:$PORT_AUTH \ + -e GOTRUE_DB_DRIVER=postgres \ + -e GOTRUE_DB_DATABASE_URL="postgresql://supabase_auth_admin:$SB_PW@$DB:5432/postgres" \ + -e GOTRUE_DB_MIGRATIONS_PATH=/usr/local/etc/auth/migrations \ + -e GOTRUE_SITE_URL=http://127.0.0.1:5173 -e GOTRUE_DISABLE_SIGNUP=false \ + -e GOTRUE_JWT_SECRET="$SB_JWT_SECRET" -e GOTRUE_JWT_EXP=3600 \ + -e GOTRUE_JWT_AUD=authenticated -e GOTRUE_JWT_DEFAULT_GROUP_NAME=authenticated \ + -e GOTRUE_JWT_ADMIN_ROLES=service_role \ + -e GOTRUE_EXTERNAL_EMAIL_ENABLED=true -e GOTRUE_EXTERNAL_PHONE_ENABLED=false \ + -e GOTRUE_EXTERNAL_ANONYMOUS_USERS_ENABLED=false -e GOTRUE_MAILER_AUTOCONFIRM=false \ + -e GOTRUE_MAILER_URLPATHS_CONFIRMATION=http://127.0.0.1:$PORT_AUTH/verify \ + -e GOTRUE_SMTP_HOST="$MAIL" -e GOTRUE_SMTP_PORT=1025 \ + -e GOTRUE_SMTP_ADMIN_EMAIL=admin@sandbox.local -e GOTRUE_SMTP_SENDER_NAME=sandbox \ + -e GOTRUE_SMTP_MAX_FREQUENCY=1s -e GOTRUE_RATE_LIMIT_EMAIL_SENT=10000 \ + -e GOTRUE_RATE_LIMIT_VERIFY=10000 -e GOTRUE_RATE_LIMIT_TOKEN_REFRESH=10000 \ + -e GOTRUE_PASSWORD_MIN_LENGTH=12 "$AUTH_IMAGE" >/dev/null + wait_for "auth" curl -fsS http://127.0.0.1:$PORT_AUTH/health + docker run -d --name "$STORAGE" --network "$NET" -p 127.0.0.1:$PORT_STORAGE:5000 \ + -e ANON_KEY="$SB_ANON_KEY" -e SERVICE_KEY="$SB_SERVICE_KEY" -e AUTH_JWT_SECRET="$SB_JWT_SECRET" \ + -e DATABASE_URL="postgresql://supabase_storage_admin:$SB_PW@$DB:5432/postgres" \ + -e FILE_SIZE_LIMIT=52428800 -e STORAGE_BACKEND=file -e FILE_STORAGE_BACKEND_PATH=/mnt \ + -e TENANT_ID=stub -e STORAGE_S3_REGION=local -e GLOBAL_S3_BUCKET=stub \ + -e ENABLE_IMAGE_TRANSFORMATION=false -e IMAGE_TRANSFORMATION_ENABLED=false \ + -e S3_PROTOCOL_ENABLED=false -e DB_MIGRATIONS_FREEZE_AT= "$STORAGE_IMAGE" >/dev/null + wait_for "storage" curl -fsS http://127.0.0.1:$PORT_STORAGE/status +} + +start_rest() { + docker run -d --name "$REST" --network "$NET" -p 127.0.0.1:$PORT_REST:3000 \ + -e PGRST_DB_URI="postgresql://authenticator:$SB_PW@$DB:5432/postgres" \ + -e PGRST_DB_SCHEMAS=public -e PGRST_DB_EXTRA_SEARCH_PATH=public,extensions \ + -e PGRST_DB_ANON_ROLE=anon -e PGRST_JWT_SECRET="$SB_JWT_SECRET" -e PGRST_DB_MAX_ROWS=1000 \ + "$REST_IMAGE" >/dev/null + wait_for "postgrest" curl -fsS -o /dev/null http://127.0.0.1:$PORT_REST/ +} + +# The CLI's own migration runner, always against the sandbox URL. +migrate_up() { # workdir + "$CLI" --workdir "$1" migration up --db-url "$(db_url)" +} + +seed() { + local paths + paths="$(sed -n 's/^sql_paths = \[\(.*\)\]/\1/p' supabase/config.toml | tr -d '" ' | tr ',' ' ')" + for f in $paths; do + echo " seed ${f#./}"; sb_psql --single-transaction < "supabase/${f#./}" >/dev/null + done +} + +gotrue_accounts() { + curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/admin/users \ + -H "Authorization: Bearer $SB_SERVICE_KEY" -H 'Content-Type: application/json' \ + -d '{"email":"pre-confirmed@sandbox.local","password":"Sandbox-only-pw-1","email_confirm":true}' >/dev/null + curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/signup -H 'Content-Type: application/json' \ + -d '{"email":"pre-unconfirmed@sandbox.local","password":"Sandbox-only-pw-1"}' >/dev/null +} + +cmd_up() { + local mode="${1:-}" + docker ps -a --format '{{.Names}}' | grep -q '^faunosteo_dbsandbox_' && die "already up (pnpm db:sandbox down)" + new_secrets; . "$SECRETS" + start_services + case "$mode" in + fresh) + migrate_up . ; seed ;; + upgrade) + local version="${2:?upgrade needs the first new migration version, e.g. 20261025100000}" + # A CLI workdir holding only the migrations before ; kept in the + # state folder and refilled at each upgrade run (the CLI writes .temp there). + local base="$STATE/upgrade-base" + mkdir -p "$base/supabase/migrations" + rm -f "$base"/supabase/migrations/*.sql + cp supabase/config.toml "$base/supabase/" + for f in supabase/migrations/*.sql; do + if [ "$(basename "$f" | cut -d_ -f1)" \< "$version" ]; then cp "$f" "$base/supabase/migrations/"; fi + done + migrate_up "$base" + seed; gotrue_accounts + echo "== before: $(sb_psql -t -A -c 'select count(*) from public.profiles') profiles" + migrate_up . ;; + *) die "up fresh | up upgrade " ;; + esac + start_rest + echo "== sandbox up ($mode): db 127.0.0.1:$PORT_DB, auth :$PORT_AUTH, rest :$PORT_REST, mail :$PORT_MAIL" +} + +cmd_down() { + docker rm -f "$REST" "$STORAGE" "$AUTH" "$MAIL" "$DB" >/dev/null 2>&1 || true + docker network rm "$NET" >/dev/null 2>&1 || true + rm -f "$SECRETS" + echo "== sandbox removed" +} + +case "${1:-}" in + up) shift; cmd_up "$@" ;; + down) cmd_down ;; + test-db) load_secrets; "$CLI" test db --db-url "$(db_url)" ;; + types) + load_secrets + out="$("$CLI" gen types typescript --db-url "$(db_url)" --schema public | node_modules/.bin/prettier --parser typescript)" + if [ "${2:-}" = --check ]; then + diff <(printf '%s\n' "$out") packages/supabase/src/database.types.ts && echo "== types match" + else + printf '%s\n' "$out" > packages/supabase/src/database.types.ts; echo "== types written" + fi ;; + test) + load_secrets + SANDBOX_DB_CONTAINER="$DB" SANDBOX_PG_PASSWORD="$SB_PW" SANDBOX_AUTH_URL="http://127.0.0.1:$PORT_AUTH" \ + SANDBOX_REST_URL="http://127.0.0.1:$PORT_REST" SANDBOX_MAIL_URL="http://127.0.0.1:$PORT_MAIL" \ + SANDBOX_ANON_KEY="$SB_ANON_KEY" SANDBOX_SERVICE_KEY="$SB_SERVICE_KEY" \ + node_modules/.bin/pnpm --filter @faunosteo/supabase test:sandbox ;; + sql) load_secrets; sb_psql ;; + *) sed -n '2,23p' "$0"; exit 1 ;; +esac From 5ed1f01c377e7e121a42a6b9c158f6271ec85a06 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:57:09 +0100 Subject: [PATCH 07/60] docs(supabase): owner procedure for M1 on DEV and the isolated stack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SUPABASE.md §3.3: target, history, drift, accounts, backup with auth data and its check, migration up without reset, checks after; every command rehearsed on the isolated stack. §5.1: pnpm db:sandbox. --- docs/development/SUPABASE.md | 100 ++++++++++++++++++++++++++++++----- 1 file changed, 87 insertions(+), 13 deletions(-) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index d14fa979..cd26d4a6 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -196,23 +196,67 @@ confirmed email, `auth.uid()` only). No API role writes either table; `anon` and `service_role` hold no privilege on them. From M2 on, record tables use the same helpers; the app passes its workspace id explicitly. -M1 is written and tested on PGlite and on an isolated stack, not applied to -the DEV stack. Applying it there is an owner action, without a reset: +M1 is written and tested on PGlite and on the isolated stack (§5.1), not +applied to the DEV stack. Applying it there is an owner action, never run by +Claude, never with `db reset`, `db push`, `migration repair` or any +destructive command. Every step below was rehearsed on the isolated stack in +upgrade mode (`pnpm db:sandbox up upgrade 20261025100000`), with the sandbox +container name in place of `supabase_db_faunosteo`. Nothing below prints a +secret: the database password stays in the container's own environment. ```bash -pnpm supabase db dump --local -f ~/faunosteo-dev-schema-before-m1.sql # optional safety copy: schema -pnpm supabase db dump --local --data-only -f ~/faunosteo-dev-data-before-m1.sql # and data (DEV accounts are fictitious) -pnpm supabase migration list --local # 20261025100000 listed as local only -pnpm supabase migration up --local # applies the pending migration; its backfill creates the missing workspaces -pnpm db:test # the 12 pgTAP files on the DEV database (each rolled back) -pnpm db:types:check # no diff with the committed types +# 0. Target: the local CLI stack of this project, nothing remote. +pnpm supabase status # API on the DEV origin, DB on port 54322; no error +test ! -f supabase/.temp/project-ref && echo "no linked project" # nothing remote is linked +docker ps --filter name=supabase_db_faunosteo --format '{{.Names}} {{.Status}}' + +# 1. History: M1 must be the only pending migration. +pnpm supabase migration list --local # every row has local = remote, except 20261025100000 (remote empty) +pnpm db:types:check # the diff must be exactly the M1 objects (workspaces, workspace_members, + # workspace_kind, workspace_member_role): anything else = drift, STOP + +# 2. Existing accounts (the backfill creates one workspace per profile). +docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U postgres -d postgres -t -A \ + -c "select (select count(*) from auth.users) || '"'"' users, '"'"' || (select count(*) from public.profiles) || '"'"' profiles'"'"'"' +# users = profiles expected; note the profile count N + +# 3. Backup outside Git (includes auth.users and the migration history), then check it. +mkdir -p ~/faunosteo-backups && chmod 700 ~/faunosteo-backups +docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -h 127.0.0.1 -U postgres -d postgres -Fc' \ + > ~/faunosteo-backups/dev-before-m1.dump && chmod 600 ~/faunosteo-backups/dev-before-m1.dump +docker exec -i supabase_db_faunosteo pg_restore --list < ~/faunosteo-backups/dev-before-m1.dump \ + | grep -E "TABLE DATA (auth users|public profiles|supabase_migrations schema_migrations)" # three lines expected + +# 4. Apply M1 without reset (its backfill runs inside the migration). +pnpm supabase migration up --local # "Applying migration 20261025100000_workspaces.sql" ``` -Afterwards every existing account has its workspace: in Studio's SQL editor, -`select count(*) from public.profiles p where not exists (select 1 from -public.workspaces w where w.personal_user_id = p.id)` returns 0. The migration is forward-only: undoing it means restoring -the dumps or writing a new migration. `pnpm db:reset` also applies it, but -replays the whole database from zero and loses the DEV accounts and data. +After applying: + +```bash +pnpm supabase migration list --local # 20261025100000 now has its remote column +docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U postgres -d postgres -t -A -c " + select (select count(*) from public.profiles) || '"'"' profiles, '"'"' + || (select count(*) from public.workspaces) || '"'"' workspaces, '"'"' + || (select count(*) from public.workspace_members) || '"'"' members, '"'"' + || (select count(*) from public.profiles p where (select count(*) from public.workspaces w + where w.personal_user_id = p.id) <> 1) || '"'"' profiles without exactly one workspace'"'"'"' +# expected: N profiles, N workspaces, N members, 0 profiles without exactly one workspace +pnpm db:test # pgTAP 001-012 (grants, policies, reads); every file runs in + # begin ... rollback: rows unchanged (checked on the sandbox) +pnpm db:types:check # no diff +pnpm e2e:avatar # avatar flow and worker on the DEV stack (fictitious seed accounts) +``` + +Stop and report instead of continuing when: `migration list` shows another +pending migration or a remote-only one; `db:types:check` before step 4 shows +anything beyond the M1 objects; the dump check misses a line; `migration up` +applies anything else than `20261025100000`; any count after it differs from +the expectation. The backup restores into a scratch database (rehearsed: +every row back; `pg_restore --no-owner` prints privilege errors on +Supabase-managed objects, which do not affect the data). Storage file bytes +(avatars) live in the storage container's volume, not in the dump; M1 does not +touch them. ## 4. Writing a migration @@ -252,6 +296,36 @@ Two parity traps met so far: counts must be scoped to fixture ids (the real stack carries `seed.sql` rows), and `order by` on text must pin `collate "C"` (the real image sorts with a locale collation, PGlite with C). +### 5.1 Isolated stack (`pnpm db:sandbox`) + +A throwaway Supabase stack for migration steps, so the DEV stack is never +reset or migrated by a test (owner rule since V1-1.1). `scripts/db-sandbox.sh` +starts the images the CLI stack uses (PostgreSQL 17.11.0.004, GoTrue v2.197.0, +Storage v1.79.36, PostgREST v16.4, Mailpit v1.31.3, pinned in the script) on +the network `faunosteo_dbsandbox_net`, containers `faunosteo_dbsandbox_*`, +ports on 127.0.0.1 only and distinct from DEV (db 57432, auth 57999, rest +57300, storage 57500, mail 57025). Nothing is mounted and the images declare +no volume, so `down` removes the containers and the network by their literal +names and can never reach a `supabase_*_faunosteo` volume. The password, JWT +secret and keys are generated at each `up` into a 600 file under +`~/.cache/faunosteo-db-sandbox` (`FAUNOSTEO_SANDBOX_DIR`), outside the +repository, deleted by `down`, never printed. Works with rootless Docker. + +| Command | What it does | +|---|---| +| `pnpm db:sandbox up fresh` | every migration through `supabase migration up --db-url`, then the seeds of `config.toml` (as `db reset`) | +| `pnpm db:sandbox up upgrade ` | the migrations before ``, the seeds, two GoTrue accounts (confirmed, unconfirmed), then `migration up`: the path a DEV database takes | +| `pnpm db:sandbox test-db` | `supabase test db --db-url`: the pgTAP files on the real image (rows unchanged afterwards) | +| `pnpm db:sandbox types [--check]` | `supabase gen types --db-url ... --schema public` through Prettier, written or diffed with the committed file | +| `pnpm db:sandbox test` | `packages/supabase/tests/sandbox/*.sandbox.ts`: real GoTrue and PostgREST sessions, concurrent SQL sessions | +| `pnpm db:sandbox sql` / `down` | psql as postgres on stdin / remove the stack | + +Every CLI call passes `--db-url` with `sslmode=disable` (the sandbox has no +TLS); none can fall back to the local DEV database. Differences from the CLI +stack: no Kong (GoTrue and PostgREST are called directly), no Studio, no +realtime or edge runtime, and the database init keeps only the role +passwords the services use. + How a test impersonates a user (same technique in both runners): ```sql From 2c0531d638fe83c4f273eea273e49235b30351dc Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 20:57:10 +0100 Subject: [PATCH 08/60] chore(memory): LRN-080/081, V1-1.2 plan --- .claude/memory/learnings.md | 11 +++++++++++ .claude/tasks/TODO.md | 11 +++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index a4c4a8f4..caf2d7bb 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -573,3 +573,14 @@ Apply: any engine deletion (R-phases): map every case first, "oracle covers it" Context: R5.7 C6. After removing anatomy, `tsx` stayed in pnpm-lock.yaml as vite's optional peer (`optional: true`, no importer, no bin); `pnpm install` keeps it, `dedupe --check` clean; only hand edit/override would drop name. Contract said "tsx gone" → false NOT-MET. Pattern: prove use by `pnpm why -r` path + importer blocks + manifest/script/source census, not lockfile name grep. Never hand-edit lockfile or add override just to drop a name. Apply: dependency-removal clauses state objective (no declared dep, no script, no import), allow transitive/optional peers; census guards declared deps and `optional: true`. Owner validated 2026-10-25. + +## LRN-080 | 2026-10-25 | Throwaway Supabase stack beside DEV: test migrations, grants, sign-up and HTTP without touching DEV + +Shown on this host (Docker rootless, daemon ip 127.0.0.1, CLI 2.120, images postgres 17.11.0.004, gotrue v2.197.0, storage v1.79.36, postgrest v16.4, mailpit v1.31.3): own network + `-p 127.0.0.1:<57xxx>` per service, no `-v` (images declare no VOLUME → nothing to drop at teardown, `docker rm -f` of literal names suffices). db needs the CLI's role-password init (`/etc/postgresql.schema.sql` via `--entrypoint sh -c`); GoTrue + storage-api migrate their schemas on start; then the CLI's own runners take `--db-url`: `migration up` (records history like DEV), `test db` (pg_prove, rows unchanged), `gen types`. Upgrade path = `--workdir` copy holding the older migrations, then `migration up` from the repo. Real sessions prove what PGlite cannot: concurrency (two psql sessions), GoTrue sign-up/confirm via Mailpit API, PostgREST role refusals, residual GoTrue-admin path. `pg_dump -Fc` as postgres with the container's `$POSTGRES_PASSWORD` dumps auth data too; restore with `--no-owner` keeps every row, prints only managed-object privilege errors. +Limits: one host; not a hosted project; vault/realtime/edge absent; CLI may change bind/runner behaviour across versions. +Apply: `scripts/db-sandbox.sh` (`pnpm db:sandbox`) for every migration step; DEV changes stay owner actions. + +## LRN-081 | 2026-10-25 | `supabase gen types --db-url` to the sandbox needs `?sslmode=disable` + +CLI 2.120 against the sandbox PostgreSQL (127.0.0.1:57432, image 17.11.0.004, no TLS configured): without the option → `DbConnectError … tls error (The server does not support SSL connections)` and the error JSON lands on stdout (piping it to prettier gives a confusing syntax error). With `?sslmode=disable` the output matched the committed `database.types.ts` byte for byte for the pre-existing schema (same generator as `--local`). Same URL works for `migration up`, `test db`. Not checked: other CLI versions, TLS-enabled targets (keep TLS there). +Apply: any `--db-url` to a local non-TLS Postgres; never pipe generator output without checking the exit code. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 7bbc728d..50558785 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -390,7 +390,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - [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 - - [ ] fresh verifier + security audit on M1; `pnpm rust:check`, `pnpm check:all`; commits pushed; checkpoint report + - [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 @@ -400,7 +400,14 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - 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 + - [ ] V1-1.2 Clients data (owner brief 2026-10-25; isolated stack only; DEV untouched; stop at checkpoint before V1-1.3) + - [ ] 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 + - [ ] M2 `_clients.sql`: unaccent, `private.fold_text`, `client_kind`, `clients` (+ `create_request_digest` for divergent replays), budget table + `private.consume_write_budget` (UTC fixed hour/day windows, row lock, last lock taken), RPCs create/update/set_archived/search, N9 audit policy, grants, RLS + - [ ] pgTAP 013; harness loads unaccent; `field-limits.ts` + behavioural parity test; types; census + - [ ] 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 + - [ ] docs: contract (budget, divergent replay, search_clients without current_animal_count until M3), SUPABASE.md, TEST_STRATEGY, BDR-075, journal + - [ ] fresh verifier + security audit; rust:check, check:all; checkpoint + - Deviation: access layer `clients.ts` + workspace read move to V1-1.5 (first consumer; brief §6 scope lists no access layer) - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack - Depends: V1-1.1; N2, N3, N6, N9 decided - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated From 4adbfcb6086c34485862b56b25a9cc3a8e08eeab Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 21:09:45 +0100 Subject: [PATCH 09/60] feat(supabase): clients M2 with RPCs, search and per-workspace budget MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit V1-1.2 (contract V1-1_OWNERS_ANIMALS.md §5, §9, §10). public.clients (person or organization, display name only, optional contact, folded search keys), create/update/set_archived as definer RPCs (identical not_found, idempotent create with divergent-replay refusal, revisions, archive read-only), search_clients invoker with keyset pages and phone search, write budget per workspace in UTC hour/day windows under a row lock, 20 000-client cap, ids-only audit hidden from platform staff (N9), nothing for anon or service_role. pgTAP 013 (130), field-limits parity test, sandbox suite (concurrency, budget races, 20 000-client search), types regenerated. --- packages/supabase/src/database.types.ts | 136 +++++ packages/supabase/src/field-limits.ts | 45 ++ .../supabase/tests/db/field-limits.test.ts | 170 ++++++ packages/supabase/tests/db/harness.ts | 4 +- .../supabase/tests/db/schema-types.test.ts | 57 ++ .../supabase/tests/sandbox/clients.sandbox.ts | 538 ++++++++++++++++++ .../migrations/20261025110000_clients.sql | 514 +++++++++++++++++ supabase/tests/001_schema.sql | 2 +- supabase/tests/013_clients.sql | 452 +++++++++++++++ 9 files changed, 1916 insertions(+), 2 deletions(-) create mode 100644 packages/supabase/src/field-limits.ts create mode 100644 packages/supabase/tests/db/field-limits.test.ts create mode 100644 packages/supabase/tests/sandbox/clients.sandbox.ts create mode 100644 supabase/migrations/20261025110000_clients.sql create mode 100644 supabase/tests/013_clients.sql diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 37fab90b..42db1288 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -308,6 +308,84 @@ export type Database = { }, ] } + clients: { + Row: { + address_line1: string | null + address_line2: string | null + archived_at: string | null + city: string | null + country: string | null + create_request_digest: string + create_request_id: string + created_at: string + display_name: string + email: string | null + id: string + kind: Database['public']['Enums']['client_kind'] + name_key: string | null + phone: string | null + phone_digits: string | null + postal_code: string | null + revision: number + search_key: string | null + updated_at: string + workspace_id: string + } + ComputedFields: never + Insert: { + address_line1?: string | null + address_line2?: string | null + archived_at?: string | null + city?: string | null + country?: string | null + create_request_digest: string + create_request_id: string + created_at?: string + display_name: string + email?: string | null + id?: string + kind: Database['public']['Enums']['client_kind'] + name_key?: never + phone?: string | null + phone_digits?: never + postal_code?: string | null + revision?: number + search_key?: never + updated_at?: string + workspace_id: string + } + Update: { + address_line1?: string | null + address_line2?: string | null + archived_at?: string | null + city?: string | null + country?: string | null + create_request_digest?: string + create_request_id?: string + created_at?: string + display_name?: string + email?: string | null + id?: string + kind?: Database['public']['Enums']['client_kind'] + name_key?: never + phone?: string | null + phone_digits?: never + postal_code?: string | null + revision?: number + search_key?: never + updated_at?: string + workspace_id?: string + } + Relationships: [ + { + foreignKeyName: 'clients_workspace_id_fkey' + columns: ['workspace_id'] + isOneToOne: false + referencedRelation: 'workspaces' + referencedColumns: ['id'] + }, + ] + } profile_roles: { Row: { granted_at: string @@ -576,6 +654,22 @@ export type Database = { } Returns: string } + create_client: { + Args: { + address_line1?: string + address_line2?: string + city?: string + country?: string + create_request_id: string + display_name: string + email?: string + kind: string + phone?: string + postal_code?: string + workspace_id: string + } + Returns: Json + } create_sheet_draft: { Args: { change_note?: string @@ -636,6 +730,30 @@ export type Database = { } Returns: string } + search_clients: { + Args: { + after_id?: string + after_name_key?: string + archived?: boolean + page_size?: number + query?: string + workspace_id: string + } + Returns: { + archived_at: string + city: string + display_name: string + email: string + id: string + kind: Database['public']['Enums']['client_kind'] + name_key: string + phone: string + }[] + } + set_client_archived: { + Args: { archived: boolean; client_id: string } + Returns: Json + } set_sheet_visibility: { Args: { sheet_id: string @@ -643,6 +761,22 @@ export type Database = { } Returns: string } + update_client: { + Args: { + address_line1: string + address_line2: string + city: string + client_id: string + country: string + display_name: string + email: string + expected_revision: number + kind: string + phone: string + postal_code: string + } + Returns: Json + } } Enums: { asset_status: @@ -651,6 +785,7 @@ export type Database = { | 'clean' | 'rejected' | 'deleted' + client_kind: 'person' | 'organization' platform_role: 'owner' | 'admin' | 'moderator' | 'support' sheet_status: 'active' | 'archived' | 'deleted' sheet_version_status: 'draft' | 'published' | 'deprecated' @@ -791,6 +926,7 @@ export const Constants = { 'rejected', 'deleted', ], + client_kind: ['person', 'organization'], platform_role: ['owner', 'admin', 'moderator', 'support'], sheet_status: ['active', 'archived', 'deleted'], sheet_version_status: ['draft', 'published', 'deprecated'], diff --git a/packages/supabase/src/field-limits.ts b/packages/supabase/src/field-limits.ts new file mode 100644 index 00000000..1ce77e1d --- /dev/null +++ b/packages/supabase/src/field-limits.ts @@ -0,0 +1,45 @@ +/** + * Bounds and patterns of the V1-1 record fields, shared by the forms (Zod + * schemas, D-R7) and proven equal to the SQL CHECK constraints by + * tests/db/field-limits.test.ts (behaviour on the migrated schema, never by + * parsing SQL). Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §12.2. + * + * Lengths count code points, as PostgreSQL's char_length does: use + * codePointLength, never String.length (UTF-16 units) or Zod's .max() alone. + */ + +export const CLIENT_FIELD_LIMITS = { + displayName: 120, + email: 254, + addressLine: 120, + postalCode: 16, + city: 80, +} as const + +/** U+0000 to U+001F, U+007F to U+009F, U+2028, U+2029 (the SQL literal starts at U+0001: text cannot hold U+0000). */ +export const CONTROL_CHARACTERS = /[\u0000-\u001F\u007F-\u009F\u2028\u2029]/u + +/** Applied to the lower-cased value. JavaScript's \s is wider than SQL's, so the form refuses at least what SQL refuses. */ +export const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/u + +export const PHONE_E164_PATTERN = /^\+[1-9][0-9]{6,14}$/ + +export const COUNTRY_CODE_PATTERN = /^[A-Z]{2}$/ + +export function codePointLength(value: string): number { + return [...value].length +} + +/** + * The text rule of contract §5: 1 to max code points, no leading or trailing + * space (U+0020, as SQL btrim checks), no control character. + */ +export function isCleanText(value: string, max: number): boolean { + const length = codePointLength(value) + return ( + length >= 1 && + length <= max && + value === value.replace(/^ +| +$/g, '') && + !CONTROL_CHARACTERS.test(value) + ) +} diff --git a/packages/supabase/tests/db/field-limits.test.ts b/packages/supabase/tests/db/field-limits.test.ts new file mode 100644 index 00000000..b0fb0db6 --- /dev/null +++ b/packages/supabase/tests/db/field-limits.test.ts @@ -0,0 +1,170 @@ +/** + * D-R7 parity: the constants of src/field-limits.ts behave like the SQL CHECK + * constraints of public.clients, proven by inserting values at and past each + * bound into the migrated PGlite schema (contract §12.2). The form may refuse + * more than SQL (never less): a value the TypeScript rule accepts must be + * accepted by SQL, and the listed samples must agree both ways. + */ +import type { PGlite } from '@electric-sql/pglite' +import { + CLIENT_FIELD_LIMITS, + COUNTRY_CODE_PATTERN, + EMAIL_PATTERN, + PHONE_E164_PATTERN, + codePointLength, + isCleanText, +} from '../../src/field-limits' +import { createMigratedDatabase } from './harness' + +type Column = + | 'display_name' + | 'email' + | 'phone' + | 'address_line1' + | 'postal_code' + | 'city' + | 'country' + +let db: PGlite +let workspaceId: string + +async function sqlAccepts(column: Column, value: string): Promise { + const name = column === 'display_name' ? value : 'Parity' + const extra = column === 'display_name' ? '' : `, ${column}` + await db.exec('begin') + try { + await db.query( + `insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest${extra}) + values ($1, 'person', $2, gen_random_uuid(), '\\x00'${column === 'display_name' ? '' : ', $3'})`, + column === 'display_name' + ? [workspaceId, name] + : [workspaceId, name, value], + ) + return true + } catch { + return false + } finally { + await db.exec('rollback') + } +} + +const textSamples = (max: number): string[] => [ + 'a'.repeat(max), + 'a'.repeat(max + 1), + 'é'.repeat(max), + 'é'.repeat(max + 1), + '𝄞'.repeat(max), + '𝄞'.repeat(max + 1), + '', + ' a', + 'a ', + 'a\tb', + 'a\u007Fb', + 'a\u0085b', + 'a\u2028b', + 'a\u2029b', + '\u00A0a', +] + +const textFields: [Column, number][] = [ + ['display_name', CLIENT_FIELD_LIMITS.displayName], + ['address_line1', CLIENT_FIELD_LIMITS.addressLine], + ['postal_code', CLIENT_FIELD_LIMITS.postalCode], + ['city', CLIENT_FIELD_LIMITS.city], +] + +const tsEmail = (v: string) => + isCleanText(v, CLIENT_FIELD_LIMITS.email) && + v === v.toLowerCase() && + EMAIL_PATTERN.test(v) +const emailSamples = [ + 'a@b.co', + 'A@b.co', + 'a b@c.de', + 'a@b', + '@b.co', + 'a@@b.co', + 'a'.repeat(246) + '@ex.test', + 'a'.repeat(247) + '@ex.test', + 'é@exemple.fr', +] +/** JavaScript's \s covers U+00A0, PostgreSQL's does not: the form refuses, SQL would accept. */ +const emailTsStricter = ['a\u00A0b@c.de'] + +describe('field limits match the SQL constraints (D-R7)', () => { + beforeAll(async () => { + db = await createMigratedDatabase() + await db.exec(`insert into auth.users (id, email, email_confirmed_at) + values ('7a000000-0000-0000-0000-000000000001', 'parity@test.local', now())`) + const { rows } = await db.query<{ id: string }>( + `select id from public.workspaces where personal_user_id = '7a000000-0000-0000-0000-000000000001'`, + ) + workspaceId = rows[0].id + }) + + afterAll(async () => { + await db?.close() + }) + + it('counts code points like char_length', () => { + expect(codePointLength('𝄞é')).toBe(2) + expect('𝄞é'.length).toBe(3) + }) + + it.each(textFields)( + '%s: the text rule and its bound %i agree', + async (column, max) => { + for (const value of textSamples(max)) { + expect([ + column, + JSON.stringify(value).slice(0, 24), + await sqlAccepts(column, value), + ]).toEqual([ + column, + JSON.stringify(value).slice(0, 24), + isCleanText(value, max), + ]) + } + }, + ) + + it('email: bound, lower case and pattern agree', async () => { + for (const value of emailSamples) { + expect([value.slice(0, 24), await sqlAccepts('email', value)]).toEqual([ + value.slice(0, 24), + tsEmail(value), + ]) + } + for (const value of emailTsStricter) { + expect(tsEmail(value)).toBe(false) + } + }) + + it('phone: E.164 agrees', async () => { + const samples = [ + '+33612345678', + '+1234567', + '+123456', + '+123456789012345', + '+1234567890123456', + '0612345678', + '+0612345678', + '+33 612345678', + ] + for (const value of samples) { + expect([value, await sqlAccepts('phone', value)]).toEqual([ + value, + PHONE_E164_PATTERN.test(value), + ]) + } + }) + + it('country: ISO alpha-2 upper case agrees', async () => { + for (const value of ['FR', 'fr', 'FRA', 'F1', 'F']) { + expect([value, await sqlAccepts('country', value)]).toEqual([ + value, + COUNTRY_CODE_PATTERN.test(value), + ]) + } + }) +}) diff --git a/packages/supabase/tests/db/harness.ts b/packages/supabase/tests/db/harness.ts index 228a6540..80006b5e 100644 --- a/packages/supabase/tests/db/harness.ts +++ b/packages/supabase/tests/db/harness.ts @@ -11,6 +11,7 @@ import { resolve, join } from 'node:path' import { fileURLToPath } from 'node:url' import { PGlite } from '@electric-sql/pglite' import { pgtap } from '@electric-sql/pglite/pgtap' +import { unaccent } from '@electric-sql/pglite/contrib/unaccent' const here = fileURLToPath(new URL('.', import.meta.url)) export const repoRoot = resolve(here, '../../../..') @@ -41,7 +42,8 @@ export async function listSeeds(): Promise { /** Boots PGlite, installs the shim and applies all migrations. */ export async function createMigratedDatabase(): Promise { - const db = await PGlite.create({ extensions: { pgtap } }) + // unaccent: created by the clients migration (search keys), as on the real image. + const db = await PGlite.create({ extensions: { pgtap, unaccent } }) await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8')) // Same placement as `supabase test db`: pgTAP lives in extensions, out of public. await db.exec('create extension if not exists pgtap with schema extensions;') diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 36aa8f45..287a82af 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -85,6 +85,28 @@ const expectedColumns = { 'status', 'updated_at', ], + clients: [ + 'address_line1', + 'address_line2', + 'archived_at', + 'city', + 'country', + 'create_request_digest', + 'create_request_id', + 'created_at', + 'display_name', + 'email', + 'id', + 'kind', + 'name_key', + 'phone', + 'phone_digits', + 'postal_code', + 'revision', + 'search_key', + 'updated_at', + 'workspace_id', + ], profile_roles: [ 'granted_at', 'granted_by', @@ -139,6 +161,19 @@ const expectedFunctionArgs = { complete_avatar_job: ['asset_id', 'byte_size', 'lock_token', 'sha256'], confirm_asset_upload: ['asset_id'], confirm_sheet_asset_upload: ['asset_id'], + create_client: [ + 'address_line1', + 'address_line2', + 'city', + 'country', + 'create_request_id', + 'display_name', + 'email', + 'kind', + 'phone', + 'postal_code', + 'workspace_id', + ], create_anatomical_sheet: [ 'description', 'document', @@ -163,7 +198,29 @@ const expectedFunctionArgs = { remove_avatar: [], restore_anatomical_sheet: ['sheet_id'], revoke_platform_role: ['reason', 'role', 'target_user_id'], + search_clients: [ + 'after_id', + 'after_name_key', + 'archived', + 'page_size', + 'query', + 'workspace_id', + ], + set_client_archived: ['archived', 'client_id'], set_sheet_visibility: ['sheet_id', 'visibility'], + update_client: [ + 'address_line1', + 'address_line2', + 'city', + 'client_id', + 'country', + 'display_name', + 'email', + 'expected_revision', + 'kind', + 'phone', + 'postal_code', + ], } as const satisfies FunctionArgs // A function without arguments is generated as `Record` diff --git a/packages/supabase/tests/sandbox/clients.sandbox.ts b/packages/supabase/tests/sandbox/clients.sandbox.ts new file mode 100644 index 00000000..c1a35d18 --- /dev/null +++ b/packages/supabase/tests/sandbox/clients.sandbox.ts @@ -0,0 +1,538 @@ +/** + * V1-1.2 clients (M2) on the real stack of `pnpm db:sandbox`: RPCs through + * PostgREST with real sessions per role, identical refusals, search without + * leaks, then concurrent writes (creates, replays, revisions, archive races, + * budget at its limit, lock contention) and the search time on 20 000 clients. + * Contract: docs/development/V1-1_OWNERS_ANIMALS.md §9, §10, §12. + */ +import { randomUUID } from 'node:crypto' +import { + confirmedAccount, + errorCode, + rest, + rpc, + sql, + stack, + type Account, + type RestResult, +} from './stack' + +const workspaceOf = (userId: string) => + sql(`select id from public.workspaces where personal_user_id = '${userId}'`) +const budgetOf = (ws: string) => + sql( + `select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = '${ws}'), 'none')`, + ) + +function create( + account: Account, + ws: string, + fields: Record, + requestId = randomUUID(), +) { + return rpc( + 'create_client', + { + workspace_id: ws, + create_request_id: requestId, + kind: 'person', + ...fields, + }, + account.token, + ) +} +const idOf = (result: RestResult) => (result.body as { id: string }).id +const fullUpdate = ( + clientId: string, + revision: number, + displayName: string, + city: string | null = null, +) => ({ + client_id: clientId, + expected_revision: revision, + kind: 'person', + display_name: displayName, + email: null, + phone: null, + address_line1: null, + address_line2: null, + postal_code: null, + city, + country: null, +}) +/** The error as the client sees it: status, code, message, details, hint. */ +const shape = (result: RestResult) => { + const body = result.body as Record + return [ + result.status, + body.code, + body.message, + body.details ?? null, + body.hint ?? null, + ] +} + +describe('clients through PostgREST, per role', () => { + let a: Account + let b: Account + let wA: string + let wB: string + let lac: string + + beforeAll(async () => { + a = await confirmedAccount('cl-a') + b = await confirmedAccount('cl-b') + wA = await workspaceOf(a.id) + wB = await workspaceOf(b.id) + const created = await create(a, wA, { + kind: 'organization', + display_name: 'Écurie du Lac', + email: 'Contact@Ecurie-Lac.test', + phone: '+33612345678', + city: 'Lyon', + }) + expect(created.status).toBe(200) + lac = idOf(created) + }) + + it('A creates, reads, searches with POST, updates and archives', async () => { + const row = await rest( + `/clients?select=id,kind,display_name,email,revision&id=eq.${lac}`, + a.token, + ) + expect(row.body).toEqual([ + { + id: lac, + kind: 'organization', + display_name: 'Écurie du Lac', + email: 'contact@ecurie-lac.test', + revision: 1, + }, + ]) + const found = await rpc( + 'search_clients', + { workspace_id: wA, query: 'ecu' }, + a.token, + ) + expect((found.body as { id: string }[]).map((r) => r.id)).toEqual([lac]) + const phone = await rpc( + 'search_clients', + { workspace_id: wA, query: '06 12' }, + a.token, + ) + expect((phone.body as { id: string }[]).map((r) => r.id)).toEqual([lac]) + expect( + ( + await rpc( + 'update_client', + fullUpdate(lac, 1, 'Écurie du Lac', 'Annecy'), + a.token, + ) + ).body, + ).toEqual({ revision: 2 }) + expect( + ( + await rpc( + 'set_client_archived', + { client_id: lac, archived: true }, + a.token, + ) + ).body, + ).toEqual({ revision: 3 }) + expect( + ( + await rpc( + 'set_client_archived', + { client_id: lac, archived: false }, + a.token, + ) + ).body, + ).toEqual({ revision: 4 }) + }) + + it('B gets nothing of A: reads, counts, search, and the same refusal as for an unknown id', async () => { + expect( + (await rest(`/clients?select=id&id=eq.${lac}`, b.token)).body, + ).toEqual([]) + const head = await rest( + `/clients?select=id&workspace_id=eq.${wA}`, + b.token, + { method: 'HEAD', headers: { Prefer: 'count=exact' } }, + ) + expect(head.headers.get('content-range')).toBe('*/0') + expect( + (await rpc('search_clients', { workspace_id: wA, query: '' }, b.token)) + .body, + ).toEqual([]) + const foreign = await rpc('update_client', fullUpdate(lac, 4, 'X'), b.token) + const unknown = await rpc( + 'update_client', + fullUpdate(randomUUID(), 4, 'X'), + b.token, + ) + expect(shape(foreign)).toEqual(shape(unknown)) + expect(shape(foreign)).toEqual([403, '42501', 'not_found', null, null]) + expect(shape(await create(b, wA, { display_name: 'X' }))).toEqual( + shape(await create(b, randomUUID(), { display_name: 'X' })), + ) + expect( + shape( + await rpc( + 'set_client_archived', + { client_id: lac, archived: true }, + b.token, + ), + ), + ).toEqual([403, '42501', 'not_found', null, null]) + }) + + it('refuses direct writes, the anon key and the service key; error bodies carry no value', async () => { + const attempts: [string, string, RequestInit, number][] = [ + [ + '/clients', + b.token, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wB, + kind: 'person', + display_name: 'Direct', + }), + }, + 403, + ], + [ + `/clients?id=eq.${lac}`, + a.token, + { method: 'PATCH', body: JSON.stringify({ display_name: 'Direct' }) }, + 403, + ], + [`/clients?id=eq.${lac}`, a.token, { method: 'DELETE' }, 403], + ['/clients?select=id', stack.anonKey, {}, 401], + [ + '/rpc/search_clients', + stack.anonKey, + { method: 'POST', body: JSON.stringify({ workspace_id: wA }) }, + 401, + ], + ['/clients?select=id', stack.serviceKey, {}, 403], + [ + '/rpc/create_client', + stack.serviceKey, + { + method: 'POST', + body: JSON.stringify({ + workspace_id: wA, + create_request_id: randomUUID(), + kind: 'person', + display_name: 'S', + }), + }, + 403, + ], + ] + for (const [path, token, init, status] of attempts) { + const result = await rest(path, token, init) + expect([path, result.status, errorCode(result)]).toEqual([ + path, + status, + '42501', + ]) + expect(result.text).not.toContain('Lac') + } + const invalid = await create(a, wA, { + display_name: 'Name', + email: 'secret-value-not-an-email', + }) + expect(shape(invalid)).toEqual([400, 'P0001', 'invalid_input', null, null]) + expect(invalid.text).not.toContain('secret-value') + }) + + it('cuts an unconfirmed or deactivated account', async () => { + await sql(`update public.profiles set active = false where id = '${a.id}'`) + expect((await rest('/clients?select=id', a.token)).body).toEqual([]) + expect( + shape(await rpc('update_client', fullUpdate(lac, 4, 'X'), a.token)), + ).toEqual([403, '42501', 'not_found', null, null]) + await sql(`update public.profiles set active = true where id = '${a.id}'`) + await sql( + `update auth.users set email_confirmed_at = null where id = '${a.id}'`, + ) + expect((await rest('/clients?select=id', a.token)).body).toEqual([]) + await sql( + `update auth.users set email_confirmed_at = now() where id = '${a.id}'`, + ) + expect((await rest('/clients?select=id', a.token)).body).toEqual([ + { id: lac }, + ]) + }) + + it('hides client audit rows from the platform owner (N9)', async () => { + expect( + await sql( + `select count(*) from audit.audit_logs where resource_id = '${lac}'`, + ), + ).toBe('4') + // audit is not exposed through PostgREST; the owner's view is its RLS-filtered SQL view. + const ownerId = await sql( + `select id from auth.users where email = 'owner@faunosteo.local'`, + ) + const asOwner = await sql(`begin; set local role authenticated; + select set_config('request.jwt.claims', '{"sub":"${ownerId}","role":"authenticated"}', true); + select count(*) from audit.audit_logs where resource_id = '${lac}'; commit;`) + expect(asOwner.split('\n').pop()).toBe('0') + }) +}) + +describe('concurrent writes', () => { + let a: Account + let wA: string + + beforeAll(async () => { + a = await confirmedAccount('cl-race') + wA = await workspaceOf(a.id) + }) + + it('20 parallel creates in one workspace all land, counted once each', async () => { + const results = await Promise.all( + Array.from({ length: 20 }, (_, i) => + create(a, wA, { display_name: `Parallel ${i}` }), + ), + ) + expect(results.map((r) => r.status)).toEqual(Array(20).fill(200)) + expect( + await sql( + `select count(*) from public.clients where workspace_id = '${wA}'`, + ), + ).toBe('20') + expect(await budgetOf(wA)).toBe('20/20') + }) + + it('the same request id sent 8 times at once creates one client and answers it 8 times', async () => { + const requestId = randomUUID() + const results = await Promise.all( + Array.from({ length: 8 }, () => + create(a, wA, { display_name: 'Replayed' }, requestId), + ), + ) + expect(new Set(results.map(idOf)).size).toBe(1) + expect( + await sql( + `select count(*) from public.clients where create_request_id = '${requestId}'`, + ), + ).toBe('1') + expect(await budgetOf(wA)).toBe('21/21') + }) + + it('two different contents racing on one request id: one created, the other refused', async () => { + const requestId = randomUUID() + const [x, y] = await Promise.all([ + create(a, wA, { display_name: 'Racer X' }, requestId), + create(a, wA, { display_name: 'Racer Y' }, requestId), + ]) + expect([x.status, y.status].sort()).toEqual([200, 400]) + expect( + [x, y] + .map((r) => + r.status === 400 ? (r.body as { message: string }).message : 'ok', + ) + .sort(), + ).toEqual(['ok', 'request_conflict']) + expect( + await sql( + `select count(*) from public.clients where create_request_id = '${requestId}'`, + ), + ).toBe('1') + }) + + it('two updates from the same revision: one wins, the other gets conflict, nothing lost', async () => { + const id = idOf(await create(a, wA, { display_name: 'Revision base' })) + const [x, y] = await Promise.all([ + rpc('update_client', fullUpdate(id, 1, 'Edited in tab X'), a.token), + rpc('update_client', fullUpdate(id, 1, 'Edited in tab Y'), a.token), + ]) + const winner = x.status === 200 ? 'Edited in tab X' : 'Edited in tab Y' + expect([x.status, y.status].sort()).toEqual([200, 400]) + expect([x, y].find((r) => r.status === 400)?.body).toMatchObject({ + message: 'conflict', + }) + expect( + await sql( + `select display_name || '/' || revision from public.clients where id = '${id}'`, + ), + ).toBe(`${winner}/2`) + }) + + it('archive, restore and edits racing on one client end consistent, without deadlock', async () => { + const id = idOf(await create(a, wA, { display_name: 'Archive race' })) + const calls = Array.from({ length: 30 }, (_, i) => + i % 3 === 0 + ? rpc('set_client_archived', { client_id: id, archived: true }, a.token) + : i % 3 === 1 + ? rpc( + 'set_client_archived', + { client_id: id, archived: false }, + a.token, + ) + : rpc('update_client', fullUpdate(id, 1, `Edit ${i}`), a.token), + ) + const results = await Promise.all(calls) + const messages = results.map((r) => + r.status === 200 ? 'ok' : (r.body as { message: string }).message, + ) + expect( + messages.every((m) => ['ok', 'archived', 'conflict'].includes(m)), + ).toBe(true) + const [revision, archived] = ( + await sql( + `select revision || '|' || (archived_at is not null) from public.clients where id = '${id}'`, + ) + ).split('|') + const audited = await sql( + `select count(*) from audit.audit_logs where resource_id = '${id}'`, + ) + expect(Number(audited)).toBe(Number(revision)) + expect(['true', 'false']).toContain(archived) + }) + + it('at the hourly limit, 20 racing writes: exactly the remaining 10 pass, refused ones consume nothing', async () => { + await sql( + `update private.workspace_write_budgets set hour_count = 990 where workspace_id = '${wA}'`, + ) + const results = await Promise.all( + Array.from({ length: 20 }, (_, i) => + create(a, wA, { display_name: `Limit ${i}` }), + ), + ) + const statuses = results.map((r) => + r.status === 200 ? 'ok' : (r.body as { message: string }).message, + ) + expect(statuses.filter((s) => s === 'ok')).toHaveLength(10) + expect(statuses.filter((s) => s === 'rate_limited')).toHaveLength(10) + expect((await budgetOf(wA)).split('/')[0]).toBe('1000') + await sql( + `update private.workspace_write_budgets set hour_count = 0, day_count = 0 where workspace_id = '${wA}'`, + ) + }) + + it('locks stay per workspace: a held budget row delays its workspace only', async () => { + const accounts = await Promise.all( + Array.from({ length: 10 }, (_, i) => confirmedAccount(`cl-iso-${i}`)), + ) + const spaces = await Promise.all(accounts.map((x) => workspaceOf(x.id))) + expect( + (await create(accounts[0], spaces[0], { display_name: 'Seed' })).status, + ).toBe(200) + const holder = + sql(`begin; select 1 from private.workspace_write_budgets where workspace_id = '${spaces[0]}' for update; + select pg_sleep(2); commit;`) + await new Promise((resolve) => setTimeout(resolve, 300)) + const started = Date.now() + const blocked = create(accounts[0], spaces[0], { + display_name: 'Waits', + }).then((r) => ({ r, ms: Date.now() - started })) + const others = await Promise.all( + accounts + .slice(1) + .map((x, i) => + create(x, spaces[i + 1], { display_name: 'Independent' }), + ), + ) + const othersMs = Date.now() - started + const waited = await blocked + await holder + expect(others.map((r) => r.status)).toEqual(Array(9).fill(200)) + expect(othersMs).toBeLessThan(1000) + expect(waited.r.status).toBe(200) + expect(waited.ms).toBeGreaterThan(1200) + console.log( + `[measure] budget row of one workspace held 2 s: 9 creates elsewhere ${othersMs} ms; the create in the held workspace waited ${waited.ms} ms`, + ) + }) + + it('a mixed burst of 60 writes in one workspace raises no deadlock', async () => { + const ids = await Promise.all( + Array.from({ length: 5 }, (_, i) => + create(a, wA, { display_name: `Burst base ${i}` }).then(idOf), + ), + ) + const started = Date.now() + const results = await Promise.all( + Array.from({ length: 60 }, (_, i) => { + const id = ids[i % 5] + if (i % 4 === 0) + return create(a, wA, { display_name: `Burst new ${i}` }) + if (i % 4 === 1) + return rpc( + 'set_client_archived', + { client_id: id, archived: i % 8 === 1 }, + a.token, + ) + return rpc( + 'update_client', + fullUpdate(id, 1, `Burst edit ${i}`), + a.token, + ) + }), + ) + const codes = results.map((r) => + r.status === 200 + ? 'ok' + : `${errorCode(r)}:${(r.body as { message: string }).message}`, + ) + expect( + codes.filter((c) => c.startsWith('40P01') || c.startsWith('40001')), + ).toEqual([]) + expect( + codes.every( + (c) => c === 'ok' || ['P0001:conflict', 'P0001:archived'].includes(c), + ), + ).toBe(true) + console.log( + `[measure] 60 mixed writes in one workspace: ${Date.now() - started} ms, ${codes.filter((c) => c === 'ok').length} applied`, + ) + }) +}) + +describe('search on 20 000 clients', () => { + it('records the time of name and phone searches (measurement, not a gate)', async () => { + const a = await confirmedAccount('cl-volume') + const ws = await workspaceOf(a.id) + await sql(`insert into public.clients (workspace_id, kind, display_name, city, email, phone, create_request_id, create_request_digest) + select '${ws}', 'person', 'Client ' || g || ' Dupont', 'Ville ' || (g % 500), 'client' || g || '@example.test', + '+336' || lpad(g::text, 8, '0'), gen_random_uuid(), '\\x00' + from generate_series(1, 20000) g; analyze public.clients;`) + const terms = [ + 'dupont', + 'client 1999', + 'ville 42', + 'example', + '06 00 01', + 'zzz-none', + '', + ] + const times: number[] = [] + for (let round = 0; round < 3; round++) { + for (const query of terms) { + const started = performance.now() + const result = await rpc( + 'search_clients', + { workspace_id: ws, query }, + a.token, + ) + times.push(performance.now() - started) + expect(result.status).toBe(200) + } + } + times.sort((x, y) => x - y) + const p95 = times[Math.ceil(times.length * 0.95) - 1] + console.log( + `[measure] search_clients over 20 000 clients, ${times.length} HTTP calls: median ${times[times.length >> 1].toFixed(1)} ms, p95 ${p95.toFixed(1)} ms, max ${times[times.length - 1].toFixed(1)} ms`, + ) + expect( + await sql( + `select count(*) from public.clients where workspace_id = '${ws}'`, + ), + ).toBe('20000') + }) +}) diff --git a/supabase/migrations/20261025110000_clients.sql b/supabase/migrations/20261025110000_clients.sql new file mode 100644 index 00000000..1594bc35 --- /dev/null +++ b/supabase/migrations/20261025110000_clients.sql @@ -0,0 +1,514 @@ +-- V1-1.2 Clients (M2): the clients of a workspace, written only through RPCs, +-- read through RLS, searched through a POST RPC. Contract: +-- docs/development/V1-1_OWNERS_ANIMALS.md §5 (text rules), §5.1 (fields), +-- §8 (schema), §9 (helpers, RLS, RPCs, failures), §10 (limits), §13.2 (N2, +-- N3, N6, N7, N9). +-- +-- Invariants pinned by supabase/tests/013_clients.sql and the sandbox suite: +-- * a client belongs to one workspace; only a member with a write role of +-- an active, confirmed account writes it, through the four RPCs; every +-- foreign or unknown id is answered with the same 42501 `not_found`; +-- * a create is idempotent by (workspace, create_request_id); a replay +-- with other content is refused (`request_conflict`), never applied; +-- * an update needs the current revision; an archived client is read-only +-- until restored; +-- * writes are capped per workspace (20 000 clients; 1 000 audited writes +-- per UTC hour, 5 000 per UTC day) under locks, so concurrent calls +-- cannot pass a cap and a refused or replayed call consumes nothing; +-- * audit rows carry ids only, and platform staff do not read them (N9). + +-- --------------------------------------------------------------------------- +-- Text folding for search keys +-- --------------------------------------------------------------------------- +create extension if not exists unaccent with schema extensions; + +-- Accents removed with the explicit dictionary, then ASCII lower case +-- (collation "C"), so PGlite and the real image fold identically. Letters +-- outside ASCII that unaccent keeps (Cyrillic, Greek) keep their case. +-- Declared immutable for the generated columns: the dictionary is fixed by +-- the extension version (contract §8). +create or replace function private.fold_text(p_value text) +returns text +language sql +immutable +parallel safe +set search_path = '' +as $$ + select lower(extensions.unaccent('extensions.unaccent'::regdictionary, p_value) collate "C"); +$$; + +comment on function private.fold_text(text) is + 'Search key folding: unaccent (explicit dictionary) then ASCII lower case. Used by generated columns and by search_clients.'; + +-- The text rule of contract §5: 1 to p_max characters (code points), no +-- leading or trailing space, no control character of the explicit ranges. +-- Null passes (an absent value is null, never an empty string). +create or replace function private.is_clean_text(p_value text, p_max integer) +returns boolean +language sql +immutable +parallel safe +set search_path = '' +as $$ + select p_value is null + or (char_length(p_value) between 1 and p_max + and p_value = btrim(p_value) + and p_value !~ '[\u0001-\u001f\u007f-\u009f\u2028\u2029]'); +$$; + +comment on function private.is_clean_text(text, integer) is + 'Contract §5 text rule for CHECK constraints: length 1..p_max in code points, trimmed, no control character.'; + +-- --------------------------------------------------------------------------- +-- clients +-- --------------------------------------------------------------------------- +create type public.client_kind as enum ('person', 'organization'); + +create table public.clients ( + id uuid primary key default gen_random_uuid(), + -- restrict: an account whose workspace holds clients cannot be deleted (D9a). + workspace_id uuid not null references public.workspaces (id) on delete restrict, + kind public.client_kind not null, + display_name text not null + constraint clients_display_name_text check (private.is_clean_text(display_name, 120)), + email text + constraint clients_email_format check ( + private.is_clean_text(email, 254) + and email = lower(email) + and email ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$' + ), + phone text + constraint clients_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'), + address_line1 text + constraint clients_address_line1_text check (private.is_clean_text(address_line1, 120)), + address_line2 text + constraint clients_address_line2_text check (private.is_clean_text(address_line2, 120)), + postal_code text + constraint clients_postal_code_text check (private.is_clean_text(postal_code, 16)), + city text + constraint clients_city_text check (private.is_clean_text(city, 80)), + country text + constraint clients_country_code check (country ~ '^[A-Z]{2}$'), + name_key text collate "C" + generated always as (private.fold_text(display_name)) stored, + search_key text collate "C" + generated always as ( + private.fold_text(display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, '')) + ) stored, + phone_digits text collate "C" generated always as (ltrim(phone, '+')) stored, + -- Idempotency: the form sends one uuid per create attempt. The digest of the + -- creation content tells a replay from a divergent reuse; never readable + -- through the API. + create_request_id uuid not null, + create_request_digest bytea not null, + revision integer not null default 1 + constraint clients_revision_positive check (revision >= 1), + archived_at timestamptz, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint clients_workspace_id_unique unique (workspace_id, id), + constraint clients_create_request_unique unique (workspace_id, create_request_id) +); + +comment on table public.clients is + 'Clients of a workspace (person or organization). Writes only through create_client, update_client, set_client_archived; reads through RLS and search_clients.'; +comment on column public.clients.display_name is + 'The single name reference (N2): display, search, sorting, documents.'; + +-- Workspace filter, name order, keyset pagination and the search scan. +create index clients_workspace_name_idx on public.clients (workspace_id, name_key, id); + +create trigger clients_set_updated_at + before update on public.clients + for each row execute function private.set_updated_at(); + +-- --------------------------------------------------------------------------- +-- Write budget per workspace (N6, owner decision on the counter) +-- --------------------------------------------------------------------------- +-- One row per workspace, fixed UTC windows: the hour starting at hh:00:00 UTC +-- and the day starting at 00:00:00 UTC. A window that has passed restarts at +-- 1 on the next write. The row lock of the upsert serialises the writes of +-- one workspace only; it is the last lock a write RPC takes, so no lock +-- cycle can form. The counts are rolled back with any refused write. +create table private.workspace_write_budgets ( + workspace_id uuid primary key references public.workspaces (id) on delete cascade, + hour_start timestamptz not null, + hour_count integer not null, + day_start timestamptz not null, + day_count integer not null +); + +comment on table private.workspace_write_budgets is + 'Audited writes per workspace in the current UTC hour and day (contract §10). Written only by private.consume_write_budget.'; + +create or replace function private.consume_write_budget(p_workspace_id uuid) +returns void +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_hour timestamptz := date_trunc('hour', now(), 'UTC'); + v_day timestamptz := date_trunc('day', now(), 'UTC'); + v_hour_count integer; + v_day_count integer; +begin + insert into private.workspace_write_budgets as b (workspace_id, hour_start, hour_count, day_start, day_count) + values (p_workspace_id, v_hour, 1, v_day, 1) + on conflict (workspace_id) do update set + hour_count = case when b.hour_start = excluded.hour_start then b.hour_count + 1 else 1 end, + hour_start = excluded.hour_start, + day_count = case when b.day_start = excluded.day_start then b.day_count + 1 else 1 end, + day_start = excluded.day_start + returning b.hour_count, b.day_count into v_hour_count, v_day_count; + + -- Raising undoes the increment with the rest of the refused write. + if v_hour_count > 1000 or v_day_count > 5000 then + raise exception 'rate_limited' using errcode = 'P0001'; + end if; +end; +$$; + +comment on function private.consume_write_budget(uuid) is + 'Counts one audited write of the workspace in its UTC hour and day; raises rate_limited past 1 000 / 5 000. Call last, after the entity locks.'; + +-- --------------------------------------------------------------------------- +-- Write RPCs (contract §9.3). Each one: authorise and lock in one statement +-- (no row = 42501 not_found, the same for a foreign and an unknown id), then +-- archived, then revision, then rules; the budget last; one audit row with +-- ids only; returns ids and revision. +-- --------------------------------------------------------------------------- +create or replace function public.create_client( + workspace_id uuid, + create_request_id uuid, + kind text, + display_name text, + email text default null, + phone text default null, + address_line1 text default null, + address_line2 text default null, + postal_code text default null, + city text default null, + country text default null +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_kind public.client_kind; + v_email text := lower(create_client.email); + v_digest bytea; + v_existing_id uuid; + v_existing_revision integer; + v_existing_digest bytea; + v_id uuid; +begin + -- Serialises the creates of this workspace (replay check, cap, insert). + perform 1 from public.workspaces w + where w.id = create_client.workspace_id + and w.id in (select private.writable_workspace_ids()) + for no key update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + + begin + v_kind := create_client.kind::public.client_kind; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + v_digest := sha256(convert_to(jsonb_build_array( + v_kind, create_client.display_name, v_email, create_client.phone, + create_client.address_line1, create_client.address_line2, + create_client.postal_code, create_client.city, create_client.country + )::text, 'UTF8')); + + select c.id, c.revision, c.create_request_digest + into v_existing_id, v_existing_revision, v_existing_digest + from public.clients c + where c.workspace_id = create_client.workspace_id + and c.create_request_id = create_client.create_request_id; + if found then + if v_existing_digest <> v_digest then + raise exception 'request_conflict' using errcode = 'P0001'; + end if; + return jsonb_build_object('id', v_existing_id, 'revision', v_existing_revision); + end if; + + if (select count(*) from public.clients c where c.workspace_id = create_client.workspace_id) >= 20000 then + raise exception 'limit_reached' using errcode = 'P0001'; + end if; + perform private.consume_write_budget(create_client.workspace_id); + + begin + insert into public.clients ( + workspace_id, kind, display_name, email, phone, address_line1, address_line2, + postal_code, city, country, create_request_id, create_request_digest + ) + values ( + create_client.workspace_id, v_kind, create_client.display_name, v_email, create_client.phone, + create_client.address_line1, create_client.address_line2, create_client.postal_code, + create_client.city, create_client.country, create_client.create_request_id, v_digest + ) + returning id into v_id; + exception when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'client.created', 'client', v_id, null, null, + jsonb_build_object('workspace_id', create_client.workspace_id) + ); + return jsonb_build_object('id', v_id, 'revision', 1); +end; +$$; + +create or replace function public.update_client( + client_id uuid, + expected_revision integer, + kind text, + display_name text, + email text, + phone text, + address_line1 text, + address_line2 text, + postal_code text, + city text, + country text +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.clients; + v_kind public.client_kind; + v_email text := lower(update_client.email); +begin + select c.* into v_row + from public.clients c + where c.id = update_client.client_id + and c.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if v_row.archived_at is not null then + raise exception 'archived' using errcode = 'P0001'; + end if; + if update_client.expected_revision is distinct from v_row.revision then + raise exception 'conflict' using errcode = 'P0001'; + end if; + + begin + v_kind := update_client.kind::public.client_kind; + exception when invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + -- No change: nothing written, nothing counted. + if (v_kind, update_client.display_name, v_email, update_client.phone, update_client.address_line1, + update_client.address_line2, update_client.postal_code, update_client.city, update_client.country) + is not distinct from + (v_row.kind, v_row.display_name, v_row.email, v_row.phone, v_row.address_line1, + v_row.address_line2, v_row.postal_code, v_row.city, v_row.country) then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + begin + update public.clients c + set kind = v_kind, display_name = update_client.display_name, email = v_email, + phone = update_client.phone, address_line1 = update_client.address_line1, + address_line2 = update_client.address_line2, postal_code = update_client.postal_code, + city = update_client.city, country = update_client.country, + revision = c.revision + 1 + where c.id = v_row.id; + exception when check_violation or not_null_violation or string_data_right_truncation + or invalid_text_representation then + raise exception 'invalid_input' using errcode = 'P0001'; + end; + + perform private.log_event( + auth.uid(), 'client.updated', 'client', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +create or replace function public.set_client_archived( + client_id uuid, + archived boolean +) +returns jsonb +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_row public.clients; +begin + select c.* into v_row + from public.clients c + where c.id = set_client_archived.client_id + and c.workspace_id in (select private.writable_workspace_ids()) + for update; + if not found then + raise exception 'not_found' using errcode = '42501'; + end if; + if set_client_archived.archived is null then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + -- Already in that state: nothing written, nothing counted. + if (v_row.archived_at is not null) = set_client_archived.archived then + return jsonb_build_object('revision', v_row.revision); + end if; + + perform private.consume_write_budget(v_row.workspace_id); + update public.clients c + set archived_at = case when set_client_archived.archived then now() end, + revision = c.revision + 1 + where c.id = v_row.id; + + perform private.log_event( + auth.uid(), + case when set_client_archived.archived then 'client.archived' else 'client.restored' end, + 'client', v_row.id, null, null, + jsonb_build_object('workspace_id', v_row.workspace_id) + ); + return jsonb_build_object('revision', v_row.revision + 1); +end; +$$; + +-- --------------------------------------------------------------------------- +-- Search (contract §9.3): security invoker, so RLS limits it to the caller's +-- workspaces; a foreign workspace id returns no row. Called with POST, so the +-- term and the cursor stay out of URLs. +-- --------------------------------------------------------------------------- +create or replace function public.search_clients( + workspace_id uuid, + query text default '', + archived boolean default false, + page_size integer default 25, + after_name_key text default null, + after_id uuid default null +) +returns table ( + id uuid, + kind public.client_kind, + display_name text, + city text, + phone text, + email text, + archived_at timestamptz, + name_key text +) +language plpgsql +stable +security invoker +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_term text := btrim(coalesce(search_clients.query, '')); + v_pattern text; + v_digits text; +begin + if char_length(v_term) > 100 + or search_clients.archived is null + or search_clients.page_size is null + or search_clients.page_size not between 1 and 100 + or (search_clients.after_name_key is null) <> (search_clients.after_id is null) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + + -- Folded term inside search_key; LIKE wildcards escaped, backslash first. + v_pattern := '%' || replace(replace(replace(private.fold_text(v_term), '\', '\\'), '%', '\%'), '_', '\_') || '%'; + -- A phone-like term (digits, spaces, dots, hyphens, +; at least 4 digits) + -- is also looked for in phone_digits, without one leading 0. + if v_term ~ '^[0-9 .+-]+$' and char_length(regexp_replace(v_term, '[^0-9]', '', 'g')) >= 4 then + v_digits := regexp_replace(regexp_replace(v_term, '[^0-9]', '', 'g'), '^0', ''); + end if; + + return query + select c.id, c.kind, c.display_name, c.city, c.phone, c.email, c.archived_at, c.name_key + from public.clients c + where c.workspace_id = search_clients.workspace_id + and (c.archived_at is not null) = search_clients.archived + and (v_term = '' + or c.search_key like v_pattern + or (v_digits is not null and c.phone_digits like '%' || v_digits || '%')) + and (search_clients.after_name_key is null + or (c.name_key, c.id) > (search_clients.after_name_key collate "C", search_clients.after_id)) + order by c.name_key, c.id + limit search_clients.page_size; +end; +$$; + +comment on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) is + 'Creates a client in a writable workspace; idempotent by create_request_id (divergent replay: request_conflict). Returns {id, revision}.'; +comment on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) is + 'Replaces the nine fields of an active client at expected_revision. Returns {revision}.'; +comment on function public.set_client_archived(uuid, boolean) is + 'Archives or restores a client (same state: no write). Returns {revision}.'; +comment on function public.search_clients(uuid, text, boolean, integer, text, uuid) is + 'Folded search (name, city, email; phone digits) in one workspace, keyset pages on (name_key, id), 25 by default, 100 at most.'; + +-- --------------------------------------------------------------------------- +-- Audit (N9): platform owners and admins keep reading platform events, not +-- the activity of private records. +-- --------------------------------------------------------------------------- +alter policy audit_logs_select_admin on audit.audit_logs + using ( + private.is_platform_admin((select auth.uid())) + and split_part(action, '.', 1) not in ('client', 'animal', 'animal_client_relation') + ); + +-- --------------------------------------------------------------------------- +-- Privileges + RLS (N7: nothing for anon or service_role) +-- --------------------------------------------------------------------------- +revoke all on public.clients from public, anon, authenticated, service_role; +grant select ( + id, workspace_id, kind, display_name, email, phone, address_line1, address_line2, + postal_code, city, country, name_key, search_key, phone_digits, create_request_id, + revision, archived_at, created_at, updated_at +) on public.clients to authenticated; + +alter table public.clients enable row level security; + +create policy clients_select_member + on public.clients + for select + to authenticated + using (workspace_id in (select private.caller_workspace_ids())); + +revoke all on private.workspace_write_budgets from public, anon, authenticated, service_role; + +revoke all on function private.fold_text(text) from public, anon, authenticated, service_role; +revoke all on function private.is_clean_text(text, integer) from public, anon, authenticated, service_role; +revoke all on function private.consume_write_budget(uuid) from public, anon, authenticated, service_role; +revoke all on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) + from public, anon, authenticated, service_role; +revoke all on function public.set_client_archived(uuid, boolean) from public, anon, authenticated, service_role; +revoke all on function public.search_clients(uuid, text, boolean, integer, text, uuid) + from public, anon, authenticated, service_role; + +grant execute on function public.create_client(uuid, uuid, text, text, text, text, text, text, text, text, text) to authenticated; +grant execute on function public.update_client(uuid, integer, text, text, text, text, text, text, text, text, text) to authenticated; +grant execute on function public.set_client_archived(uuid, boolean) to authenticated; +grant execute on function public.search_clients(uuid, text, boolean, integer, text, uuid) to authenticated; +-- The invoker search folds its term as the caller. +grant execute on function private.fold_text(text) to authenticated; diff --git a/supabase/tests/001_schema.sql b/supabase/tests/001_schema.sql index ce66814d..37283f66 100644 --- a/supabase/tests/001_schema.sql +++ b/supabase/tests/001_schema.sql @@ -62,7 +62,7 @@ select is( (select string_agg(p.proname::text, ',' order by p.proname::text collate "C") from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')), - 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', + 'caller_workspace_ids,can_edit_sheet,can_read_avatar_object,can_read_sheet_asset_object,can_upload_avatar_object,can_use_sheet,fold_text,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support', 'authenticated executes only the policy predicates in private' ); diff --git a/supabase/tests/013_clients.sql b/supabase/tests/013_clients.sql new file mode 100644 index 00000000..38857966 --- /dev/null +++ b/supabase/tests/013_clients.sql @@ -0,0 +1,452 @@ +-- V1-1.2 Clients (M2): fields and text rules, idempotent creates, revisions, +-- archive, search, isolation between workspaces, refusals for every other +-- actor, caps and write budget, minimised audit, privileges and census. +-- Contract: docs/development/V1-1_OWNERS_ANIMALS.md §5, §9, §10, §12.1. +-- Actors: A and B confirmed and active; C unconfirmed; D deactivated after +-- creating a client; S a platform owner; E (cap) and F (budget) confirmed; +-- G an account without clients. +begin; +select plan(130); + +insert into auth.users (id, email, email_confirmed_at) values + ('60000000-0000-0000-0000-00000000000a', 'alice-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000b', 'bob-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000c', 'carol-cl@test.local', null), + ('60000000-0000-0000-0000-00000000000d', 'dave-cl@test.local', now()), + ('60000000-0000-0000-0000-000000000005', 'staff-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000e', 'cap-cl@test.local', now()), + ('60000000-0000-0000-0000-00000000000f', 'budget-cl@test.local', now()), + ('60000000-0000-0000-0000-000000000010', 'empty-cl@test.local', now()); +select private.assign_platform_role(null, '60000000-0000-0000-0000-000000000005', 'owner'); + +create function pg_temp.ws(p_user uuid) returns uuid language sql stable security definer +as $$ select id from public.workspaces where personal_user_id = p_user $$; +create function pg_temp.act_as(p_user uuid) returns text language sql +as $$ select set_config('request.jwt.claims', + json_build_object('sub', p_user, 'role', 'authenticated')::text, true) $$; +create function pg_temp.client(p_id uuid) returns public.clients language sql stable security definer +as $$ select c from public.clients c where c.id = p_id $$; +create function pg_temp.budget(p_ws uuid) returns text language sql stable security definer +as $$ select coalesce((select hour_count || '/' || day_count from private.workspace_write_budgets where workspace_id = p_ws), 'none') $$; +create function pg_temp.audit_count(p_resource uuid) returns bigint language sql stable security definer +as $$ select count(*) from audit.audit_logs where resource_id = p_resource $$; +-- The whole error of a statement, run as the calling role: SQLSTATE, message, detail, hint. +create function pg_temp.err(p_sql text) returns text language plpgsql +as $$ +declare v_state text; v_msg text; v_detail text; v_hint text; +begin + execute p_sql; + return 'no error'; +exception when others then + get stacked diagnostics v_state = returned_sqlstate, v_msg = message_text, + v_detail = pg_exception_detail, v_hint = pg_exception_hint; + return v_state || '|' || v_msg || '|' || coalesce(v_detail, '') || '|' || coalesce(v_hint, ''); +end; +$$; +-- SQLSTATE and message only: the real image appends a hint to table-privilege +-- refusals ("Grant the required privileges ..."), PGlite does not. +create function pg_temp.denial(p_sql text) returns text language sql +as $$ select split_part(pg_temp.err(p_sql), '|', 1) || '|' || split_part(pg_temp.err(p_sql), '|', 2) $$; +create table pg_temp.ids (key text primary key, id uuid not null); +grant all on pg_temp.ids to authenticated, anon, service_role; +grant execute on function pg_temp.ws(uuid), pg_temp.act_as(uuid), pg_temp.client(uuid), pg_temp.budget(uuid), + pg_temp.audit_count(uuid), pg_temp.err(text), pg_temp.denial(text) to authenticated, anon, service_role; + +-- --------------------------------------------------------------------------- +-- 1. Schema, privileges, census +-- --------------------------------------------------------------------------- +select has_table('public', 'clients', 'table public.clients exists'); +select ok((select relrowsecurity from pg_class where oid = 'public.clients'::regclass), 'RLS enabled on clients'); +select enum_has_labels('public', 'client_kind', array['person', 'organization'], 'client_kind: person, organization'); +select is((select tableowner::text from pg_tables where schemaname = 'public' and tablename = 'clients'), 'postgres', 'clients belongs to postgres'); +select is( + (select count(*) from (values ('anon'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege(r.role, 'public.clients', p.priv)), + 0::bigint, 'anon and service_role hold no privilege on clients' +); +select is( + (select count(*) from (values ('insert'), ('update'), ('delete'), ('truncate'), ('references'), ('trigger')) p(priv) + where has_table_privilege('authenticated', 'public.clients', p.priv)), + 0::bigint, 'authenticated holds no write privilege on clients' +); +select ok(has_column_privilege('authenticated', 'public.clients', 'display_name', 'select') + and not has_column_privilege('authenticated', 'public.clients', 'create_request_digest', 'select'), + 'authenticated reads the record columns, never the request digest'); +select is( + (select count(*) from (values ('anon'), ('authenticated'), ('service_role')) r(role) + cross join (values ('select'), ('insert'), ('update'), ('delete')) p(priv) + where has_table_privilege(r.role, 'private.workspace_write_budgets', p.priv)), + 0::bigint, 'no API role touches the budget table' +); +select is( + (select string_agg(policyname || ':' || cmd || ':' || array_to_string(roles, '+'), ',') + from pg_policies where schemaname = 'public' and tablename = 'clients'), + 'clients_select_member:SELECT:authenticated', 'one SELECT policy on clients, for authenticated' +); +select is( + (select count(*) from pg_policies where schemaname = 'public' and tablename = 'clients' + and (qual not like '%caller_workspace_ids()%' or qual like '%platform%')), + 0::bigint, 'the clients policy goes through caller_workspace_ids() and names no platform role' +); +select is( + (select string_agg(p.proname || ':' || case when p.prosecdef then 'definer' else 'invoker' end, ',' order by p.proname::text collate "C") + from pg_proc p join pg_namespace n on n.oid = p.pronamespace + where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients', + 'fold_text', 'is_clean_text', 'consume_write_budget') + and p.proconfig = array['search_path=""'] and pg_get_userbyid(p.proowner) = 'postgres'), + 'consume_write_budget:definer,create_client:definer,fold_text:invoker,is_clean_text:invoker,search_clients:invoker,set_client_archived:definer,update_client:definer', + 'definer and invoker as designed; search_path empty; owner postgres' +); +select is( + (select string_agg(r.role || ':' || p.proname::text, ',' order by r.role, p.proname::text collate "C") + from pg_proc p cross join (values ('anon'), ('authenticated'), ('service_role')) r(role) + where p.proname in ('create_client', 'update_client', 'set_client_archived', 'search_clients', + 'fold_text', 'is_clean_text', 'consume_write_budget') + and has_function_privilege(r.role, p.oid, 'execute')), + 'authenticated:create_client,authenticated:fold_text,authenticated:search_clients,authenticated:set_client_archived,authenticated:update_client', + 'EXECUTE: authenticated on the four RPCs and the fold; anon and service_role on none' +); + +-- --------------------------------------------------------------------------- +-- 2. Creation by A: fields, normalisation, derived keys +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000a'); +insert into pg_temp.ids values + ('lac', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000001', + 'organization', 'Écurie du Lac', 'contact@ecurie-lac.test', '+33612345678', '1 chemin du Lac', null, '69000', 'Lyon', 'FR') ->> 'id')::uuid), + ('marie', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Dupont', 'MARIE@Example.TEST', null, null, null, null, 'Évian') ->> 'id')::uuid), + ('ab', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000003', 'organization', 'A_B Haras') ->> 'id')::uuid), + ('axb', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000004', 'organization', 'AxB Haras') ->> 'id')::uuid), + ('pct', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000005', 'person', '100% Cheval') ->> 'id')::uuid), + ('bsl', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000006', 'person', 'Back\slash') ->> 'id')::uuid); + +select results_eq( + $$ select kind::text, display_name, email, phone, city, country, revision, archived_at is null + from public.clients where id = (select id from pg_temp.ids where key = 'lac') $$, + $$ values ('organization'::text, 'Écurie du Lac'::text, 'contact@ecurie-lac.test'::text, '+33612345678'::text, + 'Lyon'::text, 'FR'::text, 1, true) $$, + 'A reads the created organization with revision 1' +); +select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).email, 'marie@example.test', 'the email is stored lower-case'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).name_key, 'ecurie du lac', 'name_key folds accents and case'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'lac'))).phone_digits, '33612345678', 'phone_digits drops the +'); +select is((pg_temp.client((select id from pg_temp.ids where key = 'ab'))).country, null, 'no country is set by default'); +select is((select count(*) from public.clients), 6::bigint, 'A reads its six clients'); + +-- --------------------------------------------------------------------------- +-- 3. Text rules: refused with the bare code, nothing echoed +-- --------------------------------------------------------------------------- +create function pg_temp.try_create(p_kind text, p_name text, p_email text default null, p_phone text default null, + p_postal text default null, p_country text default null) returns text language sql +as $$ select pg_temp.err(format( + 'select public.create_client(%L, gen_random_uuid(), %L, %L, %L, %L, null, null, %L, null, %L)', + pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_kind, p_name, p_email, p_phone, p_postal, p_country)) $$; +grant execute on function pg_temp.try_create(text, text, text, text, text, text) to authenticated; + +select is(pg_temp.try_create('person', ''), 'P0001|invalid_input||', 'an empty name is refused'); +select is(pg_temp.try_create('person', null), 'P0001|invalid_input||', 'a missing name is refused'); +select is(pg_temp.try_create('person', ' Lead'), 'P0001|invalid_input||', 'a leading space is refused'); +select is(pg_temp.try_create('person', e'Tab\there'), 'P0001|invalid_input||', 'a tab (control character) is refused'); +select is(pg_temp.try_create('person', e'Line\u2028sep'), 'P0001|invalid_input||', 'U+2028 is refused'); +select is(pg_temp.try_create('person', e'C1\u0085'), 'P0001|invalid_input||', 'a C1 control (U+0085) is refused'); +select is(pg_temp.try_create('person', repeat('x', 121)), 'P0001|invalid_input||', '121 characters are refused'); +select is(pg_temp.try_create('person', repeat('é', 121)), 'P0001|invalid_input||', '121 accented characters (code points) are refused'); +select is(pg_temp.try_create('robot', 'Kind'), 'P0001|invalid_input||', 'an unknown kind is refused'); +select is(pg_temp.try_create(null, 'Kind'), 'P0001|invalid_input||', 'a missing kind is refused'); +select is(pg_temp.try_create('person', 'Mail', 'not-an-email'), 'P0001|invalid_input||', 'a malformed email is refused'); +select is(pg_temp.try_create('person', 'Mail', 'a b@c.test'), 'P0001|invalid_input||', 'an email with a space is refused'); +select is(pg_temp.try_create('person', 'Mail', repeat('a', 247) || '@ex.test'), 'P0001|invalid_input||', 'a 255-character email is refused'); +select is(pg_temp.try_create('person', 'Mail', repeat('a', 246) || '@ex.test'), 'no error', 'a 254-character email is accepted'); +select is(pg_temp.try_create('person', 'Phone', null, '0612345678'), 'P0001|invalid_input||', 'a national phone (not E.164) is refused'); +select is(pg_temp.try_create('person', 'Postal', null, null, repeat('9', 17)), 'P0001|invalid_input||', 'a 17-character postal code is refused'); +select is(pg_temp.try_create('person', 'Country', null, null, null, 'fr'), 'P0001|invalid_input||', 'a lower-case country code is refused'); +select is(pg_temp.try_create('person', 'Country', null, null, null, 'FRA'), 'P0001|invalid_input||', 'a three-letter country code is refused'); +select is(pg_temp.try_create('person', repeat('é', 120)), 'no error', '120 accented characters are accepted'); +select is((select count(*) from public.clients), 8::bigint, 'only the two valid creates were written'); + +-- --------------------------------------------------------------------------- +-- 4. Idempotent create: replay, normalised replay, divergent replay +-- --------------------------------------------------------------------------- +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'eight writes counted so far'); +select is( + (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Dupont', 'marie@example.test', null, null, null, null, 'Évian') ->> 'id')::uuid, + (select id from pg_temp.ids where key = 'marie'), + 'a replay (email in another case) returns the first client' +); +select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 1::bigint, 'the replay writes no audit row'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')), '8/8', 'the replay consumes no budget'); +select is( + pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), '61000000-0000-0000-0000-000000000002', + 'person', 'Marie Durand') $$), + 'P0001|request_conflict||', 'the same request id with other content is refused' +); +select is((select count(*) from public.clients where display_name like 'Marie%'), 1::bigint, 'no divergent client was created'); + +-- --------------------------------------------------------------------------- +-- 5. Update, revision, archive +-- --------------------------------------------------------------------------- +select is( + public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie Dupont', 'marie@example.test', + '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update at the current revision gives revision 2'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 1, 'person', 'Marie D.', + null, null, null, null, null, null, null) $$), + 'P0001|conflict||', 'a stale revision is refused' +); +select is((pg_temp.client((select id from pg_temp.ids where key = 'marie'))).city, 'Vevey', 'the stale update overwrote nothing'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), null, 'person', 'Marie D.', + null, null, null, null, null, null, null) $$), + 'P0001|conflict||', 'a missing revision is refused' +); +select is( + public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', 'Marie Dupont', 'MARIE@example.test', + '+41791234567', null, null, '1800', 'Vevey', 'CH') ->> 'revision', '2', 'an update that changes nothing keeps the revision'); +select is(pg_temp.audit_count((select id from pg_temp.ids where key = 'marie')), 2::bigint, 'and writes no audit row'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'marie'), 2, 'person', '', + null, null, null, null, null, null, null) $$), + 'P0001|invalid_input||', 'an update breaking a rule is refused' +); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving adds one revision'); +select ok((pg_temp.client((select id from pg_temp.ids where key = 'axb'))).archived_at is not null, 'the client is archived'); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), true) ->> 'revision', '2', 'archiving again changes nothing'); +select is( + pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'axb'), 1, 'organization', 'AxB', + null, null, null, null, null, null, null) $$), + 'P0001|archived||', 'an archived client refuses edits, archived reported before the stale revision' +); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'axb'), null) $$), + 'P0001|invalid_input||', 'a missing archive state is refused'); + +-- --------------------------------------------------------------------------- +-- 6. Search: folding, escaping, phone formats, filters, keyset pages +-- --------------------------------------------------------------------------- +create function pg_temp.names(p_query text, p_archived boolean default false, p_size integer default 25, + p_after_key text default null, p_after_id uuid default null) returns text language sql +as $$ select coalesce(string_agg(s.display_name, '|' order by s.ord), '') + from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), p_query, p_archived, p_size, + p_after_key, p_after_id) with ordinality s(id, kind, display_name, city, phone, email, + archived_at, name_key, ord) $$; +grant execute on function pg_temp.names(text, boolean, integer, text, uuid) to authenticated; + +select is(pg_temp.names(''), '100% Cheval|A_B Haras|Back\slash|Écurie du Lac|' || repeat('é', 120) || '|Mail|Marie Dupont', + 'an empty term lists the active clients in name order (archived left out)'); +select is(pg_temp.names('', true), 'AxB Haras', 'the archived filter lists the archived client only'); +select is(pg_temp.names('ECU'), 'Écurie du Lac', 'search folds case and accents'); +select is(pg_temp.names('vevey'), 'Marie Dupont', 'search reads the city'); +select is(pg_temp.names('EXAMPLE.test'), 'Marie Dupont', 'search reads the email'); +select is(pg_temp.names('_'), 'A_B Haras', 'an underscore is a character, not a wildcard'); +select is(pg_temp.names('%'), '100% Cheval', 'a percent sign is a character, not a wildcard'); +select is(pg_temp.names('\'), 'Back\slash', 'a backslash is a character'); +select is(pg_temp.names('06 12'), 'Écurie du Lac', 'a national phone fragment finds the number'); +select is(pg_temp.names('0612345678'), 'Écurie du Lac', 'a full national number finds it'); +select is(pg_temp.names('+33 6 12'), 'Écurie du Lac', 'an international fragment finds it'); +select is(pg_temp.names('061'), '', 'fewer than four digits is not a phone search'); +select is(pg_temp.names(repeat('z', 100)), '', 'a 100-character term is accepted'); +select is(pg_temp.names('', false, 2), '100% Cheval|A_B Haras', 'page 1 of 2'); +select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'ab'))).name_key, + (select id from pg_temp.ids where key = 'ab')), 'Back\slash|Écurie du Lac', 'page 2 continues after the cursor, no gap, no repeat'); +select is(pg_temp.names('', false, 2, (pg_temp.client((select id from pg_temp.ids where key = 'marie'))).name_key, + (select id from pg_temp.ids where key = 'marie')), '', 'after the last client the page is empty'); +select is(pg_temp.err($$ select pg_temp.names(repeat('z', 101)) $$), 'P0001|invalid_input||', 'a 101-character term is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 0) $$), 'P0001|invalid_input||', 'page size 0 is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 101) $$), 'P0001|invalid_input||', 'page size 101 is refused'); +select is(pg_temp.err($$ select pg_temp.names('', false, 25, 'a') $$), 'P0001|invalid_input||', 'a cursor without its id is refused'); +select is(pg_temp.err($$ select pg_temp.names('', null) $$), 'P0001|invalid_input||', 'a missing archive filter is refused'); + +-- Restore: editable again, back in the default list. +select is(public.set_client_archived((select id from pg_temp.ids where key = 'axb'), false) ->> 'revision', '3', 'restoring adds one revision'); +select is(public.update_client((select id from pg_temp.ids where key = 'axb'), 3, 'organization', 'AxB Haras', null, null, + null, null, null, 'Annecy', null) ->> 'revision', '4', 'a restored client is editable'); + +-- D creates a client while active (used after its deactivation). +select pg_temp.act_as('60000000-0000-0000-0000-00000000000d'); +insert into pg_temp.ids values ('dave', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000d'), + gen_random_uuid(), 'person', 'Client de Dave') ->> 'id')::uuid); +reset role; +update public.profiles set active = false where id = '60000000-0000-0000-0000-00000000000d'; + +-- --------------------------------------------------------------------------- +-- 7. Isolation: the same not_found for a foreign and an unknown id +-- --------------------------------------------------------------------------- +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000b'); +select is((select count(*) from public.clients), 0::bigint, 'B reads no client'); +select is((select count(*) from public.clients where id = (select id from pg_temp.ids where key = 'lac')), 0::bigint, + 'B naming a client of A reads nothing'); +select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000a'))), 0::bigint, + 'B searching the workspace of A finds nothing'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000a'), gen_random_uuid(), 'person', 'X') $$), + pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + 'B creating in the workspace of A gets the error of an unknown workspace'); +select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + '42501|not_found||', 'that error is 42501 not_found, no detail, no hint'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + 'B updating a client of A gets the error of an unknown client'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'lac'), true) $$), + '42501|not_found||', 'B archiving a client of A gets not_found'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', '', null, null, null, null, null, null, null) $$), + '42501|not_found||', 'invalid content on a foreign id still answers not_found (authorisation first)'); +select is(pg_temp.denial($$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (pg_temp.ws('60000000-0000-0000-0000-00000000000b'), 'person', 'Direct', gen_random_uuid(), '\x00') $$), + '42501|permission denied for table clients', 'a direct insert is refused by privilege'); +select is(pg_temp.denial($$ update public.clients set display_name = 'Direct' $$), + '42501|permission denied for table clients', 'a direct update is refused by privilege'); +select is(pg_temp.denial($$ delete from public.clients $$), + '42501|permission denied for table clients', 'a direct delete is refused by privilege'); + +select pg_temp.act_as('60000000-0000-0000-0000-00000000000c'); +select is((select count(*) from public.clients), 0::bigint, 'C (unconfirmed) reads no client'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000c'), gen_random_uuid(), 'person', 'X') $$), + '42501|not_found||', 'C cannot create, even in its own workspace'); + +select pg_temp.act_as('60000000-0000-0000-0000-00000000000d'); +select is((select count(*) from public.clients), 0::bigint, 'D (deactivated) no longer reads its own client'); +select is((select count(*) from public.search_clients(pg_temp.ws('60000000-0000-0000-0000-00000000000d'))), 0::bigint, + 'D finds nothing through search'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'dave'), true) $$), + '42501|not_found||', 'D cannot write its own client'); + +select pg_temp.act_as('60000000-0000-0000-0000-000000000005'); +select is((select count(*) from public.clients), 0::bigint, 'S (platform owner) reads no client: no platform-role branch'); +select is(pg_temp.err($$ select public.update_client((select id from pg_temp.ids where key = 'lac'), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + '42501|not_found||', 'S cannot write a client of A'); +reset role; + +set local role anon; +select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', 'anon cannot read clients'); +select is(pg_temp.err($$ select public.create_client(gen_random_uuid(), gen_random_uuid(), 'person', 'X') $$), + '42501|permission denied for function create_client||', 'anon cannot execute create_client'); +select is(pg_temp.err($$ select * from public.search_clients(gen_random_uuid()) $$), + '42501|permission denied for function search_clients||', 'anon cannot execute search_clients'); +reset role; +set local role service_role; +select is(pg_temp.denial($$ select id from public.clients $$), '42501|permission denied for table clients', + 'service_role cannot read clients despite BYPASSRLS'); +select is(pg_temp.err($$ select public.update_client(gen_random_uuid(), 1, 'person', 'X', null, null, null, null, null, null, null) $$), + '42501|permission denied for function update_client||', 'service_role cannot execute update_client'); +select is(pg_temp.err($$ select private.consume_write_budget(gen_random_uuid()) $$), + '42501|permission denied for function consume_write_budget||', 'service_role cannot touch the budget'); +reset role; +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000a'); +select is(pg_temp.err($$ select private.consume_write_budget(pg_temp.ws('60000000-0000-0000-0000-00000000000a')) $$), + '42501|permission denied for function consume_write_budget||', 'A cannot call the budget directly'); +select is(pg_temp.err($$ select private.is_clean_text('x', 1) $$), + '42501|permission denied for function is_clean_text||', 'A cannot call the text rule directly'); +reset role; + +-- --------------------------------------------------------------------------- +-- 8. Write budget per workspace (fixed UTC windows), refused writes not counted +-- --------------------------------------------------------------------------- +insert into private.workspace_write_budgets values + (pg_temp.ws('60000000-0000-0000-0000-00000000000f'), date_trunc('hour', now(), 'UTC'), 999, date_trunc('day', now(), 'UTC'), 999); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +insert into pg_temp.ids values ('f1', (public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), + '62000000-0000-0000-0000-000000000001', 'person', 'Budget One') ->> 'id')::uuid); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the 1 000th write of the hour passes'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), gen_random_uuid(), 'person', 'Budget Two') $$), + 'P0001|rate_limited||', 'the 1 001st write of the hour is refused'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1000/1000', 'the refused write consumed nothing'); +select is((public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000f'), '62000000-0000-0000-0000-000000000001', + 'person', 'Budget One') ->> 'id')::uuid, (select id from pg_temp.ids where key = 'f1'), 'a replay at the limit still answers'); +select is(public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) ->> 'revision', '1', + 'a no-op at the limit still answers'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$), + 'P0001|rate_limited||', 'an archive at the limit is refused'); +reset role; +update private.workspace_write_budgets set hour_start = hour_start - interval '1 hour' +where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f'); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +select lives_ok($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), true) $$, + 'a new UTC hour restarts the hourly count'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/1001', 'hour restarted at 1, the day keeps counting'); +reset role; +update private.workspace_write_budgets set day_count = 5000 where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000f'); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000f'); +select is(pg_temp.err($$ select public.set_client_archived((select id from pg_temp.ids where key = 'f1'), false) $$), + 'P0001|rate_limited||', 'the 5 001st write of the UTC day is refused'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000f')), '1/5000', 'and consumed nothing'); +select is(pg_temp.budget(pg_temp.ws('60000000-0000-0000-0000-00000000000b')), 'none', 'the budget of another workspace is untouched'); +reset role; + +-- --------------------------------------------------------------------------- +-- 9. Cap: 20 000 clients per workspace +-- --------------------------------------------------------------------------- +insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) +select pg_temp.ws('60000000-0000-0000-0000-00000000000e'), 'person', 'Cap ' || g, gen_random_uuid(), '\x00' +from generate_series(1, 19999) g; +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-00000000000e'); +select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), + '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'the 20 000th client is accepted'); +select is(pg_temp.err($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), gen_random_uuid(), 'person', 'Cap over') $$), + 'P0001|limit_reached||', 'the 20 001st client is refused'); +select lives_ok($$ select public.create_client(pg_temp.ws('60000000-0000-0000-0000-00000000000e'), + '63000000-0000-0000-0000-000000000001', 'person', 'Cap last') $$, 'a replay at the cap still answers'); +reset role; + +-- --------------------------------------------------------------------------- +-- 10. Audit: ids only, hidden from platform staff (N9) +-- --------------------------------------------------------------------------- +select is( + (select string_agg(action, ',' order by occurred_at, action) from audit.audit_logs + where resource_id = (select id from pg_temp.ids where key = 'axb')), + 'client.archived,client.created,client.restored,client.updated', + 'each write of a client leaves one audit row' +); +select is( + (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id + where a.metadata <> jsonb_build_object('workspace_id', pg_temp.ws('60000000-0000-0000-0000-00000000000a')) + and i.key in ('lac', 'marie', 'ab', 'axb', 'pct', 'bsl')), + 0::bigint, 'audit metadata is the workspace id only' +); +select is( + (select count(*) from audit.audit_logs a join pg_temp.ids i on i.id = a.resource_id + where a.actor_user_id is distinct from '60000000-0000-0000-0000-00000000000a' and i.key in ('lac', 'marie', 'axb')), + 0::bigint, 'the actor is the caller' +); +select is( + (select count(*) from audit.audit_logs where action like 'client.%' + and (metadata::text ~* '(lac|marie|dupont|vevey|example|cheval|haras)' or correlation_id is not null)), + 0::bigint, 'no name, contact or place in the audit rows' +); +set local role authenticated; +select pg_temp.act_as('60000000-0000-0000-0000-000000000005'); +select is((select count(*) from audit.audit_logs where action like 'client.%'), 0::bigint, 'S reads no client audit row'); +select ok((select count(*) from audit.audit_logs where action like 'platform_role.%') > 0, 'S still reads platform audit rows'); +reset role; + +-- --------------------------------------------------------------------------- +-- 11. Integrity and account deletion (D9a) +-- --------------------------------------------------------------------------- +select throws_ok( + $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (gen_random_uuid(), 'person', 'Orphan', gen_random_uuid(), '\x00') $$, + '23503', null, 'a client of an unknown workspace is refused by the foreign key' +); +select throws_ok( + $$ insert into public.clients (workspace_id, kind, display_name, create_request_id, create_request_digest) + values (pg_temp.ws('60000000-0000-0000-0000-00000000000a'), 'person', 'Twice', '61000000-0000-0000-0000-000000000001', '\x00') $$, + '23505', null, 'a request id is unique per workspace' +); +select throws_ok( + $$ delete from auth.users where id = '60000000-0000-0000-0000-00000000000a' $$, + '23503', null, 'an account whose workspace holds clients cannot be deleted (D9a)' +); +select is((select count(*) from public.clients where workspace_id = pg_temp.ws('60000000-0000-0000-0000-00000000000a')), + 8::bigint, 'its clients are intact'); +select lives_ok($$ delete from auth.users where id = '60000000-0000-0000-0000-000000000010' $$, + 'an account without clients is deleted as before'); + +select * from finish(); +rollback; From f8bd1b68611e265e5d03b1adbdffad547a485520 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 21:11:53 +0100 Subject: [PATCH 10/60] docs(docs): V1-1.2 clients as built, budget windows and lock order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contract §8.2 (as built, divergent replay, fold, measured search, residual hint), §9 helpers and lock order, §9.4 request_conflict, §10 UTC budget windows. SUPABASE.md §3.4 and the DEV procedure for M1 and M2 pending together (rehearsed). TEST_STRATEGY counts. --- docs/development/SUPABASE.md | 42 ++++++++++--- docs/development/TEST_STRATEGY.md | 5 ++ docs/development/V1-1_OWNERS_ANIMALS.md | 82 ++++++++++++++++++++----- 3 files changed, 102 insertions(+), 27 deletions(-) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index cd26d4a6..7878e824 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -19,7 +19,8 @@ supabase/ │ ├─ 20261010100000_sheet_document_schema_v2.sql document schema 2: references, review_status, count_range checks │ ├─ 20261011100000_profiles_professional.sql practice_name, professional_title, siret │ ├─ 20261013100000_files_foundation.sql assets table, seven private buckets, avatar policies through assets, purge queue, browser + worker RPCs (STORAGE.md) -│ └─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3) +│ ├─ 20261025100000_workspaces.sql V1-1.1 (M1): workspaces, workspace_members, personal workspace per account, access helpers, audit correlation cap (§3.3) +│ └─ 20261025110000_clients.sql V1-1.2 (M2): clients, unaccent, client RPCs and search, write budget per workspace, N9 audit filter (§3.4) ├─ seed.sql LOCAL dev accounts + first owner (never run in prod) ├─ seed/anatomical-sheets/equine/ official equine sheet as a DRAFT, generated by `pnpm import:equine` │ ├─ legacy-sources/ the historical Horse.svg, Horse_head.svg, pathologies.json, vertebrae.ts (importer input) @@ -210,10 +211,14 @@ pnpm supabase status # API on the DEV origin, DB on por test ! -f supabase/.temp/project-ref && echo "no linked project" # nothing remote is linked docker ps --filter name=supabase_db_faunosteo --format '{{.Names}} {{.Status}}' -# 1. History: M1 must be the only pending migration. -pnpm supabase migration list --local # every row has local = remote, except 20261025100000 (remote empty) -pnpm db:types:check # the diff must be exactly the M1 objects (workspaces, workspace_members, - # workspace_kind, workspace_member_role): anything else = drift, STOP +# 1. History: only the V1-1 migrations may be pending. +pnpm supabase migration list --local # every row has local = remote, except the V1-1 ones (remote empty): + # 20261025100000 (M1) on a checkout of 6bf6978-08abe42, + # 20261025100000 and 20261025110000 (M1, M2) from 4adbfcb on +pnpm db:types:check # the diff must be exactly the objects of those migrations (M1: workspaces, + # workspace_members, workspace_kind, workspace_member_role; M2: clients, + # client_kind, create_client, update_client, set_client_archived, + # search_clients): anything else = drift, STOP # 2. Existing accounts (the backfill creates one workspace per profile). docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U postgres -d postgres -t -A \ @@ -227,14 +232,15 @@ docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump docker exec -i supabase_db_faunosteo pg_restore --list < ~/faunosteo-backups/dev-before-m1.dump \ | grep -E "TABLE DATA (auth users|public profiles|supabase_migrations schema_migrations)" # three lines expected -# 4. Apply M1 without reset (its backfill runs inside the migration). -pnpm supabase migration up --local # "Applying migration 20261025100000_workspaces.sql" +# 4. Apply without reset (M1's backfill runs inside the migration). `migration up` applies every +# pending migration of the checkout, in order: to apply M1 alone, run it from a checkout of 08abe42. +pnpm supabase migration up --local # "Applying migration 20261025100000_workspaces.sql" (then ..._clients.sql) ``` After applying: ```bash -pnpm supabase migration list --local # 20261025100000 now has its remote column +pnpm supabase migration list --local # each applied migration now has its remote column docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h 127.0.0.1 -U postgres -d postgres -t -A -c " select (select count(*) from public.profiles) || '"'"' profiles, '"'"' || (select count(*) from public.workspaces) || '"'"' workspaces, '"'"' @@ -242,7 +248,7 @@ docker exec supabase_db_faunosteo sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" psql -h || (select count(*) from public.profiles p where (select count(*) from public.workspaces w where w.personal_user_id = p.id) <> 1) || '"'"' profiles without exactly one workspace'"'"'"' # expected: N profiles, N workspaces, N members, 0 profiles without exactly one workspace -pnpm db:test # pgTAP 001-012 (grants, policies, reads); every file runs in +pnpm db:test # pgTAP 001-013 (grants, policies, reads); every file runs in # begin ... rollback: rows unchanged (checked on the sandbox) pnpm db:types:check # no diff pnpm e2e:avatar # avatar flow and worker on the DEV stack (fictitious seed accounts) @@ -251,13 +257,29 @@ pnpm e2e:avatar # avatar flow and worker on the DE Stop and report instead of continuing when: `migration list` shows another pending migration or a remote-only one; `db:types:check` before step 4 shows anything beyond the M1 objects; the dump check misses a line; `migration up` -applies anything else than `20261025100000`; any count after it differs from +applies anything else than the expected V1-1 migrations; any count after it differs from the expectation. The backup restores into a scratch database (rehearsed: every row back; `pg_restore --no-owner` prints privilege errors on Supabase-managed objects, which do not affect the data). Storage file bytes (avatars) live in the storage container's volume, not in the dump; M1 does not touch them. +### 3.4 Clients (V1-1.2, migration M2) + +Contract: `V1-1_OWNERS_ANIMALS.md` §5.1, §8.2, §9, §10. `public.clients` +holds the clients of a workspace; the browser reads them through RLS (members +of the workspace, active profile, confirmed email) and writes them only +through `create_client`, `update_client` and `set_client_archived` (security +definer); `search_clients` (invoker, POST) searches one workspace. Refusals +are closed codes: 42501 `not_found` (also for a foreign id), P0001 +`invalid_input`, `archived`, `conflict`, `request_conflict`, `limit_reached`, +`rate_limited`. Writes are counted per workspace in +`private.workspace_write_budgets` (UTC hour and day). M2 creates the +extension `unaccent` in `extensions` (available on the CLI image and in +PGlite 0.3.16, loaded by the harness). An account whose workspace holds a +client can no longer be deleted (D9a); in DEV, delete its clients first from +a privileged SQL session, or reset. + ## 4. Writing a migration 1. `pnpm supabase migration new ` creates `supabase/migrations/_.sql`. diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md index 7bf1897f..09c0cbc1 100644 --- a/docs/development/TEST_STRATEGY.md +++ b/docs/development/TEST_STRATEGY.md @@ -16,6 +16,11 @@ V1-1.1 (2026-10-25): supabase vitest 44 (config test added), 12 pgTAP files (`012_workspaces.sql`, 85 checks; 531 checks in all), also run on an isolated real stack because the DEV stack stays untouched until the owner applies M1 (`V1-1_OWNERS_ANIMALS.md` §8.1). +V1-1.2 (2026-10-25): supabase vitest 53 (field-limits parity test added), 13 +pgTAP files (`013_clients.sql`, 130 checks; 661 in all); the isolated stack is +a project tool (`pnpm db:sandbox`, SUPABASE.md §5.1) with its own suite under +`packages/supabase/tests/sandbox` (28 real-stack checks: HTTP per role, +concurrency, budget races, 20 000-client search timing). ## 1. Layers diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index 60fcc75f..ae45907f 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -6,9 +6,12 @@ BDR-073). The architecture of Parts 4 to 9 and the technical choices N1 to N9 were validated by the owner the same day (brief « Validation du contrat V1-1 et autorisation de V1-1.1 Workspaces », BDR-074, §13.2), with the precisions written into §5.3, §9 and §10. The interface choices of §13.3 stay proposals -until their UI steps. Only step V1-1.1 is authorised: migration M1 is written -and tested on an isolated database (§8.1); it is not applied to Supabase DEV, -and nothing of V1-1.2 to V1-1.6 exists. +until their UI steps. V1-1.1 was validated by the owner on 2026-10-25 (brief +« Validation V1-1.1 et autorisation V1-1.2 Données clients », BDR-075), which +authorised V1-1.2. Migrations M1 (§8.1) and M2 (§8.2) are written and tested +on the isolated stack (`pnpm db:sandbox`, SUPABASE.md §5.1); neither is +applied to Supabase DEV (owner procedure: SUPABASE.md §3.3). Nothing of +V1-1.3 to V1-1.6 exists. Branch: `feature/v1-1-clients-animals`. Roadmap position: `IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays the permission frame of Step 10. The file name keeps "OWNERS" so the documents @@ -526,7 +529,7 @@ differences from the sketch below: §8.1. | Migration | Step | Content | |---|---|---| | M1 `20261025100000_workspaces.sql` (written, V1-1.1) | V1-1.1 | enums `workspace_kind`, `workspace_member_role`; `workspaces`, `workspace_members`; helpers; trigger; backfill function called once; `private.log_event` redefined (same signature) to keep `x-correlation-id` only when it matches `^[A-Za-z0-9-]{1,64}$`, plus a NOT VALID CHECK on `audit_logs.correlation_id`; grants; RLS | -| M2 `_clients.sql` | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS | +| M2 `20261025110000_clients.sql` (written, V1-1.2) | V1-1.2 | extension `unaccent`; `private.fold_text`; enum `client_kind`; `clients`; write budget helper; client RPCs and searches; grants; RLS | | M3 `_animals_relations.sql` | V1-1.4 | species rows; enums `animal_sex`, `animal_relation_role`; `animals`, `animal_client_relations`; animal and relation RPCs; grants; RLS | Why the correlation header in M1: `private.log_event` copies that request @@ -755,6 +758,37 @@ workspace along, and the residual admin path of §6.3). The types were generated from that database: the diff with the committed file is exactly the M1 additions. +### 8.2 M2 as built (V1-1.2, 2026-10-25) + +`supabase/migrations/20261025110000_clients.sql`, tested by +`supabase/tests/013_clients.sql` (130 checks), the census of `001_schema.sql`, +the parity test `packages/supabase/tests/db/field-limits.test.ts` and the +sandbox suite `packages/supabase/tests/sandbox/clients.sandbox.ts`. +Differences from the sketch and the plan: + +| Point | Sketch or plan | As built | Why | +|---|---|---|---| +| Replay with other content | not covered | column `create_request_digest` (SHA-256 of the normalised creation content, not granted to any API role); a replay with the same id and another digest is refused `request_conflict` (§9.4), never applied | owner brief §11: a reused request id must not silently accept a divergent operation | +| Text rule in CHECKs | written inline | `private.is_clean_text(value, max)`, immutable, EXECUTE for nobody, used by every text CHECK (M3 reuses it) | one literal for the control ranges | +| Folding | `lower + unaccent` | `lower(unaccent('extensions.unaccent', value) collate "C")`: accents removed, then ASCII lower case only, identical on PGlite and the real image (checked); Cyrillic or Greek capitals keep their case | the database collations differ (C on PGlite, ICU on the image) | +| `search_key` | `concat_ws` | `display_name || ' ' || coalesce(city, '') || ' ' || coalesce(email, '')` | a generated column needs an immutable expression; `concat_ws` is stable | +| Write budget | `require_write_budget(p_actor)`, rolling windows | `private.consume_write_budget(p_workspace_id)` over `private.workspace_write_budgets` (one row per workspace), fixed UTC windows (§10) | owner decision N6 and brief §9: transactional counter per workspace, UTC windows | +| `search_clients` output | with `current_animal_count` | without it | the relations table comes with M3, which recreates the function with the column (return type change) | +| Access layer `clients.ts` | V1-1.2 | moved to V1-1.5, its first consumer, together with the personal workspace read | the brief's V1-1.2 scope lists no access layer; `field-limits.ts` (D-R7) is written now because the parity test needs it | +| Real-stack e2e | `clients-animals.e2e.ts` on the DEV stack | the sandbox suite, on the isolated stack | DEV stays untouched (owner) | + +Search measurement (owner requirement, §8): 20 000 clients in one workspace, +21 POST calls through PostgREST mixing name, city, email and phone terms: +median 9.8 ms, p95 21.4 ms, max 21.9 ms (isolated stack, this host). Under +the 100 ms threshold, so no trigram index is added. + +Residual disclosure found on the real image: a refused direct table access +(`permission denied for table clients`) carries a hint added by the Supabase +image, « Grant the required privileges to the current role with: GRANT +INSERT ON public.clients TO authenticated; ». It names the table, the role +and the privilege, never a value, and the app never sends such a request. +The RPC refusals carry no hint (checked on both engines). + --- ## 9. Policies, helpers and RPCs @@ -765,14 +799,15 @@ M1 additions. |---|---|---|---| | `private.caller_workspace_ids()` | `setof uuid` | the single source of the access rule: workspaces where `auth.uid()` is a member, with an active profile and a confirmed email | `authenticated` (policies evaluate it) | | `private.writable_workspace_ids()` | `setof uuid` | `caller_workspace_ids()` restricted to a write role (V1-1: `holder`) | none (called inside RPCs) | -| `private.require_write_budget(p_workspace_id uuid)` | `void` | raises P0001 `rate_limited` when the workspace has 1 000 audited writes within the past hour or 5 000 within the past day (N6: per workspace); the count and the write are serialised per workspace, never a bare count followed by an unprotected insert; the counter (rows counted by workspace, or a counter row per workspace and window) and its lock are fixed and documented with M2 | none | -| `private.fold_text(p_value text)` | `text` | lower case without accents (`unaccent` with an explicit dictionary), declared immutable for the generated columns | `authenticated` (the invoker search folds the term) | +| `private.consume_write_budget(p_workspace_id uuid)` | `void` | counts one write of the workspace in its UTC hour and day (upsert of its row in `private.workspace_write_budgets`, row lock), raises P0001 `rate_limited` past 1 000 / 5 000 (§10); called last by every write RPC (M2, §8.2) | none | +| `private.is_clean_text(p_value text, p_max integer)` | `boolean` | the text rule of §5 for CHECK constraints (M2) | none | +| `private.fold_text(p_value text)` | `text` | without accents (`unaccent` with an explicit dictionary), then ASCII lower case (collation "C"), declared immutable for the generated columns (§8.2) | `authenticated` (the invoker search folds the term) | | `private.ensure_personal_workspace(p_user_id uuid)` | `boolean` | the single write path: workspace and `holder` membership in one statement, `on conflict do nothing` on `personal_user_id`; true when it created (M1, §8.1) | none | | `private.create_personal_workspace()` | trigger | after insert on `profiles`: calls `ensure_personal_workspace(new.id)` | none | | `private.backfill_personal_workspaces()` | `integer` | same for every profile without a personal workspace; idempotent | none | | `private.check_personal_workspace()` | constraint trigger | deferred to commit: a personal workspace has exactly its account as `holder` (M1, §8.1) | none | -All are `security definer` (except `fold_text`, a pure SQL function), +All are `security definer` (except `fold_text` and `is_clean_text`, pure SQL functions), `set search_path = ''`, `revoke all ... from public, anon, authenticated, service_role` then the grants of the table, and listed in the census of `001_schema.sql`. The write RPCs do not call `private.require_actor()`: its @@ -811,25 +846,37 @@ Write RPCs: `language plpgsql`, `security definer`, volatile, private.writable_workspace_ids())` with its lock, so a caller outside the workspace never takes a lock and never waits on one; no row found raises 42501 `not_found`; -2. calls `private.require_write_budget`; -3. checks, in this order, archived (`archived`), then revision (`conflict`), - then the rules of the table below; +2. checks, in this order, archived (`archived`), then revision (`conflict`), + then the rules of the table below; a replayed create or a call that + changes nothing returns here, uncounted; +3. calls `private.consume_write_budget` (as built in M2: last, after the + checks, so its lock is the last one taken); 4. writes, inside a block that turns `check_violation`, `not_null_violation`, `string_data_right_truncation` and `invalid_text_representation` into `invalid_input`, `unique_violation` on the current-relation index into `duplicate_relation` and `foreign_key_violation` into `not_found`; 5. writes one audit row and returns ids and the new revision only. -Locks: create RPCs of clients and animals lock the workspace row (cap and -insert serialised per workspace); every relation RPC locks the animal row +Locks: create RPCs of clients and animals lock the workspace row `for no +key update` (cap, replay check and insert serialised per workspace, foreign +key checks of other writes not blocked); every relation RPC locks the animal row `for update` then the client row `for share`, in that order; the archive RPCs lock their row `for update`. So caps, « both active » and « animal active » cannot be passed by a concurrent call. The write budget and the 100 000 relations per workspace count rows that writes on different animals or clients can add at the same time: they are counted under a lock that serialises those writes per workspace (owner, N6: never a bare count followed -by an unprotected insert). M2 fixes that lock and the global lock order -(candidate: workspace row, then animal, then client) and documents it here. +by an unprotected insert). As built in M2: the budget row of the workspace +(`private.workspace_write_budgets`) is locked by the upsert of +`private.consume_write_budget`, which every write RPC calls last, after its +entity locks and checks; no lock is taken after it, so no cycle can form. The +lock order of every write RPC is therefore: workspace row (creates), animal +row, client row, budget row. M3 keeps it: a relation create locks the +workspace row first (its 100 000 cap), then the animal, then the client, then +the budget. The budget lock is per workspace: measured on the isolated stack, +a budget row held for 2 s delayed the create of its workspace by 1.75 s while +nine creates in nine other workspaces finished in 8 ms; 60 mixed writes in one +workspace raised no deadlock. Parameters: dates, years and enum values arrive as `text` and are parsed inside the body, so a malformed value (« 2015-02-30 ») is answered `invalid_input` @@ -873,7 +920,7 @@ with POST, so terms and cursors stay out of URLs and access logs. | RPC | Parameters | Returns (one row per record) | Rules | |---|---|---|---| -| `search_clients` | `workspace_id`, `query`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `kind`, `display_name`, `city`, `phone`, `email`, `archived_at`, `name_key`, `current_animal_count` | see below; also serves the client picker of the relation forms | +| `search_clients` | `workspace_id`, `query`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `kind`, `display_name`, `city`, `phone`, `email`, `archived_at`, `name_key`; `current_animal_count` added by M3 (§8.2) | see below; also serves the client picker of the relation forms | | `search_animals` | `workspace_id`, `query`, `species_id`, `archived`, `page_size`, `after_name_key`, `after_id` | `id`, `name`, `species_id`, `species_detail`, `sex`, `breed`, `birth_year`, `archived_at`, `name_key`, `current_owners`, `current_owner_count` | see below; optional species filter | | `list_client_animals` | `client_id`, `page_size`, `after_sort`, `after_id` | relation and animal columns | a client's relations with their animals, current first then former, each group by animal `name_key`, then `id`; keyset on that order; 50 by default, 100 at most | | `client_archive_preview` | `client_id` | `{count, animals}` | active animals for which this client holds the only current `owner` relation: their count and the first 10 by name | @@ -918,6 +965,7 @@ in FR and EN, like the auth and asset failures: | P0001 `duplicate_relation` | `duplicate_relation` | same current (animal, client, role), including the loser of a race | | P0001 `already_ended` | `already_ended` | ending an ended relation | | P0001 `invalid_input` | `invalid_input` | an RPC rule or a constraint or parse error caught inside the RPC | +| P0001 `request_conflict` | `request_conflict` | a create replayed with a known `create_request_id` but other content (§8.2); the first record is kept unchanged | | anything else | `unavailable` | network, server | pgTAP compares the whole error (SQLSTATE, message, detail, hint) of a foreign id @@ -961,7 +1009,7 @@ migration. | Search term | 0 to 100 characters after trimming | a name or a phone fits; longer is noise | RPC | | Records per workspace | 20 000 clients, 20 000 animals, 100 000 relations | a full-time practitioner sees roughly 1 000 to 2 000 visits a year, so 20 000 animals is more than a decade of distinct animals for one person | RPC, under the workspace or animal row lock | | Relations per animal | 20 current, 200 in total | co-owners, keeper and contacts fit in 20; 200 covers decades of sales; the animal page reads them in one select | RPC | -| Write rate | 1 000 audited writes per workspace per rolling hour and 5 000 per rolling day (owner, N6), counted under a per-workspace lock (§9.3); the counter is fixed with M2 | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.require_write_budget`) | +| Write rate | 1 000 audited writes per workspace per UTC hour and 5 000 per UTC day (owner, N6), fixed windows: the hour from hh:00:00 to hh:59:59.999 UTC, the day from 00:00:00 UTC; the first write of a new window restarts its count at 1; the 1 000th write of the hour passes, the 1 001st is refused `rate_limited`. Across an hour boundary up to 2 000 writes can land in 2 minutes; the daily 5 000 still holds. Counted per workspace under the budget row lock (§9.3); a refused write, a replayed create and a call that changes nothing are not counted (the count is rolled back with the refusal) | typing a whole client base by hand stays under 200 an hour; bounds the growth of the append-only audit log and the damage of a stolen session | RPC (`private.consume_write_budget`) | | Audit row size | `correlation_id` kept only when it matches `^[A-Za-z0-9-]{1,64}$`; metadata limited to the workspace id (N9) | the caller no longer chooses the size of an append-only row | M1 (`private.log_event`, CHECK) | | Concurrent writes | optimistic `revision` on every update; locks of §9.3 (workspace row for creates, animal then client row for relations, the row itself for archive); idempotent creates through `create_request_id` | no silent overwrite between two tabs or devices, no cap overshoot, no duplicate on retry | SQL and RPC | | Enumeration | random uuid ids; one 42501 `not_found` for an unknown and a forbidden id in every RPC, with no lock taken outside the caller's workspaces; reads filtered by RLS return empty, never an error that says "exists"; searches limited to one workspace of the caller; closed codes, never values, in errors | | RLS, RPC | @@ -1257,7 +1305,7 @@ validates after V1-1.1 and after the first UI step; nothing merges into | Step | Content | |---|---| | V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), awaiting the owner's checkpoint; not applied to DEV | -| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, access layer (with the personal workspace read deferred from V1-1.1), real-stack e2e | +| V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, sandbox suite. Written and tested on the isolated stack (§8.2), awaiting the owner's checkpoint; not applied to DEV | | V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13) | | V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof | | V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry | From a945e79131c5bbe32ae3dc52c92a3a8e86555fc9 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 21:27:29 +0100 Subject: [PATCH 11/60] fix(supabase): keep sandbox secrets off command lines and DEV out of reach Security gate findings on db-sandbox.sh: containers get secrets from 600 env files, psql and the CLI read PGPASSWORD (no password in --db-url), an incomplete secrets file stops the script before any CLI call, the state folder is refused inside the repository. --- docs/development/SUPABASE.md | 7 +++-- scripts/db-sandbox.sh | 56 ++++++++++++++++++++++++------------ 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 7878e824..6590e86d 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -330,8 +330,11 @@ ports on 127.0.0.1 only and distinct from DEV (db 57432, auth 57999, rest no volume, so `down` removes the containers and the network by their literal names and can never reach a `supabase_*_faunosteo` volume. The password, JWT secret and keys are generated at each `up` into a 600 file under -`~/.cache/faunosteo-db-sandbox` (`FAUNOSTEO_SANDBOX_DIR`), outside the -repository, deleted by `down`, never printed. Works with rootless Docker. +`~/.cache/faunosteo-db-sandbox` (`FAUNOSTEO_SANDBOX_DIR`, refused inside the +repository), with 600 env files that hand them to the containers; deleted by +`down`, never printed, never on a command line (the CLI and psql read +`PGPASSWORD` from the environment). An incomplete secrets file stops the +script before any CLI call. Works with rootless Docker. | Command | What it does | |---|---| diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh index 824e596c..21700f38 100755 --- a/scripts/db-sandbox.sh +++ b/scripts/db-sandbox.sh @@ -39,10 +39,22 @@ SECRETS="$STATE/secrets.sh" CLI=node_modules/.bin/supabase die() { echo "db-sandbox: $*" >&2; exit 1; } -load_secrets() { [ -f "$SECRETS" ] || die "not running (pnpm db:sandbox up fresh)"; . "$SECRETS"; } -db_url() { printf 'postgresql://postgres:%s@127.0.0.1:%s/postgres?sslmode=disable' "$SB_PW" "$PORT_DB"; } +case "$(realpath -m "$STATE")" in + "$PWD" | "$PWD"/*) die "FAUNOSTEO_SANDBOX_DIR must be outside the repository" ;; +esac +# Every value must be present: an empty password would turn --db-url into an +# argument the CLI might read as absent and fall back to the DEV database. +load_secrets() { + [ -f "$SECRETS" ] || die "not running (pnpm db:sandbox up fresh)" + . "$SECRETS" + [ -n "${SB_PW:-}" ] && [ -n "${SB_JWT_SECRET:-}" ] && [ -n "${SB_ANON_KEY:-}" ] && [ -n "${SB_SERVICE_KEY:-}" ] \ + || die "secrets file incomplete (pnpm db:sandbox down, then up)" + export PGPASSWORD="$SB_PW" +} +# No password in the URL: the CLI reads PGPASSWORD, so no secret is on a command line. +db_url() { printf 'postgresql://postgres@127.0.0.1:%s/postgres?sslmode=disable' "$PORT_DB"; } sb_psql() { - docker exec -i -e PGPASSWORD="$SB_PW" "$DB" \ + docker exec -i -e PGPASSWORD "$DB" \ psql -X -q -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 "$@" } wait_for() { @@ -64,7 +76,18 @@ new_secrets() { console.log("SB_JWT_SECRET=" + secret); console.log("SB_ANON_KEY=" + jwt({ role: "anon", iss: "db-sandbox", exp })); console.log("SB_SERVICE_KEY=" + jwt({ role: "service_role", iss: "db-sandbox", exp })); - ' > "$SECRETS" ) + ' > "$SECRETS.new" && mv "$SECRETS.new" "$SECRETS" ) + load_secrets + # The values reach the containers through 600 env files, never through argv. + ( umask 077 + printf 'POSTGRES_PASSWORD=%s\nPGPASSWORD=%s\nJWT_SECRET=%s\n' "$SB_PW" "$SB_PW" "$SB_JWT_SECRET" > "$STATE/db.env" + printf 'GOTRUE_DB_DATABASE_URL=postgresql://supabase_auth_admin:%s@%s:5432/postgres\nGOTRUE_JWT_SECRET=%s\n' \ + "$SB_PW" "$DB" "$SB_JWT_SECRET" > "$STATE/auth.env" + printf 'ANON_KEY=%s\nSERVICE_KEY=%s\nAUTH_JWT_SECRET=%s\nDATABASE_URL=postgresql://supabase_storage_admin:%s@%s:5432/postgres\n' \ + "$SB_ANON_KEY" "$SB_SERVICE_KEY" "$SB_JWT_SECRET" "$SB_PW" "$DB" > "$STATE/storage.env" + printf 'PGRST_DB_URI=postgresql://authenticator:%s@%s:5432/postgres\nPGRST_JWT_SECRET=%s\n' \ + "$SB_PW" "$DB" "$SB_JWT_SECRET" > "$STATE/rest.env" + printf 'Authorization: Bearer %s\n' "$SB_SERVICE_KEY" > "$STATE/service-header" ) } # The role passwords the CLI sets at db start (its /etc/postgresql.schema.sql), @@ -83,23 +106,21 @@ EOF' start_services() { docker network create "$NET" >/dev/null docker run -d --name "$DB" --network "$NET" -p 127.0.0.1:$PORT_DB:5432 \ - -e POSTGRES_PASSWORD="$SB_PW" -e PGPASSWORD="$SB_PW" -e POSTGRES_HOST=/var/run/postgresql \ - -e JWT_SECRET="$SB_JWT_SECRET" -e JWT_EXP=3600 \ + --env-file "$STATE/db.env" -e POSTGRES_HOST=/var/run/postgresql -e JWT_EXP=3600 \ -e POSTGRES_INITDB_ARGS="--allow-group-access --locale-provider=icu --encoding=UTF-8 --icu-locale=en_US.UTF-8" \ --entrypoint sh "$PG_IMAGE" -c "$DB_INIT" >/dev/null - wait_for "database roles" docker exec -e PGPASSWORD="$SB_PW" "$DB" \ + wait_for "database roles" docker exec -e PGPASSWORD "$DB" \ psql -h 127.0.0.1 -U supabase_auth_admin -d postgres -c 'select 1' - wait_for "database" docker exec -e PGPASSWORD="$SB_PW" "$DB" \ + wait_for "database" docker exec -e PGPASSWORD "$DB" \ psql -h 127.0.0.1 -U postgres -d postgres -c 'select 1' docker run -d --name "$MAIL" --network "$NET" -p 127.0.0.1:$PORT_MAIL:8025 "$MAIL_IMAGE" >/dev/null docker run -d --name "$AUTH" --network "$NET" -p 127.0.0.1:$PORT_AUTH:9999 \ -e GOTRUE_API_HOST=0.0.0.0 -e GOTRUE_API_PORT=9999 -e API_EXTERNAL_URL=http://127.0.0.1:$PORT_AUTH \ - -e GOTRUE_DB_DRIVER=postgres \ - -e GOTRUE_DB_DATABASE_URL="postgresql://supabase_auth_admin:$SB_PW@$DB:5432/postgres" \ + -e GOTRUE_DB_DRIVER=postgres --env-file "$STATE/auth.env" \ -e GOTRUE_DB_MIGRATIONS_PATH=/usr/local/etc/auth/migrations \ -e GOTRUE_SITE_URL=http://127.0.0.1:5173 -e GOTRUE_DISABLE_SIGNUP=false \ - -e GOTRUE_JWT_SECRET="$SB_JWT_SECRET" -e GOTRUE_JWT_EXP=3600 \ + -e GOTRUE_JWT_EXP=3600 \ -e GOTRUE_JWT_AUD=authenticated -e GOTRUE_JWT_DEFAULT_GROUP_NAME=authenticated \ -e GOTRUE_JWT_ADMIN_ROLES=service_role \ -e GOTRUE_EXTERNAL_EMAIL_ENABLED=true -e GOTRUE_EXTERNAL_PHONE_ENABLED=false \ @@ -112,8 +133,7 @@ start_services() { -e GOTRUE_PASSWORD_MIN_LENGTH=12 "$AUTH_IMAGE" >/dev/null wait_for "auth" curl -fsS http://127.0.0.1:$PORT_AUTH/health docker run -d --name "$STORAGE" --network "$NET" -p 127.0.0.1:$PORT_STORAGE:5000 \ - -e ANON_KEY="$SB_ANON_KEY" -e SERVICE_KEY="$SB_SERVICE_KEY" -e AUTH_JWT_SECRET="$SB_JWT_SECRET" \ - -e DATABASE_URL="postgresql://supabase_storage_admin:$SB_PW@$DB:5432/postgres" \ + --env-file "$STATE/storage.env" \ -e FILE_SIZE_LIMIT=52428800 -e STORAGE_BACKEND=file -e FILE_STORAGE_BACKEND_PATH=/mnt \ -e TENANT_ID=stub -e STORAGE_S3_REGION=local -e GLOBAL_S3_BUCKET=stub \ -e ENABLE_IMAGE_TRANSFORMATION=false -e IMAGE_TRANSFORMATION_ENABLED=false \ @@ -123,9 +143,9 @@ start_services() { start_rest() { docker run -d --name "$REST" --network "$NET" -p 127.0.0.1:$PORT_REST:3000 \ - -e PGRST_DB_URI="postgresql://authenticator:$SB_PW@$DB:5432/postgres" \ + --env-file "$STATE/rest.env" \ -e PGRST_DB_SCHEMAS=public -e PGRST_DB_EXTRA_SEARCH_PATH=public,extensions \ - -e PGRST_DB_ANON_ROLE=anon -e PGRST_JWT_SECRET="$SB_JWT_SECRET" -e PGRST_DB_MAX_ROWS=1000 \ + -e PGRST_DB_ANON_ROLE=anon -e PGRST_DB_MAX_ROWS=1000 \ "$REST_IMAGE" >/dev/null wait_for "postgrest" curl -fsS -o /dev/null http://127.0.0.1:$PORT_REST/ } @@ -145,7 +165,7 @@ seed() { gotrue_accounts() { curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/admin/users \ - -H "Authorization: Bearer $SB_SERVICE_KEY" -H 'Content-Type: application/json' \ + -H @"$STATE/service-header" -H 'Content-Type: application/json' \ -d '{"email":"pre-confirmed@sandbox.local","password":"Sandbox-only-pw-1","email_confirm":true}' >/dev/null curl -fsS -X POST http://127.0.0.1:$PORT_AUTH/signup -H 'Content-Type: application/json' \ -d '{"email":"pre-unconfirmed@sandbox.local","password":"Sandbox-only-pw-1"}' >/dev/null @@ -154,7 +174,7 @@ gotrue_accounts() { cmd_up() { local mode="${1:-}" docker ps -a --format '{{.Names}}' | grep -q '^faunosteo_dbsandbox_' && die "already up (pnpm db:sandbox down)" - new_secrets; . "$SECRETS" + new_secrets start_services case "$mode" in fresh) @@ -183,7 +203,7 @@ cmd_up() { cmd_down() { docker rm -f "$REST" "$STORAGE" "$AUTH" "$MAIL" "$DB" >/dev/null 2>&1 || true docker network rm "$NET" >/dev/null 2>&1 || true - rm -f "$SECRETS" + rm -f "$SECRETS" "$STATE/db.env" "$STATE/auth.env" "$STATE/storage.env" "$STATE/rest.env" "$STATE/service-header" echo "== sandbox removed" } From 5bc6631b6eab79206212294363c35375122b09b7 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 21:27:29 +0100 Subject: [PATCH 12/60] chore(memory): BDR-075, EVAL-037, V1-1.2 journal, TODO, gate contract --- .claude/memory/decisions.md | 8 +++ .claude/memory/evals.md | 8 +++ .claude/memory/journal.md | 4 ++ .claude/tasks/TODO.md | 14 ++--- .../contracts/2026-10-25-v1-1-2-clients.md | 59 +++++++++++++++++++ CLAUDE.md | 7 ++- 6 files changed, 90 insertions(+), 10 deletions(-) create mode 100644 .claude/tasks/contracts/2026-10-25-v1-1-2-clients.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index f2a17de9..47ea417f 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -550,3 +550,11 @@ M1 as built (`20261025100000_workspaces.sql`): creation = server init in sign-up 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. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 9994d592..ae3995f5 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -260,3 +260,11 @@ Method: fresh verifier on contract `.claude/tasks/contracts/2026-10-25-v1-1-1-wo 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. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 6eb7069e..230d0371 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -405,3 +405,7 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp - 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. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 50558785..8a57122c 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -401,17 +401,17 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - 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) - - [ ] 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 - - [ ] M2 `_clients.sql`: unaccent, `private.fold_text`, `client_kind`, `clients` (+ `create_request_digest` for divergent replays), budget table + `private.consume_write_budget` (UTC fixed hour/day windows, row lock, last lock taken), RPCs create/update/set_archived/search, N9 audit policy, grants, RLS - - [ ] pgTAP 013; harness loads unaccent; `field-limits.ts` + behavioural parity test; types; census - - [ ] 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 - - [ ] docs: contract (budget, divergent replay, search_clients without current_animal_count until M3), SUPABASE.md, TEST_STRATEGY, BDR-075, journal - - [ ] fresh verifier + security audit; rust:check, check:all; checkpoint + - [x] M1 closure: types re-checked with the official generator against an isolated DB holding M1 (diff 0); sandbox tool committed (`scripts/db-sandbox.sh`, `pnpm db:sandbox`: rootless, loopback, own ports, no volume, generated secrets outside Git, fresh + upgrade, official `supabase test db` / `gen types` via `--db-url`); owner DEV procedure for M1 (target, history, backup incl. auth, restore check, `db:test` non-destructive check) rehearsed on the sandbox; LRN-080/081 + - [x] M2 `_clients.sql`: unaccent, `private.fold_text`, `client_kind`, `clients` (+ `create_request_digest` for divergent replays), budget table + `private.consume_write_budget` (UTC fixed hour/day windows, row lock, last lock taken), RPCs create/update/set_archived/search, N9 audit policy, grants, RLS + - [x] pgTAP 013; harness loads unaccent; `field-limits.ts` + behavioural parity test; types; census + - [x] sandbox suite (vitest, real GoTrue/PostgREST sessions): M1 regression, clients HTTP, concurrency (creates, replay, divergent replay, stale revision, archive/restore race, budget limits, no deadlock), 20 000-client search timing + - [x] docs: contract (budget, divergent replay, search_clients without current_animal_count until M3), SUPABASE.md, TEST_STRATEGY, BDR-075, journal + - [x] fresh verifier + security audit (PASS; ECARTS closed); sandbox hardened; rust:check, check:all green; checkpoint - Deviation: access layer `clients.ts` + workspace read move to V1-1.5 (first consumer; brief §6 scope lists no access layer) - Objective: clients created, edited, archived, restored and searched through RPCs with the D15 guards, isolated per workspace, proven on the real stack - Depends: V1-1.1; N2, N3, N6, N9 decided - Files: `supabase/migrations/_clients.sql`; `supabase/tests/013_clients.sql`; `packages/supabase/tests/db/harness.ts` (load `unaccent`); `packages/supabase/src/field-limits.ts` + `tests/db/field-limits.test.ts` (behavioural parity, code points); `packages/supabase/src/clients.ts` (accessors, closed failure kinds) + unit tests; `packages/supabase/tests/e2e/clients-animals.e2e.ts` (seed and teardown through the existing psql helper), `scripts/clients-animals-e2e.sh`, root script (name to confirm); types regenerated - - Migration M2: `unaccent` in `extensions`; `private.fold_text`; `private.require_write_budget(p_workspace_id)` (N6: per workspace, 1 000/h, 5 000/day, counted under a per-workspace lock; document counter + lock order in contract §9.3); 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 + - 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 diff --git a/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md b/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md new file mode 100644 index 00000000..b1047d95 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-25-v1-1-2-clients.md @@ -0,0 +1,59 @@ +# CONTRACT: V1-1.2 Clients data (M2) + M1 closure, owner brief 2026-10-25 « Validation V1-1.1 et autorisation V1-1.2 Données clients » + +- branch `feature/v1-1-clients-animals`, base 6bf6978 (V1-1.1 validated); commits 08abe42 (sandbox tool + M1 suite), + 5ed1f01 (DEV procedure docs), 2c0531d (memory), 4adbfcb (M2 code), f8bd1b6 (docs) +- diff under review: `git diff 6bf6978..f8bd1b6 -- scripts supabase packages package.json docs` +- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §5, §5.1, §8.2, §9, §10, §12, §13.2 +- isolated stack: `pnpm db:sandbox` (scripts/db-sandbox.sh, SUPABASE.md §5.1) is UP (upgrade mode, M1+M2 applied over + older data). Allowed: `pnpm db:sandbox test-db`, `pnpm db:sandbox types --check`, `pnpm db:sandbox test`, + `echo "" | pnpm db:sandbox sql`. The DEV stack (`supabase_*_faunosteo`) must not be touched except + `pnpm supabase migration list --local` (read-only). + +## Clauses + +C1. **Scope.** M2 only: `supabase/migrations/20261025110000_clients.sql`. No M3 object (animals, relations, species +rows, animal enums), no React screen or route, no V1-1.3 tooling (Playwright, Dialog), no change to crates/, no edit of an +existing migration, no change to existing tables' grants or policies except the N9 condition on `audit_logs_select_admin`. + +C2. **M1 closure.** The committed `database.types.ts` equals the official generator's output (`supabase gen types +typescript --schema public`, through Prettier) against an isolated database holding the migrations; no hand edit; types +cover exactly the public schema objects of M1 and M2. + +C3. **Sandbox tool.** `scripts/db-sandbox.sh`: rootless Docker, ports on 127.0.0.1 only and distinct from DEV, no volume +created or removed, cleanup by literal `faunosteo_dbsandbox_*` names only, secrets generated outside the repository and +never printed or committed, image versions pinned and documented, fresh and upgrade modes, every Supabase CLI call with +an explicit sandbox `--db-url` (none can reach DEV). + +C4. **DEV procedure (doc only).** SUPABASE.md §3.3: target check, migration history, only V1-1 migrations pending, +accounts count, backup including auth data stored outside Git and checked, application without reset and without +`db push`, `migration repair` or destructive command, `db:test` shown non-destructive, post-checks (history, workspaces, +duplicates, privileges, types, e2e:avatar), stop conditions, no secret printed. Claude applied nothing to DEV. + +C5. **Clients model.** person | organization; `display_name` required, no first/last name, no notes; optional contacts; +no default country; workspace FK `on delete restrict`; text rules and bounds as contract §5/§5.1; no sensitive extra +field; `field-limits.ts` constants proven equal to the SQL CHECKs by a behavioural parity test (bounds, code points, +control ranges, patterns; TypeScript never accepts what SQL refuses). + +C6. **RPCs.** `create_client`, `update_client`, `set_client_archived` (definer) and `search_clients` (invoker): identity +from `auth.uid()` only via `writable_workspace_ids` / RLS (active profile, confirmed email); same whole error for a +foreign and an unknown id; parse errors and constraint violations → `invalid_input` without echo; idempotent create, +divergent replay → `request_conflict`; stale revision → `conflict`; archived read-only (`archived` before `conflict`); +restore allowed; no-op writes nothing; EXECUTE only for authenticated; search_path empty; owner postgres; audit rows +ids only (`{workspace_id}`), hidden from platform staff (N9). + +C7. **Budget and caps.** Transactional counter per workspace (owner §9): UTC hour/day windows documented (zone, reset, +boundaries); 1 000/h, 5 000/day, 20 000 clients; increment and write in one transaction; refused, replayed and no-op +calls not counted; concurrency-safe; stable lock order documented (workspace, animal, client, budget last); lock scope +per workspace, measured. + +C8. **Search.** POST RPC, 25 default / 100 max page, ≤ 100-character term, deterministic order `(name_key, id)` with +keyset, LIKE wildcards escaped, phone search, no leak of another workspace through rows, counts or pages; index exists; +20 000-client timing recorded. + +C9. **Tests.** pgTAP `013_clients.sql` + `001` census green on PGlite and on the isolated real image (fresh and upgrade); +sandbox suite: real authenticated sessions per role (A, B, anon key, service key, deactivated, unconfirmed), concurrent +creates, replays, divergent replay race, stale revision race, archive/restore race, budget at the limit under +concurrency, no deadlock; M1 regression (workspaces, backfill, auth/profile). `pnpm test:run` green. + +C10. **Docs and limits.** Contract §8.2 as built + deviations, SUPABASE.md §3.4/§5.1, TEST_STRATEGY, BDR-075, LRN-080/081 +(scoped, no duplicate). No merge, main and release/0.2.0 untouched, no deploy, fixtures fictitious. diff --git a/CLAUDE.md b/CLAUDE.md index 5753ea05..9d2f7038 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,8 +50,8 @@ Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1- 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`: business decisions ratified 2026-10-25, BDR-073; architecture and N1-N9 validated, BDR-074; on -`feature/v1-1-clients-animals` only V1-1.1 is built: migration `20261025100000_workspaces.sql`, tested on PGlite and an -isolated stack, not applied to Supabase DEV). +`feature/v1-1-clients-animals` V1-1.1 (validated) and V1-1.2 are built: migrations `20261025100000_workspaces.sql` and +`20261025110000_clients.sql`, tested on PGlite and the isolated stack `pnpm db:sandbox`, not applied to Supabase DEV). --- @@ -123,6 +123,7 @@ pnpm db:reset # replay from zero pnpm db:test # pgTAP on the real stack pnpm db:types # regenerate packages/supabase/src/database.types.ts pnpm db:types:check # CI diff +pnpm db:sandbox up fresh|up upgrade |test-db|types [--check]|test|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) @@ -275,7 +276,7 @@ faunosteo/ │ └─ 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), workspaces (V1-1.1: personal workspace per account, access helpers) +│ ├─ 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) │ ├─ 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) From 57922e09028af7e17699c39c2d1b495995b39f99 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 22:20:55 +0100 Subject: [PATCH 13/60] fix(supabase): refuse bad sandbox arguments before starting anything pnpm db:sandbox up with an unknown mode or a missing or malformed upgrade version started four containers and wrote the secrets before refusing. The mode and the version (fourteen digits) are now checked first. --- docs/development/SUPABASE.md | 4 +++- scripts/db-sandbox.sh | 10 ++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index 6590e86d..89a07428 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -334,7 +334,9 @@ secret and keys are generated at each `up` into a 600 file under repository), with 600 env files that hand them to the containers; deleted by `down`, never printed, never on a command line (the CLI and psql read `PGPASSWORD` from the environment). An incomplete secrets file stops the -script before any CLI call. Works with rootless Docker. +script before any CLI call, and a wrong `up` mode or version (fourteen +digits) is refused before any container or secret exists. Works with rootless +Docker. | Command | What it does | |---|---| diff --git a/scripts/db-sandbox.sh b/scripts/db-sandbox.sh index 21700f38..58d35e40 100755 --- a/scripts/db-sandbox.sh +++ b/scripts/db-sandbox.sh @@ -173,6 +173,13 @@ gotrue_accounts() { cmd_up() { local mode="${1:-}" + # Arguments checked before anything starts: a refusal leaves no container or secret. + case "$mode" in + fresh) ;; + upgrade) [[ "${2:-}" =~ ^[0-9]{14}$ ]] \ + || die "up upgrade needs the first new migration version, e.g. 20261025100000" ;; + *) die "up fresh | up upgrade " ;; + esac docker ps -a --format '{{.Names}}' | grep -q '^faunosteo_dbsandbox_' && die "already up (pnpm db:sandbox down)" new_secrets start_services @@ -180,7 +187,7 @@ cmd_up() { fresh) migrate_up . ; seed ;; upgrade) - local version="${2:?upgrade needs the first new migration version, e.g. 20261025100000}" + local version="$2" # A CLI workdir holding only the migrations before ; kept in the # state folder and refilled at each upgrade run (the CLI writes .temp there). local base="$STATE/upgrade-base" @@ -194,7 +201,6 @@ cmd_up() { seed; gotrue_accounts echo "== before: $(sb_psql -t -A -c 'select count(*) from public.profiles') profiles" migrate_up . ;; - *) die "up fresh | up upgrade " ;; esac start_rest echo "== sandbox up ($mode): db 127.0.0.1:$PORT_DB, auth :$PORT_AUTH, rest :$PORT_REST, mail :$PORT_MAIL" From 6f885eccb2b64e7a0b9e7a00340b92b7eae473d8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 22:36:31 +0100 Subject: [PATCH 14/60] feat(ui): modal dialogs on the native dialog element (D13) ModalDialog wraps showModal(): the page behind is inert and does not scroll, focus starts on the first control and returns to the opener, or to the first control of its nearest container when the opener is gone. Escape and close requests only ask the consumer. Dialog gains aria-labelledby and an optional described message; the confirmations pass theirs. The mobile drawer uses the same primitive and closes at the sidebar breakpoint. --- .../src/components/account/AvatarSection.tsx | 9 +- .../components/report/DisclaimerDialog.tsx | 8 +- .../components/report/HeldSessionPanel.tsx | 16 +- .../report/ReplaceSessionDialog.tsx | 9 +- .../app/src/components/shell/MobileDrawer.tsx | 98 +++++----- apps/app/src/components/ui/Dialog.tsx | 115 +++++------ apps/app/src/components/ui/ModalDialog.tsx | 133 +++++++++++++ apps/app/src/styles/index.css | 2 + apps/app/tests/unit/ui.Dialog.test.tsx | 178 +++++++++++++++++- 9 files changed, 450 insertions(+), 118 deletions(-) create mode 100644 apps/app/src/components/ui/ModalDialog.tsx diff --git a/apps/app/src/components/account/AvatarSection.tsx b/apps/app/src/components/account/AvatarSection.tsx index e50041fe..04a8a3d3 100644 --- a/apps/app/src/components/account/AvatarSection.tsx +++ b/apps/app/src/components/account/AvatarSection.tsx @@ -256,8 +256,13 @@ export default function AvatarSection() { {t(`account.avatar.error.${phase.failure}`)} )} {rejected && {t(`account.avatar.rejected.${rejected}`)}} - setConfirmOpen(false)} title={t('account.avatar.remove_title')} size="sm"> -

{t('account.avatar.remove_body')}

+ setConfirmOpen(false)} + title={t('account.avatar.remove_title')} + description={

{t('account.avatar.remove_body')}

} + size="sm" + >
-
+
+
) diff --git a/apps/app/src/components/report/HeldSessionPanel.tsx b/apps/app/src/components/report/HeldSessionPanel.tsx index 226fceb9..3ea0af19 100644 --- a/apps/app/src/components/report/HeldSessionPanel.tsx +++ b/apps/app/src/components/report/HeldSessionPanel.tsx @@ -114,15 +114,17 @@ export default function HeldSessionPanel({ ? 'session.held.open_title' : `session.held.discard_title_${pending?.action === 'discard' ? pending.text : 'draft'}`, )} + description={ +

+ {t( + pending?.action === 'open' + ? 'session.held.open_body' + : 'session.held.discard_body', + )} +

+ } size="sm" > -

- {t( - pending?.action === 'open' - ? 'session.held.open_body' - : 'session.held.discard_body', - )} -

-
-
- -
-
- - -
- + + - )} - +
+ +
+
+ + +
+ + ) } diff --git a/apps/app/src/components/ui/Dialog.tsx b/apps/app/src/components/ui/Dialog.tsx index 8d9211ac..5b85a9c4 100644 --- a/apps/app/src/components/ui/Dialog.tsx +++ b/apps/app/src/components/ui/Dialog.tsx @@ -1,11 +1,15 @@ -import { useEffect, type ReactNode } from 'react' +import { useId, type ReactNode } from 'react' import { AnimatePresence, motion } from 'motion/react' +import ModalDialog from './ModalDialog' import { useT } from '@/i18n/useT' export interface DialogProps { open: boolean + /** Asked on Escape, the close button and a backdrop click; the dialog leaves when `open` turns false. */ onClose: () => void title: string + /** The dialog's message, announced with its name (aria-describedby). */ + description?: ReactNode children: ReactNode size?: 'sm' | 'md' | 'lg' | 'xl' } @@ -17,61 +21,66 @@ const SIZE: Record, string> = { xl: 'max-w-4xl', } -export default function Dialog({ - open, - onClose, - title, - children, - size = 'md', -}: DialogProps) { - const t = useT() - useEffect(() => { - if (!open) return - const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [open, onClose]) - +export default function Dialog({ open, ...surface }: DialogProps) { return ( - - {open && ( -
- {open && } + ) +} + +function DialogSurface({ + onClose, + title, + description, + children, + size = 'md', +}: Omit) { + const t = useT() + const titleId = useId() + const descriptionId = useId() + return ( + + + +
+

+ {title} +

+ -
-
{children}
-
+ ✕ + + +
+ {description &&
{description}
} + {children}
- )} - +
+
) } diff --git a/apps/app/src/components/ui/ModalDialog.tsx b/apps/app/src/components/ui/ModalDialog.tsx new file mode 100644 index 00000000..f2892d37 --- /dev/null +++ b/apps/app/src/components/ui/ModalDialog.tsx @@ -0,0 +1,133 @@ +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 that can take focus: the first one on open, 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]:not([tabindex="-1"])', +].join(', ') + +/** Full-viewport transparent container: the consumer draws its own backdrop and panel. */ +const SURFACE = + 'm-0 h-full max-h-none w-full max-w-none overflow-hidden border-0 bg-transparent p-0 ' + + 'text-inherit backdrop:bg-transparent' + +/** False when the browser refused the focus (element gone, disabled, hidden or inert). */ +function tryFocus(element: HTMLElement): boolean { + element.focus() + return document.activeElement === element +} + +function ancestorsOf(element: HTMLElement | null): HTMLElement[] { + const chain: HTMLElement[] = [] + for (let node = element?.parentElement; node; node = node.parentElement) + chain.push(node) + return chain +} + +/** + * The opener when it still takes focus, else the first control of its nearest + * container still on the page. + */ +function restoreFocus( + opener: HTMLElement | null, + ancestors: HTMLElement[], +): void { + if (!opener || tryFocus(opener)) return + for (const container of ancestors) { + if (!container.isConnected) continue + const controls = Array.from( + container.querySelectorAll(FOCUSABLE), + ) + if (controls.some(tryFocus)) return + } +} + +/** + * Native modal `` shown while mounted (D13): `showModal()` makes the + * rest of the page inert and keeps focus in the top layer. The dialog never + * closes itself: Escape and close requests call `onClose`, and it leaves the + * screen when the consumer unmounts it. Focus starts on the first control and + * then returns to the opener. Tab past the last control reaches the browser's + * own interface, never the page, as the platform intends. + */ +export default function ModalDialog({ + onClose, + labelledBy, + label, + describedBy, + className = '', + children, +}: ModalDialogProps) { + const ref = useRef(null) + + useLayoutEffect(() => { + const dialog = ref.current + if (!dialog) return + const active = document.activeElement + const opener = + active instanceof HTMLElement && active !== document.body ? active : null + const ancestors = ancestorsOf(opener) + dialog.showModal() + // The first control, not the platform's pick: Chromium focuses a scrollable + // panel when the content is long, the close button otherwise. + dialog.querySelector(FOCUSABLE)?.focus() + return () => { + if (dialog.open) dialog.close() + restoreFocus(opener, ancestors) + } + }, []) + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape' || event.nativeEvent.isComposing) return + // A cancelled keydown is no close request: Chromium would otherwise close the + // dialog on a second Escape without asking (close watcher anti-abuse rule). + event.preventDefault() + event.stopPropagation() + onClose() + } + const onCancel = (event: SyntheticEvent) => { + event.preventDefault() + onClose() + } + // Closed by the platform anyway: keep the consumer's state in step. The check + // ignores the `close` event queued by a cleanup the dialog has since reopened from. + const onClosed = () => { + if (ref.current && !ref.current.open) onClose() + } + + return ( + + {children} + + ) +} diff --git a/apps/app/src/styles/index.css b/apps/app/src/styles/index.css index e7d281d3..e3013938 100644 --- a/apps/app/src/styles/index.css +++ b/apps/app/src/styles/index.css @@ -2,6 +2,8 @@ @import './tokens.css'; html, body, #root { height: 100%; } +/* A modal dialog is open (components/ui/ModalDialog): the page behind it does not scroll. */ +html:has(dialog:modal) { overflow: hidden; } body { background: var(--color-bg); color: var(--color-ink); diff --git a/apps/app/tests/unit/ui.Dialog.test.tsx b/apps/app/tests/unit/ui.Dialog.test.tsx index 32ea6659..7bd73f67 100644 --- a/apps/app/tests/unit/ui.Dialog.test.tsx +++ b/apps/app/tests/unit/ui.Dialog.test.tsx @@ -1,7 +1,14 @@ import { describe, it, expect, vi } from 'vitest' -import { render, screen } from '@testing-library/react' +import { useState } from 'react' +import { fireEvent, render, screen, waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import Dialog from '@/components/ui/Dialog' +import ModalDialog from '@/components/ui/ModalDialog' +import { useLocaleStore } from '@/state/localeStore' + +// happy-dom implements neither the top layer nor inertness nor the dialog's focus +// steps: these tests cover the React wiring, the browser behaviour is proven by +// the Playwright suites (apps/app/e2e). describe('Dialog', () => { it('renders nothing when open=false', () => { @@ -32,4 +39,173 @@ describe('Dialog', () => { await userEvent.click(screen.getByTestId('dialog-backdrop')) expect(onClose).toHaveBeenCalled() }) + + it('is a native dialog named by its title and described by its message', () => { + render( + {}} + title="Remove the photo?" + description={

It goes for good.

} + > + +
, + ) + const dialog = screen.getByRole('dialog', { name: 'Remove the photo?' }) + expect(dialog.tagName).toBe('DIALOG') + expect(dialog).toHaveAccessibleDescription('It goes for good.') + }) + + it('has no description when none is given', () => { + render( + {}} title="X"> + body + , + ) + expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-describedby') + }) + + it.each([ + ['fr', 'Fermer'], + ['en', 'Close'], + ] as const)( + 'asks to close from the close button, named in %s', + async (locale, name) => { + useLocaleStore.setState({ locale }) + const onClose = vi.fn() + render( + + body + , + ) + await userEvent.click(screen.getByRole('button', { name })) + expect(onClose).toHaveBeenCalledTimes(1) + }, + ) +}) + +describe('ModalDialog', () => { + it('opens as a modal while mounted and closes on unmount', () => { + const showModal = vi.spyOn(HTMLDialogElement.prototype, 'showModal') + const close = vi.spyOn(HTMLDialogElement.prototype, 'close') + const { unmount } = render( + {}} label="Menu"> + + , + ) + expect(showModal).toHaveBeenCalledTimes(1) + unmount() + expect(close).toHaveBeenCalledTimes(1) + showModal.mockRestore() + close.mockRestore() + }) + + it('turns Escape into a request: the consumer decides, the dialog stays open', () => { + const onClose = vi.fn() + render( + + + , + ) + const dialog = screen.getByRole('dialog', { + name: 'Menu', + }) as HTMLDialogElement + const escape = new KeyboardEvent('keydown', { + key: 'Escape', + bubbles: true, + cancelable: true, + }) + screen.getByRole('button', { name: 'Inside' }).dispatchEvent(escape) + fireEvent.keyDown(dialog, { key: 'Escape' }) + expect(escape.defaultPrevented).toBe(true) + expect(onClose).toHaveBeenCalledTimes(2) + expect(dialog.open).toBe(true) + }) + + it('ignores Escape while a composition is in progress', () => { + const onClose = vi.fn() + render( + + + , + ) + fireEvent.keyDown(screen.getByLabelText('Name'), { + key: 'Escape', + isComposing: true, + }) + expect(onClose).not.toHaveBeenCalled() + }) + + it('cancels the platform close request and asks the consumer instead', () => { + const onClose = vi.fn() + render( + + + , + ) + const cancel = new Event('cancel', { cancelable: true }) + screen.getByRole('dialog').dispatchEvent(cancel) + expect(cancel.defaultPrevented).toBe(true) + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('follows a close the platform forced, and ignores a close event while still open', () => { + const onClose = vi.fn() + render( + + + , + ) + const dialog = screen.getByRole('dialog') as HTMLDialogElement + dialog.dispatchEvent(new Event('close')) + expect(onClose).not.toHaveBeenCalled() + dialog.close() + expect(onClose).toHaveBeenCalledTimes(1) + }) +}) + +/** An opener that can disappear while its dialog is open, beside a sibling control. */ +function Harness({ removeOpener = false }: { removeOpener?: boolean }) { + const [open, setOpen] = useState(false) + const [openerShown, setOpenerShown] = useState(true) + const confirm = () => { + if (removeOpener) setOpenerShown(false) + setOpen(false) + } + return ( +
+
+ + {openerShown && ( + + )} +
+ setOpen(false)} title="Confirm"> + + +
+ ) +} + +describe('Dialog focus return', () => { + it('returns focus to the opener', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: 'Open' })) + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(screen.getByRole('button', { name: 'Open' })).toHaveFocus() + }) + + it('falls back to the first control of the opener’s container when the opener is gone', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: 'Open' })) + await userEvent.click(screen.getByRole('button', { name: 'Confirm' })) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(screen.queryByRole('button', { name: 'Open' })).toBeNull() + expect(screen.getByRole('button', { name: 'Sibling' })).toHaveFocus() + }) }) From 72ee9f99711cb61640e405fd71e98a37eaad6417 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 22:36:43 +0100 Subject: [PATCH 15/60] test(app): Playwright and axe browser suite on Chromium (D14) @playwright/test 1.64.1 and @axe-core/playwright 4.14.0, dev only and pinned. pnpm e2e:ui runs a Vite server of its own on 127.0.0.1:5191 with no backend: the Dialog contract on a dev-only test page and the local tool's dialogs, desktop and 375 px, FR and EN, axe at zero serious violation outside one listed pre-existing finding. Requests outside the allowlist are aborted and fail the test. --- .gitignore | 1 + apps/app/e2e/harness/dialog.html | 12 ++ apps/app/e2e/harness/dialog.tsx | 134 +++++++++++++++++ apps/app/e2e/playwright.ui.config.ts | 40 +++++ apps/app/e2e/support/browser.ts | 166 ++++++++++++++++++++ apps/app/e2e/tsconfig.json | 11 ++ apps/app/e2e/ui/dialog.spec.ts | 216 +++++++++++++++++++++++++++ apps/app/e2e/ui/local-tool.spec.ts | 104 +++++++++++++ apps/app/package.json | 7 +- package.json | 3 +- pnpm-lock.yaml | 49 ++++++ 11 files changed, 740 insertions(+), 3 deletions(-) create mode 100644 apps/app/e2e/harness/dialog.html create mode 100644 apps/app/e2e/harness/dialog.tsx create mode 100644 apps/app/e2e/playwright.ui.config.ts create mode 100644 apps/app/e2e/support/browser.ts create mode 100644 apps/app/e2e/tsconfig.json create mode 100644 apps/app/e2e/ui/dialog.spec.ts create mode 100644 apps/app/e2e/ui/local-tool.spec.ts diff --git a/.gitignore b/.gitignore index 499350c1..fc5056b2 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ Thumbs.db coverage/ playwright-report/ test-results/ +blob-report/ .nyc_output/ # Cache diff --git a/apps/app/e2e/harness/dialog.html b/apps/app/e2e/harness/dialog.html new file mode 100644 index 00000000..a4009d0e --- /dev/null +++ b/apps/app/e2e/harness/dialog.html @@ -0,0 +1,12 @@ + + + + + + Dialog harness + + +
+ + + diff --git a/apps/app/e2e/harness/dialog.tsx b/apps/app/e2e/harness/dialog.tsx new file mode 100644 index 00000000..62b15716 --- /dev/null +++ b/apps/app/e2e/harness/dialog.tsx @@ -0,0 +1,134 @@ +/** + * Test page for the shared Dialog in a real browser (e2e/ui/dialog.spec.ts). + * Served by the Vite dev server only (`/e2e/harness/dialog.html`); the build + * has a single entry, index.html, so this page never ships. Each scenario is a + * case of the D13 contract, not a product journey: `?lang=en` picks the language. + */ +import { StrictMode, useState } from 'react' +import { createRoot } from 'react-dom/client' +import '@/styles/index.css' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import { useLocaleStore } from '@/state/localeStore' +import type { Locale } from '@/i18n/types' + +const lang: Locale = + new URLSearchParams(location.search).get('lang') === 'en' ? 'en' : 'fr' +useLocaleStore.setState({ locale: lang }) +document.documentElement.lang = lang + +type Scenario = 'basic' | 'long' | 'guarded' | 'vanishing' | null + +function Background({ onOpen }: { onOpen: (scenario: Scenario) => void }) { + const [clicks, setClicks] = useState(0) + return ( +
+
+ + + +
+ +

{clicks}

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

Dialog harness

+ +
+ + {item && ( + + )} +
+ {/* Taller than any viewport: the page would scroll if the dialog let it. */} +
+ ) +} + +createRoot(document.getElementById('root') as HTMLElement).render( + + + , +) diff --git a/apps/app/e2e/playwright.ui.config.ts b/apps/app/e2e/playwright.ui.config.ts new file mode 100644 index 00000000..4b61a066 --- /dev/null +++ b/apps/app/e2e/playwright.ui.config.ts @@ -0,0 +1,40 @@ +/** + * `pnpm e2e:ui`: Chromium against a Vite dev server with no backend, on a + * loopback port of its own (never the owner's `pnpm dev` on 5173, never + * reused): the Dialog test page and the local tool. docs/development/BROWSER_TESTS.md. + */ +import { defineConfig } from '@playwright/test' +import type { GuardOptions } from './support/browser' +import { PROJECTS } from './support/browser' + +const ORIGIN = 'http://127.0.0.1:5191' + +export default defineConfig({ + testDir: './ui', + // The local tool runs the core: a missing or stale module stops the run (pnpm wasm:build). + globalSetup: '../../../packages/core-wasm/tests/global-setup.ts', + outputDir: './test-results/ui', + fullyParallel: true, + forbidOnly: true, + retries: 0, + reporter: [ + ['list'], + ['html', { outputFolder: './playwright-report/ui', open: 'never' }], + ], + use: { + baseURL: ORIGIN, + allowedOrigins: [ORIGIN], + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + }, + projects: PROJECTS, + webServer: { + command: 'node_modules/.bin/vite --host 127.0.0.1 --port 5191 --strictPort', + cwd: '..', + url: `${ORIGIN}/`, + reuseExistingServer: false, + timeout: 120_000, + // No backend: an empty connection keeps any .env value out of this server. + env: { VITE_SUPABASE_URL: '', VITE_SUPABASE_ANON_KEY: '' }, + }, +}) diff --git a/apps/app/e2e/support/browser.ts b/apps/app/e2e/support/browser.ts new file mode 100644 index 00000000..bfec691f --- /dev/null +++ b/apps/app/e2e/support/browser.ts @@ -0,0 +1,166 @@ +/** + * 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. */ +export const PROJECTS: Project[] = [ + { + name: 'chromium-desktop', + 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[] +} + +/** + * 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. + */ +export const test = base.extend({ + allowedOrigins: [[], { option: true }], + forbiddenInUrls: [[], { option: true }], + requestGuard: [ + async ({ context, allowedOrigins, forbiddenInUrls }, use) => { + const refused: string[] = [] + const leaking: string[] = [] + await context.route( + (url) => !allowedOrigins.includes(url.origin), + (route) => { + refused.push(route.request().url()) + return route.abort('blockedbyclient') + }, + ) + context.on('request', (request) => { + const url = decodeURIComponent(request.url()) + if (forbiddenInUrls.some((value) => value && url.includes(value))) + leaking.push(url) + }) + await use() + 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 these exact nodes through and fails on any + * other. The language switcher's buttons show « FR » / « EN » but are named + * « Passer en français » / « Switch to English » (WCAG 2.5.3 label in name). + */ +const KNOWN_VIOLATIONS: { id: string; target: RegExp }[] = [ + { + id: 'label-content-name-mismatch', + target: /^button\[aria-label="(Passer en français|Switch to English)"\]$/, + }, +] + +const isKnown = (id: string, target: string) => + KNOWN_VIOLATIONS.some((known) => known.id === id && known.target.test(target)) + +/** + * Zero serious or critical axe violation on the page as it stands (WCAG 2.0 to + * 2.2 A and AA rules plus axe best practices), known ones aside; the failure + * message lists them. + */ +export async function expectAccessible( + page: Page, + state: string, +): Promise { + // Colours are measured at rest: an entrance animation still running would blend them. + await page.waitForFunction(() => + document + .getAnimations() + .every((animation) => animation.playState !== 'running'), + ) + const { violations } = await new AxeBuilder({ page }) + .withTags([ + 'wcag2a', + 'wcag2aa', + 'wcag21a', + 'wcag21aa', + 'wcag22aa', + 'best-practice', + ]) + .analyze() + const blocking = violations + .filter((v) => v.impact === 'serious' || v.impact === 'critical') + .flatMap((v) => + v.nodes + .map((node) => node.target.join(' ')) + .filter((target) => !isKnown(v.id, target)) + .map((target) => `${v.impact} ${v.id}: ${v.help} → ${target}`), + ) + expect(blocking, `axe on ${state}`).toEqual([]) +} + +/** + * Where the focus is: in the open modal dialog, in the browser's own interface + * (the document lost focus, as Tab past a modal dialog's last control does), or + * on something else of the page. + */ +export function focusOwner(page: Page): Promise { + return page.evaluate(() => { + const active = document.activeElement + if (!document.hasFocus()) return 'browser' + if (!active || active === document.body) return 'body' + if (active.closest('dialog:modal')) return 'dialog' + return `outside:${active.tagName.toLowerCase()}:${active.textContent?.trim().slice(0, 40)}` + }) +} + +/** Accessible name of the focused element (aria-label, else its text). */ +export function focusedName(page: Page): Promise { + return page.evaluate(() => { + const active = document.activeElement as HTMLElement | null + return ( + active?.getAttribute('aria-label') ?? active?.textContent?.trim() ?? '' + ) + }) +} + +/** No horizontal page scroll: the document is no wider than the viewport. */ +export async function expectNoHorizontalOverflow( + page: Page, + state: string, +): Promise { + const { scrollWidth, clientWidth } = await page.evaluate(() => ({ + scrollWidth: document.documentElement.scrollWidth, + clientWidth: document.documentElement.clientWidth, + })) + expect(scrollWidth, `horizontal overflow on ${state}`).toBeLessThanOrEqual( + clientWidth, + ) +} diff --git a/apps/app/e2e/tsconfig.json b/apps/app/e2e/tsconfig.json new file mode 100644 index 00000000..ea6716e8 --- /dev/null +++ b/apps/app/e2e/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["node", "vite/client"], + "baseUrl": "..", + "paths": { + "@/*": ["src/*"] + } + }, + "include": ["."] +} diff --git a/apps/app/e2e/ui/dialog.spec.ts b/apps/app/e2e/ui/dialog.spec.ts new file mode 100644 index 00000000..833b6bb0 --- /dev/null +++ b/apps/app/e2e/ui/dialog.spec.ts @@ -0,0 +1,216 @@ +import { en } from '@/i18n/en' +import { fr } from '@/i18n/fr' +import { + expect, + expectAccessible, + expectNoHorizontalOverflow, + focusOwner, + focusedName, + test, +} from '../support/browser' +import type { Page } from '@playwright/test' + +// The D13 contract of components/ui/Dialog on its test page (e2e/harness/dialog.tsx). + +async function openScenario(page: Page, opener: string, title: string) { + await page.getByRole('button', { name: opener }).focus() + await page.keyboard.press('Enter') + const dialog = page.getByRole('dialog', { name: title }) + await expect(dialog).toBeVisible() + return dialog +} + +/** Names of the elements the focus visits over `count` presses of `key`. */ +async function focusWalk(page: Page, key: 'Tab' | 'Shift+Tab', count: number) { + const visited: { owner: string; name: string }[] = [] + for (let i = 0; i < count; i++) { + await page.keyboard.press(key) + visited.push({ + owner: await focusOwner(page), + name: await focusedName(page), + }) + } + return visited +} + +test.beforeEach(async ({ page }) => { + await page.goto('/e2e/harness/dialog.html') + await expect( + page.getByRole('heading', { name: 'Dialog harness' }), + ).toBeVisible() +}) + +test('is a named, described modal dialog and moves focus into it', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open basic', 'Basic dialog') + await expect(dialog).toHaveAccessibleDescription('Three controls follow.') + expect( + await dialog.evaluate((d) => d.tagName === 'DIALOG' && d.matches(':modal')), + ).toBe(true) + expect(await focusOwner(page)).toBe('dialog') + expect(await focusedName(page)).toBe(fr['common.close']) +}) + +// Past either end the focus visits the browser's interface (one step, the page +// holds no focus) and comes back into the dialog; it never reaches the page. +test('Tab and Shift+Tab cycle through the dialog, never the page', async ({ + page, +}) => { + await openScenario(page, 'Open basic', 'Basic dialog') + const step = (f: { owner: string; name: string }) => + f.owner === 'dialog' ? f.name : f.owner + const forward = await focusWalk(page, 'Tab', 10) + expect(forward.map(step)).toEqual([ + 'First', + 'Second', + 'Done', + 'browser', + fr['common.close'], + 'First', + 'Second', + 'Done', + 'browser', + fr['common.close'], + ]) + const backward = await focusWalk(page, 'Shift+Tab', 10) + expect(backward.map(step)).toEqual([ + 'browser', + 'Done', + 'Second', + 'First', + fr['common.close'], + 'browser', + 'Done', + 'Second', + 'First', + fr['common.close'], + ]) +}) + +test('the page behind is inert: no focus, no click, no scroll', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog') + const background = page.getByRole('button', { + name: 'Background action', + includeHidden: true, + }) + const box = await background.boundingBox() + if (!box) throw new Error('background button not laid out') + await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2) + await background.evaluate((b) => (b as HTMLElement).focus()) + expect(await focusOwner(page)).toBe('dialog') + await page.mouse.move(box.x + 5, box.y + 5) + await page.mouse.wheel(0, 800) + await page.waitForTimeout(200) + expect(await page.evaluate(() => window.scrollY)).toBe(0) + await expect(dialog).toBeVisible() + await expect(page.getByTestId('background-clicks')).toHaveText('0') +}) + +test('Escape closes when allowed and focus returns to the opener', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open basic', 'Basic dialog') + await page.keyboard.press('Escape') + await expect(dialog).toBeHidden() + expect(await focusedName(page)).toBe('Open basic') + await expect( + page.getByRole('button', { name: 'Background action' }), + ).toBeEnabled() +}) + +test('Escape is only a request: refused twice, the dialog stays open', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open guarded', 'Guarded dialog') + await page.keyboard.press('Escape') + await page.keyboard.press('Escape') + await expect(dialog).toBeVisible() + expect(await dialog.evaluate((d) => (d as HTMLDialogElement).open)).toBe(true) + expect(await focusOwner(page)).toBe('dialog') + await page.getByRole('checkbox', { name: 'Busy' }).uncheck() + await page.keyboard.press('Escape') + await expect(dialog).toBeHidden() + expect(await focusedName(page)).toBe('Open guarded') +}) + +test('the close button closes from the keyboard and restores focus', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open basic', 'Basic dialog') + expect(await focusedName(page)).toBe(fr['common.close']) + await page.keyboard.press('Enter') + await expect(dialog).toBeHidden() + expect(await focusedName(page)).toBe('Open basic') +}) + +test('an opener gone on close hands focus to its container’s first control', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Remove item', 'Remove the item?') + await page.getByRole('button', { name: 'Confirm removal' }).click() + await expect(dialog).toBeHidden() + await expect(page.getByRole('button', { name: 'Remove item' })).toHaveCount(0) + expect(await focusedName(page)).toBe('Add item') +}) + +test('long content scrolls inside the panel, the page stays put', async ({ + page, +}) => { + const dialog = await openScenario(page, 'Open long', 'Long dialog') + const panel = dialog.locator('header').locator('..') + const { scrollHeight, clientHeight } = await panel.evaluate((p) => ({ + scrollHeight: p.scrollHeight, + clientHeight: p.clientHeight, + })) + expect(scrollHeight).toBeGreaterThan(clientHeight) + expect(await focusedName(page)).toBe(fr['common.close']) + await page.keyboard.press('Tab') + const end = page.getByRole('button', { name: 'End of content' }) + await expect(end).toBeFocused() + await expect(end).toBeInViewport() + expect(await page.evaluate(() => window.scrollY)).toBe(0) + const box = await panel.boundingBox() + const viewport = page.viewportSize() + expect( + box && viewport && box.y >= 0 && box.y + box.height <= viewport.height, + ).toBe(true) +}) + +test('fits the viewport without horizontal page scroll', async ({ page }) => { + await expectNoHorizontalOverflow(page, 'the page') + for (const [opener, title] of [ + ['Open basic', 'Basic dialog'], + ['Open long', 'Long dialog'], + ]) { + const dialog = await openScenario(page, opener, title) + const box = await dialog.locator('header').locator('..').boundingBox() + const width = page.viewportSize()?.width ?? 0 + expect( + box && box.x >= 0 && box.x + box.width <= width, + `${title} inside the viewport`, + ).toBe(true) + await expectNoHorizontalOverflow(page, title) + await page.keyboard.press('Escape') + await expect(dialog).toBeHidden() + } +}) + +for (const [lang, dict] of [ + ['fr', fr], + ['en', en], +] as const) { + test(`axe finds no serious violation, close control named in ${lang}`, async ({ + page, + }) => { + await page.goto(`/e2e/harness/dialog.html?lang=${lang}`) + await expectAccessible(page, `the harness (${lang})`) + await openScenario(page, 'Open basic', 'Basic dialog') + await expect( + page.getByRole('button', { name: dict['common.close'] }), + ).toBeFocused() + await expectAccessible(page, `the open dialog (${lang})`) + }) +} diff --git a/apps/app/e2e/ui/local-tool.spec.ts b/apps/app/e2e/ui/local-tool.spec.ts new file mode 100644 index 00000000..547613cf --- /dev/null +++ b/apps/app/e2e/ui/local-tool.spec.ts @@ -0,0 +1,104 @@ +import { en } from '@/i18n/en' +import { fr } from '@/i18n/fr' +import { + expect, + expectAccessible, + expectNoHorizontalOverflow, + focusOwner, + focusedName, + test, +} from '../support/browser' +import type { Page } from '@playwright/test' +import type { Dict } from '@/i18n/types' + +// The shared Dialog where the local tool uses it, on the real routes with no +// backend: the sheet disclaimer, the edit dialog and the replace confirmation. +// Fictitious names only. + +const ANIMAL = 'Fictif Alezan' + +/** Required label text without the trailing « * » marker. */ +const label = (dict: Dict, key: string) => dict[key].replace(/\s*\*$/, '') + +async function startReport(page: Page, dict: Dict) { + await page + .getByLabel(label(dict, 'form.practitioner.name')) + .fill('Praticien Fictif') + await page.getByLabel(label(dict, 'form.animal.name')).fill(ANIMAL) + await page + .getByLabel(label(dict, 'form.owner.name')) + .fill('Propriétaire Fictif') + await page.getByRole('button', { name: dict['new_report.submit'] }).click() +} + +for (const [locale, dict] of [ + ['fr-FR', fr], + ['en-GB', en], +] as const) { + test.describe(`local tool (${locale})`, () => { + test.use({ locale, forbiddenInUrls: [ANIMAL, 'Fictif'] }) + + test('editor dialogs: disclaimer, edit, replace confirmation', async ({ + page, + }) => { + await page.goto('/') + // Scanned once the sheet is loaded: the import button fades in from disabled. + await expect( + page.getByRole('button', { name: dict['home.import.cta'] }), + ).toBeEnabled() + await expectAccessible(page, 'home') + await page + .getByRole('button', { name: dict['home.new_report.cta'] }) + .click() + await expect(page).toHaveURL(/\/new$/) + await expectNoHorizontalOverflow(page, 'new report') + await startReport(page, dict) + + await expect(page).toHaveURL(/\/editor$/) + const disclaimer = page.getByRole('dialog', { + name: dict['editor.disclaimer_title'], + }) + await expect(disclaimer).toBeVisible() + expect(await disclaimer.getAttribute('aria-describedby')).toBeTruthy() + expect(await focusOwner(page)).toBe('dialog') + expect(await focusedName(page)).toBe(dict['common.close']) + await page.keyboard.press('Tab') + expect(await focusedName(page)).toBe(dict['common.understood']) + await expectAccessible(page, 'editor with the disclaimer') + await expectNoHorizontalOverflow(page, 'editor with the disclaimer') + await page.keyboard.press('Escape') + await expect(disclaimer).toBeHidden() + + const edit = page.getByRole('button', { name: dict['editor.edit_infos'] }) + await edit.focus() + await page.keyboard.press('Enter') + const editDialog = page.getByRole('dialog', { + name: dict['editor.edit_dialog_title'], + }) + await expect(editDialog).toBeVisible() + expect(await focusOwner(page)).toBe('dialog') + await expectNoHorizontalOverflow(page, 'edit dialog') + await page.keyboard.press('Escape') + await expect(editDialog).toBeHidden() + await expect(edit).toBeFocused() + + // A reload: the bilan stays in the tab, not yet in the store (the « unloaded » message). + await page.goto('/new') + await startReport(page, dict) + const replace = page.getByRole('dialog', { + name: dict['session.replace.title'], + }) + await expect(replace).toBeVisible() + await expect(replace).toHaveAccessibleDescription( + dict['session.replace.body_unloaded'], + ) + await expectAccessible(page, 'replace confirmation') + await page.keyboard.press('Escape') + await expect(replace).toBeHidden() + await expect(page).toHaveURL(/\/new$/) + await expect( + page.getByRole('button', { name: dict['new_report.submit'] }), + ).toBeFocused() + }) + }) +} diff --git a/apps/app/package.json b/apps/app/package.json index 121dad4f..63ed3519 100644 --- a/apps/app/package.json +++ b/apps/app/package.json @@ -8,10 +8,11 @@ "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" }, "dependencies": { "@faunosteo/core-wasm": "workspace:*", @@ -24,6 +25,8 @@ "zustand": "^5.0.2" }, "devDependencies": { + "@axe-core/playwright": "4.14.0", + "@playwright/test": "1.64.1", "@tailwindcss/vite": "^4.3.0", "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.1.0", diff --git a/package.json b/package.json index f68f9a2c..90a61252 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,8 @@ "wasm:build:docker": "bash docker/rust-run.sh bash scripts/wasm-build.sh", "worker:test": "docker build -f crates/worker/Dockerfile --target test -t faunosteo_worker:test .", "worker:image": "docker build -f crates/worker/Dockerfile -t faunosteo_worker:dev .", - "e2e:avatar": "bash scripts/avatar-e2e.sh" + "e2e:avatar": "bash scripts/avatar-e2e.sh", + "e2e:ui": "pnpm --filter @faunosteo/app e2e:ui" }, "devDependencies": { "pnpm": "10.13.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b8b9c5f5..319c7c81 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -45,6 +45,12 @@ importers: specifier: ^5.0.2 version: 5.0.13(@types/react@19.2.14)(react@19.2.6) devDependencies: + '@axe-core/playwright': + specifier: 4.14.0 + version: 4.14.0(playwright-core@1.64.1) + '@playwright/test': + specifier: 1.64.1 + version: 1.64.1 '@tailwindcss/vite': specifier: ^4.3.0 version: 4.3.0(vite@7.3.6(@types/node@20.19.41)(jiti@2.7.0)(lightningcss@1.32.0)(tsx@4.23.15)) @@ -161,6 +167,12 @@ packages: '@adobe/css-tools@4.4.4': resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==} + '@axe-core/playwright@4.14.0': + resolution: {integrity: sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==} + engines: {node: '>=22.12.0'} + peerDependencies: + playwright-core: '>= 1.0.0' + '@babel/code-frame@7.29.0': resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} engines: {node: '>=6.9.0'} @@ -424,6 +436,11 @@ packages: resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} + '@playwright/test@1.64.1': + resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==} + engines: {node: '>=20'} + hasBin: true + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -1033,6 +1050,10 @@ packages: resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} engines: {node: '>= 0.4'} + axe-core@4.14.0: + resolution: {integrity: sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==} + engines: {node: '>=4'} + balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} @@ -1252,6 +1273,7 @@ packages: eslint@9.39.4: resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. hasBin: true peerDependencies: jiti: '*' @@ -1807,6 +1829,16 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + playwright-core@1.64.1: + resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.64.1: + resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==} + engines: {node: '>=20'} + hasBin: true + pnpm@10.13.1: resolution: {integrity: sha512-N+vxpcejDV+r4MXfRO6NpMllygxa89urKMOhaBtwolYhjQXIHJwNz3Z+9rhVHrW5YAQrntQwDFkkIzY3fgHPrQ==} engines: {node: '>=18.12'} @@ -2253,6 +2285,11 @@ snapshots: '@adobe/css-tools@4.4.4': {} + '@axe-core/playwright@4.14.0(playwright-core@1.64.1)': + dependencies: + axe-core: 4.14.0 + playwright-core: 1.64.1 + '@babel/code-frame@7.29.0': dependencies: '@babel/helper-validator-identifier': 7.28.5 @@ -2436,6 +2473,10 @@ snapshots: '@noble/hashes@1.8.0': {} + '@playwright/test@1.64.1': + dependencies: + playwright: 1.64.1 + '@rolldown/pluginutils@1.0.0-beta.27': {} '@rollup/rollup-android-arm-eabi@4.60.4': @@ -2999,6 +3040,8 @@ snapshots: dependencies: possible-typed-array-names: 1.1.0 + axe-core@4.14.0: {} + balanced-match@1.0.2: {} balanced-match@4.0.4: {} @@ -3868,6 +3911,12 @@ snapshots: picomatch@4.0.4: {} + playwright-core@1.64.1: {} + + playwright@1.64.1: + dependencies: + playwright-core: 1.64.1 + pnpm@10.13.1: {} possible-typed-array-names@1.1.0: {} From 8371aa0a2a9b783e19244d9e5d3d9ba73af3b53f Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 22:46:18 +0100 Subject: [PATCH 16/60] fix(ui): keep the photo confirmation open until the removal settles The dialog closed before the request, focus went back to the remove button, then the button vanished and focus fell on the page. The confirmation now closes with the photo gone, Escape and Cancel wait for it, and ModalDialog restores focus after the commit so its fallback sees the opener removed. The sr-only file input leaves the tab order: it was an invisible tab stop. --- .../src/components/account/AvatarSection.tsx | 22 +++++++++++++++---- apps/app/src/components/ui/ModalDialog.tsx | 17 ++++++++++---- .../unit/components.AvatarSection.test.tsx | 19 ++++++++++++++++ 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/apps/app/src/components/account/AvatarSection.tsx b/apps/app/src/components/account/AvatarSection.tsx index 04a8a3d3..d93923d0 100644 --- a/apps/app/src/components/account/AvatarSection.tsx +++ b/apps/app/src/components/account/AvatarSection.tsx @@ -90,6 +90,7 @@ export default function AvatarSection() { avatar?.inFlight ? { kind: 'processing', long: false } : { kind: 'idle' }, ) const [confirmOpen, setConfirmOpen] = useState(false) + const [removing, setRemoving] = useState(false) const inputRef = useRef(null) const pollRef = useRef(null) @@ -171,16 +172,27 @@ export default function AvatarSection() { } } + const closeConfirm = () => !removing && setConfirmOpen(false) + + // The confirmation stays open until the removal settles: it closes with the + // photo gone, so focus moves past the vanished button (ModalDialog fallback). async function onRemove() { const client = getSupabaseClient() - setConfirmOpen(false) - if (!client) return + if (removing) return + if (!client) { + setConfirmOpen(false) + return + } + setRemoving(true) try { await removeAvatar(client) clearAvatar() setPhase({ kind: 'removed' }) } catch (error) { setPhase({ kind: 'failed', failure: classifyAssetError(error) }) + } finally { + setRemoving(false) + setConfirmOpen(false) } } @@ -211,6 +223,8 @@ export default function AvatarSection() { accept={ACCEPT} onChange={onPick} className="sr-only" + // Opened by the visible button: an invisible tab stop would hide the focus. + tabIndex={-1} aria-label={t('account.avatar.change')} disabled={busy} /> @@ -258,13 +272,13 @@ export default function AvatarSection() { {rejected && {t(`account.avatar.rejected.${rejected}`)}} setConfirmOpen(false)} + onClose={closeConfirm} title={t('account.avatar.remove_title')} description={

{t('account.avatar.remove_body')}

} size="sm" >
- +
+ ) +} diff --git a/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx b/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx new file mode 100644 index 00000000..f9007f40 --- /dev/null +++ b/apps/app/src/app/routes/app/clients/ClientCreateRoute.tsx @@ -0,0 +1,40 @@ +import { useNavigate } from 'react-router-dom' +import ClientForm from '@/components/clients/ClientForm' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { useLeaveGuard } from '@/app/useLeaveGuard' +import { usePageHeading } from '@/app/usePageHeading' +import { useClientForm } from '@/clients/useClientForm' +import { useT } from '@/i18n/useT' +import type { ClientFlash } from './ClientDetailRoute' + +/** /app/clients/new: one creation intent, one request id, kept for retries. */ +export default function ClientCreateRoute() { + const t = useT() + const heading = usePageHeading() + const navigate = useNavigate() + const workspaceId = useWorkspaceId() + const form = useClientForm({ mode: 'create', workspaceId }, (clientId) => + navigate(`/app/clients/${clientId}`, { + replace: true, + state: { flash: 'created' satisfies ClientFlash }, + }), + ) + useLeaveGuard(form.dirty) + + return ( +
+

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

+ +
+ ) +} diff --git a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx new file mode 100644 index 00000000..ac6cbce3 --- /dev/null +++ b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx @@ -0,0 +1,242 @@ +import { useEffect, useState, type ReactNode } from 'react' +import { Link, useLocation, useNavigate, useParams } from 'react-router-dom' +import { + classifyRecordError, + setClientArchived, + type ClientRecord, + type RecordFailureKind, +} from '@faunosteo/supabase' +import ArchiveClientDialog from '@/components/clients/ArchiveClientDialog' +import ClientAnimals from '@/components/clients/ClientAnimals' +import ClientNotFound from '@/components/clients/ClientNotFound' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { usePageHeading } from '@/app/usePageHeading' +import { countryName } from '@/clients/countries' +import { useClientRecord } from '@/clients/useClientRecord' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +/** What a page that saved the client asks this page to announce (no value in it). */ +export type ClientFlash = 'created' | 'updated' + +const linkClass = + 'text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded-sm' + +function ContactCard({ record }: { record: ClientRecord }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const place = [record.postal_code, record.city].filter(Boolean).join(' ') + const address = [record.address_line1, record.address_line2, place].filter( + Boolean, + ) + const rows: [string, ReactNode][] = [] + if (record.phone) + rows.push([ + t('clients.detail.phone'), +
+ {record.phone} + , + ]) + if (record.email) + rows.push([ + t('clients.detail.email'), + + {record.email} + , + ]) + if (address.length) + rows.push([ + t('clients.detail.address'), + address.map((line) => ( + + {line} + + )), + ]) + if (record.country) + rows.push([ + t('clients.detail.country'), + countryName(record.country, locale), + ]) + + return ( + +

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

+ {rows.length === 0 ? ( +

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

+ ) : ( +
+ {rows.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ )} +
+ ) +} + +/** /app/clients/:clientId: identity, contact, animals (read-only), edit, archive or restore. */ +export default function ClientDetailRoute() { + const t = useT() + const heading = usePageHeading() + const navigate = useNavigate() + const location = useLocation() + const { clientId = '' } = useParams() + const { state, refresh } = useClientRecord(clientId) + const flash = (location.state as { flash?: ClientFlash } | null)?.flash + const [status, setStatus] = useState( + flash ? t(`clients.detail.${flash}`) : null, + ) + const [archiveOpen, setArchiveOpen] = useState(false) + const [restoring, setRestoring] = useState(false) + const [failure, setFailure] = useState(null) + + // The announcement is read once; a reload of the page does not repeat it. + useEffect(() => { + if (flash) navigate(location.pathname, { replace: true, state: null }) + }, [flash, navigate, location.pathname]) + + async function restore() { + const client = getSupabaseClient() + if (restoring || !client) return + setRestoring(true) + setFailure(null) + try { + await setClientArchived(client, clientId, false) + setStatus(t('clients.detail.restored')) + refresh() + } catch (error) { + setFailure(classifyRecordError(error)) + } finally { + setRestoring(false) + } + } + + if (state.status === 'not_found') return + if (state.status === 'loading') + return ( +

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

+ ) + if (state.status === 'error') + return ( +
+ {t(`clients.failure.${state.failure}`)} + +
+ ) + + const record = state.record + const archived = record.archived_at !== null + + return ( +
+ + {t('clients.detail.back')} + +
+
+

+ {record.display_name} +

+
+ {t(`clients.kind.${record.kind}`)} + {archived && ( + {t('clients.archived_badge')} + )} +
+
+
+ {archived ? ( + + ) : ( + <> + + {t('clients.detail.edit')} + + + + )} +
+
+ + {status && {status}} + {failure && ( + {t(`clients.failure.${failure}`)} + )} + {archived && ( + {t('clients.detail.archived_notice')} + )} + + + + + setArchiveOpen(false)} + onArchived={() => { + setArchiveOpen(false) + setStatus(t('clients.detail.archived')) + refresh() + }} + /> +
+ ) +} diff --git a/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx b/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx new file mode 100644 index 00000000..d62311d1 --- /dev/null +++ b/apps/app/src/app/routes/app/clients/ClientEditRoute.tsx @@ -0,0 +1,78 @@ +import { Link, useNavigate, useParams } from 'react-router-dom' +import type { ClientRecord } from '@faunosteo/supabase' +import ClientForm from '@/components/clients/ClientForm' +import ClientNotFound from '@/components/clients/ClientNotFound' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { useLeaveGuard } from '@/app/useLeaveGuard' +import { usePageHeading } from '@/app/usePageHeading' +import { useClientForm } from '@/clients/useClientForm' +import { useClientRecord } from '@/clients/useClientRecord' +import { useT } from '@/i18n/useT' +import type { ClientFlash } from './ClientDetailRoute' + +function EditForm({ record }: { record: ClientRecord }) { + const t = useT() + const navigate = useNavigate() + const form = useClientForm({ mode: 'edit', record }, (clientId) => + navigate(`/app/clients/${clientId}`, { + state: { flash: 'updated' satisfies ClientFlash }, + }), + ) + useLeaveGuard(form.dirty) + return ( + + ) +} + +/** /app/clients/:clientId/edit: the stored values at their revision; an archived client is read-only. */ +export default function ClientEditRoute() { + const t = useT() + const heading = usePageHeading() + const { clientId = '' } = useParams() + const { state, refresh } = useClientRecord(clientId) + + if (state.status === 'not_found') return + return ( +
+

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

+ {state.status === 'loading' && ( +

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

+ )} + {state.status === 'error' && ( +
+ {t(`clients.failure.${state.failure}`)} + +
+ )} + {state.status === 'ready' && state.record.archived_at && ( +
+ {t('clients.detail.archived_notice')} + + {t('clients.form.back_to_client')} + +
+ )} + {state.status === 'ready' && !state.record.archived_at && ( + + )} +
+ ) +} diff --git a/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx b/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx new file mode 100644 index 00000000..363b81e4 --- /dev/null +++ b/apps/app/src/app/routes/app/clients/ClientsListRoute.tsx @@ -0,0 +1,180 @@ +import { Link } from 'react-router-dom' +import type { ClientListItem } from '@faunosteo/supabase' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import FormField from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { usePageHeading } from '@/app/usePageHeading' +import { useClientList } from '@/clients/useClientList' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType + +function animalCount(count: number, t: Translate): string { + if (count === 0) return t('clients.list.animals_none') + return count === 1 + ? t('clients.list.animals_one') + : t('clients.list.animals_other').replace('{count}', String(count)) +} + +function ClientRow({ client, t }: { client: ClientListItem; t: Translate }) { + const details = [ + client.city, + client.phone, + animalCount(client.current_animal_count, t), + ].filter(Boolean) + return ( +
  • + + + + {client.display_name} + + {t(`clients.kind.${client.kind}`)} + {client.archived_at && ( + {t('clients.archived_badge')} + )} + + + {details.join(' · ')} + + +
  • + ) +} + +/** /app/clients: search, the archived toggle (U2) and « Afficher plus » pages (U1). */ +export default function ClientsListRoute() { + const t = useT() + const heading = usePageHeading() + const workspaceId = useWorkspaceId() + const list = useClientList(workspaceId) + const { state } = list + + const emptyMessage = list.term + ? t('clients.list.no_results') + : list.archived + ? t('clients.list.archived_empty') + : t('clients.list.empty') + + return ( +
    +
    +

    + {t('clients.list.title')} +

    + + {t('clients.list.new')} + +
    + +
    + + list.setQuery(e.target.value)} + maxLength={100} + autoComplete="off" + aria-describedby="client-search-hint" + /> + + +
    + + {/* The number of rows shown is announced; an empty result announces itself below. */} +
    + {state.status === 'ready' && + state.rows.length > 0 && + t( + state.rows.length === 1 + ? 'clients.list.count_one' + : 'clients.list.count_other', + ).replace('{count}', String(state.rows.length))} +
    + + {state.status === 'loading' && ( +

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

    + )} + {state.status === 'error' && ( +
    + {t(`clients.failure.${state.failure}`)} + +
    + )} + {state.status === 'ready' && state.rows.length === 0 && ( +
    +

    {emptyMessage}

    + {!list.term && !list.archived && ( +

    + {t('clients.list.empty_hint')} +

    + )} +
    + )} + {state.status === 'ready' && state.rows.length > 0 && ( + <> +
      + {state.rows.map((client) => ( + + ))} +
    + {state.moreFailure && ( + + {t(`clients.failure.${state.moreFailure}`)} + + )} + {state.next && ( +
    + +
    + )} + + )} +
    + ) +} diff --git a/apps/app/src/app/useLeaveGuard.ts b/apps/app/src/app/useLeaveGuard.ts new file mode 100644 index 00000000..9f0e672b --- /dev/null +++ b/apps/app/src/app/useLeaveGuard.ts @@ -0,0 +1,25 @@ +import { useEffect } from 'react' +import { useLeaveGuardStore } from '@/state/leaveGuardStore' + +/** + * While `dirty`, a reload, a tab close or a full-page redirect asks first + * (beforeunload), and AppLayout asks before following a link of the app. The + * declarative router has no navigation blocker: the browser's own back and + * forward buttons are not intercepted (contract §11.3). + */ +export function useLeaveGuard(dirty: boolean): void { + const arm = useLeaveGuardStore((s) => s.arm) + useEffect(() => { + arm(dirty) + return () => arm(false) + }, [dirty, arm]) + useEffect(() => { + if (!dirty) return + const guard = (event: BeforeUnloadEvent) => { + event.preventDefault() + event.returnValue = '' + } + window.addEventListener('beforeunload', guard) + return () => window.removeEventListener('beforeunload', guard) + }, [dirty]) +} diff --git a/apps/app/src/app/usePageHeading.ts b/apps/app/src/app/usePageHeading.ts new file mode 100644 index 00000000..ffec3ba0 --- /dev/null +++ b/apps/app/src/app/usePageHeading.ts @@ -0,0 +1,33 @@ +import { useCallback, useRef } from 'react' + +/** + * Focus moves to the page heading when a page opens (contract §11.5), so a + * screen reader starts at the new page and Tab continues from it. The heading + * carries tabIndex={-1} and this callback ref; it takes focus once, when it + * first appears (a page that loads its record renders it later). A page + * opened from the mobile drawer appears while the drawer still holds the page + * inert for its exit: the heading then takes focus once that dialog closed + * and gave focus back, so it has the last word. The one-shot listener checks + * the heading is still on the page; no effect cleanup, which React's + * StrictMode would run once before the dialog closes. + */ +export function usePageHeading() { + const done = useRef(false) + return useCallback((element: T | null) => { + if (!element || done.current) return + done.current = true + const modal = document.querySelector('dialog:modal') + if (!modal) { + element.focus() + return + } + modal.addEventListener( + 'close', + () => + setTimeout(() => { + if (element.isConnected) element.focus() + }, 0), + { once: true }, + ) + }, []) +} diff --git a/apps/app/src/clients/countries.ts b/apps/app/src/clients/countries.ts new file mode 100644 index 00000000..f7e13453 --- /dev/null +++ b/apps/app/src/clients/countries.ts @@ -0,0 +1,40 @@ +import type { Locale } from '@/i18n/types' + +/** + * ISO 3166-1 alpha-2 codes officially assigned (249), committed so the form + * never depends on a network list; the names come from the browser's + * Intl.DisplayNames in the UI language (contract §5). + */ +export const COUNTRY_CODES: readonly string[] = ( + 'AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ ' + + 'BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ ' + + 'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ ' + + 'DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR ' + + 'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ' + + 'ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ ' + + 'LA LB LC LI LK LR LS LT LU LV LY ' + + 'MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ ' + + 'NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA ' + + 'RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ ' + + 'TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ ' + + 'VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW' +).split(' ') + +export interface CountryOption { + code: string + label: string +} + +/** Every code with its name in `locale`, sorted by name in that language. */ +export function countryOptions(locale: Locale): CountryOption[] { + const names = new Intl.DisplayNames([locale], { type: 'region' }) + return COUNTRY_CODES.map((code) => ({ + code, + label: names.of(code) ?? code, + })).sort((a, b) => a.label.localeCompare(b.label, locale)) +} + +/** The country's name in `locale`, or the code when the browser has none. */ +export function countryName(code: string, locale: Locale): string { + return new Intl.DisplayNames([locale], { type: 'region' }).of(code) ?? code +} diff --git a/apps/app/src/clients/useClientForm.ts b/apps/app/src/clients/useClientForm.ts new file mode 100644 index 00000000..618ece98 --- /dev/null +++ b/apps/app/src/clients/useClientForm.ts @@ -0,0 +1,163 @@ +import { useRef, useState, type FormEvent } from 'react' +import { + classifyRecordError, + createClientRecord, + fetchClientRecord, + updateClientRecord, + type ClientRecord, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { generateUuid } from '@/lib/id' +import { + EMPTY_CLIENT_VALUES, + clientFieldErrors, + clientFormValues, + clientSchema, + normalizePhoneEntry, + type ClientFieldErrors, + type ClientFormValues, +} from './validation' + +export type ClientFormTarget = + | { mode: 'create'; workspaceId: string } + | { mode: 'edit'; record: ClientRecord } + +export type ClientFormPhase = + | { kind: 'idle' } + | { kind: 'saving' } + | { kind: 'failed'; failure: RecordFailureKind } + +const FIELDS = Object.keys(EMPTY_CLIENT_VALUES) as (keyof ClientFormValues)[] + +function sameValues(a: ClientFormValues, b: ClientFormValues): boolean { + return FIELDS.every((key) => a[key] === b[key]) +} + +/** + * The client form: typed values, the D-R7 schema, one save. A create keeps + * one request id for the life of the form, so a retry after a lost answer + * returns the client already made instead of a second one. An update sends + * the revision it was read at; on `conflict` the stored client is read again + * and shown beside the typed values, which stay, and the next save applies + * them over it knowingly. + */ +export function useClientForm( + target: ClientFormTarget, + onSaved: (clientId: string) => void, +) { + const initial = + target.mode === 'edit' + ? clientFormValues(target.record) + : EMPTY_CLIENT_VALUES + const [values, setValues] = useState(initial) + const [baseline, setBaseline] = useState(initial) + const [errors, setErrors] = useState({}) + const [errorRound, setErrorRound] = useState(0) + const [phase, setPhase] = useState({ kind: 'idle' }) + const [stored, setStored] = useState(null) + const [requestId] = useState(generateUuid) + const revision = useRef(target.mode === 'edit' ? target.record.revision : 0) + const inFlight = useRef(false) + + const setField = (key: keyof ClientFormValues) => (value: string) => + setValues((v) => ({ ...v, [key]: value })) + + /** Shows the converted phone as soon as the field is left (contract §11.3). */ + function convertPhone() { + const phone = normalizePhoneEntry(values.phone, values.country) + if (phone.ok && phone.value && phone.value !== values.phone) + setValues((v) => ({ ...v, phone: phone.value as string })) + } + + async function readStored(clientId: string) { + const client = getSupabaseClient() + const record = client + ? await fetchClientRecord(client, clientId).catch(() => null) + : null + if (record) { + revision.current = record.revision + setStored(record) + } + } + + async function submit(event: FormEvent) { + event.preventDefault() + if (inFlight.current) return + const parsed = clientSchema.safeParse(values) + if (!parsed.success) { + setErrors(clientFieldErrors(parsed.error)) + setErrorRound((n) => n + 1) + return + } + setErrors({}) + const sent = { ...values, phone: parsed.data.phone ?? '' } + setValues(sent) + const client = getSupabaseClient() + if (!client) { + setPhase({ kind: 'failed', failure: 'unavailable' }) + return + } + inFlight.current = true + setPhase({ kind: 'saving' }) + try { + let clientId: string + if (target.mode === 'create') { + clientId = ( + await createClientRecord(client, { + workspaceId: target.workspaceId, + requestId, + fields: parsed.data, + }) + ).id + } else { + clientId = target.record.id + revision.current = ( + await updateClientRecord(client, { + clientId, + expectedRevision: revision.current, + fields: parsed.data, + }) + ).revision + } + setBaseline(sent) + setPhase({ kind: 'idle' }) + onSaved(clientId) + } catch (error) { + const failure = classifyRecordError(error) + if (failure === 'conflict' && target.mode === 'edit') + await readStored(target.record.id) + setPhase({ kind: 'failed', failure }) + } finally { + inFlight.current = false + } + } + + /** Drops the typed values for the stored ones after a conflict. */ + function takeStored() { + if (!stored) return + const next = clientFormValues(stored) + setValues(next) + setBaseline(next) + setStored(null) + setErrors({}) + setPhase({ kind: 'idle' }) + } + + return { + values, + setField, + convertPhone, + errors, + /** Changes after each refused submit, so the form can focus the first error. */ + errorRound, + phase, + /** The stored client after a conflict, shown beside the typed values. */ + stored, + takeStored, + dirty: !sameValues(values, baseline), + submit, + } +} + +export type ClientForm = ReturnType diff --git a/apps/app/src/clients/useClientList.ts b/apps/app/src/clients/useClientList.ts new file mode 100644 index 00000000..fbf401dd --- /dev/null +++ b/apps/app/src/clients/useClientList.ts @@ -0,0 +1,107 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + classifyRecordError, + searchClients, + type ClientListItem, + type NameCursor, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' + +/** Time without typing before the term is sent: one search per pause, not per key. */ +export const SEARCH_DELAY_MS = 300 + +export type ClientListState = + | { status: 'loading' } + | { + status: 'ready' + rows: ClientListItem[] + next: NameCursor | null + moreFailure: RecordFailureKind | null + } + | { status: 'error'; failure: RecordFailureKind } + +/** + * The clients of the workspace for a term and the archived toggle: the + * server searches (search_clients, POST), pages of 25 in name order, « Afficher + * plus » appends the next page. An answer to an older term is dropped. + */ +export function useClientList(workspaceId: string) { + const [query, setQuery] = useState('') + const [term, setTerm] = useState('') + const [archived, setArchived] = useState(false) + const [state, setState] = useState({ status: 'loading' }) + const [loadingMore, setLoadingMore] = useState(false) + const [reload, setReload] = useState(0) + const generation = useRef(0) + + useEffect(() => { + const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS) + return () => clearTimeout(timer) + }, [query]) + + useEffect(() => { + const current = ++generation.current + const client = getSupabaseClient() + setState({ status: 'loading' }) + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + searchClients(client, { workspaceId, query: term, archived }) + .then((page) => { + if (current === generation.current) + setState({ + status: 'ready', + rows: page.rows, + next: page.next, + moreFailure: null, + }) + }) + .catch((error: unknown) => { + if (current === generation.current) + setState({ status: 'error', failure: classifyRecordError(error) }) + }) + }, [workspaceId, term, archived, reload]) + + const loadMore = useCallback(async () => { + const client = getSupabaseClient() + if (state.status !== 'ready' || !state.next || !client || loadingMore) + return + const current = generation.current + setLoadingMore(true) + try { + const page = await searchClients(client, { + workspaceId, + query: term, + archived, + after: state.next, + }) + if (current === generation.current) + setState({ + status: 'ready', + rows: [...state.rows, ...page.rows], + next: page.next, + moreFailure: null, + }) + } catch (error) { + if (current === generation.current) + setState({ ...state, moreFailure: classifyRecordError(error) }) + } finally { + setLoadingMore(false) + } + }, [state, loadingMore, workspaceId, term, archived]) + + return { + query, + setQuery, + /** The term the shown rows answer (the typed one after the pause). */ + term, + archived, + setArchived, + state, + loadingMore, + loadMore, + retry: () => setReload((n) => n + 1), + } +} diff --git a/apps/app/src/clients/useClientRecord.ts b/apps/app/src/clients/useClientRecord.ts new file mode 100644 index 00000000..46f76719 --- /dev/null +++ b/apps/app/src/clients/useClientRecord.ts @@ -0,0 +1,50 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + classifyRecordError, + fetchClientRecord, + type ClientRecord, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' + +export type ClientRecordState = + | { status: 'loading' } + | { status: 'ready'; record: ClientRecord } + | { status: 'not_found' } + | { status: 'error'; failure: RecordFailureKind } + +/** One client by id; an unknown id and an id of another workspace are both not_found. */ +export function useClientRecord(clientId: string) { + const [state, setState] = useState({ status: 'loading' }) + const [reload, setReload] = useState(0) + const shownId = useRef(null) + + useEffect(() => { + let live = true + const client = getSupabaseClient() + // A refresh of the same client keeps it on screen until the new answer. + if (shownId.current !== clientId) setState({ status: 'loading' }) + shownId.current = clientId + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + fetchClientRecord(client, clientId) + .then((record) => { + if (live) + setState( + record ? { status: 'ready', record } : { status: 'not_found' }, + ) + }) + .catch((error: unknown) => { + if (live) + setState({ status: 'error', failure: classifyRecordError(error) }) + }) + return () => { + live = false + } + }, [clientId, reload]) + + const refresh = useCallback(() => setReload((n) => n + 1), []) + return { state, refresh } +} diff --git a/apps/app/src/clients/validation.ts b/apps/app/src/clients/validation.ts new file mode 100644 index 00000000..22c29955 --- /dev/null +++ b/apps/app/src/clients/validation.ts @@ -0,0 +1,179 @@ +import { z } from 'zod' +import { + CLIENT_FIELD_LIMITS, + CONTROL_CHARACTERS, + EMAIL_PATTERN, + PHONE_E164_PATTERN, + codePointLength, + type ClientFields, + type ClientRecord, +} from '@faunosteo/supabase' +import { COUNTRY_CODES } from './countries' + +/** + * The client form (contract §5, §5.1, §11.3; D-R7): the bounds and patterns + * come from field-limits, proven equal to the SQL CHECKs, so the form never + * sends what the database refuses. Messages are i18n keys; `|n` carries the + * {max} placeholder. Lengths count code points, like char_length. + */ + +export interface ClientFormValues { + kind: 'person' | 'organization' + display_name: string + email: string + phone: string + address_line1: string + address_line2: string + postal_code: string + city: string + country: string +} + +export const EMPTY_CLIENT_VALUES: ClientFormValues = { + kind: 'person', + display_name: '', + email: '', + phone: '', + address_line1: '', + address_line2: '', + postal_code: '', + city: '', + country: '', +} + +/** The form's view of a stored client: null fields become empty inputs. */ +export function clientFormValues(record: ClientRecord): ClientFormValues { + return { + kind: record.kind, + display_name: record.display_name, + email: record.email ?? '', + phone: record.phone ?? '', + address_line1: record.address_line1 ?? '', + address_line2: record.address_line2 ?? '', + postal_code: record.postal_code ?? '', + city: record.city ?? '', + country: record.country ?? '', + } +} + +/** Without separators: spaces, dots, hyphens, parentheses. */ +function compactPhone(raw: string): string { + return raw.replace(/[\s.\-()]/g, '') +} + +export type PhoneEntry = + | { ok: true; value: string | null } + | { ok: false; error: string } + +/** + * The phone entry rule of contract §11.3: an international number (+32…) is + * kept as typed; a French national number (06 12 34 56 78) becomes +33… only + * when the country is empty or France; with another country a national + * number is refused and asks for the country code. + */ +export function normalizePhoneEntry(raw: string, country: string): PhoneEntry { + const compact = compactPhone(raw) + if (compact === '') return { ok: true, value: null } + if (compact.startsWith('+')) { + return PHONE_E164_PATTERN.test(compact) + ? { ok: true, value: compact } + : { ok: false, error: 'clients.error.phone_format' } + } + const frenchContext = country === '' || country === 'FR' + if (frenchContext && /^0[1-9][0-9]{8}$/.test(compact)) { + return { ok: true, value: `+33${compact.slice(1)}` } + } + return frenchContext + ? { ok: false, error: 'clients.error.phone_format' } + : { ok: false, error: 'clients.error.phone_country_code' } +} + +/** Trimmed text of at most `max` code points without control characters; '' → null. */ +function optionalText(max: number) { + return z + .string() + .trim() + .superRefine((value, ctx) => { + if (codePointLength(value) > max) + ctx.addIssue({ + code: 'custom', + message: `clients.error.too_long|${max}`, + }) + else if (CONTROL_CHARACTERS.test(value)) + ctx.addIssue({ code: 'custom', message: 'clients.error.characters' }) + }) + .transform((value) => (value === '' ? null : value)) +} + +const displayName = z + .string() + .trim() + .superRefine((value, ctx) => { + if (value === '') + ctx.addIssue({ code: 'custom', message: 'clients.error.required' }) + else if (codePointLength(value) > CLIENT_FIELD_LIMITS.displayName) + ctx.addIssue({ + code: 'custom', + message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.displayName}`, + }) + else if (CONTROL_CHARACTERS.test(value)) + ctx.addIssue({ code: 'custom', message: 'clients.error.characters' }) + }) + +const email = z + .string() + .trim() + .transform((value) => value.toLowerCase()) + .superRefine((value, ctx) => { + if (value === '') return + if (codePointLength(value) > CLIENT_FIELD_LIMITS.email) + ctx.addIssue({ + code: 'custom', + message: `clients.error.too_long|${CLIENT_FIELD_LIMITS.email}`, + }) + else if (CONTROL_CHARACTERS.test(value) || !EMAIL_PATTERN.test(value)) + ctx.addIssue({ code: 'custom', message: 'clients.error.email_format' }) + }) + .transform((value) => (value === '' ? null : value)) + +/** Parses the typed values into the nine fields the RPCs take. */ +export const clientSchema = z + .object({ + kind: z.enum(['person', 'organization']), + display_name: displayName, + email, + phone: z.string(), + address_line1: optionalText(CLIENT_FIELD_LIMITS.addressLine), + address_line2: optionalText(CLIENT_FIELD_LIMITS.addressLine), + postal_code: optionalText(CLIENT_FIELD_LIMITS.postalCode), + city: optionalText(CLIENT_FIELD_LIMITS.city), + country: z + .string() + .refine( + (value) => value === '' || COUNTRY_CODES.includes(value), + 'clients.error.country', + ) + .transform((value) => (value === '' ? null : value)), + }) + // A refinement runs even when another field failed, so every error shows at once. + .superRefine((values, ctx) => { + const phone = normalizePhoneEntry(values.phone, values.country ?? '') + if (!phone.ok) + ctx.addIssue({ code: 'custom', path: ['phone'], message: phone.error }) + }) + .transform((values): ClientFields => { + const phone = normalizePhoneEntry(values.phone, values.country ?? '') + return { ...values, phone: phone.ok ? phone.value : null } + }) + +export type ClientFieldErrors = Partial> + +/** The first message of each field, in form order. */ +export function clientFieldErrors(error: z.ZodError): ClientFieldErrors { + const errors: ClientFieldErrors = {} + for (const issue of error.issues) { + const key = issue.path[0] as keyof ClientFormValues + errors[key] ??= issue.message + } + return errors +} diff --git a/apps/app/src/components/clients/ArchiveClientDialog.tsx b/apps/app/src/components/clients/ArchiveClientDialog.tsx new file mode 100644 index 00000000..25a7be73 --- /dev/null +++ b/apps/app/src/components/clients/ArchiveClientDialog.tsx @@ -0,0 +1,160 @@ +import { useEffect, useState } from 'react' +import { + classifyRecordError, + fetchClientArchivePreview, + setClientArchived, + type ClientArchivePreview, + type RecordFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import Notice from '@/components/ui/Notice' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +export interface ArchiveClientDialogProps { + open: boolean + clientId: string + onClose: () => void + /** Called once the server archived the client; the page then closes the dialog. */ + onArchived: () => void +} + +type Preview = + | { status: 'loading' } + | { status: 'ready'; preview: ClientArchivePreview } + | { status: 'failed' } + +/** + * Confirmation before archiving (contract §7.1): it lists the active animals + * for which this client is the only current owner, then archives through + * set_client_archived. Closing it is never a confirmation, and while the + * request runs it refuses to close, so focus is restored once, after it. + */ +export default function ArchiveClientDialog({ + open, + clientId, + onClose, + onArchived, +}: ArchiveClientDialogProps) { + const t = useT() + const [preview, setPreview] = useState({ status: 'loading' }) + const [pending, setPending] = useState(false) + const [failure, setFailure] = useState(null) + + useEffect(() => { + if (!open) return + let live = true + setPreview({ status: 'loading' }) + setFailure(null) + const client = getSupabaseClient() + if (!client) { + setPreview({ status: 'failed' }) + return + } + fetchClientArchivePreview(client, clientId) + .then((result) => { + if (live) setPreview({ status: 'ready', preview: result }) + }) + .catch(() => { + if (live) setPreview({ status: 'failed' }) + }) + return () => { + live = false + } + }, [open, clientId]) + + const close = () => { + if (!pending) onClose() + } + + async function confirm() { + const client = getSupabaseClient() + if (pending) return + if (!client) return setFailure('unavailable') + setPending(true) + setFailure(null) + try { + await setClientArchived(client, clientId, true) + onArchived() + } catch (error) { + setFailure(classifyRecordError(error)) + } finally { + setPending(false) + } + } + + const sole = preview.status === 'ready' ? preview.preview : null + const others = sole ? sole.count - sole.animals.length : 0 + + return ( + + {t('clients.archive.body')} +

    + } + size="sm" + > +
    + {preview.status === 'loading' && ( +

    + {t('clients.archive.preview_loading')} +

    + )} + {preview.status === 'failed' && ( + {t('clients.archive.preview_failed')} + )} + {sole && sole.count > 0 && ( +
    +

    + {sole.count === 1 + ? t('clients.archive.sole_owner_one') + : t('clients.archive.sole_owner_other').replace( + '{count}', + String(sole.count), + )} +

    +
      + {sole.animals.map((animal) => ( +
    • {animal.name}
    • + ))} +
    + {others > 0 && ( +

    + {t('clients.archive.others').replace('{count}', String(others))} +

    + )} +
    + )} + {failure && ( + {t(`clients.failure.${failure}`)} + )} +
    +
    + {/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */} + + +
    +
    + ) +} diff --git a/apps/app/src/components/clients/ClientAnimals.tsx b/apps/app/src/components/clients/ClientAnimals.tsx new file mode 100644 index 00000000..93276547 --- /dev/null +++ b/apps/app/src/components/clients/ClientAnimals.tsx @@ -0,0 +1,201 @@ +import { useEffect, useState } from 'react' +import { + classifyRecordError, + fetchSpeciesLabels, + listClientAnimals, + type ClientAnimalItem, + type RecordFailureKind, + type RelationCursor, + type SpeciesLabel, +} from '@faunosteo/supabase' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { getSupabaseClient } from '@/lib/supabase' +import { formatDate } from '@/lib/dates' +import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type State = + | { status: 'loading' } + | { + status: 'ready' + rows: ClientAnimalItem[] + next: RelationCursor | null + species: SpeciesLabel[] + } + | { status: 'error'; failure: RecordFailureKind } + +async function loadPage( + clientId: string, + after: RelationCursor | null, + species: SpeciesLabel[] | null, +) { + const client = getSupabaseClient() + if (!client) throw new TypeError('no backend') + const page = await listClientAnimals(client, clientId, { after }) + // Species names are read only when there is an animal to name. + const labels = + species ?? (page.rows.length ? await fetchSpeciesLabels(client) : []) + return { ...page, species: labels } +} + +/** + * The client's animals, read-only in V1-1.5 (owner choice 2026-10-26): the + * real relations from list_client_animals, current then former, each with + * its role. No link and no « ajouter » until the animal screens exist. + */ +export default function ClientAnimals({ clientId }: { clientId: string }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const [state, setState] = useState({ status: 'loading' }) + const [loadingMore, setLoadingMore] = useState(false) + + useEffect(() => { + let live = true + loadPage(clientId, null, null) + .then((page) => live && setState({ status: 'ready', ...page })) + .catch( + (error: unknown) => + live && + setState({ status: 'error', failure: classifyRecordError(error) }), + ) + return () => { + live = false + } + }, [clientId]) + + async function more() { + if (state.status !== 'ready' || !state.next) return + setLoadingMore(true) + try { + const page = await loadPage(clientId, state.next, state.species) + setState({ + ...state, + rows: [...state.rows, ...page.rows], + next: page.next, + }) + } catch (error) { + setState({ status: 'error', failure: classifyRecordError(error) }) + } finally { + setLoadingMore(false) + } + } + + const speciesName = (row: ClientAnimalItem, species: SpeciesLabel[]) => { + const label = species.find((s) => s.id === row.species_id) + const name = label + ? pickLocaleLabel(label.name_fr, label.name_en, locale, row.species_id) + : row.species_id + return row.species_detail ? `${name} (${row.species_detail})` : name + } + const period = (row: ClientAnimalItem) => + [ + row.started_on && + t('clients.animals.since').replace( + '{date}', + formatDate(row.started_on, locale), + ), + row.ended_on && + t('clients.animals.until').replace( + '{date}', + formatDate(row.ended_on, locale), + ), + ] + .filter(Boolean) + .join(' · ') + + function group( + rows: ClientAnimalItem[], + species: SpeciesLabel[], + current: boolean, + ) { + const shown = rows.filter((r) => r.is_current === current) + if (!shown.length) return null + const id = current ? 'client-animals-current' : 'client-animals-former' + return ( +
    +

    + {t(current ? 'clients.animals.current' : 'clients.animals.former')} +

    +
      + {shown.map((row) => ( +
    • + + + {row.animal_name} + {' '} + + {speciesName(row, species)} + + {row.animal_archived_at && ( + {t('clients.archived_badge')} + )} + + + {t( + `clients.role.${current ? '' : 'former_'}${row.relation_role}`, + )} + {period(row) && ` · ${period(row)}`} + +
    • + ))} +
    +
    + ) + } + + return ( + +

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

    + {state.status === 'loading' && ( +

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

    + )} + {state.status === 'error' && ( + {t(`clients.failure.${state.failure}`)} + )} + {state.status === 'ready' && state.rows.length === 0 && ( +

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

    + )} + {state.status === 'ready' && ( + <> + {group(state.rows, state.species, true)} + {group(state.rows, state.species, false)} + {state.next && ( + + )} + + )} +
    + ) +} diff --git a/apps/app/src/components/clients/ClientForm.tsx b/apps/app/src/components/clients/ClientForm.tsx new file mode 100644 index 00000000..0b666cba --- /dev/null +++ b/apps/app/src/components/clients/ClientForm.tsx @@ -0,0 +1,305 @@ +import { useEffect, useMemo } from 'react' +import { Link } from 'react-router-dom' +import { CLIENT_FIELD_LIMITS } from '@faunosteo/supabase' +import Button, { buttonClassName } from '@/components/ui/Button' +import Card from '@/components/ui/Card' +import FormField, { fieldDescribedBy } from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import Select from '@/components/ui/Select' +import { countryName, countryOptions } from '@/clients/countries' +import { + EMPTY_CLIENT_VALUES, + type ClientFormValues, +} from '@/clients/validation' +import type { ClientForm as ClientFormState } from '@/clients/useClientForm' +import { translateFieldError } from '@/account/validation' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +const FIELD_ORDER = Object.keys( + EMPTY_CLIENT_VALUES, +) as (keyof ClientFormValues)[] +const fieldId = (key: keyof ClientFormValues) => + `client-${key.replace('_', '-')}` + +export interface ClientFormProps { + form: ClientFormState + submitLabel: string + /** Where « Annuler » leads; the shell asks first while the form holds changes. */ + cancelTo: string +} + +/** + * The client form, one page on every screen (contract §11.3, §11.4): the kind + * first with « Personne » selected, the name whose label follows the kind, + * then contact and address. Every field is labelled, errors sit under their + * field and the first one takes focus after a refused submit. + */ +export default function ClientForm({ + form, + submitLabel, + cancelTo, +}: ClientFormProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const countries = useMemo(() => countryOptions(locale), [locale]) + const { values, errors, phase, stored } = form + + useEffect(() => { + if (form.errorRound === 0) return + const first = FIELD_ORDER.find((key) => errors[key]) + if (first) document.getElementById(fieldId(first))?.focus() + }, [form.errorRound, errors]) + + const err = (key: keyof ClientFormValues) => + translateFieldError(t, errors[key]) + /** After a conflict: the stored value under each field that differs from the typed one. */ + const storedHint = (key: keyof ClientFormValues): string | undefined => { + if (!stored) return undefined + const raw = key === 'country' ? stored.country : stored[key] + const value = raw ?? '' + if (value === values[key]) return undefined + const shown = + key === 'country' && value + ? countryName(value, locale) + : key === 'kind' + ? t(`clients.kind.${value}`) + : value + return shown + ? t('clients.form.stored_value').replace('{value}', shown) + : t('clients.form.stored_empty') + } + const describedBy = (key: keyof ClientFormValues, hint?: string) => + fieldDescribedBy(fieldId(key), hint, errors[key]) + + function textField( + key: keyof ClientFormValues, + label: string, + max: number, + extra: Record = {}, + ) { + const hint = storedHint(key) + return ( + + form.setField(key)(e.target.value)} + maxLength={max} + aria-invalid={Boolean(errors[key])} + aria-describedby={describedBy(key, hint)} + {...extra} + /> + + ) + } + + const nameKey = values.kind === 'organization' ? 'organization' : 'person' + const nameHint = + storedHint('display_name') ?? t(`clients.form.display_name_hint.${nameKey}`) + const saving = phase.kind === 'saving' + + return ( +
    + {stored && ( + +

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

    +

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

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

    + {storedHint('kind')} +

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

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

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

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

    + {textField( + 'address_line1', + t('clients.form.address_line1'), + CLIENT_FIELD_LIMITS.addressLine, + { + autoComplete: 'off', + }, + )} + {textField( + 'address_line2', + t('clients.form.address_line2'), + CLIENT_FIELD_LIMITS.addressLine, + { + autoComplete: 'off', + }, + )} +
    + {textField( + 'postal_code', + t('clients.form.postal_code'), + CLIENT_FIELD_LIMITS.postalCode, + { + autoComplete: 'off', + }, + )} + {textField('city', t('clients.form.city'), CLIENT_FIELD_LIMITS.city, { + autoComplete: 'off', + })} +
    + + + +
    + + {phase.kind === 'failed' && !stored && ( + {t(`clients.failure.${phase.failure}`)} + )} +
    + + {t('common.cancel')} + + +
    + + ) +} diff --git a/apps/app/src/components/clients/ClientNotFound.tsx b/apps/app/src/components/clients/ClientNotFound.tsx new file mode 100644 index 00000000..d8138274 --- /dev/null +++ b/apps/app/src/components/clients/ClientNotFound.tsx @@ -0,0 +1,21 @@ +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import { useT } from '@/i18n/useT' + +/** The same screen for an unknown id and an id of another workspace (contract §11.1). */ +export default function ClientNotFound() { + const t = useT() + return ( + +

    + {t('clients.not_found.title')} +

    +

    + {t('clients.not_found.body')} +

    + + {t('clients.not_found.back')} + +
    + ) +} diff --git a/apps/app/src/components/shell/AppLayout.tsx b/apps/app/src/components/shell/AppLayout.tsx index a4540646..4c684376 100644 --- a/apps/app/src/components/shell/AppLayout.tsx +++ b/apps/app/src/components/shell/AppLayout.tsx @@ -1,13 +1,16 @@ -import { useState } from 'react' -import { Link, Outlet, useLocation } from 'react-router-dom' +import { useState, type MouseEvent } from 'react' +import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom' import Brand from '@/components/brand/Brand' import LanguageSwitcher from '@/components/brand/LanguageSwitcher' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' import Icon from '@/components/ui/Icon' import MobileDrawer from './MobileDrawer' import SidebarNav, { NAV_ITEMS } from './SidebarNav' import SignOutButton from './SignOutButton' import UserBadge, { AvatarCircle } from './UserBadge' import { useAuthStore } from '@/state/authStore' +import { useLeaveGuardStore } from '@/state/leaveGuardStore' import { useT } from '@/i18n/useT' /** Title of the current /app page for the top bar, from the nav table. */ @@ -18,20 +21,53 @@ function pageTitleKey(pathname: string): string { return match?.labelKey ?? 'shell.nav.dashboard' } +/** An in-app link a plain click would follow: same origin, same tab, no modifier key. */ +function followedLink(event: MouseEvent): HTMLAnchorElement | null { + if (event.defaultPrevented || event.button !== 0) return null + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null + const anchor = (event.target as Element).closest('a[href]') as HTMLAnchorElement | null + if (!anchor || anchor.target === '_blank' || anchor.origin !== window.location.origin) return null + return anchor +} + /** * Authenticated shell: fixed sidebar on large screens, light top bar with a - * drawer button below. The page content scrolls on its own. + * drawer button below. The page content scrolls on its own. While a page + * holds unsaved changes (useLeaveGuard), following any link of the shell or + * of the page asks first; staying is the default. */ export default function AppLayout() { const t = useT() const location = useLocation() + const navigate = useNavigate() const [drawerOpen, setDrawerOpen] = useState(false) + const guarded = useLeaveGuardStore((s) => s.armed) + const arm = useLeaveGuardStore((s) => s.arm) + const [leaveTo, setLeaveTo] = useState(null) + + function askBeforeLeaving(event: MouseEvent) { + if (!guarded) return + const anchor = followedLink(event) + if (!anchor) return + event.preventDefault() + event.stopPropagation() + setLeaveTo(anchor.pathname + anchor.search + anchor.hash) + } + + function leave() { + const to = leaveTo + if (!to) return + arm(false) + setLeaveTo(null) + setDrawerOpen(false) + navigate(to) + } const profile = useAuthStore((s) => s.profile) const user = useAuthStore((s) => s.user) const displayName = profile?.display_name ?? user?.email ?? '' return ( -
    +
    ) } diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx index 98f9830e..9cc46a5f 100644 --- a/apps/app/src/components/shell/SidebarNav.tsx +++ b/apps/app/src/components/shell/SidebarNav.tsx @@ -12,6 +12,7 @@ interface NavItem { export const NAV_ITEMS: readonly NavItem[] = [ { to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true }, + { to: '/app/clients', icon: 'users', labelKey: 'shell.nav.clients' }, { to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' }, { to: '/', @@ -31,7 +32,7 @@ function linkClass(active: boolean): string { ].join(' ') } -/** The three destinations of the shell; `onNavigate` closes the mobile drawer. */ +/** The destinations of the shell, in the validated mockup's order; `onNavigate` closes the mobile drawer. */ export default function SidebarNav({ onNavigate }: { onNavigate?: () => void }) { const t = useT() return ( diff --git a/apps/app/src/components/ui/Icon.tsx b/apps/app/src/components/ui/Icon.tsx index 0123c7bd..79a5b3cb 100644 --- a/apps/app/src/components/ui/Icon.tsx +++ b/apps/app/src/components/ui/Icon.tsx @@ -5,6 +5,7 @@ export type IconName = | 'close' | 'dashboard' | 'user' + | 'users' | 'tool' | 'logout' | 'eye' @@ -20,6 +21,7 @@ const PATHS: Record = { close: 'M6 6l12 12M18 6L6 18', dashboard: 'M4 4h7v7H4zM13 4h7v4h-7zM13 11h7v9h-7zM4 14h7v6H4z', user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0', + users: 'M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M16 3.5a4 4 0 0 1 0 7M22 21a7 7 0 0 0-4.5-6.5', tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3', logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9', eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 8846d23c..6a77bfc1 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -362,6 +362,7 @@ export const en: Dict = { 'shell.close_menu': 'Close menu', 'shell.nav.dashboard': 'Dashboard', 'shell.nav.account': 'My account', + 'shell.nav.clients': 'Clients', 'shell.nav.local_tool': 'Report tool', 'shell.nav.local_tool_hint': 'No account, PDF export', 'shell.sign_out': 'Sign out', @@ -489,4 +490,143 @@ export const en: Dict = { 'Photo refused: between 64 and 4096 pixels per side.', 'account.avatar.rejected.processing_error': 'Photo refused: processing failed. Try another image.', + + // V1-1.5 clients, workspace, leave guard + 'common.retry': 'Retry', + 'workspace.loading': 'Loading your workspace…', + 'workspace.inactive': + 'Your account is deactivated: your records are not accessible. Contact Faunosteo support.', + 'workspace.unconfirmed': 'Confirm your email address to access your records.', + 'workspace.missing': + 'Your workspace does not answer. Retry; if it persists, contact Faunosteo support.', + 'workspace.error': 'Your workspace could not be loaded.', + 'clients.failure.not_found': 'This client cannot be found.', + 'clients.failure.archived': 'This client is archived: restore it to edit it.', + 'clients.failure.conflict': 'This client was changed in the meantime.', + 'clients.failure.request_conflict': + 'An earlier attempt of this creation carried other values and may already have created the client. Check the client list before trying again.', + 'clients.failure.limit_reached': + 'Your workspace has reached its maximum number of clients.', + 'clients.failure.rate_limited': + 'Too many changes in a short time. Try again in a few minutes.', + 'clients.failure.invalid_input': + 'A value was not accepted. Check the fields.', + 'clients.failure.session_expired': 'Your session has expired. Sign in again.', + 'clients.failure.network': 'No connection. Check your network, then retry.', + 'clients.failure.unavailable': + 'The service is not answering right now. Retry.', + 'clients.kind.person': 'Person', + 'clients.kind.organization': 'Organization', + 'clients.archived_badge': 'Archived', + 'clients.list.title': 'Clients', + 'clients.list.new': 'New client', + 'clients.list.search_label': 'Search clients', + 'clients.list.search_hint': 'Name, city, email or phone', + 'clients.list.archived_toggle': 'Show archived', + 'clients.list.loading': 'Loading clients…', + 'clients.list.results_label': 'Clients found', + 'clients.list.count_one': '1 client shown', + 'clients.list.count_other': '{count} clients shown', + 'clients.list.empty': 'No clients yet.', + 'clients.list.empty_hint': 'Create your first client with “New client”.', + 'clients.list.no_results': 'No client matches this search.', + 'clients.list.archived_empty': 'No archived clients.', + 'clients.list.more': 'Show more', + 'clients.list.loading_more': 'Loading…', + 'clients.list.animals_none': 'No animals', + 'clients.list.animals_one': '1 animal', + 'clients.list.animals_other': '{count} animals', + 'clients.form.create_title': 'New client', + 'clients.form.edit_title': 'Edit client', + 'clients.form.kind_legend': 'Client type', + 'clients.form.display_name.person': 'Display name', + 'clients.form.display_name.organization': 'Organization name', + 'clients.form.display_name_hint.person': + 'As you say it: “Marie Dupont”, “Mrs Dupont”.', + 'clients.form.display_name_hint.organization': + 'The name of the organization: “Écurie du Lac”.', + 'clients.form.required': 'required', + 'clients.form.optional': 'optional', + 'clients.form.contact_title': 'Contact details', + 'clients.form.address_title': 'Address', + 'clients.form.email': 'Email', + 'clients.form.phone': 'Phone', + 'clients.form.phone_hint': + 'With its country code (+32…); a French number (06…) is converted to +33.', + 'clients.form.address_line1': 'Address', + 'clients.form.address_line2': 'Address line 2', + 'clients.form.postal_code': 'Postal code', + 'clients.form.city': 'City', + 'clients.form.country': 'Country', + 'clients.form.country_none': 'Not given', + 'clients.form.submit_create': 'Create client', + 'clients.form.submit_update': 'Save', + 'clients.form.saving': 'Saving…', + 'clients.form.back_to_client': 'Back to the client', + 'clients.form.conflict_title': 'This client was changed elsewhere.', + 'clients.form.conflict_body': + 'What you typed is kept and the saved value is shown under each field that differs. “Save” will replace the saved values with yours.', + 'clients.form.conflict_take_stored': 'Use the saved values', + 'clients.form.stored_value': 'Saved value: {value}', + 'clients.form.stored_empty': 'Saved value: empty', + 'clients.error.required': 'This field is required.', + 'clients.error.too_long': '{max} characters at most.', + 'clients.error.characters': 'Character not accepted (tab, line break…).', + 'clients.error.email_format': 'Invalid email address.', + 'clients.error.phone_format': + 'Invalid number: +33 6 12 34 56 78 or 06 12 34 56 78.', + 'clients.error.phone_country_code': + 'Enter the number with its country code (+32…).', + 'clients.error.country': 'Unknown country.', + 'clients.detail.loading': 'Loading client…', + 'clients.detail.back': '← Clients', + 'clients.detail.contact': 'Contact details', + 'clients.detail.no_contact': 'No contact details given.', + 'clients.detail.phone': 'Phone', + 'clients.detail.email': 'Email', + 'clients.detail.address': 'Address', + 'clients.detail.country': 'Country', + 'clients.detail.edit': 'Edit', + 'clients.detail.archive': 'Archive', + 'clients.detail.restore': 'Restore', + 'clients.detail.restoring': 'Restoring…', + 'clients.detail.archived_notice': + 'This client is archived: the record is read-only. Restore it to edit it.', + 'clients.detail.created': 'Client created.', + 'clients.detail.updated': 'Changes saved.', + 'clients.detail.archived': 'Client archived.', + 'clients.detail.restored': 'Client restored.', + 'clients.animals.title': 'Animals', + 'clients.animals.loading': 'Loading animals…', + 'clients.animals.none': 'No animal linked to this client.', + 'clients.animals.current': 'Current', + 'clients.animals.former': 'Former', + 'clients.animals.since': 'since {date}', + 'clients.animals.until': 'until {date}', + 'clients.role.owner': 'Owner', + 'clients.role.keeper': 'Keeper', + 'clients.role.contact': 'Contact', + 'clients.role.former_owner': 'Former owner', + 'clients.role.former_keeper': 'Former keeper', + 'clients.role.former_contact': 'Former contact', + 'clients.archive.title': 'Archive this client?', + 'clients.archive.body': + 'The client will be hidden from the lists and the record becomes read-only. Its animals are not archived and its relations are kept. You can restore it at any time.', + 'clients.archive.preview_loading': 'Checking linked animals…', + 'clients.archive.preview_failed': 'Linked animals could not be checked.', + 'clients.archive.sole_owner_one': + 'It is the only current owner of this active animal:', + 'clients.archive.sole_owner_other': + 'It is the only current owner of these {count} active animals:', + 'clients.archive.others': 'and {count} more.', + 'clients.archive.confirm': 'Archive', + 'clients.archive.archiving': 'Archiving…', + 'clients.not_found.title': 'Client not found', + 'clients.not_found.body': + 'This client does not exist or is not available to your account.', + 'clients.not_found.back': 'Back to clients', + 'leave.title': 'Leave without saving?', + 'leave.body': 'The changes in this form will be lost.', + 'leave.stay': 'Stay on the page', + 'leave.confirm': 'Leave without saving', } diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 319712a9..fe462ee7 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -378,6 +378,7 @@ export const fr: Dict = { 'shell.close_menu': 'Fermer le menu', 'shell.nav.dashboard': 'Tableau de bord', 'shell.nav.account': 'Mon compte', + 'shell.nav.clients': 'Clients', 'shell.nav.local_tool': 'Outil de bilan', 'shell.nav.local_tool_hint': 'Sans compte, export PDF', 'shell.sign_out': 'Se déconnecter', @@ -507,4 +508,150 @@ export const fr: Dict = { 'Photo refusée : entre 64 et 4096 pixels de côté.', 'account.avatar.rejected.processing_error': 'Photo refusée : le traitement a échoué. Réessayez avec une autre image.', + + // V1-1.5 clients, workspace, leave guard + 'common.retry': 'Réessayer', + 'workspace.loading': 'Chargement de votre espace…', + 'workspace.inactive': + 'Votre compte est désactivé : vos dossiers ne sont pas accessibles. Contactez le support Faunosteo.', + 'workspace.unconfirmed': + 'Confirmez votre adresse e-mail pour accéder à vos dossiers.', + 'workspace.missing': + 'Votre espace de travail ne répond pas. Réessayez ; si cela persiste, contactez le support Faunosteo.', + 'workspace.error': "Votre espace de travail n'a pas pu être chargé.", + 'clients.failure.not_found': 'Ce client est introuvable.', + 'clients.failure.archived': + 'Ce client est archivé : restaurez-le pour le modifier.', + 'clients.failure.conflict': 'Ce client a été modifié entre-temps.', + 'clients.failure.request_conflict': + "Une tentative précédente de cette création portait d'autres valeurs et a peut-être déjà créé le client. Vérifiez la liste des clients avant de recommencer.", + 'clients.failure.limit_reached': + 'Le nombre maximal de clients de votre espace est atteint.', + 'clients.failure.rate_limited': + "Trop d'enregistrements en peu de temps. Réessayez dans quelques minutes.", + 'clients.failure.invalid_input': + "Une valeur n'a pas été acceptée. Vérifiez les champs.", + 'clients.failure.session_expired': + 'Votre session a expiré. Reconnectez-vous.', + 'clients.failure.network': + 'Connexion impossible. Vérifiez votre réseau, puis réessayez.', + 'clients.failure.unavailable': + 'Le service ne répond pas pour le moment. Réessayez.', + 'clients.kind.person': 'Personne', + 'clients.kind.organization': 'Structure', + 'clients.archived_badge': 'Archivé', + 'clients.list.title': 'Clients', + 'clients.list.new': 'Nouveau client', + 'clients.list.search_label': 'Rechercher un client', + 'clients.list.search_hint': 'Nom, ville, e-mail ou téléphone', + 'clients.list.archived_toggle': 'Afficher les archivés', + 'clients.list.loading': 'Chargement des clients…', + 'clients.list.results_label': 'Clients trouvés', + 'clients.list.count_one': '1 client affiché', + 'clients.list.count_other': '{count} clients affichés', + 'clients.list.empty': "Aucun client pour l'instant.", + 'clients.list.empty_hint': + 'Créez votre premier client avec « Nouveau client ».', + 'clients.list.no_results': 'Aucun client ne correspond à cette recherche.', + 'clients.list.archived_empty': 'Aucun client archivé.', + 'clients.list.more': 'Afficher plus', + 'clients.list.loading_more': 'Chargement…', + 'clients.list.animals_none': 'Aucun animal', + 'clients.list.animals_one': '1 animal', + 'clients.list.animals_other': '{count} animaux', + 'clients.form.create_title': 'Nouveau client', + 'clients.form.edit_title': 'Modifier le client', + 'clients.form.kind_legend': 'Type de client', + 'clients.form.display_name.person': 'Nom affiché', + 'clients.form.display_name.organization': 'Dénomination', + 'clients.form.display_name_hint.person': + 'Tel que vous le dites : « Marie Dupont », « Mme Dupont ».', + 'clients.form.display_name_hint.organization': + 'Le nom de la structure : « Écurie du Lac ».', + 'clients.form.required': 'obligatoire', + 'clients.form.optional': 'facultatif', + 'clients.form.contact_title': 'Coordonnées', + 'clients.form.address_title': 'Adresse', + 'clients.form.email': 'E-mail', + 'clients.form.phone': 'Téléphone', + 'clients.form.phone_hint': + 'Avec son indicatif (+32…) ; un numéro français (06…) est converti en +33.', + 'clients.form.address_line1': 'Adresse', + 'clients.form.address_line2': "Complément d'adresse", + 'clients.form.postal_code': 'Code postal', + 'clients.form.city': 'Ville', + 'clients.form.country': 'Pays', + 'clients.form.country_none': 'Non renseigné', + 'clients.form.submit_create': 'Créer le client', + 'clients.form.submit_update': 'Enregistrer', + 'clients.form.saving': 'Enregistrement…', + 'clients.form.back_to_client': 'Retour à la fiche', + 'clients.form.conflict_title': 'Ce client a été modifié ailleurs.', + 'clients.form.conflict_body': + 'Vos saisies sont conservées et la valeur enregistrée est indiquée sous chaque champ qui diffère. « Enregistrer » remplacera les valeurs enregistrées par les vôtres.', + 'clients.form.conflict_take_stored': 'Reprendre les valeurs enregistrées', + 'clients.form.stored_value': 'Valeur enregistrée : {value}', + 'clients.form.stored_empty': 'Valeur enregistrée : vide', + 'clients.error.required': 'Ce champ est obligatoire.', + 'clients.error.too_long': '{max} caractères au maximum.', + 'clients.error.characters': + 'Caractère non accepté (tabulation, saut de ligne…).', + 'clients.error.email_format': 'Adresse e-mail invalide.', + 'clients.error.phone_format': + 'Numéro invalide : +33 6 12 34 56 78 ou 06 12 34 56 78.', + 'clients.error.phone_country_code': + 'Indiquez le numéro avec son indicatif (+32…).', + 'clients.error.country': 'Pays inconnu.', + 'clients.detail.loading': 'Chargement du client…', + 'clients.detail.back': '← Clients', + 'clients.detail.contact': 'Coordonnées', + 'clients.detail.no_contact': 'Aucune coordonnée renseignée.', + 'clients.detail.phone': 'Téléphone', + 'clients.detail.email': 'E-mail', + 'clients.detail.address': 'Adresse', + 'clients.detail.country': 'Pays', + 'clients.detail.edit': 'Modifier', + 'clients.detail.archive': 'Archiver', + 'clients.detail.restore': 'Restaurer', + 'clients.detail.restoring': 'Restauration…', + 'clients.detail.archived_notice': + 'Ce client est archivé : sa fiche est en lecture seule. Restaurez-le pour la modifier.', + 'clients.detail.created': 'Client créé.', + 'clients.detail.updated': 'Modifications enregistrées.', + 'clients.detail.archived': 'Client archivé.', + 'clients.detail.restored': 'Client restauré.', + 'clients.animals.title': 'Animaux', + 'clients.animals.loading': 'Chargement des animaux…', + 'clients.animals.none': 'Aucun animal lié à ce client.', + 'clients.animals.current': 'Actuels', + 'clients.animals.former': 'Anciens', + 'clients.animals.since': 'depuis le {date}', + 'clients.animals.until': "jusqu'au {date}", + 'clients.role.owner': 'Propriétaire', + 'clients.role.keeper': 'Détenteur', + 'clients.role.contact': 'Contact', + 'clients.role.former_owner': 'Ancien propriétaire', + 'clients.role.former_keeper': 'Ancien détenteur', + 'clients.role.former_contact': 'Ancien contact', + 'clients.archive.title': 'Archiver ce client ?', + 'clients.archive.body': + 'Le client sera masqué des listes et sa fiche passera en lecture seule. Ses animaux ne sont pas archivés et ses relations sont conservées. Vous pourrez le restaurer à tout moment.', + 'clients.archive.preview_loading': 'Vérification des animaux liés…', + 'clients.archive.preview_failed': + "Les animaux liés n'ont pas pu être vérifiés.", + 'clients.archive.sole_owner_one': + "C'est le seul propriétaire actuel de cet animal actif :", + 'clients.archive.sole_owner_other': + "C'est le seul propriétaire actuel de ces {count} animaux actifs :", + 'clients.archive.others': 'et {count} de plus.', + 'clients.archive.confirm': 'Archiver', + 'clients.archive.archiving': 'Archivage…', + 'clients.not_found.title': 'Client introuvable', + 'clients.not_found.body': + "Ce client n'existe pas ou n'est pas accessible depuis votre compte.", + 'clients.not_found.back': 'Retour aux clients', + 'leave.title': 'Quitter sans enregistrer ?', + 'leave.body': 'Les modifications de ce formulaire seront perdues.', + 'leave.stay': 'Rester sur la page', + 'leave.confirm': 'Quitter sans enregistrer', } diff --git a/apps/app/src/state/leaveGuardStore.ts b/apps/app/src/state/leaveGuardStore.ts new file mode 100644 index 00000000..8477f247 --- /dev/null +++ b/apps/app/src/state/leaveGuardStore.ts @@ -0,0 +1,16 @@ +import { create } from 'zustand' + +/** + * Whether the page holds unsaved changes the user would lose by following a + * link of the shell. Armed by useLeaveGuard; read by AppLayout, which asks + * before an in-app link click while it is armed. + */ +interface LeaveGuardState { + armed: boolean + arm: (armed: boolean) => void +} + +export const useLeaveGuardStore = create((set) => ({ + armed: false, + arm: (armed) => set({ armed }), +})) diff --git a/apps/app/tests/unit/clients.validation.test.ts b/apps/app/tests/unit/clients.validation.test.ts new file mode 100644 index 00000000..f69c19ef --- /dev/null +++ b/apps/app/tests/unit/clients.validation.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest' +import { CLIENT_FIELD_LIMITS } from '@faunosteo/supabase' +import { COUNTRY_CODES, countryName, countryOptions } from '@/clients/countries' +import { + EMPTY_CLIENT_VALUES, + clientFieldErrors, + clientSchema, + normalizePhoneEntry, + type ClientFormValues, +} from '@/clients/validation' + +const parse = (patch: Partial) => clientSchema.safeParse({ ...EMPTY_CLIENT_VALUES, ...patch }) +const errorsOf = (patch: Partial) => { + const result = parse(patch) + return result.success ? {} : clientFieldErrors(result.error) +} + +describe('client form schema (D-R7 on field-limits)', () => { + it('needs only a kind and a display name; empty optionals become null', () => { + const result = parse({ display_name: ' Marie Dupont ' }) + expect(result.success && result.data).toEqual({ + kind: 'person', + display_name: 'Marie Dupont', + email: null, + phone: null, + address_line1: null, + address_line2: null, + postal_code: null, + city: null, + country: null, + }) + }) + + it('refuses a missing name and names the field', () => { + expect(errorsOf({ display_name: ' ' })).toEqual({ display_name: 'clients.error.required' }) + }) + + it('counts code points like char_length: 120 accepted, 121 refused, astral characters count once', () => { + expect(errorsOf({ display_name: 'é'.repeat(120) })).toEqual({}) + expect(errorsOf({ display_name: '𝄞'.repeat(120) })).toEqual({}) + expect(errorsOf({ display_name: 'é'.repeat(121) })).toEqual({ display_name: 'clients.error.too_long|120' }) + expect(errorsOf({ display_name: 'M', city: 'x'.repeat(CLIENT_FIELD_LIMITS.city + 1) })).toEqual({ city: 'clients.error.too_long|80' }) + expect(errorsOf({ display_name: 'M', postal_code: '9'.repeat(17) })).toEqual({ postal_code: 'clients.error.too_long|16' }) + expect(errorsOf({ display_name: 'M', address_line1: 'a'.repeat(121) })).toEqual({ address_line1: 'clients.error.too_long|120' }) + }) + + it('refuses control characters, U+2028 included, and trims Unicode spaces', () => { + expect(errorsOf({ display_name: 'Tab\there' })).toEqual({ display_name: 'clients.error.characters' }) + expect(errorsOf({ display_name: 'M', city: 'Line
sep' })).toEqual({ city: 'clients.error.characters' }) + const result = parse({ display_name: ' Marie ' }) + expect(result.success && result.data.display_name).toBe('Marie') + }) + + it('lower-cases the email and checks the shared pattern and its 254 bound', () => { + const result = parse({ display_name: 'M', email: ' Marie@Example.TEST ' }) + expect(result.success && result.data.email).toBe('marie@example.test') + expect(errorsOf({ display_name: 'M', email: 'a b@c.de' })).toEqual({ email: 'clients.error.email_format' }) + expect(errorsOf({ display_name: 'M', email: 'a'.repeat(247) + '@ex.test' })).toEqual({ email: 'clients.error.too_long|254' }) + expect(errorsOf({ display_name: 'M', email: 'a'.repeat(246) + '@ex.test' })).toEqual({}) + }) + + it('accepts only listed countries and sets none by default', () => { + expect(errorsOf({ display_name: 'M', country: 'XX' })).toEqual({ country: 'clients.error.country' }) + const result = parse({ display_name: 'M', country: 'BE' }) + expect(result.success && result.data.country).toBe('BE') + }) + + it('reports every field error at once, the phone included', () => { + expect(errorsOf({ display_name: '', phone: '12' })).toEqual({ + display_name: 'clients.error.required', + phone: 'clients.error.phone_format', + }) + }) + + it('stores the converted phone', () => { + const result = parse({ display_name: 'M', phone: '06 12 34 56 78' }) + expect(result.success && result.data.phone).toBe('+33612345678') + }) +}) + +describe('phone entry rule (contract §11.3)', () => { + it.each([ + ['06 12 34 56 78', '', { ok: true, value: '+33612345678' }], + ['06.12.34.56.78', 'FR', { ok: true, value: '+33612345678' }], + ['+32 475 12 34 56', 'BE', { ok: true, value: '+32475123456' }], + ['+33 6 12 34 56 78', 'BE', { ok: true, value: '+33612345678' }], + ['', 'BE', { ok: true, value: null }], + ['0475 12 34 56', 'BE', { ok: false, error: 'clients.error.phone_country_code' }], + ['06 12 34 56 78', 'CH', { ok: false, error: 'clients.error.phone_country_code' }], + ['0612', '', { ok: false, error: 'clients.error.phone_format' }], + ['0032475123456', 'FR', { ok: false, error: 'clients.error.phone_format' }], + ['+0612345678', '', { ok: false, error: 'clients.error.phone_format' }], + ])('%s with country %s', (raw, country, expected) => { + expect(normalizePhoneEntry(raw, country)).toEqual(expected) + }) +}) + +describe('countries', () => { + it('commits the 249 ISO 3166-1 alpha-2 codes, unique and upper-case', () => { + expect(COUNTRY_CODES).toHaveLength(249) + expect(new Set(COUNTRY_CODES).size).toBe(249) + expect(COUNTRY_CODES.every((code) => /^[A-Z]{2}$/.test(code))).toBe(true) + }) + + it('names them in the UI language, sorted by name', () => { + expect(countryName('BE', 'fr')).toBe('Belgique') + expect(countryName('BE', 'en')).toBe('Belgium') + const fr = countryOptions('fr') + expect(fr).toHaveLength(249) + const labels = fr.map((o) => o.label) + expect([...labels].sort((a, b) => a.localeCompare(b, 'fr'))).toEqual(labels) + }) +}) diff --git a/apps/app/tests/unit/routes.clients.test.tsx b/apps/app/tests/unit/routes.clients.test.tsx new file mode 100644 index 00000000..cadc10ea --- /dev/null +++ b/apps/app/tests/unit/routes.clients.test.tsx @@ -0,0 +1,371 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom' +import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase' + +const mocks = vi.hoisted(() => ({ fake: null as unknown })) +vi.mock('@/lib/supabase', () => ({ + getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, + isSupabaseConfigured: () => mocks.fake !== null, +})) + +import AppLayout from '@/components/shell/AppLayout' +import RequireWorkspace from '@/app/guards/RequireWorkspace' +import ClientsListRoute from '@/app/routes/app/clients/ClientsListRoute' +import ClientCreateRoute from '@/app/routes/app/clients/ClientCreateRoute' +import ClientDetailRoute from '@/app/routes/app/clients/ClientDetailRoute' +import ClientEditRoute from '@/app/routes/app/clients/ClientEditRoute' +import { SEARCH_DELAY_MS } from '@/clients/useClientList' +import { useAuthStore, type WorkspaceState } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' + +/** + * The client screens on a fake client: states, the calls they make and what + * they keep. The RPC signatures are checked by the compiler in + * packages/supabase and against real PostgREST in its sandbox suite; the + * journeys run in Chromium in e2e/shell/clients.spec.ts. + */ +const WS = '11111111-1111-4111-8111-111111111111' +const ID = '22222222-2222-4222-8222-222222222222' + +let fake: FakeSupabase + +function listRow(i: number, patch: Record = {}) { + return { + id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, + kind: 'person', + display_name: `Client ${String(i).padStart(2, '0')}`, + city: null, + phone: null, + email: null, + archived_at: null, + name_key: `client ${String(i).padStart(2, '0')}`, + current_animal_count: 0, + ...patch, + } +} + +function clientRow(patch: Record = {}) { + return { + id: ID, + kind: 'person', + display_name: 'Marie Dupont', + email: null, + phone: null, + address_line1: null, + address_line2: null, + postal_code: null, + city: 'Lyon', + country: null, + revision: 1, + archived_at: null, + created_at: '2026-10-26T10:00:00Z', + updated_at: '2026-10-26T10:00:00Z', + ...patch, + } +} + +/** The page itself, without the shell's top bar (which repeats the page title). */ +const page = () => within(screen.getByRole('main')) + +const rpcArgs = (name: string) => fake.rpcCalls.filter(([n]) => n === name).map(([, a]) => a as Record) + +function Where() { + return {useLocation().pathname} +} + +function mount(path: string, workspace: WorkspaceState = { status: 'ready', id: WS }) { + useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), workspace }) + return render( + + + }> + dashboard

    } /> + }> + } /> + } /> + } /> + } /> + + +
    + +
    , + ) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + fake = createFakeSupabase() + fake.tables.clients = [] + fake.rpcResults.search_clients = { data: [] } + fake.rpcResults.list_client_animals = { data: [] } + mocks.fake = fake +}) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) + +describe('RequireWorkspace', () => { + it.each([ + [{ status: 'loading' }, 'workspace.loading'], + [{ status: 'inactive' }, 'workspace.inactive'], + [{ status: 'unconfirmed' }, 'workspace.unconfirmed'], + [{ status: 'missing' }, 'workspace.missing'], + ] as const)('says %o and renders no client screen', (workspace, key) => { + mount('/app/clients', workspace) + expect(screen.getByText(fr[key])).toBeInTheDocument() + expect(page().queryByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeNull() + expect(fake.rpcCalls).toEqual([]) + }) + + it('names a read failure and reads again on retry', async () => { + fake.tables.workspaces = [{ id: WS, personal_user_id: 'user-1' }] + mount('/app/clients', { status: 'error', failure: 'network' }) + expect(screen.getByText(`${fr['workspace.error']} ${fr['clients.failure.network']}`)).toBeInTheDocument() + await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] })) + expect(await page().findByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeInTheDocument() + }) + + it('remounts the screens on another workspace: no row of the previous one stays', async () => { + fake.rpcResults.search_clients = { data: [listRow(1, { display_name: 'Client de A' })] } + mount('/app/clients') + expect(await screen.findByText('Client de A')).toBeInTheDocument() + fake.rpcResults.search_clients = { data: [] } + act(() => useAuthStore.setState({ workspace: { status: 'loading' } })) + expect(screen.queryByText('Client de A')).toBeNull() + act(() => useAuthStore.setState({ workspace: { status: 'ready', id: '33333333-3333-4333-8333-333333333333' } })) + expect(await screen.findByText(fr['clients.list.empty'])).toBeInTheDocument() + expect(screen.queryByText('Client de A')).toBeNull() + expect(rpcArgs('search_clients').at(-1)?.workspace_id).toBe('33333333-3333-4333-8333-333333333333') + }) +}) + +describe('client list', () => { + it('lists the first page in the workspace, focuses its heading, offers « Afficher plus »', async () => { + fake.rpcResults.search_clients = { data: Array.from({ length: 26 }, (_, i) => listRow(i + 1)) } + mount('/app/clients') + expect(await screen.findByText('Client 01')).toBeInTheDocument() + expect(page().getByRole('heading', { level: 1, name: fr['clients.list.title'] })).toHaveFocus() + expect(screen.getAllByRole('listitem')).toHaveLength(25) + expect(rpcArgs('search_clients')[0]).toMatchObject({ workspace_id: WS, query: '', archived: false, page_size: 26 }) + fake.rpcResults.search_clients = { data: [listRow(26), listRow(27)] } + await userEvent.click(screen.getByRole('button', { name: fr['clients.list.more'] })) + expect(await screen.findByText('Client 27')).toBeInTheDocument() + expect(screen.getAllByRole('listitem')).toHaveLength(27) + expect(rpcArgs('search_clients').at(-1)).toMatchObject({ after_name_key: 'client 25', after_id: listRow(25).id }) + expect(screen.queryByRole('button', { name: fr['clients.list.more'] })).toBeNull() + }) + + it('waits for a pause in typing before searching, once', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + mount('/app/clients') + await screen.findByText(fr['clients.list.empty']) + const before = rpcArgs('search_clients').length + const box = screen.getByRole('searchbox', { name: new RegExp(fr['clients.list.search_label']) }) + for (const value of ['m', 'ma', 'mar', 'mari']) fireEvent.change(box, { target: { value } }) + await act(() => vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS + 10)) + await waitFor(() => expect(rpcArgs('search_clients').length).toBe(before + 1)) + expect(rpcArgs('search_clients').at(-1)?.query).toBe('mari') + expect(await screen.findByText(fr['clients.list.no_results'])).toBeInTheDocument() + }) + + it('switches to the archived clients', async () => { + mount('/app/clients') + await screen.findByText(fr['clients.list.empty']) + fake.rpcResults.search_clients = { data: [listRow(1, { archived_at: '2026-10-26T10:00:00Z' })] } + await userEvent.click(screen.getByRole('switch', { name: fr['clients.list.archived_toggle'] })) + expect(await screen.findByText(fr['clients.archived_badge'])).toBeInTheDocument() + expect(rpcArgs('search_clients').at(-1)?.archived).toBe(true) + }) + + it('names a failure and retries', async () => { + fake.rpcResults.search_clients = { error: { code: '', message: 'FetchError' } } + mount('/app/clients') + expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument() + fake.rpcResults.search_clients = { data: [listRow(1)] } + await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] })) + expect(await screen.findByText('Client 01')).toBeInTheDocument() + }) +}) + +describe('client creation', () => { + it('refuses an empty name and focuses it, without a request', async () => { + mount('/app/clients/new') + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])) + expect(name).toHaveFocus() + expect(name).toHaveAttribute('aria-invalid', 'true') + expect(screen.getByText(fr['clients.error.required'])).toBeInTheDocument() + expect(rpcArgs('create_client')).toEqual([]) + }) + + it('sends the same request id again after a lost answer, then opens the client', async () => { + fake.rpcResults.create_client = { error: { code: '', message: 'TypeError: fetch failed' } } + mount('/app/clients/new') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Marie Dupont') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.phone'])), '06 12 34 56 78') + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument() + fake.rpcResults.create_client = { data: { id: ID, revision: 1 } } + fake.tables.clients = [clientRow()] + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`)) + const [first, second] = rpcArgs('create_client') + expect(first.create_request_id).toBe(second.create_request_id) + expect(first).toMatchObject({ workspace_id: WS, kind: 'person', display_name: 'Marie Dupont', phone: '+33612345678' }) + expect(await screen.findByText(fr['clients.detail.created'])).toBeInTheDocument() + }) + + it('a double click sends one creation', async () => { + let release: () => void = () => undefined + const pending = new Promise((resolve) => (release = resolve)) + const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise } + client.rpc = async (name, args) => { + fake.rpcCalls.push([name, args]) + await pending + return { data: { id: ID, revision: 1 }, error: null } + } + mount('/app/clients/new') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Double') + const submit = screen.getByRole('button', { name: fr['clients.form.submit_create'] }) + fireEvent.click(submit) + fireEvent.click(submit) + fireEvent.submit(submit.closest('form') as HTMLFormElement) + await act(async () => release()) + expect(rpcArgs('create_client')).toHaveLength(1) + }) + + it('a new form is a new intent: another request id', async () => { + fake.rpcResults.create_client = { error: { code: 'P0001', message: 'rate_limited' } } + const first = mount('/app/clients/new') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A') + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + expect(await screen.findByText(fr['clients.failure.rate_limited'])).toBeInTheDocument() + first.unmount() + mount('/app/clients/new') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A') + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + await screen.findByText(fr['clients.failure.rate_limited']) + const ids = rpcArgs('create_client').map((a) => a.create_request_id) + expect(ids[0]).not.toBe(ids[1]) + }) + + it('says a divergent replay plainly', async () => { + fake.rpcResults.create_client = { error: { code: 'P0001', message: 'request_conflict' } } + mount('/app/clients/new') + await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'B') + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] })) + expect(await screen.findByText(fr['clients.failure.request_conflict'])).toBeInTheDocument() + }) +}) + +describe('client edit', () => { + it('on conflict shows the stored value beside the typed one, then saves at the new revision', async () => { + fake.tables.clients = [clientRow()] + mount(`/app/clients/${ID}/edit`) + const city = await screen.findByLabelText(new RegExp(fr['clients.form.city'])) + await userEvent.clear(city) + await userEvent.type(city, 'Annecy') + fake.tables.clients = [clientRow({ city: 'Vevey', revision: 2 })] + fake.rpcResults.update_client = { error: { code: 'P0001', message: 'conflict' } } + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] })) + expect(await screen.findByText(fr['clients.form.conflict_title'])).toBeInTheDocument() + expect(city).toHaveValue('Annecy') + expect(screen.getByText(fr['clients.form.stored_value'].replace('{value}', 'Vevey'))).toBeInTheDocument() + fake.rpcResults.update_client = { data: { revision: 3 } } + await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] })) + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`)) + expect(rpcArgs('update_client').map((a) => a.expected_revision)).toEqual([1, 2]) + expect(rpcArgs('update_client')[1]).toMatchObject({ city: 'Annecy', email: null }) + }) + + it('an archived client has no form', async () => { + fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z' })] + mount(`/app/clients/${ID}/edit`) + expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument() + expect(screen.queryByRole('button', { name: fr['clients.form.submit_update'] })).toBeNull() + }) +}) + +describe('client page', () => { + it('shows the same « introuvable » for an unknown id and a malformed one', async () => { + mount(`/app/clients/${ID}`) + expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument() + cleanup() + mount('/app/clients/not-an-id') + expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument() + }) + + it('an archived client is read-only and can be restored', async () => { + fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })] + mount(`/app/clients/${ID}`) + expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument() + expect(screen.queryByRole('link', { name: fr['clients.detail.edit'] })).toBeNull() + fake.rpcResults.set_client_archived = { data: { revision: 3 } } + fake.tables.clients = [clientRow({ revision: 3 })] + await userEvent.click(screen.getByRole('button', { name: fr['clients.detail.restore'] })) + expect(await screen.findByText(fr['clients.detail.restored'])).toBeInTheDocument() + expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: false }]) + expect(await screen.findByRole('link', { name: fr['clients.detail.edit'] })).toBeInTheDocument() + }) + + it('archives after the confirmation, which refuses to close while the request runs', async () => { + fake.tables.clients = [clientRow()] + fake.rpcResults.client_archive_preview = { + data: { count: 1, animals: [{ id: '44444444-4444-4444-8444-444444444444', name: 'Éclair' }] }, + } + let release: () => void = () => undefined + const pending = new Promise((resolve) => (release = resolve)) + const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise } + const rpc = client.rpc.bind(client) + client.rpc = async (name, args) => { + if (name === 'set_client_archived') { + fake.rpcCalls.push([name, args]) + await pending + return { data: { revision: 2 }, error: null } + } + return rpc(name, args) + } + mount(`/app/clients/${ID}`) + await userEvent.click(await screen.findByRole('button', { name: fr['clients.detail.archive'] })) + const dialog = await screen.findByRole('dialog', { name: fr['clients.archive.title'] }) + expect(await screen.findByText('Éclair')).toBeInTheDocument() + expect(screen.getByText(fr['clients.archive.sole_owner_one'])).toBeInTheDocument() + await userEvent.click(within(dialog).getByRole('button', { name: fr['clients.archive.confirm'] })) + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] })) + expect(dialog).toBeInTheDocument() + fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })] + await act(async () => release()) + expect(await screen.findByText(fr['clients.detail.archived'])).toBeInTheDocument() + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: true }]) + }) +}) + +describe('leave guard', () => { + it('asks before a link leaves a form with changes; staying keeps them', async () => { + mount('/app/clients/new') + const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])) + await userEvent.type(name, 'Brouillon') + await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] })) + expect(await screen.findByRole('dialog', { name: fr['leave.title'] })).toBeInTheDocument() + expect(screen.getByTestId('where')).toHaveTextContent('/app/clients/new') + await userEvent.click(screen.getByRole('button', { name: fr['leave.stay'] })) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(name).toHaveValue('Brouillon') + await userEvent.click(screen.getAllByRole('link', { name: fr['shell.nav.dashboard'] })[0]) + await userEvent.click(await screen.findByRole('button', { name: fr['leave.confirm'] })) + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app$/)) + }) + + it('lets a clean form go without asking', async () => { + mount('/app/clients/new') + await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] })) + await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app\/clients$/)) + expect(screen.queryByRole('dialog')).toBeNull() + }) +}) From d33a8f6dad2add68b56bdc065fc73bc78bfa8107 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 01:59:26 +0100 Subject: [PATCH 32/60] test(app): client journeys in Chromium on the isolated stack Create, search, edit, archive, archived filter, restore; pages of 25; keyboard only; two accounts; a concurrent edit; a retry after a lost answer sends the same request id; network failures; the leave guard; a change of language; FR/EN, desktop and 375 px, axe on every state. signIn shared. --- apps/app/e2e/shell/clients.spec.ts | 599 +++++++++++++++++++++++++++++ apps/app/e2e/shell/shell.spec.ts | 20 +- apps/app/e2e/support/sandbox.ts | 29 +- apps/app/e2e/support/shell.ts | 17 + 4 files changed, 638 insertions(+), 27 deletions(-) create mode 100644 apps/app/e2e/shell/clients.spec.ts create mode 100644 apps/app/e2e/support/shell.ts diff --git a/apps/app/e2e/shell/clients.spec.ts b/apps/app/e2e/shell/clients.spec.ts new file mode 100644 index 00000000..4096862d --- /dev/null +++ b/apps/app/e2e/shell/clients.spec.ts @@ -0,0 +1,599 @@ +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, + 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('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() + }) + + 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'], + }), + ).toBeVisible() + await expect(page.getByText(secret)).toHaveCount(0) + } + await expectAccessible(page, 'the client not found screen') + }) + + test('a concurrent edit: the saved values beside the typed ones, then a knowing save', async ({ + page, + requests, + }) => { + const name = `Révision Fictive ${randomUUID().slice(0, 8)}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + ) + const id = await seedClient(account, name, 'Lyon') + await signIn(page, account, dict) + await page.goto(`/app/clients/${id}/edit`) + const city = page.getByLabel(dict['clients.form.city']) + await expect(city).toHaveValue('Lyon') + await city.fill('Annecy') + await sql( + `update public.clients set city = 'Vevey', revision = revision + 1 where id = '${id}'`, + ) + await page + .getByRole('button', { + name: dict['clients.form.submit_update'], + exact: true, + }) + .click() + await expect( + page.getByText(dict['clients.form.conflict_title']), + ).toBeVisible() + await expect(city).toHaveValue('Annecy') + await expect( + page.getByText( + dict['clients.form.stored_value'].replace('{value}', 'Vevey'), + ), + ).toBeVisible() + expect( + await sql( + `select city || '/' || revision from public.clients where id = '${id}'`, + ), + ).toBe('Vevey/2') + await expectAccessible(page, 'the conflict') + await page + .getByRole('button', { + name: dict['clients.form.submit_update'], + exact: true, + }) + .click() + await expect(page.getByText(dict['clients.detail.updated'])).toBeVisible() + expect( + await sql( + `select city || '/' || revision from public.clients where id = '${id}'`, + ), + ).toBe('Annecy/3') + }) + + test('a lost answer: the retry sends the same request id and one client exists', async ({ + page, + requests, + }) => { + const name = `Reprise Fictive ${randomUUID().slice(0, 8)}` + const account = await createAccount(locale, false) + requests.forbid( + account.email, + account.password, + account.displayName, + name, + ) + await signIn(page, account, dict) + const sent: string[] = [] + await page.route('**/rest/v1/rpc/create_client', async (route) => { + sent.push( + JSON.parse(route.request().postData() ?? '{}').create_request_id, + ) + if (sent.length > 1) return route.fallback() + // The server creates the client; its answer never reaches the page. + await route.fetch({ url: sandboxUrl(route.request().url()) ?? '' }) + await route.abort('failed') + }) + await page.goto('/app/clients/new') + await page.getByLabel(dict['clients.form.display_name.person']).fill(name) + const submit = page.getByRole('button', { + name: dict['clients.form.submit_create'], + }) + await submit.click() + await expect( + page.getByText(dict['clients.failure.network']), + ).toBeVisible() + expect( + await sql( + `select count(*) from public.clients where display_name = '${name}'`, + ), + ).toBe('1') + await submit.click() + await expect( + page.getByRole('main').getByRole('heading', { level: 1, name }), + ).toBeVisible() + expect(sent).toHaveLength(2) + expect(sent[0]).toBe(sent[1]) + expect( + await sql( + `select count(*) from public.clients where display_name = '${name}'`, + ), + ).toBe('1') + }) + + test('a failed list says so and retries; a failed save keeps the form', async ({ + page, + requests, + }, info) => { + const account = await createAccount(locale, false) + requests.forbid(account.email, account.password, account.displayName) + await seedClient(account, 'Client Réseau') + await signIn(page, account, dict) + let failing = true + await page.route('**/rest/v1/rpc/search_clients', (route) => + failing ? route.abort('failed') : route.fallback(), + ) + await openClients(page, dict, info) + await expect( + page.getByText(dict['clients.failure.network']), + ).toBeVisible() + failing = false + await page.getByRole('button', { name: dict['common.retry'] }).click() + await expect(listRows(page, dict)).toHaveCount(1) + + await page.route('**/rest/v1/rpc/create_client', (route) => + route.fulfill({ + status: 400, + contentType: 'application/json', + body: '{"code":"P0001","message":"rate_limited"}', + }), + ) + await page.goto('/app/clients/new') + await page + .getByLabel(dict['clients.form.display_name.person']) + .fill('Client Limité') + await page + .getByRole('button', { name: dict['clients.form.submit_create'] }) + .click() + await expect( + page.getByText(dict['clients.failure.rate_limited']), + ).toBeVisible() + await expect( + page.getByLabel(dict['clients.form.display_name.person']), + ).toHaveValue('Client Limité') + }) + + test('unsaved changes: a link asks first, staying keeps them', async ({ + page, + requests, + }, info) => { + const account = await createAccount(locale, false) + requests.forbid(account.email, account.password, account.displayName) + await signIn(page, account, dict) + await page.goto('/app/clients/new') + const field = page.getByLabel(dict['clients.form.display_name.person']) + await field.fill('Brouillon Fictif') + const cancel = page.getByRole('link', { name: dict['common.cancel'] }) + await cancel.click() + const dialog = page.getByRole('dialog', { name: dict['leave.title'] }) + await expect(dialog).toBeVisible() + await expectAccessible(page, 'the leave confirmation') + await dialog.getByRole('button', { name: dict['leave.stay'] }).click() + await expect(dialog).toBeHidden() + await expect(page).toHaveURL(/\/app\/clients\/new$/) + await expect(field).toHaveValue('Brouillon Fictif') + await expect(cancel).toBeFocused() + + if (isPhone(info)) { + await page + .getByRole('button', { name: dict['shell.open_menu'] }) + .click() + await page + .getByRole('dialog', { name: dict['shell.nav_label'] }) + .getByRole('navigation') + .getByRole('link', { name: dict['shell.nav.dashboard'] }) + .click() + } else { + await page + .getByRole('navigation', { name: dict['shell.nav_label'] }) + .getByRole('link', { name: dict['shell.nav.dashboard'] }) + .click() + } + await expect(dialog).toBeVisible() + await dialog.getByRole('button', { name: dict['leave.confirm'] }).click() + await expect(page).toHaveURL(/\/app\/?$/) + await expect(page.getByRole('dialog')).toHaveCount(0) + }) + + test('the list follows a change of language', async ({ + page, + requests, + }, info) => { + const account = await createAccount(locale, false) + requests.forbid(account.email, account.password, account.displayName) + await seedClient(account, 'Client Bilingue') + await signIn(page, account, dict) + await openClients(page, dict, info) + const other = locale === 'fr' ? en : fr + await page + .getByRole('button', { + name: dict[ + locale === 'fr' ? 'lang.switch_to_en' : 'lang.switch_to_fr' + ], + }) + .click() + await expect( + page.getByRole('link', { name: other['clients.list.new'] }), + ).toBeVisible() + await expect( + page.getByRole('searchbox', { + name: other['clients.list.search_label'], + }), + ).toBeVisible() + await expect(listRows(page, other).first()).toContainText( + other['clients.kind.person'], + ) + await expectAccessible(page, 'the list after a change of language') + }) + }) +} diff --git a/apps/app/e2e/shell/shell.spec.ts b/apps/app/e2e/shell/shell.spec.ts index 7bb018f2..5cf63dbf 100644 --- a/apps/app/e2e/shell/shell.spec.ts +++ b/apps/app/e2e/shell/shell.spec.ts @@ -1,6 +1,5 @@ import { en } from '@/i18n/en' import { fr } from '@/i18n/fr' -import type { Dict } from '@/i18n/types' import type { Page } from '@playwright/test' import { expect, @@ -10,11 +9,8 @@ import { focusedName, test, } from '../support/browser' -import { - createAccount, - routeToSandbox, - type SandboxAccount, -} from '../support/sandbox' +import { createAccount, 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. @@ -24,18 +20,6 @@ const LANGUAGES = [ ['en', en], ] as const -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) -} - /** Focus steps of `count` Tab presses, the browser's interface written « browser ». */ async function tabWalk(page: Page, count: number): Promise { const steps: string[] = [] diff --git a/apps/app/e2e/support/sandbox.ts b/apps/app/e2e/support/sandbox.ts index dec7ebdb..c333264e 100644 --- a/apps/app/e2e/support/sandbox.ts +++ b/apps/app/e2e/support/sandbox.ts @@ -21,17 +21,20 @@ const ROUTES: [prefix: string, target: string][] = [ ['/storage/v1/', `${storageUrl}/`], ] +/** The sandbox URL a request to the fake Supabase origin maps to, or null when unmapped. */ +export function sandboxUrl(url: string): string | null { + const { pathname, search } = new URL(url) + const path = pathname + search + const mapped = ROUTES.find(([prefix]) => path.startsWith(prefix)) + return mapped ? mapped[1] + path.slice(mapped[0].length) : null +} + /** Replays the page's Supabase calls on the sandbox; an unmapped path is refused. */ export async function routeToSandbox(context: BrowserContext): Promise { await context.route(`${FAKE_SUPABASE_ORIGIN}/**`, async (route) => { - const path = - new URL(route.request().url()).pathname + - new URL(route.request().url()).search - const mapped = ROUTES.find(([prefix]) => path.startsWith(prefix)) - if (!mapped) return route.abort('blockedbyclient') - const response = await route.fetch({ - url: mapped[1] + path.slice(mapped[0].length), - }) + const target = sandboxUrl(route.request().url()) + if (!target) return route.abort('blockedbyclient') + const response = await route.fetch({ url: target }) await route.fulfill({ response }) }) } @@ -43,6 +46,7 @@ const AVATAR_WEBP = Buffer.from( ) export interface SandboxAccount { + id: string email: string password: string displayName: string @@ -105,5 +109,12 @@ export async function createAccount( }) const { id } = (await response.json()) as { id: string } if (withAvatar) await seedAvatar(id) - return account + return { ...account, id } +} + +/** The personal workspace of a sandbox account (created by the server at sign-up). */ +export function workspaceOf(account: SandboxAccount): Promise { + return sql( + `select id from public.workspaces where personal_user_id = '${account.id}'`, + ) } diff --git a/apps/app/e2e/support/shell.ts b/apps/app/e2e/support/shell.ts new file mode 100644 index 00000000..95c9d9c7 --- /dev/null +++ b/apps/app/e2e/support/shell.ts @@ -0,0 +1,17 @@ +import type { Dict } from '@/i18n/types' +import type { Page } from '@playwright/test' +import { expect } from './browser' +import type { SandboxAccount } from './sandbox' + +/** Signs in through the login form; resolves on the dashboard once the profile answered. */ +export async function signIn(page: Page, account: SandboxAccount, dict: Dict) { + await page.goto('/login') + await page.getByLabel(dict['auth.email']).fill(account.email) + await page + .getByLabel(dict['auth.password'], { exact: true }) + .fill(account.password) + await page.getByRole('button', { name: dict['auth.login.submit'] }).click() + await expect(page).toHaveURL(/\/app\/?$/) + // The greeting needs the profile: the session and the first REST call went through. + await expect(page.locator('main h1')).toContainText(account.displayName) +} From db81928dfa7fedfbbe108d51b895cfaed48d2e15 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:00:33 +0100 Subject: [PATCH 33/60] fix(app): no HTML report for the shell suite, it kept typed passwords The report's step titles held what the tests typed, the throwaway sandbox accounts' passwords included, contrary to BROWSER_TESTS.md. The shell suite keeps the terminal output and failure screenshots; the old report deleted. --- apps/app/e2e/playwright.shell.config.ts | 11 ++++++----- docs/development/BROWSER_TESTS.md | 14 +++++++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/apps/app/e2e/playwright.shell.config.ts b/apps/app/e2e/playwright.shell.config.ts index 9ceaf607..a05cad07 100644 --- a/apps/app/e2e/playwright.shell.config.ts +++ b/apps/app/e2e/playwright.shell.config.ts @@ -3,7 +3,8 @@ * 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 is kept: it would hold the session tokens. + * 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' @@ -23,10 +24,10 @@ export default defineConfig({ fullyParallel: true, forbidOnly: true, retries: 0, - reporter: [ - ['list'], - ['html', { outputFolder: './playwright-report/shell', open: 'never' }], - ], + // 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], diff --git a/docs/development/BROWSER_TESTS.md b/docs/development/BROWSER_TESTS.md index 708e742e..5e19ec8d 100644 --- a/docs/development/BROWSER_TESTS.md +++ b/docs/development/BROWSER_TESTS.md @@ -69,14 +69,18 @@ object with the service key). `pnpm db:sandbox down` removes all of it. inherits an exception (owner brief 2026-10-26). - Reports: `apps/app/e2e/test-results/` and `apps/app/e2e/playwright-report/`, git-ignored. The UI suite keeps a trace and a screenshot of a failed test - (no backend, no secret). The shell suite keeps a screenshot only: a trace - would hold the session tokens and the typed password. + (no backend, no secret). The shell suite keeps the terminal output and a + screenshot of a failed test only: a trace would hold the session tokens, and + an HTML report the typed values, the fictitious accounts' passwords included + (found in the V1-1.5 report check, 2026-10-26; the HTML reporter was removed + from the shell config). Screenshots and the failure's page snapshot show + fictitious names and addresses only. ## 4. Reading a failure -The terminal shows each step and the failing assertion. The HTML report: -`pnpm --filter @faunosteo/app exec playwright show-report e2e/playwright-report/ui` -(or `.../shell`); a UI trace: `pnpm --filter @faunosteo/app exec playwright +The terminal shows each step and the failing assertion. The HTML report of +the UI suite: `pnpm --filter @faunosteo/app exec playwright show-report +e2e/playwright-report/ui` (the shell suite has none); a UI trace: `pnpm --filter @faunosteo/app exec playwright show-trace `. Setup failures are named: a missing Chromium (Playwright prints the install command), a stale core module (`run pnpm wasm:build`), the shell suite outside its wrapper From ae0bd3f8d84bf9c40c9d9f0879022eeac5b977cc Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:01:55 +0100 Subject: [PATCH 34/60] docs(docs): V1-1.5 clients screens as built, owner choices, tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contract §11.7 (U1, U2, animals read-only, first-animal section deferred; access layer, workspace state, routes, form, page, leave guard, focus, deviations, counts), FRONTEND_ARCHITECTURE note, design README owners row, TEST_STRATEGY, SUPABASE.md access layer and DEV note, CLAUDE.md map. --- CLAUDE.md | 15 ++++++-- docs/design/README.md | 2 +- docs/development/FRONTEND_ARCHITECTURE.md | 6 +++ docs/development/SUPABASE.md | 5 +++ docs/development/TEST_STRATEGY.md | 5 +++ docs/development/V1-1_OWNERS_ANIMALS.md | 45 +++++++++++++++++++++-- 6 files changed, 70 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 622743f8..b5dfef52 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,10 +50,11 @@ Product roadmap (owner, 2026-10-25): P0 docs, then V1-1 clients and animals, V1- 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`: 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.3 (validated) and V1-1.4 are built: migrations `20261025100000_workspaces.sql`, +`feature/v1-1-clients-animals` V1-1.1 to V1-1.4 (validated) and V1-1.5 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`); no client or animal screen yet). +(D14, `docs/development/BROWSER_TESTS.md`); V1-1.5 the client screens (`/app/clients`, contract §11.7) on the +isolated stack; no animal screen yet). --- @@ -223,7 +224,9 @@ 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 +│ │ ├─ guards/{RequireAuth,RedirectIfSignedIn,SessionLoading,RequireWorkspace}.tsx ← RequireWorkspace: personal workspace ready, remount per workspace +│ │ ├─ 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 @@ -239,10 +242,12 @@ 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 │ ├─ anatomy/drawing.ts ← the core's composed view (`view.canvas`) → DOMParser → importNode (R3; no sanitiser here) │ ├─ components/ │ │ ├─ ui/{Button,ButtonLink,Card,Dialog,ModalDialog,Input,Label,Select,Textarea,Badge,Chip,Icon,FormField,Notice}.tsx ← ModalDialog: native showModal (D13), Dialog and MobileDrawer on it @@ -254,6 +259,7 @@ 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 │ │ ├─ 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 @@ -283,6 +289,7 @@ 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,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/ diff --git a/docs/design/README.md b/docs/design/README.md index 1cce98d6..ffdaa84a 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -30,7 +30,7 @@ step has built yet, with the step that owns them: | Element | Owner | |---|---| -| Clients and Animaux entries and screens | roadmap V1-1 (plan Step 12 reduced, `docs/development/V1-1_OWNERS_ANIMALS.md`) | +| Clients and Animaux entries and screens | roadmap V1-1 (plan Step 12 reduced, `docs/development/V1-1_OWNERS_ANIMALS.md`). Clients built in V1-1.5 (2026-10-26): the entry in the sidebar and the drawer after Tableau de bord, the screens on the existing cards, fields, badges and buttons (the mockup draws no client screen); Animaux with V1-1.6 | | Fiches anatomiques entry and screen | roadmap V1-2 (plan Step 13 reduced) | | Bilans entry and screens | roadmap V1-3 (plan Step 14) | | Agenda entry and screens | plan Step 20 | diff --git a/docs/development/FRONTEND_ARCHITECTURE.md b/docs/development/FRONTEND_ARCHITECTURE.md index 904a78cc..bd7a7631 100644 --- a/docs/development/FRONTEND_ARCHITECTURE.md +++ b/docs/development/FRONTEND_ARCHITECTURE.md @@ -13,6 +13,12 @@ architecture) is the current description. V1-1.3 (2026-10-25): every modal (`Dialog`, the mobile drawer) is built on `components/ui/ModalDialog.tsx`, the native `` in modal mode (behaviour in `V1-1_OWNERS_ANIMALS.md` §11.6), and the real-browser suites live in `apps/app/e2e` (`BROWSER_TESTS.md`). +V1-1.5 (2026-10-26): the first record screens, the clients +(`V1-1_OWNERS_ANIMALS.md` §11.7): data access only through +`packages/supabase` (closed `RecordFailure` kinds), page-local state in hooks +under `apps/app/src/clients/`, the personal workspace in `authStore`, the +routes behind `RequireWorkspace`, unsaved changes guarded by `useLeaveGuard` +and `AppLayout`. No data cache library: each page reads what it shows. ## 1. Starting point diff --git a/docs/development/SUPABASE.md b/docs/development/SUPABASE.md index a0f8dc9f..6ccc5ff9 100644 --- a/docs/development/SUPABASE.md +++ b/docs/development/SUPABASE.md @@ -315,6 +315,11 @@ M2. An account whose workspace holds an animal can no longer be deleted either (D9a): in DEV, delete its relations, animals and clients first from a privileged SQL session, in that order. +The browser reaches these tables through `packages/supabase/src/{workspaces,clients,species,records}.ts` +since V1-1.5 (contract §11.7). The client screens run against DEV only once +the owner has applied M1 to M3 with §3.3; until then they are developed and +tested on the isolated stack, and no DEV acceptance is recorded. + ## 4. Writing a migration 1. `pnpm supabase migration new ` creates `supabase/migrations/_.sql`. diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md index 6c939362..d3d6bcef 100644 --- a/docs/development/TEST_STRATEGY.md +++ b/docs/development/TEST_STRATEGY.md @@ -34,6 +34,11 @@ shared budget under concurrency, D9a through GoTrue admin, read timings on 20 000 animals), run in four migration states; 14 deliberate faults of M3 caught (`V1-1_OWNERS_ANIMALS.md` §8.3). The axe exceptions match rule, selector, markup and route. +V1-1.5 (2026-10-26): supabase vitest 92 (access layer 33); sandbox suites 54 +(`clients-access.sandbox.ts` 8: the access layer through supabase-js against +real GoTrue and PostgREST); app vitest 508 (client screens 22, form schema 20, +workspace and account change 6); `e2e:shell` 42 (client journeys 36, FR/EN, +desktop and 375 px, axe). The shell suite keeps no HTML report. ## 1. Layers diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index 3624e908..e8c4001d 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -13,7 +13,10 @@ authorised V1-1.2. V1-1.2 and V1-1.3 were validated on 2026-10-25 and Animaux et relations », BDR-077), which authorised V1-1.4. Migrations M1 (§8.1), M2 (§8.2) and M3 (§8.3) are written and tested on the isolated stack (`pnpm db:sandbox`, SUPABASE.md §5.1); none is applied to Supabase DEV (owner -procedure: SUPABASE.md §3.3). Nothing of V1-1.5 and V1-1.6 exists. +procedure: SUPABASE.md §3.3). V1-1.4 was validated on 2026-10-26 (brief +« Validation V1-1.4 et autorisation V1-1.5 Interface Clients »), which +authorised the client screens of V1-1.5 (§11.7), built and tested on the +isolated stack. Nothing of V1-1.6 exists. Branch: `feature/v1-1-clients-animals`. Roadmap position: `IMPLEMENTATION_PLAN.md` §0; this step is a reduced plan Step 12 that also lays the permission frame of Step 10. The file name keeps "OWNERS" so the documents @@ -1261,6 +1264,42 @@ validated mockups unchanged). | The mockup's bar now | Bilans and Agenda lead nowhere until V1-3 and later (hidden or disabled tabs); Clients and Animaux stay in the drawer anyway; a fixed bottom bar competes with the save action that §11.4 keeps reachable with the keyboard open | | A bar adapted to V1-1 (Accueil, Clients, Animaux, Profil) | one tap to the V1-1 screens; departs from the validated mockup, so it needs a new validated design file first; the bar changes again when Bilans and Agenda arrive | +### 11.7 V1-1.5 as built (2026-10-26) + +Owner choices of 2026-10-26, asked before the screens: U1 « Afficher plus » +(keyset pages of 25, no numbered page), U2 one « Afficher les archivés » +toggle, the client page shows its animals read-only (no link, no « ajouter » +until the animal screens), the « Ajouter un premier animal » section of +`/app/clients/new` moves to V1-1.6 with the animal screens. + +| Part | As built | +|---|---| +| Access layer | `packages/supabase/src/workspaces.ts` (`fetchPersonalWorkspaceId`), `clients.ts` (search with one probe row for « Afficher plus », read by id with an explicit column list and no request for an id that is not a uuid, create with a request id, update sending every field, archive, client animals, archive preview), `species.ts` (labels), `records.ts`: the closed kinds of §9.4 plus `session_expired` (HTTP 401, PGRST30x) and `network` (no answer); every RPC answer checked by Zod. Proven by unit tests and by `tests/sandbox/clients-access.sandbox.ts`, the same functions through supabase-js against the sandbox's real GoTrue and PostgREST | +| Personal workspace | read by `state/authStore.ts` with the account: `loading`, `ready`, `inactive` (profile deactivated), `unconfirmed` (no confirmed email), `missing`, `error`; never created in the browser. A change of account drops profile, roles, avatar and workspace in the same update, and an answer that arrives for the previous account is ignored. `app/guards/RequireWorkspace.tsx` renders the client routes only when ready and remounts them per workspace | +| Routes | `/app/clients`, `/app/clients/new`, `/app/clients/:clientId`, `/app/clients/:clientId/edit` (`app/routes/app/clients/`); an unknown, foreign or malformed id shows the same « Client introuvable » inside the shell | +| List | search sent after 300 ms without typing (POST, the term never in a URL), the archived toggle, rows with kind, city, phone and `current_animal_count`, « Afficher plus », loading, empty, no-result, error and retry states, the row count announced | +| Form | `clients/validation.ts` on `field-limits.ts` (D-R7: code points, control ranges, email pattern, ISO country list); the phone entry rule of §11.3, shown converted when the field is left; « Personne » checked, the name label follows the kind, required and optional marked in the labels, the first error focused; one request id per creation intent, sent again on a retry; on `conflict` the stored values appear under the fields that differ, the typed ones stay, the next save applies them knowingly; submit guarded against double clicks; the save bar stays reachable at the bottom on a phone | +| Page | identity, kind and archived badges, phone as `tel:`, email as `mailto:`, address and country name, the animals read-only (current then former, role, dates when known, species name); archive through a confirmation listing the active animals for which the client is the only current owner (it refuses to close while the request runs), restore by one button, outcomes announced | +| Leave guard | `useLeaveGuard`: `beforeunload` while the form holds changes, and `AppLayout` asks before following any in-app link (sidebar, drawer, top bar, the form's own « Annuler »); the browser's back and forward buttons are not intercepted (declarative router, §11.3) | +| Navigation | « Clients » in the sidebar and the drawer after « Tableau de bord » (the validated mockup's order); no tab bar (D11 unchanged) | +| Focus | each client page focuses its heading when it opens, also when opened from the drawer (after the drawer closed and returned focus) | + +Deviations and limits: the contract's `beforeunload` plus Cancel guard is +extended to every in-app link; the search term and the archived toggle are not +kept when returning from a client page (no storage of terms); phones show in +E.164 as stored; the dashboard tiles (D12) are not built. The shell's top bar +already carried an `h1` with the page title on large screens before V1-1.5; +the client pages add their own `h1` in `main`, as the existing pages do. + +Tests: supabase vitest 92 (access layer 33), sandbox suites 54 (access layer +8); app vitest 508 (client screens 22, form schema 20, store 15); Chromium +`e2e:shell` 42 (client journeys 36: create, search, edit, archive, archived +filter, restore, pages, keyboard only, two accounts, concurrent edit, retry +after a lost answer, network failures, leave guard, change of language; FR +and EN, desktop and 375 px, axe on every state with no exception of RR-7 +inherited). Report check: the shell suite's HTML report kept the typed +passwords of its throwaway accounts; it was removed (`BROWSER_TESTS.md` §3). + --- ## 12. Tests and Definition of Done @@ -1446,8 +1485,8 @@ validates after V1-1.1 and after the first UI step; nothing merges into | V1-1.1 | Workspaces: M1 (with the correlation header cap), helpers, trigger, backfill, RLS, pgTAP `012`. Written and tested on an isolated stack (§8.1), validated 2026-10-25; not applied to DEV | | V1-1.2 | Clients data: M2, RPCs, searches, D15 guards (budget per workspace, its lock), N9 audit policy, field limits and parity test, sandbox suite. Written and tested on the isolated stack (§8.2), validated 2026-10-25; not applied to DEV | | V1-1.3 | UI foundations: Playwright Chromium and axe (D14), `Dialog` containment and restore (D13). Built (§11.6), validated 2026-10-26 | -| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof. Written and tested on the isolated stack (§8.3), awaiting the owner's checkpoint; not applied to DEV | -| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry | +| V1-1.4 | Animals and relations data: M3 with the species rows, RPCs, history rules, D9a proof. Written and tested on the isolated stack (§8.3), validated 2026-10-26; not applied to DEV | +| V1-1.5 | Clients UI: routes, forms, list and search, archive, navigation entry. Built and tested on the isolated stack (§11.7), awaiting the owner's checkpoint; the owner's check over the LAN needs M1 to M3 on DEV | | V1-1.6 | Animals and relations UI, navigation (D11), dashboard tiles (D12), documents, Definition of Done | Recommended first step: V1-1.1. It is SQL only, has no visible choice, and From e1c198094973a1d5a6415fb6baefd4d3548f7c00 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:08:25 +0100 Subject: [PATCH 35/60] fix(app): a re-read of the same account keeps its workspace on screen USER_UPDATED (or a retry) set the workspace back to loading, which unmounted the client routes and lost an open form's typed values. A ready workspace now stays until the answer; found by the V1-1.5 security audit. --- apps/app/src/state/authStore.ts | 9 ++++++--- apps/app/tests/unit/state.authStore.test.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/apps/app/src/state/authStore.ts b/apps/app/src/state/authStore.ts index 7669c1fe..99a155ab 100644 --- a/apps/app/src/state/authStore.ts +++ b/apps/app/src/state/authStore.ts @@ -116,10 +116,13 @@ async function loadWorkspace( 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' } }) - set({ workspace: { status: 'loading' } }) + // 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' } }) @@ -136,7 +139,7 @@ async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: G ]) setOwn({ profile, roles }) await Promise.all([ - loadWorkspace(client, user, profile, setOwn), + loadWorkspace(client, user, profile, setOwn, get), syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })), ]) } @@ -242,7 +245,7 @@ export const useAuthStore = create((set, get) => ({ refreshWorkspace: async () => { const user = requireUser(get().user) - await loadWorkspace(requireClient(), user, get().profile, setForUser(user, set, get)) + await loadWorkspace(requireClient(), user, get().profile, setForUser(user, set, get), get) }, refreshAvatar: async () => { diff --git a/apps/app/tests/unit/state.authStore.test.ts b/apps/app/tests/unit/state.authStore.test.ts index 54d47bda..7a9bec6e 100644 --- a/apps/app/tests/unit/state.authStore.test.ts +++ b/apps/app/tests/unit/state.authStore.test.ts @@ -298,6 +298,22 @@ describe('authStore', () => { }) }) + it('keeps a ready workspace on screen while the same account is read again', async () => { + fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] + stop = useAuthStore.getState().start() + fake.emit('SIGNED_IN', fakeSession()) + await flush() + await flush() + const seen: string[] = [] + const unsubscribe = useAuthStore.subscribe((s) => seen.push(s.workspace.status)) + fake.emit('USER_UPDATED', fakeSession()) + await flush() + await flush() + unsubscribe() + expect(seen).not.toContain('loading') + expect(useAuthStore.getState().workspace).toEqual({ status: 'ready', id: 'ws-1' }) + }) + it('forgets the workspace on sign-out', async () => { fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }] stop = useAuthStore.getState().start() From 567ad40c80fa334a9d212b7876135f4a44266676 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:11:15 +0100 Subject: [PATCH 36/60] =?UTF-8?q?fix(app):=20the=20=C2=AB=20Client=20intro?= =?UTF-8?q?uvable=20=C2=BB=20screen=20focuses=20its=20heading=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every client screen focuses its heading when it opens (contract §11.7); the not-found screen did not. Unit and Chromium tests now assert the focus. Found by the V1-1.5 verifier. --- apps/app/e2e/shell/clients.spec.ts | 2 +- apps/app/src/components/clients/ClientNotFound.tsx | 8 ++++---- apps/app/tests/unit/routes.clients.test.tsx | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/apps/app/e2e/shell/clients.spec.ts b/apps/app/e2e/shell/clients.spec.ts index 4096862d..f89feb25 100644 --- a/apps/app/e2e/shell/clients.spec.ts +++ b/apps/app/e2e/shell/clients.spec.ts @@ -369,7 +369,7 @@ for (const [locale, dict] of LANGUAGES) { level: 1, name: dict['clients.not_found.title'], }), - ).toBeVisible() + ).toBeFocused() await expect(page.getByText(secret)).toHaveCount(0) } await expectAccessible(page, 'the client not found screen') diff --git a/apps/app/src/components/clients/ClientNotFound.tsx b/apps/app/src/components/clients/ClientNotFound.tsx index d8138274..02a015ac 100644 --- a/apps/app/src/components/clients/ClientNotFound.tsx +++ b/apps/app/src/components/clients/ClientNotFound.tsx @@ -1,18 +1,18 @@ import ButtonLink from '@/components/ui/ButtonLink' import Card from '@/components/ui/Card' +import { usePageHeading } from '@/app/usePageHeading' import { useT } from '@/i18n/useT' /** The same screen for an unknown id and an id of another workspace (contract §11.1). */ export default function ClientNotFound() { const t = useT() + const heading = usePageHeading() return ( -

    +

    {t('clients.not_found.title')}

    -

    - {t('clients.not_found.body')} -

    +

    {t('clients.not_found.body')}

    {t('clients.not_found.back')} diff --git a/apps/app/tests/unit/routes.clients.test.tsx b/apps/app/tests/unit/routes.clients.test.tsx index cadc10ea..9e4c6d42 100644 --- a/apps/app/tests/unit/routes.clients.test.tsx +++ b/apps/app/tests/unit/routes.clients.test.tsx @@ -294,7 +294,7 @@ describe('client edit', () => { describe('client page', () => { it('shows the same « introuvable » for an unknown id and a malformed one', async () => { mount(`/app/clients/${ID}`) - expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument() + expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toHaveFocus() cleanup() mount('/app/clients/not-an-id') expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument() From d8e86a422925d3194bc7394257591bd0068f5dfd Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:22:34 +0100 Subject: [PATCH 37/60] docs(docs): V1-1.5 counts after the gate fixes, what the gates found --- docs/development/TEST_STRATEGY.md | 4 ++-- docs/development/V1-1_OWNERS_ANIMALS.md | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/development/TEST_STRATEGY.md b/docs/development/TEST_STRATEGY.md index d3d6bcef..a4558619 100644 --- a/docs/development/TEST_STRATEGY.md +++ b/docs/development/TEST_STRATEGY.md @@ -36,8 +36,8 @@ caught (`V1-1_OWNERS_ANIMALS.md` §8.3). The axe exceptions match rule, selector, markup and route. V1-1.5 (2026-10-26): supabase vitest 92 (access layer 33); sandbox suites 54 (`clients-access.sandbox.ts` 8: the access layer through supabase-js against -real GoTrue and PostgREST); app vitest 508 (client screens 22, form schema 20, -workspace and account change 6); `e2e:shell` 42 (client journeys 36, FR/EN, +real GoTrue and PostgREST); app vitest 509 (client screens 22, form schema 20, +workspace and account change 7); `e2e:shell` 42 (client journeys 36, FR/EN, desktop and 375 px, axe). The shell suite keeps no HTML report. ## 1. Layers diff --git a/docs/development/V1-1_OWNERS_ANIMALS.md b/docs/development/V1-1_OWNERS_ANIMALS.md index e8c4001d..5964b353 100644 --- a/docs/development/V1-1_OWNERS_ANIMALS.md +++ b/docs/development/V1-1_OWNERS_ANIMALS.md @@ -1292,13 +1292,17 @@ already carried an `h1` with the page title on large screens before V1-1.5; the client pages add their own `h1` in `main`, as the existing pages do. Tests: supabase vitest 92 (access layer 33), sandbox suites 54 (access layer -8); app vitest 508 (client screens 22, form schema 20, store 15); Chromium +8); app vitest 509 (client screens 22, form schema 20, store 16); Chromium `e2e:shell` 42 (client journeys 36: create, search, edit, archive, archived filter, restore, pages, keyboard only, two accounts, concurrent edit, retry after a lost answer, network failures, leave guard, change of language; FR and EN, desktop and 375 px, axe on every state with no exception of RR-7 inherited). Report check: the shell suite's HTML report kept the typed passwords of its throwaway accounts; it was removed (`BROWSER_TESTS.md` §3). +Gates also found: a re-read of the same account (`USER_UPDATED`) set the +workspace back to loading and unmounted an open form (fixed: a ready workspace +stays on screen until the answer); the « introuvable » screen did not focus its +heading (fixed). --- From 3c2b503fc9efd8806acd4fe060b69f59daa70206 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 02:31:53 +0100 Subject: [PATCH 38/60] chore(memory): BDR-078, LRN-085/086, EVAL-040, V1-1.5 journal, TODO, gate contract --- .claude/memory/decisions.md | 6 ++ .claude/memory/evals.md | 7 ++ .claude/memory/journal.md | 5 ++ .claude/memory/learnings.md | 10 +++ .claude/tasks/TODO.md | 13 +++- .../contracts/2026-10-26-v1-1-5-clients-ui.md | 75 +++++++++++++++++++ 6 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 .claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 23156a96..1c4e6055 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -570,3 +570,9 @@ Status: active. Contract §11.6, BROWSER_TESTS.md. 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). diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index b3ca4fc7..ededacbd 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -282,3 +282,10 @@ Method: 14 mutations of M3 (PGlite pgTAP; M9 swapped into the sandbox, restored, 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. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index f27bf008..f2e845de 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -419,3 +419,8 @@ R5.4: `draft/{labels,changelog,review_report,drawing,overlay,app_review,svg_comp - Owner validated V1-1.3, authorised V1-1.4. M3 `20261026100000_animals_relations.sql` (b54c8e5): species 8+other, animals, relations current/ended/voided, 7 write RPCs + 3 reads, search_clients count; pgTAP 014 (258), parity, sandbox suite 18; sandbox `up upgrade ` (2dc04bc). - 14 mutations, 2 gaps closed (533a1c4); 4 migration states green; axe exceptions scoped (ba3a51e), check:all statuses (d7845b7); docs + DEV procedure to M3, not run (bc6a7dd). BDR-077, LRN-083/084, EVAL-039. - Verifier CONFORME 11/11, security PASS, check:all green. STOP at checkpoint: no V1-1.5, no DEV, no merge. + +## 2026-10-26 (V1-1.5 client screens, branch feature/v1-1-clients-animals) +- Owner validated V1-1.4, authorised V1-1.5. Owner choices: U1 « Afficher plus », U2 archived toggle, animals read-only, first-animal section → V1-1.6. Built access layer (a0e0699), workspace in authStore (ff028ec), screens (b38e627), Chromium journeys (d33a8f6), docs (ae0bd3f, d8e86a4). +- Fixes from gates: shell HTML report kept passwords (db81928), re-read unmounted forms (e1c1980), not-found heading focus (567ad40). BDR-078, LRN-085/086, EVAL-040. +- Security PASS, verifier CONFORME 11/11 (3rd round), check:all green. STOP at checkpoint: no V1-1.6, DEV untouched, no merge. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index f1d19bfb..ff400828 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -599,3 +599,13 @@ Apply: any plpgsql RPC parsing text input; any pgTAP string_agg over same-transa 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. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index c08595e1..b611afd9 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -457,7 +457,18 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - 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 + - [ ] 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` diff --git a/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md b/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md new file mode 100644 index 00000000..ae19db1c --- /dev/null +++ b/.claude/tasks/contracts/2026-10-26-v1-1-5-clients-ui.md @@ -0,0 +1,75 @@ +# CONTRACT: V1-1.5 Clients UI, owner brief 2026-10-26 « Validation V1-1.4 et autorisation V1-1.5 Interface Clients » + +- branch `feature/v1-1-clients-animals`, base 6251051 (V1-1.4 validated); commits a0e0699 (access layer), ff028ec + (workspace state), b38e627 (client screens), d33a8f6 (Playwright journeys), db81928 (shell report fix), ae0bd3f (docs) +- diff under review: `git diff 6251051..HEAD -- packages apps docs CLAUDE.md` (HEAD includes e1c1980 workspace kept during a re-read, 567ad40 not-found heading focus, and the docs count update) +- functional contract `docs/development/V1-1_OWNERS_ANIMALS.md` §5.1, §7.1, §9.3, §9.4, §11 (§11.7 as built), §12.4, §12.5 +- owner choices recorded in TODO (V1-1.5) and contract §11.7: U1 « Afficher plus », U2 archived toggle, animals + read-only on the client page, « premier animal » section deferred to V1-1.6 +- isolated stack `pnpm db:sandbox` is UP. Allowed: `pnpm db:sandbox test`, `pnpm db:sandbox test-db`, + `pnpm db:sandbox types --check`, `pnpm e2e:shell`, `pnpm --filter @faunosteo/supabase test:run`, + `pnpm --filter @faunosteo/app exec vitest run`, typecheck and lint, read-only SQL through `pnpm db:sandbox sql`. + Not allowed: `pnpm check:all` and builds (a run is in progress), `db:sandbox up/down`, anything on the DEV stack + except `pnpm supabase migration list --local`. + +## Clauses + +C1. **Scope.** Client screens and their data access only: no animal screen, route or form, no `animals.ts` or +`relations.ts` access module, no migration, no change under `crates/` or `supabase/`, no mobile tab bar, no +dashboard tiles, no change to the validated mockups. Existing files changed only where the clients need it +(App routes, AppLayout guard, SidebarNav entry, Icon, i18n, authStore, lib/id, e2e support). + +C2. **Access layer.** `packages/supabase/src/{records,workspaces,clients,species}.ts`: only the authorised RPCs and +reads (search/list/preview through POST RPCs, read by id with an explicit column list, no `select=*`, no text +filter in a GET URL); pagination contract (25 default, ≤ 100, keyset, one probe row); generated types used for +argument names; failures folded into closed kinds keeping not_found, archived, conflict, request_conflict, +limit_reached, rate_limited, invalid_input, session_expired, network, unavailable; nothing distinguishes a foreign +id from an unknown one; no service key; the workspace id is a context the server re-checks, never an authorisation. + +C3. **Personal workspace and identity.** Read after sign-in, never created by the browser; states session absent +(RequireAuth), unconfirmed, inactive, loading, ready, missing, error each rendered; a change of account clears the +previous account's profile, roles, avatar and workspace at once, and late answers of the previous account are +dropped; the client routes remount per workspace, so no row of a previous session shows. + +C4. **List.** Search through the backend only (no client-side engine), debounced, ≤ 100 characters; 25 per page +with « Afficher plus »; deterministic order; archived toggle; status badges; access to the page; empty, loading, +network error with retry; reload after changes; no private value in URLs or logs. + +C5. **Form.** Person | organization, display name required, no first/last name, optional contacts, no default +country, no notes; bounds and patterns from `field-limits.ts` (D-R7), code points, control characters, Unicode; +phone entry rule of contract §11.3; FR/EN messages; submitting state; double-click guard; one create_request_id per +creation intent reused on retry, a new form a new id, request_conflict explicit; update with the expected revision, +no silent overwrite, conflict understandable with the saved values; archived refusal. + +C6. **Archive and restore.** Confirmation through the shared Dialog/ModalDialog (closing is not confirming, +refuses to close while pending, focus D13 kept), preview of sole-owned active animals, no deletion, no cascade to +animals, read-only archived page, restore through the RPC. + +C7. **Client page.** Contract fields; `tel:` and `mailto:`; animals read-only from `list_client_animals` (no link, +no add, no invented data); `current_animal_count` from the backend in the list; same « introuvable » for unknown, +foreign and malformed ids. + +C8. **Navigation, design, accessibility.** Clients entry in sidebar and drawer in the mockup's order, existing +navigation kept, no tab bar; existing components and tokens reused; labels, visible focus, errors announced next +to fields, first error focused, page heading focused on open; 375 px without horizontal overflow; FR/EN; the new +pages pass axe without any KNOWN exception applying to their own elements. + +C9. **Unsaved changes.** `beforeunload` while dirty; in-app links ask first (ModalDialog), staying keeps the +values; what the router cannot intercept (browser back/forward) documented, not claimed. + +C10. **Tests.** Unit tests (access layer call shapes and failure mapping; schema; store identity change; screens: +states, retry idempotence, new intent, conflict, archived, archive dialog pending, leave guard, double click); +the access layer against real PostgREST (`clients-access.sandbox.ts`); Chromium journeys on the sandbox +(`e2e/shell/clients.spec.ts`: create, search, edit, archive, filter, restore, pagination, keyboard, two accounts, +conflict, retry, errors, leave guard, language, desktop + 375, axe); request URLs free of fixture values; suites +green when run. + +C11. **Reports and docs.** No private data in test reports beyond fictitious fixtures (the shell HTML report that +kept typed passwords removed); contract §11.7, BROWSER_TESTS, TEST_STRATEGY, SUPABASE.md, FRONTEND_ARCHITECTURE, +design README, CLAUDE.md updated; commits pushed; no merge; main and release/0.2.0 untouched; DEV untouched. + +## CLARIFICATIONS + +- FLOOR ASSERT_DROP `apps/app/e2e/shell/shell.spec.ts` (2 → 0 assertion lines): the `signIn` helper, with its two + `expect` lines, moved verbatim to `apps/app/e2e/support/shell.ts` so both shell specs share it; both specs still + await it, no assertion is lost. Authorised. From e22357630f761bdb44fbcd426ecc24b3ef9a3900 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:11:23 +0100 Subject: [PATCH 39/60] feat(supabase): animals and relations access layer animals.ts: POST search with species filter and a probe row, read by id with explicit columns, create with the optional first client in one call, update, archive. relations.ts: an animal's relations in one select (voided left out), create, end, dates, void. Kinds duplicate_relation and already_ended added. --- packages/supabase/src/animals.ts | 235 +++++++ packages/supabase/src/clients.ts | 20 +- packages/supabase/src/index.ts | 29 + packages/supabase/src/records.ts | 13 + packages/supabase/src/relations.ts | 165 +++++ packages/supabase/tests/animals.test.ts | 592 ++++++++++++++++++ .../tests/sandbox/animals-access.sandbox.ts | 570 +++++++++++++++++ 7 files changed, 1612 insertions(+), 12 deletions(-) create mode 100644 packages/supabase/src/animals.ts create mode 100644 packages/supabase/src/relations.ts create mode 100644 packages/supabase/tests/animals.test.ts create mode 100644 packages/supabase/tests/sandbox/animals-access.sandbox.ts diff --git a/packages/supabase/src/animals.ts b/packages/supabase/src/animals.ts new file mode 100644 index 00000000..f6ea41c7 --- /dev/null +++ b/packages/supabase/src/animals.ts @@ -0,0 +1,235 @@ +import { z } from 'zod' +import type { FaunosteoClient } from './client' +import type { Database, Tables } from './database.types' +import { + RevisionSchema, + type AnimalRelationRole, + type NameCursor, +} from './clients' +import { + failRecord, + parseRecordAnswer, + UUID_PATTERN, + type RecordPage, +} from './records' + +/** + * Browser side of the animals of a workspace (contract §5.2, §8.3, §9.3): one + * read by id under RLS with an explicit column list, the POST search, the + * three write RPCs. `create_animal` takes the optional initial relation in the + * same transaction, so an animal and its first client are never half made. + * The database rules decide; every failure is a RecordFailure of a closed kind. + */ + +/** Columns the page reads; the derived keys and the request digest stay server-side. */ +export const ANIMAL_COLUMNS = + 'id, name, species_id, species_detail, sex, breed, birth_year, birth_date, revision, archived_at, created_at, updated_at' + +export type AnimalRecord = Pick< + Tables<'animals'>, + | 'id' + | 'name' + | 'species_id' + | 'species_detail' + | 'sex' + | 'breed' + | 'birth_year' + | 'birth_date' + | 'revision' + | 'archived_at' + | 'created_at' + | 'updated_at' +> + +/** The seven fields an animal is created or replaced with; an absent value is null, never ''. */ +export type AnimalFields = Pick< + AnimalRecord, + | 'name' + | 'species_id' + | 'species_detail' + | 'sex' + | 'breed' + | 'birth_year' + | 'birth_date' +> + +const AnimalListItemSchema = z.object({ + id: z.string().uuid(), + name: z.string(), + species_id: z.string(), + species_detail: z.string().nullable(), + sex: z.enum(['male', 'female', 'unknown']), + breed: z.string().nullable(), + birth_year: z.number().int().nullable(), + archived_at: z.string().nullable(), + name_key: z.string(), + /** The first three current owners in name order, archived clients flagged. */ + current_owners: z.array( + z.object({ + client_id: z.string().uuid(), + display_name: z.string(), + archived: z.boolean(), + }), + ), + current_owner_count: z.number().int(), +}) +export type AnimalListItem = z.infer + +export interface AnimalSearch { + workspaceId: string + /** Trimmed by the server; 0 to 100 characters. */ + query: string + /** A species id, or null for every species. */ + speciesId: string | null + archived: boolean + /** 1 to 99; one more row is asked to know whether a next page exists. */ + pageSize?: number + after?: NameCursor | null +} + +/** One page of `search_animals` (POST: the term stays out of the URL). */ +export async function searchAnimals( + client: FaunosteoClient, + search: AnimalSearch, +): Promise> { + const size = search.pageSize ?? 25 + const { data, error, status } = await client.rpc('search_animals', { + workspace_id: search.workspaceId, + query: search.query, + species_filter: search.speciesId ?? undefined, + archived: search.archived, + page_size: size + 1, + after_name_key: search.after?.nameKey, + after_id: search.after?.id, + }) + if (error) failRecord(error, status) + const found = parseRecordAnswer(z.array(AnimalListItemSchema), data) + const rows = found.slice(0, size) + const last = rows.at(-1) + return { + rows, + next: + found.length > size && last + ? { nameKey: last.name_key, id: last.id } + : null, + } +} + +/** The animal, or null for an unknown id and for an id of another workspace alike. */ +export async function fetchAnimalRecord( + client: FaunosteoClient, + animalId: string, +): Promise { + if (!UUID_PATTERN.test(animalId)) return null + const { data, error, status } = await client + .from('animals') + .select(ANIMAL_COLUMNS) + .eq('id', animalId) + .maybeSingle() + if (error) failRecord(error, status) + return data +} + +/** The client the animal is linked to at creation, with an explicit role. */ +export interface InitialRelation { + clientId: string + relationRole: AnimalRelationRole + /** YYYY-MM-DD when known, else null (never filled by default). */ + startedOn: string | null +} + +export interface CreateAnimalInput { + workspaceId: string + /** One per creation intent, sent again on a retry: the server answers the first animal. */ + requestId: string + fields: AnimalFields + relation: InitialRelation | null +} + +const CreatedAnimalSchema = z.object({ + id: z.string().uuid(), + revision: z.number().int(), + relation_id: z.string().uuid().nullable(), +}) + +/** Years and dates travel as text: the RPC parses them and answers invalid_input on a bad one. */ +const yearText = (year: number | null) => + year === null ? undefined : String(year) + +export async function createAnimalRecord( + client: FaunosteoClient, + input: CreateAnimalInput, +): Promise<{ id: string; revision: number; relationId: string | null }> { + const f = input.fields + const r = input.relation + const { data, error, status } = await client.rpc('create_animal', { + workspace_id: input.workspaceId, + create_request_id: input.requestId, + name: f.name, + species_id: f.species_id, + sex: f.sex, + species_detail: f.species_detail ?? undefined, + breed: f.breed ?? undefined, + birth_year: yearText(f.birth_year), + birth_date: f.birth_date ?? undefined, + client_id: r?.clientId, + relation_role: r?.relationRole, + started_on: r?.startedOn ?? undefined, + }) + if (error) failRecord(error, status) + const created = parseRecordAnswer(CreatedAnimalSchema, data) + return { + id: created.id, + revision: created.revision, + relationId: created.relation_id, + } +} + +type UpdateAnimalArgs = Database['public']['Functions']['update_animal']['Args'] + +export interface UpdateAnimalInput { + animalId: string + expectedRevision: number + fields: AnimalFields +} + +/** Replaces the seven fields at `expectedRevision`; a stale revision is `conflict`. */ +export async function updateAnimalRecord( + client: FaunosteoClient, + input: UpdateAnimalInput, +): Promise<{ revision: number }> { + const f = input.fields + // The update RPC has no defaults: every field is sent, null included (see + // updateClientRecord for why the generated type is widened this way). + const args = { + animal_id: input.animalId, + expected_revision: input.expectedRevision, + name: f.name, + species_id: f.species_id, + sex: f.sex, + species_detail: f.species_detail, + breed: f.breed, + birth_year: f.birth_year === null ? null : String(f.birth_year), + birth_date: f.birth_date, + } satisfies { [K in keyof UpdateAnimalArgs]: UpdateAnimalArgs[K] | null } + const { data, error, status } = await client.rpc( + 'update_animal', + args as UpdateAnimalArgs, + ) + if (error) failRecord(error, status) + return parseRecordAnswer(RevisionSchema, data) +} + +/** Archives or restores; the relations are kept either way (contract §7.1). */ +export async function setAnimalArchived( + client: FaunosteoClient, + animalId: string, + archived: boolean, +): Promise<{ revision: number }> { + const { data, error, status } = await client.rpc('set_animal_archived', { + animal_id: animalId, + archived, + }) + if (error) failRecord(error, status) + return parseRecordAnswer(RevisionSchema, data) +} diff --git a/packages/supabase/src/clients.ts b/packages/supabase/src/clients.ts index f4918280..5b312254 100644 --- a/packages/supabase/src/clients.ts +++ b/packages/supabase/src/clients.ts @@ -3,6 +3,7 @@ import type { FaunosteoClient } from './client' import type { Database, Enums, Tables } from './database.types' import { failRecord, + parseRecordAnswer, RecordFailure, UUID_PATTERN, type RecordPage, @@ -132,13 +133,8 @@ const CreatedSchema = z.object({ id: z.string().uuid(), revision: z.number().int(), }) -const RevisionSchema = z.object({ revision: z.number().int() }) - -function parsed(schema: z.ZodType, data: unknown): T { - const result = schema.safeParse(data) - if (!result.success) throw new RecordFailure('unavailable', result.error) - return result.data -} +/** The answer of every update, archive and relation write RPC. */ +export const RevisionSchema = z.object({ revision: z.number().int() }) export interface CreateClientInput { workspaceId: string @@ -166,7 +162,7 @@ export async function createClientRecord( country: f.country ?? undefined, }) if (error) failRecord(error, status) - return parsed(CreatedSchema, data) + return parseRecordAnswer(CreatedSchema, data) } type UpdateClientArgs = Database['public']['Functions']['update_client']['Args'] @@ -204,7 +200,7 @@ export async function updateClientRecord( args as UpdateClientArgs, ) if (error) failRecord(error, status) - return parsed(RevisionSchema, data) + return parseRecordAnswer(RevisionSchema, data) } export async function setClientArchived( @@ -217,7 +213,7 @@ export async function setClientArchived( archived, }) if (error) failRecord(error, status) - return parsed(RevisionSchema, data) + return parseRecordAnswer(RevisionSchema, data) } const ArchivePreviewSchema = z.object({ @@ -235,7 +231,7 @@ export async function fetchClientArchivePreview( client_id: clientId, }) if (error) failRecord(error, status) - return parsed(ArchivePreviewSchema, data) + return parseRecordAnswer(ArchivePreviewSchema, data) } const ClientAnimalSchema = z.object({ @@ -274,7 +270,7 @@ export async function listClientAnimals( after_id: options.after?.relationId, }) if (error) failRecord(error, status) - const rows = parsed(z.array(ClientAnimalSchema), data) + const rows = parseRecordAnswer(z.array(ClientAnimalSchema), data) const page = rows.slice(0, size) const last = page.at(-1) return { diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts index 332e3649..7c0cc634 100644 --- a/packages/supabase/src/index.ts +++ b/packages/supabase/src/index.ts @@ -93,6 +93,8 @@ export { RECORD_FAILURE_KINDS, RecordFailure, classifyRecordError, + parseRecordAnswer, + UUID_PATTERN, type RecordFailureKind, type RecordPage, } from './records' @@ -121,6 +123,33 @@ export { type RelationCursor, type UpdateClientInput, } from './clients' +export { + ANIMAL_COLUMNS, + createAnimalRecord, + fetchAnimalRecord, + searchAnimals, + setAnimalArchived, + updateAnimalRecord, + type AnimalFields, + type AnimalListItem, + type AnimalRecord, + type AnimalSearch, + type CreateAnimalInput, + type InitialRelation, + type UpdateAnimalInput, +} from './animals' +export { + ANIMAL_RELATION_COLUMNS, + createAnimalClientRelation, + endAnimalClientRelation, + fetchAnimalRelations, + updateAnimalClientRelation, + voidAnimalClientRelation, + type AnimalRelationItem, + type CreateRelationInput, + type EndRelationInput, + type UpdateRelationDatesInput, +} from './relations' export { ANIMAL_FIELD_LIMITS, BIRTH_YEAR_MIN, diff --git a/packages/supabase/src/records.ts b/packages/supabase/src/records.ts index 1f85f2f8..f8f34b58 100644 --- a/packages/supabase/src/records.ts +++ b/packages/supabase/src/records.ts @@ -1,3 +1,5 @@ +import type { z } from 'zod' + /** * Closed failure kinds of the V1-1 record reads and RPCs (clients, animals, * relations): contract docs/development/V1-1_OWNERS_ANIMALS.md §9.4. The @@ -14,6 +16,8 @@ export const RECORD_FAILURE_KINDS = [ 'limit_reached', 'rate_limited', 'invalid_input', + 'duplicate_relation', + 'already_ended', 'session_expired', 'network', 'unavailable', @@ -37,6 +41,8 @@ const RPC_MESSAGE_KINDS: ReadonlySet = new Set([ 'limit_reached', 'rate_limited', 'invalid_input', + 'duplicate_relation', + 'already_ended', ]) interface PostgrestLikeError { @@ -70,6 +76,13 @@ export function failRecord(error: unknown, status?: number): never { throw new RecordFailure(classifyRecordError(error, status), error) } +/** The RPC answer checked against its contract; a different shape is `unavailable`. */ +export function parseRecordAnswer(schema: z.ZodType, data: unknown): T { + const result = schema.safeParse(data) + if (!result.success) throw new RecordFailure('unavailable', result.error) + return result.data +} + /** Ids are uuids: anything else is answered as unknown without a request. */ export const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i diff --git a/packages/supabase/src/relations.ts b/packages/supabase/src/relations.ts new file mode 100644 index 00000000..8b956305 --- /dev/null +++ b/packages/supabase/src/relations.ts @@ -0,0 +1,165 @@ +import { z } from 'zod' +import type { FaunosteoClient } from './client' +import type { Database } from './database.types' +import { RevisionSchema } from './clients' +import { failRecord, parseRecordAnswer, UUID_PATTERN } from './records' + +/** + * Browser side of the relations between an animal and its clients (contract + * §5.3, §8.3, §9.3). The animal page reads them with one select by animal id + * (at most 200 by the cap), the client embedded through the composite foreign + * key; voided relations are left out, as every V1-1 screen leaves them out. + * Writes go through the four relation RPCs only. + */ + +const RELATION_ROLES = ['owner', 'keeper', 'contact'] as const + +/** + * `ended_at` tells a current relation from a former one; it is a technical + * time, never shown as the end date (`ended_on` is). + */ +export const ANIMAL_RELATION_COLUMNS = + 'id, relation_role, started_on, ended_on, ended_at, revision, client:clients!animal_client_relations_client_fk(id, kind, display_name, phone, email, archived_at)' + +const AnimalRelationSchema = z.object({ + id: z.string().uuid(), + relation_role: z.enum(RELATION_ROLES), + started_on: z.string().nullable(), + ended_on: z.string().nullable(), + ended_at: z.string().nullable(), + revision: z.number().int(), + client: z.object({ + id: z.string().uuid(), + kind: z.enum(['person', 'organization']), + display_name: z.string(), + phone: z.string().nullable(), + email: z.string().nullable(), + archived_at: z.string().nullable(), + }), +}) +export type AnimalRelationItem = z.infer + +/** The cap of relations per animal (contract §10), ended and voided included. */ +const RELATIONS_PER_ANIMAL = 200 + +/** The animal's relations that existed (voided ones left out), in creation order. */ +export async function fetchAnimalRelations( + client: FaunosteoClient, + animalId: string, +): Promise { + if (!UUID_PATTERN.test(animalId)) return [] + const { data, error, status } = await client + .from('animal_client_relations') + .select(ANIMAL_RELATION_COLUMNS) + .eq('animal_id', animalId) + .is('voided_at', null) + .order('created_at') + .order('id') + .limit(RELATIONS_PER_ANIMAL) + if (error) failRecord(error, status) + return parseRecordAnswer(z.array(AnimalRelationSchema), data) +} + +export interface CreateRelationInput { + animalId: string + clientId: string + /** One per creation intent, sent again on a retry: the server answers the first relation. */ + requestId: string + relationRole: (typeof RELATION_ROLES)[number] + /** YYYY-MM-DD when known, else null (never filled by default). */ + startedOn: string | null +} + +const CreatedSchema = z.object({ + id: z.string().uuid(), + revision: z.number().int(), +}) + +/** A current relation between an active animal and an active client of one workspace. */ +export async function createAnimalClientRelation( + client: FaunosteoClient, + input: CreateRelationInput, +): Promise<{ id: string; revision: number }> { + const { data, error, status } = await client.rpc( + 'create_animal_client_relation', + { + animal_id: input.animalId, + client_id: input.clientId, + create_request_id: input.requestId, + relation_role: input.relationRole, + started_on: input.startedOn ?? undefined, + }, + ) + if (error) failRecord(error, status) + return parseRecordAnswer(CreatedSchema, data) +} + +export interface EndRelationInput { + relationId: string + expectedRevision: number + /** The real end date when known; null records the end without one. */ + endedOn: string | null +} + +/** Ends a current relation: it stays as a former one, with its dates. */ +export async function endAnimalClientRelation( + client: FaunosteoClient, + input: EndRelationInput, +): Promise<{ revision: number }> { + const { data, error, status } = await client.rpc( + 'end_animal_client_relation', + { + relation_id: input.relationId, + expected_revision: input.expectedRevision, + ended_on: input.endedOn ?? undefined, + }, + ) + if (error) failRecord(error, status) + return parseRecordAnswer(RevisionSchema, data) +} + +type UpdateRelationArgs = + Database['public']['Functions']['update_animal_client_relation']['Args'] + +export interface UpdateRelationDatesInput { + relationId: string + expectedRevision: number + startedOn: string | null + /** Only on an ended relation; the server refuses one on a current relation. */ + endedOn: string | null +} + +/** Corrects the dates; both are sent, an empty one is null (the RPC has no defaults). */ +export async function updateAnimalClientRelation( + client: FaunosteoClient, + input: UpdateRelationDatesInput, +): Promise<{ revision: number }> { + const args = { + relation_id: input.relationId, + expected_revision: input.expectedRevision, + started_on: input.startedOn, + ended_on: input.endedOn, + } satisfies { [K in keyof UpdateRelationArgs]: UpdateRelationArgs[K] | null } + const { data, error, status } = await client.rpc( + 'update_animal_client_relation', + args as UpdateRelationArgs, + ) + if (error) failRecord(error, status) + return parseRecordAnswer(RevisionSchema, data) +} + +/** Voids a relation entered by mistake (N4): kept, frozen and shown nowhere; never a deletion. */ +export async function voidAnimalClientRelation( + client: FaunosteoClient, + input: { relationId: string; expectedRevision: number }, +): Promise<{ revision: number }> { + const { data, error, status } = await client.rpc( + 'void_animal_client_relation', + { + relation_id: input.relationId, + expected_revision: input.expectedRevision, + }, + ) + if (error) failRecord(error, status) + return parseRecordAnswer(RevisionSchema, data) +} diff --git a/packages/supabase/tests/animals.test.ts b/packages/supabase/tests/animals.test.ts new file mode 100644 index 00000000..53121f03 --- /dev/null +++ b/packages/supabase/tests/animals.test.ts @@ -0,0 +1,592 @@ +import { + ANIMAL_COLUMNS, + ANIMAL_RELATION_COLUMNS, + RECORD_FAILURE_KINDS, + RecordFailure, + classifyRecordError, + createAnimalClientRelation, + createAnimalRecord, + endAnimalClientRelation, + fetchAnimalRecord, + fetchAnimalRelations, + parseRecordAnswer, + searchAnimals, + setAnimalArchived, + updateAnimalClientRelation, + updateAnimalRecord, + voidAnimalClientRelation, + type AnimalFields, + type FaunosteoClient, +} from '../src' +import { z } from 'zod' + +/** + * Call shapes and closed failure kinds of the animals and relations access + * layer. The argument names are checked by the compiler against the generated + * types; the RPC bodies by supabase/tests/014_animals_relations.sql; the same + * functions run against real PostgREST in tests/sandbox/animals-access.sandbox.ts. + */ +type Answer = { data?: unknown; error?: unknown; status?: number } + +function stubClient(answers: { rpc?: Answer; select?: Answer } = {}) { + const rpcCalls: Array<[string, Record]> = [] + const query: Record = {} + const orders: string[] = [] + const settle = (a: Answer = {}) => ({ + data: a.data ?? null, + error: a.error ?? null, + status: a.status ?? (a.error ? 400 : 200), + }) + const chain = { + select: (cols: string) => ((query.select = cols), chain), + eq: (col: string, value: unknown) => ((query[`eq:${col}`] = value), chain), + is: (col: string, value: unknown) => ((query[`is:${col}`] = value), chain), + order: (col: string) => (orders.push(col), chain), + limit: (n: number) => ((query.limit = n), chain), + maybeSingle: async () => settle(answers.select), + then: (resolve: (v: unknown) => void) => resolve(settle(answers.select)), + } + const client = { + from: (table: string) => ((query.table = table), chain), + rpc: async (name: string, args: Record) => { + rpcCalls.push([name, args]) + return settle(answers.rpc) + }, + } as unknown as FaunosteoClient + return { client, rpcCalls, query, orders } +} + +const WS = '11111111-1111-4111-8111-111111111111' +const ID = '22222222-2222-4222-8222-222222222222' +const REQUEST = '33333333-3333-4333-8333-333333333333' +const CLIENT = '44444444-4444-4444-8444-444444444444' +const RELATION = '55555555-5555-4555-8555-555555555555' + +const fields: AnimalFields = { + name: 'Éclair', + species_id: 'equine', + species_detail: null, + sex: 'female', + breed: null, + birth_year: 2015, + birth_date: null, +} + +function listRow(i: number) { + return { + id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`, + name: `Animal ${i}`, + species_id: 'equine', + species_detail: null, + sex: 'unknown', + breed: null, + birth_year: null, + archived_at: null, + name_key: `animal ${String(i).padStart(3, '0')}`, + current_owners: [], + current_owner_count: 0, + } +} + +function relationRow(patch: Record = {}) { + return { + id: RELATION, + relation_role: 'owner', + started_on: null, + ended_on: null, + ended_at: null, + revision: 1, + client: { + id: CLIENT, + kind: 'person', + display_name: 'Marie Dupont', + phone: null, + email: null, + archived_at: null, + }, + ...patch, + } +} + +async function kindOf(promise: Promise) { + try { + await promise + return 'no failure' + } catch (error) { + return error instanceof RecordFailure ? error.kind : 'not a RecordFailure' + } +} + +describe('relation failure kinds', () => { + it('are closed kinds of the record failures', () => { + expect(RECORD_FAILURE_KINDS).toContain('duplicate_relation') + expect(RECORD_FAILURE_KINDS).toContain('already_ended') + }) + + it.each(['duplicate_relation', 'already_ended'])( + 'P0001 %s is that kind', + (message) => { + expect(classifyRecordError({ code: 'P0001', message }, 400)).toBe(message) + }, + ) + + it('parseRecordAnswer returns the parsed value or throws unavailable', async () => { + const schema = z.object({ revision: z.number().int() }) + expect(parseRecordAnswer(schema, { revision: 2 })).toEqual({ revision: 2 }) + expect( + await kindOf(Promise.resolve().then(() => parseRecordAnswer(schema, {}))), + ).toBe('unavailable') + }) +}) + +describe('searchAnimals', () => { + it('posts the term, every species when null, one row more than the page', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: [listRow(1)] } }) + const page = await searchAnimals(client, { + workspaceId: WS, + query: 'ecl', + speciesId: null, + archived: false, + }) + expect(rpcCalls).toEqual([ + [ + 'search_animals', + { + workspace_id: WS, + query: 'ecl', + species_filter: undefined, + archived: false, + page_size: 26, + after_name_key: undefined, + after_id: undefined, + }, + ], + ]) + expect(page).toEqual({ rows: [listRow(1)], next: null }) + }) + + it('sends the species filter and the cursor; the probe row becomes next', async () => { + const rows = Array.from({ length: 11 }, (_, i) => listRow(i + 1)) + const { client, rpcCalls } = stubClient({ rpc: { data: rows } }) + const page = await searchAnimals(client, { + workspaceId: WS, + query: '', + speciesId: 'canine', + archived: true, + pageSize: 10, + after: { nameKey: 'animal 000', id: ID }, + }) + expect(rpcCalls[0][1]).toMatchObject({ + species_filter: 'canine', + archived: true, + page_size: 11, + after_name_key: 'animal 000', + after_id: ID, + }) + expect(page.rows).toHaveLength(10) + expect(page.next).toEqual({ nameKey: rows[9].name_key, id: rows[9].id }) + }) + + it('refuses an answer of another shape as unavailable', async () => { + const { client } = stubClient({ rpc: { data: [{ id: ID }] } }) + expect( + await kindOf( + searchAnimals(client, { + workspaceId: WS, + query: '', + speciesId: null, + archived: false, + }), + ), + ).toBe('unavailable') + }) +}) + +describe('fetchAnimalRecord', () => { + it('reads one animal by id with the explicit column list', async () => { + const { client, query } = stubClient({ select: { data: { id: ID } } }) + expect(await fetchAnimalRecord(client, ID)).toEqual({ id: ID }) + expect(query).toEqual({ + table: 'animals', + select: ANIMAL_COLUMNS, + 'eq:id': ID, + }) + expect(ANIMAL_COLUMNS).not.toContain('*') + expect(ANIMAL_COLUMNS).not.toContain('create_request') + expect(ANIMAL_COLUMNS).not.toContain('workspace_id') + }) + + it('answers null for an id that is not a uuid, without a request', async () => { + const { client, query } = stubClient() + expect(await fetchAnimalRecord(client, 'not-a-uuid')).toBeNull() + expect(query.table).toBeUndefined() + }) + + it('maps a lost answer to network and an expired session to session_expired', async () => { + const lost = stubClient({ + select: { error: { code: '', message: 'FetchError' }, status: 0 }, + }) + expect(await kindOf(fetchAnimalRecord(lost.client, ID))).toBe('network') + const expired = stubClient({ + select: { + error: { code: 'PGRST301', message: 'JWT expired' }, + status: 401, + }, + }) + expect(await kindOf(fetchAnimalRecord(expired.client, ID))).toBe( + 'session_expired', + ) + }) +}) + +describe('animal writes', () => { + it('creates without relation: optionals left to their defaults, year as text', async () => { + const { client, rpcCalls } = stubClient({ + rpc: { data: { id: ID, revision: 1, relation_id: null } }, + }) + expect( + await createAnimalRecord(client, { + workspaceId: WS, + requestId: REQUEST, + fields, + relation: null, + }), + ).toEqual({ id: ID, revision: 1, relationId: null }) + expect(rpcCalls[0]).toEqual([ + 'create_animal', + { + workspace_id: WS, + create_request_id: REQUEST, + name: 'Éclair', + species_id: 'equine', + sex: 'female', + species_detail: undefined, + breed: undefined, + birth_year: '2015', + birth_date: undefined, + client_id: undefined, + relation_role: undefined, + started_on: undefined, + }, + ]) + }) + + it('creates with an initial relation in the same call', async () => { + const { client, rpcCalls } = stubClient({ + rpc: { data: { id: ID, revision: 1, relation_id: RELATION } }, + }) + const created = await createAnimalRecord(client, { + workspaceId: WS, + requestId: REQUEST, + fields: { + ...fields, + species_id: 'other', + species_detail: 'Furet', + birth_year: 2015, + birth_date: '2015-04-12', + }, + relation: { + clientId: CLIENT, + relationRole: 'keeper', + startedOn: '2020-01-02', + }, + }) + expect(created.relationId).toBe(RELATION) + expect(rpcCalls[0][1]).toMatchObject({ + species_id: 'other', + species_detail: 'Furet', + birth_year: '2015', + birth_date: '2015-04-12', + client_id: CLIENT, + relation_role: 'keeper', + started_on: '2020-01-02', + }) + const noDate = stubClient({ + rpc: { data: { id: ID, revision: 1, relation_id: RELATION } }, + }) + await createAnimalRecord(noDate.client, { + workspaceId: WS, + requestId: REQUEST, + fields: { ...fields, birth_year: null }, + relation: { clientId: CLIENT, relationRole: 'owner', startedOn: null }, + }) + expect(noDate.rpcCalls[0][1]).toMatchObject({ + birth_year: undefined, + started_on: undefined, + client_id: CLIENT, + }) + }) + + it('updates with every field, null included, at the expected revision', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } }) + expect( + await updateAnimalRecord(client, { + animalId: ID, + expectedRevision: 2, + fields: { ...fields, birth_year: null }, + }), + ).toEqual({ revision: 3 }) + expect(rpcCalls[0]).toEqual([ + 'update_animal', + { + animal_id: ID, + expected_revision: 2, + name: 'Éclair', + species_id: 'equine', + sex: 'female', + species_detail: null, + breed: null, + birth_year: null, + birth_date: null, + }, + ]) + const withYear = stubClient({ rpc: { data: { revision: 3 } } }) + await updateAnimalRecord(withYear.client, { + animalId: ID, + expectedRevision: 2, + fields, + }) + expect(withYear.rpcCalls[0][1].birth_year).toBe('2015') + }) + + it('archives and restores through set_animal_archived', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) + expect(await setAnimalArchived(client, ID, false)).toEqual({ revision: 2 }) + expect(rpcCalls[0]).toEqual([ + 'set_animal_archived', + { animal_id: ID, archived: false }, + ]) + }) + + it.each([ + 'conflict', + 'request_conflict', + 'archived', + 'rate_limited', + 'limit_reached', + 'invalid_input', + ])('a %s refusal reaches the caller as that kind', async (message) => { + const { client } = stubClient({ + rpc: { error: { code: 'P0001', message } }, + }) + expect( + await kindOf( + updateAnimalRecord(client, { + animalId: ID, + expectedRevision: 1, + fields, + }), + ), + ).toBe(message) + }) + + it('an unknown or foreign id is not_found; a created answer of another shape is unavailable', async () => { + const { client } = stubClient({ + rpc: { error: { code: '42501', message: 'not_found' }, status: 403 }, + }) + expect(await kindOf(setAnimalArchived(client, ID, true))).toBe('not_found') + const odd = stubClient({ rpc: { data: { id: ID, revision: 1 } } }) + expect( + await kindOf( + createAnimalRecord(odd.client, { + workspaceId: WS, + requestId: REQUEST, + fields, + relation: null, + }), + ), + ).toBe('unavailable') + }) +}) + +describe('fetchAnimalRelations', () => { + it('reads by animal id, voided left out, explicit columns, bounded and ordered', async () => { + const { client, query, orders } = stubClient({ + select: { data: [relationRow()] }, + }) + expect(await fetchAnimalRelations(client, ID)).toEqual([relationRow()]) + expect(query).toEqual({ + table: 'animal_client_relations', + select: ANIMAL_RELATION_COLUMNS, + 'eq:animal_id': ID, + 'is:voided_at': null, + limit: 200, + }) + expect(orders).toEqual(['created_at', 'id']) + expect(ANIMAL_RELATION_COLUMNS).not.toContain('*') + expect(ANIMAL_RELATION_COLUMNS).not.toContain('create_request') + }) + + it('answers [] for an id that is not a uuid, without a request', async () => { + const { client, query } = stubClient() + expect(await fetchAnimalRelations(client, 'nope')).toEqual([]) + expect(query.table).toBeUndefined() + }) + + it('refuses a row without its client as unavailable, maps failures', async () => { + const { client } = stubClient({ + select: { data: [relationRow({ client: null })] }, + }) + expect(await kindOf(fetchAnimalRelations(client, ID))).toBe('unavailable') + const lost = stubClient({ + select: { error: { message: 'TypeError: Failed to fetch' }, status: 0 }, + }) + expect(await kindOf(fetchAnimalRelations(lost.client, ID))).toBe('network') + }) +}) + +describe('relation writes', () => { + it('creates with the request id; a missing start date is left to its default', async () => { + const { client, rpcCalls } = stubClient({ + rpc: { data: { id: RELATION, revision: 1 } }, + }) + expect( + await createAnimalClientRelation(client, { + animalId: ID, + clientId: CLIENT, + requestId: REQUEST, + relationRole: 'contact', + startedOn: null, + }), + ).toEqual({ id: RELATION, revision: 1 }) + expect(rpcCalls[0]).toEqual([ + 'create_animal_client_relation', + { + animal_id: ID, + client_id: CLIENT, + create_request_id: REQUEST, + relation_role: 'contact', + started_on: undefined, + }, + ]) + }) + + it('ends with or without a date', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) + await endAnimalClientRelation(client, { + relationId: RELATION, + expectedRevision: 1, + endedOn: null, + }) + await endAnimalClientRelation(client, { + relationId: RELATION, + expectedRevision: 1, + endedOn: '2024-05-01', + }) + expect(rpcCalls).toEqual([ + [ + 'end_animal_client_relation', + { relation_id: RELATION, expected_revision: 1, ended_on: undefined }, + ], + [ + 'end_animal_client_relation', + { relation_id: RELATION, expected_revision: 1, ended_on: '2024-05-01' }, + ], + ]) + }) + + it('corrects the dates sending both, null included', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 3 } } }) + expect( + await updateAnimalClientRelation(client, { + relationId: RELATION, + expectedRevision: 2, + startedOn: '2020-01-01', + endedOn: null, + }), + ).toEqual({ revision: 3 }) + expect(rpcCalls[0]).toEqual([ + 'update_animal_client_relation', + { + relation_id: RELATION, + expected_revision: 2, + started_on: '2020-01-01', + ended_on: null, + }, + ]) + }) + + it('voids at the expected revision', async () => { + const { client, rpcCalls } = stubClient({ rpc: { data: { revision: 2 } } }) + expect( + await voidAnimalClientRelation(client, { + relationId: RELATION, + expectedRevision: 1, + }), + ).toEqual({ revision: 2 }) + expect(rpcCalls[0]).toEqual([ + 'void_animal_client_relation', + { relation_id: RELATION, expected_revision: 1 }, + ]) + }) + + it.each([ + ['duplicate_relation', 'P0001', 400], + ['already_ended', 'P0001', 400], + ['conflict', 'P0001', 400], + ['archived', 'P0001', 400], + ['limit_reached', 'P0001', 400], + ['not_found', '42501', 403], + ])( + 'a %s refusal reaches the caller as that kind', + async (message, code, status) => { + const { client } = stubClient({ + rpc: { error: { code, message }, status }, + }) + expect( + await kindOf( + createAnimalClientRelation(client, { + animalId: ID, + clientId: CLIENT, + requestId: REQUEST, + relationRole: 'owner', + startedOn: null, + }), + ), + ).toBe(message) + expect( + await kindOf( + endAnimalClientRelation(client, { + relationId: RELATION, + expectedRevision: 1, + endedOn: null, + }), + ), + ).toBe(message) + }, + ) + + it('an expired session, a lost answer and an odd answer are closed kinds', async () => { + const expired = stubClient({ + rpc: { error: { code: 'PGRST301', message: 'JWT expired' }, status: 401 }, + }) + expect( + await kindOf( + voidAnimalClientRelation(expired.client, { + relationId: RELATION, + expectedRevision: 1, + }), + ), + ).toBe('session_expired') + const lost = stubClient({ + rpc: { error: { message: 'TypeError: Failed to fetch' }, status: 0 }, + }) + expect( + await kindOf( + voidAnimalClientRelation(lost.client, { + relationId: RELATION, + expectedRevision: 1, + }), + ), + ).toBe('network') + const odd = stubClient({ rpc: { data: { revision: 'x' } } }) + expect( + await kindOf( + voidAnimalClientRelation(odd.client, { + relationId: RELATION, + expectedRevision: 1, + }), + ), + ).toBe('unavailable') + }) +}) diff --git a/packages/supabase/tests/sandbox/animals-access.sandbox.ts b/packages/supabase/tests/sandbox/animals-access.sandbox.ts new file mode 100644 index 00000000..611bd108 --- /dev/null +++ b/packages/supabase/tests/sandbox/animals-access.sandbox.ts @@ -0,0 +1,570 @@ +/** + * The V1-1.6 access layer (src/animals.ts, src/relations.ts) against the real + * GoTrue and PostgREST of `pnpm db:sandbox`, through supabase-js as the + * browser uses it: the generated argument names, the explicit columns, the + * embedded client of a relation, the keyset pages and every closed failure + * kind come from the real server, not from a stub. Fictitious data only. + */ +import { randomUUID } from 'node:crypto' +import { createClient } from '@supabase/supabase-js' +import { + RecordFailure, + createAnimalClientRelation, + createAnimalRecord, + createClientRecord, + endAnimalClientRelation, + fetchAnimalRecord, + fetchAnimalRelations, + fetchPersonalWorkspaceId, + listClientAnimals, + searchAnimals, + setAnimalArchived, + updateAnimalClientRelation, + updateAnimalRecord, + voidAnimalClientRelation, + type AnimalFields, + type Database, + type FaunosteoClient, +} from '../../src' +import { PASSWORD, confirmedAccount, stack, type Account } from './stack' + +const BASE = 'http://sandbox.faunosteo.invalid' + +function browserClient(): FaunosteoClient { + const mapped: typeof fetch = (input, init) => { + const url = String(input instanceof Request ? input.url : input) + .replace(`${BASE}/auth/v1`, stack.authUrl) + .replace(`${BASE}/rest/v1`, stack.restUrl) + return fetch(url, init) + } + return createClient(BASE, stack.anonKey, { + auth: { persistSession: false, autoRefreshToken: false }, + global: { fetch: mapped }, + }) +} + +async function signedIn(account: Account): Promise { + const client = browserClient() + const { error } = await client.auth.signInWithPassword({ + email: account.email, + password: PASSWORD, + }) + if (error) throw error + return client +} + +async function kindOf(promise: Promise) { + try { + await promise + return 'no failure' + } catch (error) { + return error instanceof RecordFailure ? error.kind : String(error) + } +} + +const animal = ( + name: string, + patch: Partial = {}, +): AnimalFields => ({ + name, + species_id: 'equine', + species_detail: null, + sex: 'unknown', + breed: null, + birth_year: null, + birth_date: null, + ...patch, +}) + +describe('animals and relations access layer on the sandbox', () => { + let a: Account + let b: Account + let asA: FaunosteoClient + let asB: FaunosteoClient + let wA: string + let wB: string + + async function clientOfA(name: string): Promise { + const { id } = await createClientRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields: { + kind: 'person', + display_name: name, + email: null, + phone: '+33612345678', + address_line1: null, + address_line2: null, + postal_code: null, + city: null, + country: null, + }, + }) + return id + } + + async function animalOfA(name: string): Promise { + return ( + await createAnimalRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields: animal(name), + relation: null, + }) + ).id + } + + beforeAll(async () => { + a = await confirmedAccount('animals-a') + b = await confirmedAccount('animals-b') + asA = await signedIn(a) + asB = await signedIn(b) + wA = (await fetchPersonalWorkspaceId(asA, a.id)) as string + wB = (await fetchPersonalWorkspaceId(asB, b.id)) as string + }) + + it('creates without a relation and reads the explicit columns', async () => { + const fields = animal('Tornado Fictif', { + sex: 'male', + breed: 'Selle français', + birth_year: 2015, + birth_date: '2015-04-12', + }) + const created = await createAnimalRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields, + relation: null, + }) + expect(created).toMatchObject({ revision: 1, relationId: null }) + const record = await fetchAnimalRecord(asA, created.id) + expect(Object.keys(record ?? {}).sort()).toEqual( + [ + 'archived_at', + 'birth_date', + 'birth_year', + 'breed', + 'created_at', + 'id', + 'name', + 'revision', + 'sex', + 'species_detail', + 'species_id', + 'updated_at', + ].sort(), + ) + expect(record).toMatchObject({ ...fields, revision: 1, archived_at: null }) + expect(await fetchAnimalRelations(asA, created.id)).toEqual([]) + }) + + it('creates with an initial relation, replays idempotently, refuses a divergent replay', async () => { + const clientId = await clientOfA('Marie Initiale') + const requestId = randomUUID() + const input = { + workspaceId: wA, + requestId, + fields: animal('Furet Fictif', { + species_id: 'other', + species_detail: 'Furet', + }), + relation: { + clientId, + relationRole: 'owner' as const, + startedOn: '2020-01-02', + }, + } + const first = await createAnimalRecord(asA, input) + expect(first.relationId).not.toBeNull() + expect(await createAnimalRecord(asA, input)).toEqual(first) + expect( + await kindOf( + createAnimalRecord(asA, { + ...input, + fields: animal('Autre Nom', { + species_id: 'other', + species_detail: 'Furet', + }), + }), + ), + ).toBe('request_conflict') + const relations = await fetchAnimalRelations(asA, first.id) + expect(relations).toEqual([ + { + id: first.relationId, + relation_role: 'owner', + started_on: '2020-01-02', + ended_on: null, + ended_at: null, + revision: 1, + client: { + id: clientId, + kind: 'person', + display_name: 'Marie Initiale', + phone: '+33612345678', + email: null, + archived_at: null, + }, + }, + ]) + const found = await searchAnimals(asA, { + workspaceId: wA, + query: 'furet fictif', + speciesId: null, + archived: false, + }) + expect(found.rows).toHaveLength(1) + expect(found.rows[0]).toMatchObject({ + id: first.id, + current_owner_count: 1, + current_owners: [ + { + client_id: clientId, + display_name: 'Marie Initiale', + archived: false, + }, + ], + }) + }) + + it('searches by term, species filter and archived toggle, in pages', async () => { + const c = await confirmedAccount('animals-page') + const asC = await signedIn(c) + const wC = (await fetchPersonalWorkspaceId(asC, c.id)) as string + for (let i = 1; i <= 12; i++) { + await createAnimalRecord(asC, { + workspaceId: wC, + requestId: randomUUID(), + fields: animal(`Cheval ${String(i).padStart(2, '0')}`), + relation: null, + }) + } + const dog = await createAnimalRecord(asC, { + workspaceId: wC, + requestId: randomUUID(), + fields: animal('Chien Unique', { species_id: 'canine' }), + relation: null, + }) + const one = await searchAnimals(asC, { + workspaceId: wC, + query: 'cheval', + speciesId: 'equine', + archived: false, + pageSize: 10, + }) + expect(one.rows).toHaveLength(10) + expect(one.next).not.toBeNull() + const two = await searchAnimals(asC, { + workspaceId: wC, + query: 'cheval', + speciesId: 'equine', + archived: false, + pageSize: 10, + after: one.next, + }) + expect(two.rows.map((r) => r.name)).toEqual(['Cheval 11', 'Cheval 12']) + expect(two.next).toBeNull() + const equines = await searchAnimals(asC, { + workspaceId: wC, + query: '', + speciesId: 'equine', + archived: false, + pageSize: 50, + }) + expect(equines.rows.map((r) => r.id)).not.toContain(dog.id) + const canines = await searchAnimals(asC, { + workspaceId: wC, + query: '', + speciesId: 'canine', + archived: false, + }) + expect(canines.rows.map((r) => r.id)).toEqual([dog.id]) + expect(await setAnimalArchived(asC, dog.id, true)).toEqual({ revision: 2 }) + const active = await searchAnimals(asC, { + workspaceId: wC, + query: 'chien', + speciesId: null, + archived: false, + }) + expect(active.rows).toEqual([]) + const archived = await searchAnimals(asC, { + workspaceId: wC, + query: 'chien', + speciesId: null, + archived: true, + }) + expect(archived.rows.map((r) => r.id)).toEqual([dog.id]) + }) + + it('nothing of A reaches B: reads empty, writes not_found', async () => { + const clientId = await clientOfA('Client Secret') + const created = await createAnimalRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields: animal('Animal Secret'), + relation: { clientId, relationRole: 'owner', startedOn: null }, + }) + const relationId = created.relationId as string + expect(await fetchAnimalRecord(asB, created.id)).toBeNull() + expect(await fetchAnimalRecord(asA, randomUUID())).toBeNull() + expect(await fetchAnimalRelations(asB, created.id)).toEqual([]) + const search = await searchAnimals(asB, { + workspaceId: wB, + query: 'secret', + speciesId: null, + archived: false, + }) + expect(search.rows).toEqual([]) + const bAnimal = await createAnimalRecord(asB, { + workspaceId: wB, + requestId: randomUUID(), + fields: animal('Animal de B'), + relation: null, + }) + for (const write of [ + () => + updateAnimalRecord(asB, { + animalId: created.id, + expectedRevision: 1, + fields: animal('X'), + }), + () => setAnimalArchived(asB, created.id, true), + () => + createAnimalClientRelation(asB, { + animalId: bAnimal.id, + clientId, + requestId: randomUUID(), + relationRole: 'owner', + startedOn: null, + }), + () => + endAnimalClientRelation(asB, { + relationId, + expectedRevision: 1, + endedOn: null, + }), + () => + updateAnimalClientRelation(asB, { + relationId, + expectedRevision: 1, + startedOn: null, + endedOn: null, + }), + () => voidAnimalClientRelation(asB, { relationId, expectedRevision: 1 }), + () => + createAnimalRecord(asB, { + workspaceId: wA, + requestId: randomUUID(), + fields: animal('Intrus'), + relation: null, + }), + ]) + expect(await kindOf(write())).toBe('not_found') + expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1) + }) + + it('a relation: duplicate refused, end with and without date, already_ended, dates, conflict', async () => { + const animalId = await animalOfA('Relation Fictive') + const owner = await clientOfA('Propriétaire Fictif') + const keeper = await clientOfA('Détenteur Fictif') + const rel = await createAnimalClientRelation(asA, { + animalId, + clientId: owner, + requestId: randomUUID(), + relationRole: 'owner', + startedOn: '2019-03-01', + }) + expect(rel.revision).toBe(1) + expect( + await kindOf( + createAnimalClientRelation(asA, { + animalId, + clientId: owner, + requestId: randomUUID(), + relationRole: 'owner', + startedOn: null, + }), + ), + ).toBe('duplicate_relation') + const keep = await createAnimalClientRelation(asA, { + animalId, + clientId: keeper, + requestId: randomUUID(), + relationRole: 'keeper', + startedOn: null, + }) + expect( + await endAnimalClientRelation(asA, { + relationId: rel.id, + expectedRevision: 1, + endedOn: '2024-05-01', + }), + ).toEqual({ revision: 2 }) + expect( + await endAnimalClientRelation(asA, { + relationId: keep.id, + expectedRevision: 1, + endedOn: null, + }), + ).toEqual({ revision: 2 }) + expect( + await kindOf( + endAnimalClientRelation(asA, { + relationId: rel.id, + expectedRevision: 2, + endedOn: null, + }), + ), + ).toBe('already_ended') + const relations = await fetchAnimalRelations(asA, animalId) + const byId = new Map(relations.map((r) => [r.id, r])) + expect(byId.get(rel.id)).toMatchObject({ + ended_on: '2024-05-01', + started_on: '2019-03-01', + }) + expect(byId.get(rel.id)?.ended_at).not.toBeNull() + expect(byId.get(keep.id)).toMatchObject({ ended_on: null }) + expect(byId.get(keep.id)?.ended_at).not.toBeNull() + expect( + await updateAnimalClientRelation(asA, { + relationId: rel.id, + expectedRevision: 2, + startedOn: null, + endedOn: '2024-06-01', + }), + ).toEqual({ revision: 3 }) + expect( + (await fetchAnimalRelations(asA, animalId)).find((r) => r.id === rel.id), + ).toMatchObject({ started_on: null, ended_on: '2024-06-01', revision: 3 }) + expect( + await kindOf( + updateAnimalClientRelation(asA, { + relationId: rel.id, + expectedRevision: 2, + startedOn: null, + endedOn: null, + }), + ), + ).toBe('conflict') + // A successive relation of the same triple once the first has ended. + expect( + ( + await createAnimalClientRelation(asA, { + animalId, + clientId: owner, + requestId: randomUUID(), + relationRole: 'owner', + startedOn: null, + }) + ).revision, + ).toBe(1) + }) + + it('a voided relation leaves the relations, the current owners and the client animals', async () => { + const owner = await clientOfA('Erreur de Saisie') + const created = await createAnimalRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields: animal('Annulation Fictive'), + relation: { clientId: owner, relationRole: 'owner', startedOn: null }, + }) + const relationId = created.relationId as string + expect((await listClientAnimals(asA, owner)).rows).toHaveLength(1) + expect( + await voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }), + ).toEqual({ revision: 2 }) + expect(await fetchAnimalRelations(asA, created.id)).toEqual([]) + const search = await searchAnimals(asA, { + workspaceId: wA, + query: 'annulation fictive', + speciesId: null, + archived: false, + }) + expect(search.rows[0]).toMatchObject({ + current_owners: [], + current_owner_count: 0, + }) + expect((await listClientAnimals(asA, owner)).rows).toEqual([]) + // Voided is frozen: no end, no date change, no second void. + expect( + await kindOf( + endAnimalClientRelation(asA, { + relationId, + expectedRevision: 2, + endedOn: null, + }), + ), + ).toBe('invalid_input') + expect( + await kindOf( + voidAnimalClientRelation(asA, { relationId, expectedRevision: 2 }), + ), + ).toBe('invalid_input') + }) + + it('an archived animal refuses its edits and relation writes, then restores', async () => { + const clientId = await clientOfA('Client Archive') + const created = await createAnimalRecord(asA, { + workspaceId: wA, + requestId: randomUUID(), + fields: animal('Archive Fictive'), + relation: { clientId, relationRole: 'keeper', startedOn: null }, + }) + const relationId = created.relationId as string + expect(await setAnimalArchived(asA, created.id, true)).toEqual({ + revision: 2, + }) + const other = await clientOfA('Autre Client') + for (const write of [ + () => + updateAnimalRecord(asA, { + animalId: created.id, + expectedRevision: 2, + fields: animal('Renommé'), + }), + () => + createAnimalClientRelation(asA, { + animalId: created.id, + clientId: other, + requestId: randomUUID(), + relationRole: 'owner', + startedOn: null, + }), + () => + endAnimalClientRelation(asA, { + relationId, + expectedRevision: 1, + endedOn: null, + }), + () => + updateAnimalClientRelation(asA, { + relationId, + expectedRevision: 1, + startedOn: '2020-01-01', + endedOn: null, + }), + () => voidAnimalClientRelation(asA, { relationId, expectedRevision: 1 }), + ]) + expect(await kindOf(write())).toBe('archived') + expect(await fetchAnimalRelations(asA, created.id)).toHaveLength(1) + expect(await setAnimalArchived(asA, created.id, false)).toEqual({ + revision: 3, + }) + expect( + await updateAnimalRecord(asA, { + animalId: created.id, + expectedRevision: 3, + fields: animal('Restaurée Fictive', { sex: 'female' }), + }), + ).toEqual({ revision: 4 }) + expect( + await kindOf( + updateAnimalRecord(asA, { + animalId: created.id, + expectedRevision: 3, + fields: animal('Périmée'), + }), + ), + ).toBe('conflict') + }) +}) From 930499cd250589e7d87078758e1e170e44145fc1 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 26 Oct 2026 17:11:28 +0100 Subject: [PATCH 40/60] feat(app): animal screens, relation panels, animals on the client page Routes /app/animals, new, :animalId, edit under one workspace gate; list with species filter; form (D-R7, U3 birth, no default sex or role, optional first client); page with current and former relations, end, dates, void; client page links its animals, adds one pre-associated, links an existing one. Card now passes aria-labelledby, which it silently dropped. --- apps/app/src/animals/age.ts | 29 + apps/app/src/animals/species.tsx | 100 ++ apps/app/src/animals/useAnimalForm.ts | 232 ++++ apps/app/src/animals/useAnimalList.ts | 110 ++ apps/app/src/animals/useAnimalRecord.ts | 50 + apps/app/src/animals/validation.ts | 253 ++++ apps/app/src/app/App.tsx | 23 +- apps/app/src/app/guards/RequireWorkspace.tsx | 16 +- .../routes/app/animals/AnimalCreateRoute.tsx | 108 ++ .../routes/app/animals/AnimalDetailRoute.tsx | 248 ++++ .../routes/app/animals/AnimalEditRoute.tsx | 85 ++ .../routes/app/animals/AnimalsListRoute.tsx | 240 ++++ .../routes/app/clients/ClientDetailRoute.tsx | 16 +- .../app/src/components/animals/AnimalForm.tsx | 439 ++++++ .../src/components/animals/AnimalNotFound.tsx | 27 + .../animals/ArchiveAnimalDialog.tsx | 98 ++ .../src/components/clients/ClientAnimals.tsx | 283 ++-- .../components/relations/AnimalRelations.tsx | 276 ++++ apps/app/src/components/relations/Pickers.tsx | 78 ++ .../src/components/relations/RecordPicker.tsx | 159 +++ .../relations/RelationActionDialog.tsx | 123 ++ .../components/relations/RelationDialogs.tsx | 211 +++ .../components/relations/RelationPanel.tsx | 237 ++++ apps/app/src/components/shell/SidebarNav.tsx | 1 + apps/app/src/components/ui/Button.tsx | 4 +- apps/app/src/components/ui/Card.tsx | 4 + apps/app/src/components/ui/ChoiceRadios.tsx | 86 ++ apps/app/src/components/ui/Icon.tsx | 2 + apps/app/src/i18n/en.ts | 228 ++++ apps/app/src/i18n/fr.ts | 234 ++++ apps/app/src/lib/dates.ts | 7 + apps/app/src/relations/choices.ts | 50 + apps/app/src/relations/groups.ts | 34 + apps/app/src/relations/useAnimalRelations.ts | 54 + .../app/tests/unit/animals.validation.test.ts | 349 +++++ apps/app/tests/unit/routes.animals.test.tsx | 1198 +++++++++++++++++ 36 files changed, 5579 insertions(+), 113 deletions(-) create mode 100644 apps/app/src/animals/age.ts create mode 100644 apps/app/src/animals/species.tsx create mode 100644 apps/app/src/animals/useAnimalForm.ts create mode 100644 apps/app/src/animals/useAnimalList.ts create mode 100644 apps/app/src/animals/useAnimalRecord.ts create mode 100644 apps/app/src/animals/validation.ts create mode 100644 apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx create mode 100644 apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx create mode 100644 apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx create mode 100644 apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx create mode 100644 apps/app/src/components/animals/AnimalForm.tsx create mode 100644 apps/app/src/components/animals/AnimalNotFound.tsx create mode 100644 apps/app/src/components/animals/ArchiveAnimalDialog.tsx create mode 100644 apps/app/src/components/relations/AnimalRelations.tsx create mode 100644 apps/app/src/components/relations/Pickers.tsx create mode 100644 apps/app/src/components/relations/RecordPicker.tsx create mode 100644 apps/app/src/components/relations/RelationActionDialog.tsx create mode 100644 apps/app/src/components/relations/RelationDialogs.tsx create mode 100644 apps/app/src/components/relations/RelationPanel.tsx create mode 100644 apps/app/src/components/ui/ChoiceRadios.tsx create mode 100644 apps/app/src/relations/choices.ts create mode 100644 apps/app/src/relations/groups.ts create mode 100644 apps/app/src/relations/useAnimalRelations.ts create mode 100644 apps/app/tests/unit/animals.validation.test.ts create mode 100644 apps/app/tests/unit/routes.animals.test.tsx diff --git a/apps/app/src/animals/age.ts b/apps/app/src/animals/age.ts new file mode 100644 index 00000000..6e0ca5c6 --- /dev/null +++ b/apps/app/src/animals/age.ts @@ -0,0 +1,29 @@ +/** + * The age shown on an animal's page, for display only (contract §5.2): from + * the full date when known, else « environ N ans » from the year. Nothing is + * stored or sent. + */ +export interface AnimalAge { + unit: 'year' | 'month' + count: number + /** From the year alone: the day is unknown. */ + about: boolean +} + +export function animalAge( + birthYear: number | null, + birthDate: string | null, + today: string, +): AnimalAge | null { + const [ty, tm, td] = today.split('-').map(Number) + if (birthDate) { + const [by, bm, bd] = birthDate.split('-').map(Number) + const months = (ty - by) * 12 + (tm - bm) - (td < bd ? 1 : 0) + if (months < 0) return null + return months >= 12 + ? { unit: 'year', count: Math.floor(months / 12), about: false } + : { unit: 'month', count: months, about: false } + } + if (birthYear === null || birthYear > ty) return null + return { unit: 'year', count: ty - birthYear, about: true } +} diff --git a/apps/app/src/animals/species.tsx b/apps/app/src/animals/species.tsx new file mode 100644 index 00000000..0c445b4c --- /dev/null +++ b/apps/app/src/animals/species.tsx @@ -0,0 +1,100 @@ +import { + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useState, + type ReactNode, +} from 'react' +import { + classifyRecordError, + fetchSpeciesLabels, + type RecordFailureKind, + type SpeciesLabel, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +import type { Locale } from '@/i18n/types' + +export type SpeciesState = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'ready'; labels: SpeciesLabel[] } + | { status: 'error'; failure: RecordFailureKind } + +interface SpeciesContextValue { + state: SpeciesState + /** Starts the read once; later calls change nothing. */ + request: () => void + retry: () => void +} + +const SpeciesContext = createContext(null) + +/** + * The active species (reference rows of contract §5.4), read once per + * workspace and only when a page needs them: the list filter, the form and + * the record pages share one answer. Mounted under RequireWorkspace, it + * leaves with the workspace on a change of account. + */ +export function SpeciesProvider({ children }: { children: ReactNode }) { + const [state, setState] = useState({ status: 'idle' }) + // 0 until a page asks; each retry bumps it. + const [attempt, setAttempt] = useState(0) + + useEffect(() => { + if (attempt === 0) return + let live = true + const client = getSupabaseClient() + setState({ status: 'loading' }) + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + fetchSpeciesLabels(client) + .then((labels) => { + if (live) setState({ status: 'ready', labels }) + }) + .catch((error: unknown) => { + if (live) + setState({ status: 'error', failure: classifyRecordError(error) }) + }) + return () => { + live = false + } + }, [attempt]) + + const request = useCallback(() => setAttempt((n) => (n === 0 ? 1 : n)), []) + const retry = useCallback(() => setAttempt((n) => n + 1), []) + const value = useMemo( + () => ({ state, request, retry }), + [state, request, retry], + ) + return ( + {children} + ) +} + +/** The species labels of the workspace; the first page that asks starts the read. */ +export function useSpecies(): Omit { + const context = useContext(SpeciesContext) + if (!context) throw new Error('useSpecies needs a SpeciesProvider') + const { request } = context + useEffect(() => request(), [request]) + return { state: context.state, retry: context.retry } +} + +/** The species name in the locale, followed by the « Autre » detail when there is one. */ +export function speciesName( + labels: readonly SpeciesLabel[], + speciesId: string, + detail: string | null, + locale: Locale, +): string { + const label = labels.find((s) => s.id === speciesId) + const name = label + ? pickLocaleLabel(label.name_fr, label.name_en, locale, speciesId) + : speciesId + return detail ? `${name} (${detail})` : name +} diff --git a/apps/app/src/animals/useAnimalForm.ts b/apps/app/src/animals/useAnimalForm.ts new file mode 100644 index 00000000..958a029c --- /dev/null +++ b/apps/app/src/animals/useAnimalForm.ts @@ -0,0 +1,232 @@ +import { useRef, useState, type FormEvent } from 'react' +import { + classifyRecordError, + createAnimalRecord, + fetchAnimalRecord, + updateAnimalRecord, + type AnimalRecord, + type AnimalRelationRole, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { generateUuid } from '@/lib/id' +import { localDateIso } from '@/lib/dates' +import { + EMPTY_ANIMAL_VALUES, + EMPTY_RELATION_VALUES, + animalFieldErrors, + animalFormValues, + animalSchema, + relationIssues, + withBirthDate, + type AnimalFieldErrors, + type AnimalFormValues, + type RelationFieldErrors, + type RelationFormValues, +} from './validation' + +export interface PickedClient { + id: string + display_name: string +} + +export type AnimalFormTarget = + | { + mode: 'create' + workspaceId: string + /** The client the form opened from, pre-associated; the practitioner may remove it. */ + initialClient: PickedClient | null + } + | { mode: 'edit'; record: AnimalRecord } + +export type AnimalFormPhase = + | { kind: 'idle' } + | { kind: 'saving' } + | { kind: 'failed'; failure: RecordFailureKind } + +export interface AnimalSaved { + animalId: string + /** The client the new animal was linked to, if any. */ + linkedClientId: string | null +} + +const FIELDS = Object.keys(EMPTY_ANIMAL_VALUES) as (keyof AnimalFormValues)[] + +function sameValues(a: AnimalFormValues, b: AnimalFormValues): boolean { + return FIELDS.every((key) => a[key] === b[key]) +} + +function sameRelation(a: RelationFormValues, b: RelationFormValues): boolean { + return ( + a.client?.id === b.client?.id && + a.relation_role === b.relation_role && + a.started_on === b.started_on + ) +} + +/** + * The animal form: typed values, the D-R7 schema, one save. A create keeps + * one request id for the life of the form, and sends the animal with its + * optional first client in one create_animal call, so a retry after a lost + * answer returns the animal (and relation) already made. An update sends the + * revision it was read at; on `conflict` the stored animal is shown beside + * the typed values, which stay. + */ +export function useAnimalForm( + target: AnimalFormTarget, + activeSpeciesIds: readonly string[], + onSaved: (saved: AnimalSaved) => void, +) { + const initial = + target.mode === 'edit' + ? animalFormValues(target.record) + : EMPTY_ANIMAL_VALUES + const initialRelation: RelationFormValues = + target.mode === 'create' + ? { ...EMPTY_RELATION_VALUES, client: target.initialClient } + : EMPTY_RELATION_VALUES + const [values, setValues] = useState(initial) + const [baseline, setBaseline] = useState(initial) + const [relation, setRelation] = useState(initialRelation) + const [relationBaseline, setRelationBaseline] = useState(initialRelation) + const [errors, setErrors] = useState({}) + const [relationErrors, setRelationErrors] = useState({}) + const [errorRound, setErrorRound] = useState(0) + const [phase, setPhase] = useState({ kind: 'idle' }) + const [stored, setStored] = useState(null) + const [requestId] = useState(generateUuid) + const revision = useRef(target.mode === 'edit' ? target.record.revision : 0) + const inFlight = useRef(false) + + const setField = (key: keyof AnimalFormValues) => (value: string) => + setValues((v) => ({ ...v, [key]: value })) + const setBirthDate = (value: string) => + setValues((v) => withBirthDate(v, value)) + const chooseClient = (client: PickedClient | null) => + setRelation((r) => ({ ...r, client })) + const setRelationRole = (role: AnimalRelationRole) => + setRelation((r) => ({ ...r, relation_role: role })) + const setStartedOn = (value: string) => + setRelation((r) => ({ ...r, started_on: value })) + + /** The species the form may send: on an edit, the stored one even if it left the active list. */ + const speciesIds = + target.mode === 'edit' && + !activeSpeciesIds.includes(target.record.species_id) + ? [...activeSpeciesIds, target.record.species_id] + : activeSpeciesIds + + async function readStored(animalId: string) { + const client = getSupabaseClient() + const record = client + ? await fetchAnimalRecord(client, animalId).catch(() => null) + : null + if (record) { + revision.current = record.revision + setStored(record) + } + } + + function validate() { + const today = localDateIso() + const parsed = animalSchema({ speciesIds, today }).safeParse(values) + const linkIssues = + target.mode === 'create' ? relationIssues(relation, today, false) : {} + const fieldIssues = parsed.success ? {} : animalFieldErrors(parsed.error) + setErrors(fieldIssues) + setRelationErrors(linkIssues) + if (!parsed.success || Object.keys(linkIssues).length > 0) { + setErrorRound((n) => n + 1) + return null + } + return parsed.data + } + + async function save(fields: NonNullable>) { + const client = getSupabaseClient() + if (!client) throw new TypeError('no backend') + if (target.mode === 'edit') { + revision.current = ( + await updateAnimalRecord(client, { + animalId: target.record.id, + expectedRevision: revision.current, + fields, + }) + ).revision + return { animalId: target.record.id, linkedClientId: null } + } + const linked = relation.client + const created = await createAnimalRecord(client, { + workspaceId: target.workspaceId, + requestId, + fields, + relation: linked + ? { + clientId: linked.id, + relationRole: relation.relation_role as AnimalRelationRole, + startedOn: relation.started_on || null, + } + : null, + }) + return { animalId: created.id, linkedClientId: linked?.id ?? null } + } + + async function submit(event: FormEvent) { + event.preventDefault() + if (inFlight.current) return + const fields = validate() + if (!fields) return + inFlight.current = true + setPhase({ kind: 'saving' }) + try { + const saved = await save(fields) + setBaseline(values) + setRelationBaseline(relation) + setPhase({ kind: 'idle' }) + onSaved(saved) + } catch (error) { + const failure = classifyRecordError(error) + if (failure === 'conflict' && target.mode === 'edit') + await readStored(target.record.id) + setPhase({ kind: 'failed', failure }) + } finally { + inFlight.current = false + } + } + + /** Drops the typed values for the stored ones after a conflict. */ + function takeStored() { + if (!stored) return + const next = animalFormValues(stored) + setValues(next) + setBaseline(next) + setStored(null) + setErrors({}) + setPhase({ kind: 'idle' }) + } + + return { + mode: target.mode, + values, + setField, + setBirthDate, + relation, + chooseClient, + setRelationRole, + setStartedOn, + errors, + relationErrors, + /** Changes after each refused submit, so the form can focus the first error. */ + errorRound, + phase, + /** The stored animal after a conflict, shown beside the typed values. */ + stored, + takeStored, + dirty: + !sameValues(values, baseline) || + !sameRelation(relation, relationBaseline), + submit, + } +} + +export type AnimalForm = ReturnType diff --git a/apps/app/src/animals/useAnimalList.ts b/apps/app/src/animals/useAnimalList.ts new file mode 100644 index 00000000..bcefddab --- /dev/null +++ b/apps/app/src/animals/useAnimalList.ts @@ -0,0 +1,110 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + classifyRecordError, + searchAnimals, + type AnimalListItem, + type NameCursor, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { SEARCH_DELAY_MS } from '@/clients/useClientList' + +export type AnimalListState = + | { status: 'loading' } + | { + status: 'ready' + rows: AnimalListItem[] + next: NameCursor | null + moreFailure: RecordFailureKind | null + } + | { status: 'error'; failure: RecordFailureKind } + +/** + * The animals of the workspace for a term, a species and the archived + * toggle: the server searches (search_animals, POST), pages of 25 in name + * order, « Afficher plus » appends the next page. An answer to an older + * search is dropped. + */ +export function useAnimalList(workspaceId: string) { + const [query, setQuery] = useState('') + const [term, setTerm] = useState('') + const [speciesId, setSpeciesId] = useState(null) + const [archived, setArchived] = useState(false) + const [state, setState] = useState({ status: 'loading' }) + const [loadingMore, setLoadingMore] = useState(false) + const [reload, setReload] = useState(0) + const generation = useRef(0) + + useEffect(() => { + const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS) + return () => clearTimeout(timer) + }, [query]) + + useEffect(() => { + const current = ++generation.current + const client = getSupabaseClient() + setState({ status: 'loading' }) + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + searchAnimals(client, { workspaceId, query: term, speciesId, archived }) + .then((page) => { + if (current === generation.current) + setState({ + status: 'ready', + rows: page.rows, + next: page.next, + moreFailure: null, + }) + }) + .catch((error: unknown) => { + if (current === generation.current) + setState({ status: 'error', failure: classifyRecordError(error) }) + }) + }, [workspaceId, term, speciesId, archived, reload]) + + const loadMore = useCallback(async () => { + const client = getSupabaseClient() + if (state.status !== 'ready' || !state.next || !client || loadingMore) + return + const current = generation.current + setLoadingMore(true) + try { + const page = await searchAnimals(client, { + workspaceId, + query: term, + speciesId, + archived, + after: state.next, + }) + if (current === generation.current) + setState({ + status: 'ready', + rows: [...state.rows, ...page.rows], + next: page.next, + moreFailure: null, + }) + } catch (error) { + if (current === generation.current) + setState({ ...state, moreFailure: classifyRecordError(error) }) + } finally { + setLoadingMore(false) + } + }, [state, loadingMore, workspaceId, term, speciesId, archived]) + + return { + query, + setQuery, + /** The term the shown rows answer (the typed one after the pause). */ + term, + speciesId, + setSpeciesId, + archived, + setArchived, + state, + loadingMore, + loadMore, + retry: () => setReload((n) => n + 1), + } +} diff --git a/apps/app/src/animals/useAnimalRecord.ts b/apps/app/src/animals/useAnimalRecord.ts new file mode 100644 index 00000000..fd920920 --- /dev/null +++ b/apps/app/src/animals/useAnimalRecord.ts @@ -0,0 +1,50 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + classifyRecordError, + fetchAnimalRecord, + type AnimalRecord, + type RecordFailureKind, +} from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' + +export type AnimalRecordState = + | { status: 'loading' } + | { status: 'ready'; record: AnimalRecord } + | { status: 'not_found' } + | { status: 'error'; failure: RecordFailureKind } + +/** One animal by id; an unknown id and an id of another workspace are both not_found. */ +export function useAnimalRecord(animalId: string) { + const [state, setState] = useState({ status: 'loading' }) + const [reload, setReload] = useState(0) + const shownId = useRef(null) + + useEffect(() => { + let live = true + const client = getSupabaseClient() + // A refresh of the same animal keeps it on screen until the new answer. + if (shownId.current !== animalId) setState({ status: 'loading' }) + shownId.current = animalId + if (!client) { + setState({ status: 'error', failure: 'unavailable' }) + return + } + fetchAnimalRecord(client, animalId) + .then((record) => { + if (live) + setState( + record ? { status: 'ready', record } : { status: 'not_found' }, + ) + }) + .catch((error: unknown) => { + if (live) + setState({ status: 'error', failure: classifyRecordError(error) }) + }) + return () => { + live = false + } + }, [animalId, reload]) + + const refresh = useCallback(() => setReload((n) => n + 1), []) + return { state, refresh } +} diff --git a/apps/app/src/animals/validation.ts b/apps/app/src/animals/validation.ts new file mode 100644 index 00000000..15b6be94 --- /dev/null +++ b/apps/app/src/animals/validation.ts @@ -0,0 +1,253 @@ +import { z } from 'zod' +import { + ANIMAL_FIELD_LIMITS, + BIRTH_YEAR_MIN, + CONTROL_CHARACTERS, + RECORD_DATE_MIN, + codePointLength, + type AnimalFields, + type AnimalRecord, + type AnimalRelationRole, + type AnimalSex, +} from '@faunosteo/supabase' + +/** + * The animal form (contract §5.2, §11.3; D-R7): bounds from field-limits, + * proven equal to the SQL CHECKs, so the form never sends what the database + * refuses. The birth keeps the precision given (D6b): a year alone stays a + * year, a full date carries its year again. « Not in the future » is the + * device's local date (`today`); the RPCs allow up to tomorrow UTC. Messages + * are i18n keys; `|n` carries the {max} placeholder. + */ + +export const ANIMAL_SEXES: readonly AnimalSex[] = ['male', 'female', 'unknown'] +export const RELATION_ROLES: readonly AnimalRelationRole[] = [ + 'owner', + 'keeper', + 'contact', +] + +/** The species that asks for a detail (« Autre »). */ +export const OTHER_SPECIES = 'other' + +export interface AnimalFormValues { + name: string + species_id: string + species_detail: string + /** '' until the practitioner picks one: no default (N8). */ + sex: AnimalSex | '' + breed: string + birth_year: string + birth_date: string +} + +export const EMPTY_ANIMAL_VALUES: AnimalFormValues = { + name: '', + species_id: '', + species_detail: '', + sex: '', + breed: '', + birth_year: '', + birth_date: '', +} + +/** The form's view of a stored animal: null fields become empty inputs. */ +export function animalFormValues(record: AnimalRecord): AnimalFormValues { + return { + name: record.name, + species_id: record.species_id, + species_detail: record.species_detail ?? '', + sex: record.sex, + breed: record.breed ?? '', + birth_year: record.birth_year === null ? '' : String(record.birth_year), + birth_date: record.birth_date ?? '', + } +} + +/** + * U3: a complete date fills the year (which the form then locks); clearing + * the date leaves the year as it was, editable again. + */ +export function withBirthDate( + values: AnimalFormValues, + birthDate: string, +): AnimalFormValues { + const year = /^\d{4}-\d{2}-\d{2}$/.test(birthDate) + ? birthDate.slice(0, 4) + : values.birth_year + return { ...values, birth_date: birthDate, birth_year: year } +} + +function isCalendarDate(value: string): boolean { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value) + if (!match) return false + const [y, m, d] = match.slice(1).map(Number) + const date = new Date(Date.UTC(y, m - 1, d)) + return ( + date.getUTCFullYear() === y && + date.getUTCMonth() === m - 1 && + date.getUTCDate() === d + ) +} + +/** + * The issue of an optional record date (birth, relation start or end), or + * null when it is fine: a real calendar date from 1900 to `today` (ISO text + * compares in date order). + */ +export function recordDateIssue(value: string, today: string): string | null { + if (value === '') return null + if (!isCalendarDate(value)) return 'animals.error.date_format' + if (value < RECORD_DATE_MIN || value > today) + return 'animals.error.date_range' + return null +} + +/** Trimmed text of at most `max` code points without control characters. */ +function textIssue(value: string, max: number): string | null { + if (codePointLength(value) > max) return `animals.error.too_long|${max}` + if (CONTROL_CHARACTERS.test(value)) return 'animals.error.characters' + return null +} + +export interface AnimalSchemaContext { + /** The species the form may send: the active ones, plus the stored one on an edit. */ + speciesIds: readonly string[] + /** The device's local date, YYYY-MM-DD. */ + today: string +} + +type Issue = { path: keyof AnimalFormValues; message: string } + +function identityIssues(v: AnimalFormValues, ctx: AnimalSchemaContext) { + const issues: Issue[] = [] + const name = v.name.trim() + const nameIssue = + name === '' + ? 'animals.error.required' + : textIssue(name, ANIMAL_FIELD_LIMITS.name) + if (nameIssue) issues.push({ path: 'name', message: nameIssue }) + if (!ctx.speciesIds.includes(v.species_id)) + issues.push({ path: 'species_id', message: 'animals.error.species' }) + if (v.species_id === OTHER_SPECIES) { + const detail = v.species_detail.trim() + const detailIssue = + detail === '' + ? 'animals.error.species_detail' + : textIssue(detail, ANIMAL_FIELD_LIMITS.speciesDetail) + if (detailIssue) + issues.push({ path: 'species_detail', message: detailIssue }) + } + if (!ANIMAL_SEXES.includes(v.sex as AnimalSex)) + issues.push({ path: 'sex', message: 'animals.error.sex' }) + const breedIssue = textIssue(v.breed.trim(), ANIMAL_FIELD_LIMITS.breed) + if (breedIssue) issues.push({ path: 'breed', message: breedIssue }) + return issues +} + +function birthIssues(v: AnimalFormValues, today: string) { + const issues: Issue[] = [] + if (v.birth_year !== '') { + if (!/^\d{4}$/.test(v.birth_year)) + issues.push({ path: 'birth_year', message: 'animals.error.year_format' }) + else if ( + Number(v.birth_year) < BIRTH_YEAR_MIN || + Number(v.birth_year) > Number(today.slice(0, 4)) + ) + issues.push({ path: 'birth_year', message: 'animals.error.year_range' }) + } + const dateIssue = recordDateIssue(v.birth_date, today) + if (dateIssue) issues.push({ path: 'birth_date', message: dateIssue }) + else if (v.birth_date !== '' && v.birth_date.slice(0, 4) !== v.birth_year) + issues.push({ path: 'birth_year', message: 'animals.error.date_year' }) + return issues +} + +const nullIfEmpty = (value: string) => (value === '' ? null : value) + +/** Parses the typed values into the seven fields the RPCs take. */ +export function animalSchema(ctx: AnimalSchemaContext) { + return z + .object({ + name: z.string(), + species_id: z.string(), + species_detail: z.string(), + sex: z.string(), + breed: z.string(), + birth_year: z.string(), + birth_date: z.string(), + }) + .superRefine((raw, zctx) => { + const v = raw as AnimalFormValues + for (const issue of [ + ...identityIssues(v, ctx), + ...birthIssues(v, ctx.today), + ]) + zctx.addIssue({ + code: 'custom', + path: [issue.path], + message: issue.message, + }) + }) + .transform( + (v): AnimalFields => ({ + name: v.name.trim(), + species_id: v.species_id, + // Any other species refuses a detail: a hidden leftover is dropped, never sent. + species_detail: + v.species_id === OTHER_SPECIES ? v.species_detail.trim() : null, + sex: v.sex as AnimalSex, + breed: nullIfEmpty(v.breed.trim()), + birth_year: v.birth_year === '' ? null : Number(v.birth_year), + birth_date: nullIfEmpty(v.birth_date), + }), + ) +} + +/** The optional client of a new animal, or of a relation added from a page. */ +export interface RelationFormValues { + client: { id: string; display_name: string } | null + /** '' until chosen: no role is preselected (owner decision 2026-10-26). */ + relation_role: AnimalRelationRole | '' + started_on: string +} + +export const EMPTY_RELATION_VALUES: RelationFormValues = { + client: null, + relation_role: '', + started_on: '', +} + +export type RelationFieldErrors = Partial< + Record<'client' | 'relation_role' | 'started_on', string> +> + +/** Errors of a relation choice; `requireClient` when the client is the point of the form. */ +export function relationIssues( + values: RelationFormValues, + today: string, + requireClient: boolean, +): RelationFieldErrors { + const errors: RelationFieldErrors = {} + if (!values.client) { + if (requireClient) errors.client = 'animals.error.client' + return errors + } + if (!RELATION_ROLES.includes(values.relation_role as AnimalRelationRole)) + errors.relation_role = 'animals.error.role' + const dateIssue = recordDateIssue(values.started_on, today) + if (dateIssue) errors.started_on = dateIssue + return errors +} + +export type AnimalFieldErrors = Partial> + +/** The first message of each field, in form order. */ +export function animalFieldErrors(error: z.ZodError): AnimalFieldErrors { + const errors: AnimalFieldErrors = {} + for (const issue of error.issues) { + const key = issue.path[0] as keyof AnimalFormValues + errors[key] ??= issue.message + } + return errors +} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index cc2bc844..b952bc8d 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -21,6 +21,10 @@ 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. */ @@ -55,11 +59,20 @@ export function AppRoutes() { }> } /> } /> - }> - } /> - } /> - } /> - } /> + {/* One workspace gate for the records: moving between clients and animals keeps it. */} + }> + + } /> + } /> + } /> + } /> + + + } /> + } /> + } /> + } /> + } /> diff --git a/apps/app/src/app/guards/RequireWorkspace.tsx b/apps/app/src/app/guards/RequireWorkspace.tsx index 309151e8..f320c770 100644 --- a/apps/app/src/app/guards/RequireWorkspace.tsx +++ b/apps/app/src/app/guards/RequireWorkspace.tsx @@ -2,6 +2,7 @@ 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' @@ -15,9 +16,10 @@ export function useWorkspaceId(): string { } /** - * Wraps the record routes: they render only once the personal workspace is - * read, and remount when it changes, so no list or form of another account - * survives a change of account. Every other state is said, never guessed. + * 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() @@ -27,9 +29,11 @@ export default function RequireWorkspace() { if (workspace.status === 'ready') { return ( - + + + ) } diff --git a/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx new file mode 100644 index 00000000..aca11539 --- /dev/null +++ b/apps/app/src/app/routes/app/animals/AnimalCreateRoute.tsx @@ -0,0 +1,108 @@ +import { useLocation, useNavigate } from 'react-router-dom' +import { UUID_PATTERN } from '@faunosteo/supabase' +import AnimalForm from '@/components/animals/AnimalForm' +import Notice from '@/components/ui/Notice' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { useLeaveGuard } from '@/app/useLeaveGuard' +import { usePageHeading } from '@/app/usePageHeading' +import { useSpecies } from '@/animals/species' +import { useAnimalForm, type PickedClient } from '@/animals/useAnimalForm' +import { useClientRecord } from '@/clients/useClientRecord' +import { useT } from '@/i18n/useT' +import type { ClientFlash } from '../clients/ClientDetailRoute' +import type { AnimalFlash } from './AnimalDetailRoute' + +/** + * What a client page hands to this page: the client to pre-associate, in + * the navigation state, never in the URL (brief V1-1.6 §6). + */ +export interface AnimalCreateState { + clientId: string +} + +type Origin = + | { status: 'none' } + | { status: 'loading' } + | { status: 'ready'; client: PickedClient } + | { status: 'unavailable' } + +/** The client the form opened from, read again: only an active client of this workspace is pre-associated. */ +function useOrigin(clientId: string | null): Origin { + const { state } = useClientRecord(clientId ?? '') + if (!clientId) return { status: 'none' } + if (state.status === 'loading') return { status: 'loading' } + if (state.status === 'ready' && state.record.archived_at === null) + return { + status: 'ready', + client: { id: state.record.id, display_name: state.record.display_name }, + } + return { status: 'unavailable' } +} + +function CreateForm({ origin }: { origin: PickedClient | null }) { + const t = useT() + const navigate = useNavigate() + const workspaceId = useWorkspaceId() + const { state: species } = useSpecies() + const activeIds = + species.status === 'ready' ? species.labels.map((s) => s.id) : [] + const form = useAnimalForm( + { mode: 'create', workspaceId, initialClient: origin }, + activeIds, + (saved) => { + if (origin && saved.linkedClientId === origin.id) + navigate(`/app/clients/${origin.id}`, { + replace: true, + state: { flash: 'animal_added' satisfies ClientFlash }, + }) + else + navigate(`/app/animals/${saved.animalId}`, { + replace: true, + state: { flash: 'created' satisfies AnimalFlash }, + }) + }, + ) + useLeaveGuard(form.dirty) + return ( + + ) +} + +/** /app/animals/new: one creation intent, one request id kept for retries, an optional first client. */ +export default function AnimalCreateRoute() { + const t = useT() + const heading = usePageHeading() + const location = useLocation() + const passed = (location.state as Partial | null)?.clientId + const origin = useOrigin( + typeof passed === 'string' && UUID_PATTERN.test(passed) ? passed : null, + ) + + return ( +
    +

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

    + {origin.status === 'loading' && ( +

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

    + )} + {origin.status === 'unavailable' && ( + {t('animals.form.origin_unavailable')} + )} + {origin.status !== 'loading' && ( + + )} +
    + ) +} diff --git a/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx new file mode 100644 index 00000000..8d2874f3 --- /dev/null +++ b/apps/app/src/app/routes/app/animals/AnimalDetailRoute.tsx @@ -0,0 +1,248 @@ +import { useEffect, useState, type ReactNode } from 'react' +import { Link, useLocation, useNavigate, useParams } from 'react-router-dom' +import { + classifyRecordError, + setAnimalArchived, + type AnimalRecord, + type RecordFailureKind, +} from '@faunosteo/supabase' +import AnimalNotFound from '@/components/animals/AnimalNotFound' +import ArchiveAnimalDialog from '@/components/animals/ArchiveAnimalDialog' +import AnimalRelations from '@/components/relations/AnimalRelations' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { usePageHeading } from '@/app/usePageHeading' +import { animalAge, type AnimalAge } from '@/animals/age' +import { speciesName, useSpecies } from '@/animals/species' +import { useAnimalRecord } from '@/animals/useAnimalRecord' +import { formatDate, localDateIso } from '@/lib/dates' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +/** What a page that saved the animal asks this page to announce (no value in it). */ +export type AnimalFlash = 'created' | 'updated' + +type Translate = ReturnType + +const linkClass = + 'rounded-sm text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' + +function ageText(age: AnimalAge | null, t: Translate): string | null { + if (!age) return null + if (age.about && age.count === 0) return t('animals.age.under_one') + const unit = age.unit === 'year' ? 'years' : 'months' + const base = t( + `animals.age.${unit}_${age.count === 1 ? 'one' : 'other'}`, + ).replace('{count}', String(age.count)) + return age.about ? t('animals.age.about').replace('{age}', base) : base +} + +/** The birth with the precision known (D6b): a date, a year, or « inconnue »; never a made-up day. */ +function birthText(record: AnimalRecord, t: Translate, locale: 'fr' | 'en') { + const age = ageText( + animalAge(record.birth_year, record.birth_date, localDateIso()), + t, + ) + const when = record.birth_date + ? t('animals.detail.birth_on').replace( + '{date}', + formatDate(record.birth_date, locale), + ) + : record.birth_year !== null + ? t('animals.detail.birth_in').replace( + '{year}', + String(record.birth_year), + ) + : null + if (!when) return t('animals.detail.birth_unknown') + return age ? `${when} (${age})` : when +} + +function IdentityCard({ record }: { record: AnimalRecord }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const { state: species } = useSpecies() + const labels = species.status === 'ready' ? species.labels : [] + const rows: [string, ReactNode][] = [ + [ + t('animals.detail.species'), + speciesName(labels, record.species_id, record.species_detail, locale), + ], + [t('animals.detail.sex'), t(`animals.sex.${record.sex}`)], + [t('animals.detail.breed'), record.breed ?? t('animals.detail.breed_none')], + [t('animals.detail.birth'), birthText(record, t, locale)], + [ + t('animals.detail.status'), + record.archived_at + ? t('animals.detail.status_archived') + : t('animals.detail.status_active'), + ], + ] + return ( + +

    + {t('animals.detail.identity')} +

    +
    + {rows.map(([label, value]) => ( +
    +
    {label}
    +
    {value}
    +
    + ))} +
    +
    + ) +} + +/** /app/animals/:animalId: identity, clients current and former, edit, archive or restore. */ +export default function AnimalDetailRoute() { + const t = useT() + const heading = usePageHeading() + const navigate = useNavigate() + const location = useLocation() + const workspaceId = useWorkspaceId() + const { animalId = '' } = useParams() + const { state, refresh } = useAnimalRecord(animalId) + const flash = (location.state as { flash?: AnimalFlash } | null)?.flash + const [status, setStatus] = useState( + flash ? t(`animals.detail.${flash}`) : null, + ) + const [archiveOpen, setArchiveOpen] = useState(false) + const [restoring, setRestoring] = useState(false) + const [failure, setFailure] = useState(null) + + // The announcement is read once; a reload of the page does not repeat it. + useEffect(() => { + if (flash) navigate(location.pathname, { replace: true, state: null }) + }, [flash, navigate, location.pathname]) + + async function restore() { + const client = getSupabaseClient() + if (restoring || !client) return + setRestoring(true) + setFailure(null) + try { + await setAnimalArchived(client, animalId, false) + setStatus(t('animals.detail.restored')) + refresh() + } catch (error) { + setFailure(classifyRecordError(error)) + } finally { + setRestoring(false) + } + } + + if (state.status === 'not_found') return + if (state.status === 'loading') + return ( +

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

    + ) + if (state.status === 'error') + return ( +
    + {t(`animals.failure.${state.failure}`)} + +
    + ) + + const record = state.record + const archived = record.archived_at !== null + + return ( +
    + + {t('animals.detail.back')} + +
    +
    +

    + {record.name} +

    + {archived && {t('animals.archived_badge')}} +
    +
    + {archived ? ( + + ) : ( + <> + + {t('animals.detail.edit')} + + + + )} +
    +
    + + {status && {status}} + {failure && ( + {t(`animals.failure.${failure}`)} + )} + {archived && ( + {t('animals.detail.archived_notice')} + )} + + + + + setArchiveOpen(false)} + onArchived={() => { + setArchiveOpen(false) + setStatus(t('animals.detail.archived')) + refresh() + }} + /> +
    + ) +} diff --git a/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx new file mode 100644 index 00000000..b2df7811 --- /dev/null +++ b/apps/app/src/app/routes/app/animals/AnimalEditRoute.tsx @@ -0,0 +1,85 @@ +import { Link, useNavigate, useParams } from 'react-router-dom' +import type { AnimalRecord } from '@faunosteo/supabase' +import AnimalForm from '@/components/animals/AnimalForm' +import AnimalNotFound from '@/components/animals/AnimalNotFound' +import Button from '@/components/ui/Button' +import Notice from '@/components/ui/Notice' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { useLeaveGuard } from '@/app/useLeaveGuard' +import { usePageHeading } from '@/app/usePageHeading' +import { useSpecies } from '@/animals/species' +import { useAnimalForm } from '@/animals/useAnimalForm' +import { useAnimalRecord } from '@/animals/useAnimalRecord' +import { useT } from '@/i18n/useT' +import type { AnimalFlash } from './AnimalDetailRoute' + +function EditForm({ record }: { record: AnimalRecord }) { + const t = useT() + const navigate = useNavigate() + const workspaceId = useWorkspaceId() + const { state: species } = useSpecies() + const activeIds = + species.status === 'ready' ? species.labels.map((s) => s.id) : [] + const form = useAnimalForm({ mode: 'edit', record }, activeIds, (saved) => + navigate(`/app/animals/${saved.animalId}`, { + state: { flash: 'updated' satisfies AnimalFlash }, + }), + ) + useLeaveGuard(form.dirty) + return ( + + ) +} + +/** /app/animals/:animalId/edit: the stored values at their revision; an archived animal is read-only. */ +export default function AnimalEditRoute() { + const t = useT() + const heading = usePageHeading() + const { animalId = '' } = useParams() + const { state, refresh } = useAnimalRecord(animalId) + + if (state.status === 'not_found') return + return ( +
    +

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

    + {state.status === 'loading' && ( +

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

    + )} + {state.status === 'error' && ( +
    + {t(`animals.failure.${state.failure}`)} + +
    + )} + {state.status === 'ready' && state.record.archived_at && ( +
    + {t('animals.detail.archived_notice')} + + {t('animals.form.back_to_animal')} + +
    + )} + {state.status === 'ready' && !state.record.archived_at && ( + + )} +
    + ) +} diff --git a/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx new file mode 100644 index 00000000..7d218841 --- /dev/null +++ b/apps/app/src/app/routes/app/animals/AnimalsListRoute.tsx @@ -0,0 +1,240 @@ +import { Link } from 'react-router-dom' +import type { AnimalListItem, SpeciesLabel } from '@faunosteo/supabase' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import ButtonLink from '@/components/ui/ButtonLink' +import FormField from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import Select from '@/components/ui/Select' +import { useWorkspaceId } from '@/app/guards/RequireWorkspace' +import { usePageHeading } from '@/app/usePageHeading' +import { speciesName, useSpecies } from '@/animals/species' +import { useAnimalList } from '@/animals/useAnimalList' +import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +import type { Locale } from '@/i18n/types' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type Translate = ReturnType + +/** « Propriétaires : A, B, C +2 », or « Propriétaire non renseigné » (no placeholder client). */ +function ownersText(animal: AnimalListItem, t: Translate): string { + if (animal.current_owner_count === 0) return t('animals.no_owner') + const names = animal.current_owners + .map((o) => + o.archived + ? t('animals.owner_archived').replace('{name}', o.display_name) + : o.display_name, + ) + .join(', ') + const more = animal.current_owner_count - animal.current_owners.length + const list = + more > 0 + ? `${names} ${t('animals.list.owners_more').replace('{count}', String(more))}` + : names + return t( + animal.current_owner_count === 1 + ? 'animals.list.owner' + : 'animals.list.owners', + ).replace('{names}', list) +} + +function AnimalRow(props: { + animal: AnimalListItem + labels: readonly SpeciesLabel[] + locale: Locale + t: Translate +}) { + const { animal, t } = props + const details = [ + speciesName( + props.labels, + animal.species_id, + animal.species_detail, + props.locale, + ), + animal.breed, + t(`animals.sex.${animal.sex}`), + ].filter(Boolean) + return ( +
  • + + + + {animal.name} + + {animal.archived_at && ( + {t('animals.archived_badge')} + )} + + + {details.join(' · ')} + + + {ownersText(animal, t)} + + +
  • + ) +} + +/** /app/animals: search, species filter, the archived toggle (U2) and « Afficher plus » pages (U1). */ +export default function AnimalsListRoute() { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const heading = usePageHeading() + const workspaceId = useWorkspaceId() + const { state: species } = useSpecies() + const labels = species.status === 'ready' ? species.labels : [] + const list = useAnimalList(workspaceId) + const { state } = list + + const emptyMessage = + list.term || list.speciesId + ? t('animals.list.no_results') + : list.archived + ? t('animals.list.archived_empty') + : t('animals.list.empty') + + return ( +
    +
    +

    + {t('animals.list.title')} +

    + + {t('animals.list.new')} + +
    + +
    + + list.setQuery(e.target.value)} + maxLength={100} + autoComplete="off" + aria-describedby="animal-search-hint" + /> + + + + + +
    + + {/* The number of rows shown is announced; an empty result announces itself below. */} +
    + {state.status === 'ready' && + state.rows.length > 0 && + t( + state.rows.length === 1 + ? 'animals.list.count_one' + : 'animals.list.count_other', + ).replace('{count}', String(state.rows.length))} +
    + + {state.status === 'loading' && ( +

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

    + )} + {state.status === 'error' && ( +
    + {t(`animals.failure.${state.failure}`)} + +
    + )} + {state.status === 'ready' && state.rows.length === 0 && ( +
    +

    {emptyMessage}

    + {!list.term && !list.speciesId && !list.archived && ( +

    + {t('animals.list.empty_hint')} +

    + )} +
    + )} + {state.status === 'ready' && state.rows.length > 0 && ( + <> +
      + {state.rows.map((animal) => ( + + ))} +
    + {state.moreFailure && ( + + {t(`animals.failure.${state.moreFailure}`)} + + )} + {state.next && ( +
    + +
    + )} + + )} +
    + ) +} diff --git a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx index ac6cbce3..b9956224 100644 --- a/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx +++ b/apps/app/src/app/routes/app/clients/ClientDetailRoute.tsx @@ -14,6 +14,7 @@ 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' @@ -21,8 +22,8 @@ import { getSupabaseClient } from '@/lib/supabase' import { useLocaleStore } from '@/state/localeStore' import { useT } from '@/i18n/useT' -/** What a page that saved the client asks this page to announce (no value in it). */ -export type ClientFlash = 'created' | 'updated' +/** 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' @@ -102,12 +103,13 @@ function ContactCard({ record }: { record: ClientRecord }) { ) } -/** /app/clients/:clientId: identity, contact, animals (read-only), edit, archive or restore. */ +/** /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 @@ -225,7 +227,13 @@ export default function ClientDetailRoute() { )} - + = { + name: 'animal-name', + species_id: 'animal-species', + species_detail: 'animal-species-detail', + sex: firstChoiceId('animal-sex', 'male'), + breed: 'animal-breed', + birth_year: 'animal-birth-year', + birth_date: 'animal-birth-date', + client: 'animal-client-search', + relation_role: firstChoiceId('animal-role', 'owner'), + started_on: 'animal-started-on', +} + +export interface AnimalFormProps { + form: AnimalFormState + workspaceId: string + submitLabel: string + /** Where « Annuler » leads; the shell asks first while the form holds changes. */ + cancelTo: string +} + +/** + * The animal form, one page on every screen (contract §11.3): identity + * (name, species with its detail for « Autre », sex with no default, breed), + * birth (a year, or a full date that fills and locks the year: U3), and on + * a creation the optional first client with an explicit role. Every field + * is labelled, errors sit under their field and the first one takes focus. + */ +export default function AnimalForm({ + form, + workspaceId, + submitLabel, + cancelTo, +}: AnimalFormProps) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const { state: species, retry: retrySpecies } = useSpecies() + const { values, errors, relation, relationErrors, phase, stored } = form + const labels = species.status === 'ready' ? species.labels : [] + const today = localDateIso() + const chosenText = useRef(null) + const shownClient = useRef(relation.client?.id ?? null) + + // Choosing a client focuses the choice; removing it focuses the search that replaces it. + useEffect(() => { + const id = relation.client?.id ?? null + if (id === shownClient.current) return + shownClient.current = id + if (id) chosenText.current?.focus() + else document.getElementById(FIELD_IDS.client)?.focus() + }, [relation.client]) + + useEffect(() => { + if (form.errorRound === 0) return + const all = { ...errors, ...relationErrors } as Record + const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find( + (key) => all[key], + ) + if (first) document.getElementById(FIELD_IDS[first])?.focus() + }, [form.errorRound, errors, relationErrors]) + + const err = (key: keyof AnimalFormValues) => + translateFieldError(t, errors[key]) + const relErr = (key: keyof RelationFieldErrors) => + translateFieldError(t, relationErrors[key]) + + /** After a conflict: the stored value under each field that differs from the typed one. */ + const storedHint = (key: keyof AnimalFormValues): string | undefined => { + if (!stored) return undefined + const value = animalFormValues(stored)[key] + if (value === values[key]) return undefined + const shown = + value === '' + ? '' + : key === 'species_id' + ? speciesName(labels, value, null, locale) + : key === 'sex' + ? t(`animals.sex.${value}`) + : key === 'birth_date' + ? formatDate(value, locale) + : value + return shown + ? t('animals.form.stored_value').replace('{value}', shown) + : t('animals.form.stored_empty') + } + const describedBy = (key: keyof AnimalFormValues, hint?: string) => + fieldDescribedBy(FIELD_IDS[key], hint, errors[key]) + + function textField( + key: 'name' | 'breed' | 'species_detail', + label: string, + max: number, + isRequired: boolean, + hint?: string, + ) { + const shownHint = storedHint(key) ?? hint + return ( + + form.setField(key)(e.target.value)} + maxLength={max} + autoComplete="off" + aria-invalid={Boolean(errors[key])} + aria-describedby={describedBy(key, shownHint)} + required={isRequired} + /> + + ) + } + + const required = t('animals.form.required') + const optional = t('animals.form.optional') + const saving = phase.kind === 'saving' + const yearLocked = /^\d{4}-\d{2}-\d{2}$/.test(values.birth_date) + const yearHint = + storedHint('birth_year') ?? + t( + yearLocked + ? 'animals.form.birth_year_locked' + : 'animals.form.birth_year_hint', + ) + const speciesHint = storedHint('species_id') + + return ( +
    + {stored && ( + +

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

    +

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

    + +
    + )} + + +

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

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

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

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

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

    +

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

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

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

    + +
    + ({ + value, + label: t(`clients.role.${value}`), + }))} + value={relation.relation_role} + onChange={form.setRelationRole} + error={relErr('relation_role')} + /> + + form.setStartedOn(e.target.value)} + aria-invalid={Boolean(relationErrors.started_on)} + aria-describedby={ + relationErrors.started_on + ? `${FIELD_IDS.started_on}-error` + : `${FIELD_IDS.started_on}-hint` + } + className="sm:max-w-xs" + /> + + + ) : ( + + form.chooseClient({ id: chosen.id, display_name: chosen.name }) + } + /> + )} +
    + )} + + {phase.kind === 'failed' && !stored && ( + {t(`animals.failure.${phase.failure}`)} + )} +
    + + {t('common.cancel')} + + +
    + + ) +} diff --git a/apps/app/src/components/animals/AnimalNotFound.tsx b/apps/app/src/components/animals/AnimalNotFound.tsx new file mode 100644 index 00000000..e10ebfbc --- /dev/null +++ b/apps/app/src/components/animals/AnimalNotFound.tsx @@ -0,0 +1,27 @@ +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import { usePageHeading } from '@/app/usePageHeading' +import { useT } from '@/i18n/useT' + +/** The same screen for an unknown id, a malformed one and an id of another workspace (contract §11.1). */ +export default function AnimalNotFound() { + const t = useT() + const heading = usePageHeading() + return ( + +

    + {t('animals.not_found.title')} +

    +

    + {t('animals.not_found.body')} +

    + + {t('animals.not_found.back')} + +
    + ) +} diff --git a/apps/app/src/components/animals/ArchiveAnimalDialog.tsx b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx new file mode 100644 index 00000000..2f434ebc --- /dev/null +++ b/apps/app/src/components/animals/ArchiveAnimalDialog.tsx @@ -0,0 +1,98 @@ +import { useState } from 'react' +import { + classifyRecordError, + setAnimalArchived, + type RecordFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import Notice from '@/components/ui/Notice' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +export interface ArchiveAnimalDialogProps { + open: boolean + animalId: string + onClose: () => void + /** Called once the server archived the animal; the page then closes the dialog. */ + onArchived: () => void +} + +/** + * Confirmation before archiving an animal (contract §7.1): its relations are + * kept and frozen, no client is archived. Closing it is never a + * confirmation, and while the request runs it refuses to close. + */ +export default function ArchiveAnimalDialog({ + open, + animalId, + onClose, + onArchived, +}: ArchiveAnimalDialogProps) { + const t = useT() + const [pending, setPending] = useState(false) + const [failure, setFailure] = useState(null) + + const close = () => { + if (pending) return + setFailure(null) + onClose() + } + + async function confirm() { + const client = getSupabaseClient() + if (pending) return + if (!client) return setFailure('unavailable') + setPending(true) + setFailure(null) + try { + await setAnimalArchived(client, animalId, true) + onArchived() + } catch (error) { + setFailure(classifyRecordError(error)) + } finally { + setPending(false) + } + } + + return ( + + {t('animals.archive.body')} +

    + } + size="sm" + > + {failure && ( + + {t(`animals.failure.${failure}`)} + + )} +
    + {/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */} + + +
    +
    + ) +} diff --git a/apps/app/src/components/clients/ClientAnimals.tsx b/apps/app/src/components/clients/ClientAnimals.tsx index 93276547..44ced86b 100644 --- a/apps/app/src/components/clients/ClientAnimals.tsx +++ b/apps/app/src/components/clients/ClientAnimals.tsx @@ -1,98 +1,145 @@ -import { useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' +import { Link } from 'react-router-dom' import { classifyRecordError, - fetchSpeciesLabels, listClientAnimals, type ClientAnimalItem, type RecordFailureKind, type RelationCursor, - type SpeciesLabel, } from '@faunosteo/supabase' import Badge from '@/components/ui/Badge' import Button from '@/components/ui/Button' +import 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 { pickLocaleLabel } from '@/i18n/pickLocaleLabel' import { useLocaleStore } from '@/state/localeStore' import { useT } from '@/i18n/useT' type State = | { status: 'loading' } - | { - status: 'ready' - rows: ClientAnimalItem[] - next: RelationCursor | null - species: SpeciesLabel[] - } + | { status: 'ready'; rows: ClientAnimalItem[]; next: RelationCursor | null } | { status: 'error'; failure: RecordFailureKind } -async function loadPage( - clientId: string, - after: RelationCursor | null, - species: SpeciesLabel[] | null, -) { - const client = getSupabaseClient() - if (!client) throw new TypeError('no backend') - const page = await listClientAnimals(client, clientId, { after }) - // Species names are read only when there is an animal to name. - const labels = - species ?? (page.rows.length ? await fetchSpeciesLabels(client) : []) - return { ...page, species: labels } +/** One animal of the client with every relation of one group (current or former). */ +interface AnimalGroup { + animalId: string + rows: ClientAnimalItem[] } /** - * The client's animals, read-only in V1-1.5 (owner choice 2026-10-26): the - * real relations from list_client_animals, current then former, each with - * its role. No link and no « ajouter » until the animal screens exist. + * 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. */ -export default function ClientAnimals({ clientId }: { clientId: string }) { +function byAnimal(rows: ClientAnimalItem[], current: boolean): AnimalGroup[] { + const groups = new Map() + for (const row of rows.filter((r) => r.is_current === current)) { + const group = groups.get(row.animal_id) + if (group) group.rows.push(row) + else groups.set(row.animal_id, { animalId: row.animal_id, rows: [row] }) + } + return [...groups.values()] +} + +const linkClass = + 'rounded-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2 hover:text-[var(--color-accent)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]' + +export interface ClientAnimalsProps { + clientId: string + workspaceId: string + /** An archived client takes no new relation (contract §7.1): no add, no link. */ + archived: boolean + /** A change made here, announced by the page. */ + onStatus: (message: string) => void +} + +/** + * The client's animals from list_client_animals, current then former, each + * with the client's roles and their dates when known, linked to the animal's + * page. On an active client: « Ajouter un animal » opens the animal form + * with this client pre-associated, « Associer un animal existant » links an + * animal already recorded. + */ +export default function ClientAnimals({ + clientId, + workspaceId, + archived, + onStatus, +}: ClientAnimalsProps) { const t = useT() const locale = useLocaleStore((s) => s.locale) + const { state: species } = useSpecies() + const labels = species.status === 'ready' ? species.labels : [] const [state, setState] = useState({ status: 'loading' }) const [loadingMore, setLoadingMore] = useState(false) + const [panelOpen, setPanelOpen] = useState(false) + const linkButton = useRef(null) + const panelWasOpen = useRef(false) + const generation = useRef(0) - useEffect(() => { - let live = true - loadPage(clientId, null, null) - .then((page) => live && setState({ status: 'ready', ...page })) - .catch( - (error: unknown) => - live && - setState({ status: 'error', failure: classifyRecordError(error) }), - ) - return () => { - live = false + 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() { - if (state.status !== 'ready' || !state.next) return + const client = getSupabaseClient() + if (state.status !== 'ready' || !state.next || !client || loadingMore) + return + const current = generation.current setLoadingMore(true) try { - const page = await loadPage(clientId, state.next, state.species) - setState({ - ...state, - rows: [...state.rows, ...page.rows], - next: page.next, + 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) { - setState({ status: 'error', failure: classifyRecordError(error) }) + if (current === generation.current) + setState({ status: 'error', failure: classifyRecordError(error) }) } finally { setLoadingMore(false) } } - const speciesName = (row: ClientAnimalItem, species: SpeciesLabel[]) => { - const label = species.find((s) => s.id === row.species_id) - const name = label - ? pickLocaleLabel(label.name_fr, label.name_en, locale, row.species_id) - : row.species_id - return row.species_detail ? `${name} (${row.species_detail})` : name - } - const period = (row: ClientAnimalItem) => - [ + 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}', @@ -103,17 +150,12 @@ export default function ClientAnimals({ clientId }: { clientId: string }) { '{date}', formatDate(row.ended_on, locale), ), - ] - .filter(Boolean) - .join(' · ') + ].filter(Boolean) + return [role, ...dates].join(' · ') + } - function group( - rows: ClientAnimalItem[], - species: SpeciesLabel[], - current: boolean, - ) { - const shown = rows.filter((r) => r.is_current === current) - if (!shown.length) return null + function section(groups: AnimalGroup[], current: boolean) { + if (!groups.length) return null const id = current ? 'client-animals-current' : 'client-animals-former' return (
    @@ -124,70 +166,104 @@ export default function ClientAnimals({ clientId }: { clientId: string }) { {t(current ? 'clients.animals.current' : 'clients.animals.former')}
      - {shown.map((row) => ( -
    • - - - {row.animal_name} - {' '} - - {speciesName(row, species)} + {groups.map(({ animalId, rows }) => { + const first = rows[0] + return ( +
    • + + + {first.animal_name} + + + {speciesName( + labels, + first.species_id, + first.species_detail, + locale, + )} + + {first.animal_archived_at && ( + {t('animals.archived_badge')} + )} - {row.animal_archived_at && ( - {t('clients.archived_badge')} - )} - - - {t( - `clients.role.${current ? '' : 'former_'}${row.relation_role}`, - )} - {period(row) && ` · ${period(row)}`} - -
    • - ))} +
        + {rows.map((row) => ( +
      • {roleText(row)}
      • + ))} +
      + + ) + })}
    ) } + const empty = state.status === 'ready' && state.rows.length === 0 + return ( -

    - {t('clients.animals.title')} -

    +
    +

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

    + {!archived && !panelOpen && ( +
    + + {t(empty ? 'clients.animals.add_first' : 'clients.animals.add')} + + +
    + )} +
    {state.status === 'loading' && (

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

    )} {state.status === 'error' && ( - {t(`clients.failure.${state.failure}`)} +
    + {t(`clients.failure.${state.failure}`)} + +
    )} - {state.status === 'ready' && state.rows.length === 0 && ( + {empty && (

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

    )} {state.status === 'ready' && ( <> - {group(state.rows, state.species, true)} - {group(state.rows, state.species, false)} + {section(byAnimal(state.rows, true), true)} + {section(byAnimal(state.rows, false), false)} {state.next && ( + ) + return ( +
  • +
    + + + {r.client.display_name} + + {r.client.archived_at && ( + {t('clients.archived_badge')} + )} + + + {roleLabel(r)} + {period(r) && ` · ${period(r)}`} + +
    + {r.client.phone && ( + + {r.client.phone} + + )} + {editable && ( +
    + {r.ended_at === null && action('end', 'relations.end.action')} + {action('dates', 'relations.dates.action')} + {action('void', 'relations.void.action')} +
    + )} +
  • + ) + } + + function group(rows: AnimalRelationItem[], key: string, id: string) { + if (!rows.length) return null + return ( +
    +

    + {t(key)} +

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

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

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

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

    + )} + {state.status === 'error' && ( +
    + + {t(`relations.failure.${state.failure}`)} + + +
    + )} + {stale && {t(`relations.failure.${stale}`)}} + {groups && !groups.hasOwner && ( +

    + {t('animals.no_owner')} +

    + )} + {groups && groups.current.length + groups.former.length === 0 && ( +

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

    + )} + {groups && + group(groups.current, 'relations.current', 'animal-relations-current')} + {groups && + group(groups.former, 'relations.former', 'animal-relations-former')} + {panelOpen && ( + setPanelOpen(false)} + onSaved={async () => { + await reload() + setStale(null) + onStatus(t('relations.added_client')) + setPanelOpen(false) + }} + /> + )} + {target?.action === 'end' && ( + handlers.onDone(t('relations.end.done'))} + /> + )} + {target?.action === 'dates' && ( + handlers.onDone(t('relations.dates.done'))} + /> + )} + {target?.action === 'void' && ( + handlers.onDone(t('relations.void.done'))} + /> + )} +
    + ) +} diff --git a/apps/app/src/components/relations/Pickers.tsx b/apps/app/src/components/relations/Pickers.tsx new file mode 100644 index 00000000..030d66c7 --- /dev/null +++ b/apps/app/src/components/relations/Pickers.tsx @@ -0,0 +1,78 @@ +import type { AnimalListItem, ClientListItem } from '@faunosteo/supabase' +import RecordPicker from './RecordPicker' +import { speciesName, useSpecies } from '@/animals/species' +import { useAnimalChoices, useClientChoices } from '@/relations/choices' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +/** The record a picker handed over: its id and the name to show. */ +export interface Chosen { + id: string + name: string +} + +/** A client of the workspace, active only, found by the server search. */ +export function ClientPicker(props: { + id: string + workspaceId: string + error?: string + onChoose: (chosen: Chosen) => void +}) { + const t = useT() + const search = useClientChoices(props.workspaceId) + return ( + + id={props.id} + label={t('relations.picker.client_label')} + hint={t('relations.picker.client_hint')} + resultsLabel={t('relations.picker.client_results')} + emptyLabel={t('relations.picker.client_none')} + search={search} + toItem={(row) => ({ + id: row.id, + name: row.display_name, + detail: [t(`clients.kind.${row.kind}`), row.city] + .filter(Boolean) + .join(' · '), + })} + onChoose={(row) => props.onChoose({ id: row.id, name: row.display_name })} + error={props.error} + /> + ) +} + +/** An animal of the workspace, active only, found by the server search. */ +export function AnimalPicker(props: { + id: string + workspaceId: string + error?: string + onChoose: (chosen: Chosen) => void +}) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const { state: species } = useSpecies() + const labels = species.status === 'ready' ? species.labels : [] + const search = useAnimalChoices(props.workspaceId) + return ( + + id={props.id} + label={t('relations.picker.animal_label')} + hint={t('relations.picker.animal_hint')} + resultsLabel={t('relations.picker.animal_results')} + emptyLabel={t('relations.picker.animal_none')} + search={search} + toItem={(row) => ({ + id: row.id, + name: row.name, + detail: [ + speciesName(labels, row.species_id, row.species_detail, locale), + row.breed, + ] + .filter(Boolean) + .join(' · '), + })} + onChoose={(row) => props.onChoose({ id: row.id, name: row.name })} + error={props.error} + /> + ) +} diff --git a/apps/app/src/components/relations/RecordPicker.tsx b/apps/app/src/components/relations/RecordPicker.tsx new file mode 100644 index 00000000..e189339e --- /dev/null +++ b/apps/app/src/components/relations/RecordPicker.tsx @@ -0,0 +1,159 @@ +import { useEffect, useRef, useState } from 'react' +import { + classifyRecordError, + type RecordFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import FormField from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { SEARCH_DELAY_MS } from '@/clients/useClientList' +import { useT } from '@/i18n/useT' + +export interface PickerItem { + id: string + name: string + /** One muted line under the name: kind and city, or species and breed. */ + detail: string +} + +export interface RecordPickerProps { + id: string + label: string + hint: string + /** Accessible name of the result list. */ + resultsLabel: string + emptyLabel: string + /** The server search (POST): the term never reaches a URL. Stable across renders. */ + search: (term: string) => Promise + /** How a row reads, computed at render so a change of language needs no new search. */ + toItem: (row: Row) => PickerItem + onChoose: (row: Row) => void + /** The field's own error (« choisissez un client »). */ + error?: string +} + +type Results = + | { status: 'loading' } + | { status: 'ready'; items: Row[] } + | { status: 'error'; failure: RecordFailureKind } + +/** + * Finds one record to link through the server search, the active records + * only: a search field, then the first matches as buttons named by the + * record. No local copy of the records; an answer to an older term is + * dropped. Choosing hands the item to the parent, which replaces the picker. + */ +export default function RecordPicker({ + id, + label, + hint, + resultsLabel, + emptyLabel, + search, + toItem, + onChoose, + error, +}: RecordPickerProps) { + const t = useT() + const [query, setQuery] = useState('') + const [term, setTerm] = useState('') + const [results, setResults] = useState>({ status: 'loading' }) + const [attempt, setAttempt] = useState(0) + const generation = useRef(0) + + useEffect(() => { + const timer = setTimeout(() => setTerm(query.trim()), SEARCH_DELAY_MS) + return () => clearTimeout(timer) + }, [query]) + + useEffect(() => { + const current = ++generation.current + setResults({ status: 'loading' }) + search(term) + .then((items) => { + if (current === generation.current) + setResults({ status: 'ready', items }) + }) + .catch((failure: unknown) => { + if (current === generation.current) + setResults({ + status: 'error', + failure: classifyRecordError(failure), + }) + }) + }, [search, term, attempt]) + + const describedBy = error ? `${id}-error` : `${id}-hint` + + return ( +
    + + setQuery(e.target.value)} + maxLength={100} + autoComplete="off" + aria-invalid={Boolean(error)} + aria-describedby={describedBy} + /> + + {results.status === 'loading' && ( +

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

    + )} + {results.status === 'error' && ( +
    + + {t(`relations.failure.${results.failure}`)} + + +
    + )} + {results.status === 'ready' && results.items.length === 0 && ( +

    + {emptyLabel} +

    + )} + {results.status === 'ready' && results.items.length > 0 && ( +
      + {results.items.map((row) => { + const item = toItem(row) + return ( +
    • + +
    • + ) + })} +
    + )} +
    + ) +} diff --git a/apps/app/src/components/relations/RelationActionDialog.tsx b/apps/app/src/components/relations/RelationActionDialog.tsx new file mode 100644 index 00000000..ce7e569b --- /dev/null +++ b/apps/app/src/components/relations/RelationActionDialog.tsx @@ -0,0 +1,123 @@ +import { useState, type ReactNode } from 'react' +import { + classifyRecordError, + type RecordFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import Notice from '@/components/ui/Notice' +import { useT } from '@/i18n/useT' + +export interface RelationActionHandlers { + onClose: () => void + /** After a success: the page reloads the relations, announces, then closes the dialog. */ + onDone: () => Promise + /** + * The relation changed or left elsewhere (`conflict`, `not_found`): the page + * reloads and says so, then closes the dialog; the stale row is never retried. + */ + onStale: (failure: RecordFailureKind) => Promise +} + +export interface RelationActionDialogProps extends RelationActionHandlers { + title: string + /** Which relation: « Marie Dupont · Propriétaire ». */ + relationLabel: string + body: string + confirmLabel: string + pendingLabel: string + danger?: boolean + children?: ReactNode + /** Checks the fields; false keeps the dialog open with their errors. */ + validate?: () => boolean + /** The relation RPC; throws a RecordFailure. */ + action: () => Promise +} + +/** + * Confirmation of one relation write (end, dates, void) on the shared + * ModalDialog: closing is never confirming; while the write and the reload + * that shows it run, the dialog refuses to close, so focus returns once, + * after the change is on the page (to the opener, or to its container when + * the opener left with the row). Other failures stay in the dialog with the + * values typed. + */ +export default function RelationActionDialog({ + title, + relationLabel, + body, + confirmLabel, + pendingLabel, + danger = false, + children, + validate, + action, + onClose, + onDone, + onStale, +}: RelationActionDialogProps) { + const t = useT() + const [pending, setPending] = useState(false) + const [failure, setFailure] = useState(null) + + const close = () => { + if (!pending) onClose() + } + + async function confirm() { + if (pending || (validate && !validate())) return + setPending(true) + setFailure(null) + try { + await action() + await onDone() + } catch (error) { + const kind = classifyRecordError(error) + if (kind === 'conflict' || kind === 'not_found') await onStale(kind) + else setFailure(kind) + } finally { + setPending(false) + } + } + + return ( + +

    {relationLabel}

    +

    {body}

    +
    + } + size="sm" + > +
    + {children} + {failure && ( + {t(`relations.failure.${failure}`)} + )} +
    +
    + {/* Not disabled while pending: a button that turns disabled drops the focus out of the dialog. */} + + +
    +
    + ) +} diff --git a/apps/app/src/components/relations/RelationDialogs.tsx b/apps/app/src/components/relations/RelationDialogs.tsx new file mode 100644 index 00000000..d4684f94 --- /dev/null +++ b/apps/app/src/components/relations/RelationDialogs.tsx @@ -0,0 +1,211 @@ +import { useState } from 'react' +import { + endAnimalClientRelation, + updateAnimalClientRelation, + voidAnimalClientRelation, + type AnimalRelationItem, +} from '@faunosteo/supabase' +import FormField from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import RelationActionDialog, { + type RelationActionHandlers, +} from './RelationActionDialog' +import { recordDateIssue } from '@/animals/validation' +import { localDateIso } from '@/lib/dates' +import { getSupabaseClient } from '@/lib/supabase' +import { translateFieldError } from '@/account/validation' +import { useT } from '@/i18n/useT' + +interface RelationDialogProps extends RelationActionHandlers { + relation: AnimalRelationItem + /** « Marie Dupont · Propriétaire ». */ + relationLabel: string +} + +function backend() { + const client = getSupabaseClient() + if (!client) throw new TypeError('no backend') + return client +} + +/** The issue of an end date: a record date, and not before a known start. */ +function endIssue(endedOn: string, startedOn: string, today: string) { + const issue = recordDateIssue(endedOn, today) + if (issue) return issue + return startedOn && endedOn && endedOn < startedOn + ? 'relations.error.end_before_start' + : null +} + +function DateField(props: { + id: string + label: string + value: string + error: string | null + today: string + onChange: (value: string) => void +}) { + const t = useT() + return ( + + props.onChange(e.target.value)} + aria-invalid={Boolean(props.error)} + aria-describedby={ + props.error ? `${props.id}-error` : `${props.id}-hint` + } + /> + + ) +} + +/** Ends a current relation, with its real end date when known (N5: never invented). */ +export function EndRelationDialog({ + relation, + relationLabel, + ...handlers +}: RelationDialogProps) { + const t = useT() + const today = localDateIso() + const [endedOn, setEndedOn] = useState('') + const [error, setError] = useState(null) + return ( + { + const issue = endIssue(endedOn, relation.started_on ?? '', today) + setError(issue) + if (issue) document.getElementById('relation-ended-on')?.focus() + return issue === null + }} + action={() => + endAnimalClientRelation(backend(), { + relationId: relation.id, + expectedRevision: relation.revision, + endedOn: endedOn || null, + }) + } + > + + + ) +} + +/** Corrects the start date, and the end date of an ended relation; client and role never change. */ +export function RelationDatesDialog({ + relation, + relationLabel, + ...handlers +}: RelationDialogProps) { + const t = useT() + const today = localDateIso() + const ended = relation.ended_at !== null + const [startedOn, setStartedOn] = useState(relation.started_on ?? '') + const [endedOn, setEndedOn] = useState(relation.ended_on ?? '') + const [errors, setErrors] = useState<{ + start: string | null + end: string | null + }>({ start: null, end: null }) + return ( + { + const start = recordDateIssue(startedOn, today) + const end = ended ? endIssue(endedOn, startedOn, today) : null + setErrors({ start, end }) + const first = start + ? 'relation-started-on' + : end + ? 'relation-ended-on' + : null + if (first) document.getElementById(first)?.focus() + return !start && !end + }} + action={() => + updateAnimalClientRelation(backend(), { + relationId: relation.id, + expectedRevision: relation.revision, + startedOn: startedOn || null, + endedOn: ended ? endedOn || null : null, + }) + } + > + + {ended && ( + + )} + + ) +} + +/** + * Voids a relation entered by mistake (N4): it disappears from every page + * and list, is kept frozen for the record lifecycle, and cannot come back. + * The text says when to use « Terminer » instead. + */ +export function VoidRelationDialog({ + relation, + relationLabel, + ...handlers +}: RelationDialogProps) { + const t = useT() + return ( + + voidAnimalClientRelation(backend(), { + relationId: relation.id, + expectedRevision: relation.revision, + }) + } + /> + ) +} diff --git a/apps/app/src/components/relations/RelationPanel.tsx b/apps/app/src/components/relations/RelationPanel.tsx new file mode 100644 index 00000000..cef60fc7 --- /dev/null +++ b/apps/app/src/components/relations/RelationPanel.tsx @@ -0,0 +1,237 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react' +import { + classifyRecordError, + createAnimalClientRelation, + type AnimalRelationRole, + type RecordFailureKind, +} from '@faunosteo/supabase' +import Button from '@/components/ui/Button' +import ChoiceRadios, { firstChoiceId } from '@/components/ui/ChoiceRadios' +import FormField from '@/components/ui/FormField' +import Input from '@/components/ui/Input' +import Notice from '@/components/ui/Notice' +import { AnimalPicker, ClientPicker, type Chosen } from './Pickers' +import { useLeaveGuard } from '@/app/useLeaveGuard' +import { + RELATION_ROLES, + relationIssues, + type RelationFieldErrors, +} from '@/animals/validation' +import { generateUuid } from '@/lib/id' +import { localDateIso } from '@/lib/dates' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' +import { translateFieldError } from '@/account/validation' + +export type RelationPanelProps = { + workspaceId: string + /** Called once the server made the relation; the page reloads, then closes the panel. */ + onSaved: () => Promise + onCancel: () => void +} & ( + | { pick: 'client'; animalId: string } + | { pick: 'animal'; clientId: string } +) + +const PANEL = 'relation-panel' +const FIELD_IDS = { + client: `${PANEL}-search`, + relation_role: firstChoiceId(`${PANEL}-role`, 'owner'), + started_on: `${PANEL}-started-on`, +} as const + +/** + * Links a client and an animal from one of their pages, inside the page (no + * modal form, contract §11.4): find the other record, pick the role (none + * preselected), the start date when known. One request id per opening of + * the panel, sent again on a retry, so a lost answer never makes a second + * relation. Both records must be active; the server says so otherwise. + */ +export default function RelationPanel(props: RelationPanelProps) { + const t = useT() + const heading = useRef(null) + const chosenText = useRef(null) + const [chosen, setChosen] = useState(null) + const [role, setRole] = useState('') + const [startedOn, setStartedOn] = useState('') + const [errors, setErrors] = useState({}) + const [errorRound, setErrorRound] = useState(0) + const [pending, setPending] = useState(false) + const [failure, setFailure] = useState(null) + const [requestId] = useState(generateUuid) + const inFlight = useRef(false) + const today = localDateIso() + useLeaveGuard(Boolean(chosen || role || startedOn)) + + useEffect(() => heading.current?.focus(), []) + useEffect(() => { + if (chosen) chosenText.current?.focus() + }, [chosen]) + useEffect(() => { + if (errorRound === 0) return + const first = (Object.keys(FIELD_IDS) as (keyof typeof FIELD_IDS)[]).find( + (key) => errors[key], + ) + if (first) document.getElementById(FIELD_IDS[first])?.focus() + }, [errorRound, errors]) + + async function submit(event: FormEvent) { + event.preventDefault() + if (inFlight.current) return + const issues = relationIssues( + { + client: chosen && { id: chosen.id, display_name: chosen.name }, + relation_role: role, + started_on: startedOn, + }, + localDateIso(), + true, + ) + setErrors(issues) + if (Object.keys(issues).length > 0 || !chosen || role === '') { + setErrorRound((n) => n + 1) + return + } + const client = getSupabaseClient() + if (!client) return setFailure('unavailable') + inFlight.current = true + setPending(true) + setFailure(null) + try { + await createAnimalClientRelation(client, { + animalId: props.pick === 'client' ? props.animalId : chosen.id, + clientId: props.pick === 'client' ? chosen.id : props.clientId, + requestId, + relationRole: role, + startedOn: startedOn || null, + }) + await props.onSaved() + } catch (error) { + setFailure(classifyRecordError(error)) + } finally { + inFlight.current = false + setPending(false) + } + } + + const err = (key: keyof RelationFieldErrors) => + translateFieldError(t, errors[key]) + const pickLabel = + props.pick === 'client' + ? 'relations.panel.client_chosen' + : 'relations.panel.animal_chosen' + + return ( +
    +

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

    + {chosen ? ( +
    +

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

    + +
    + ) : props.pick === 'client' ? ( + + ) : ( + + )} + ({ + value, + label: t(`clients.role.${value}`), + }))} + value={role} + onChange={setRole} + error={err('relation_role')} + /> + + setStartedOn(e.target.value)} + aria-invalid={Boolean(errors.started_on)} + aria-describedby={ + errors.started_on + ? `${FIELD_IDS.started_on}-error` + : `${FIELD_IDS.started_on}-hint` + } + className="sm:max-w-xs" + /> + + {failure && ( + {t(`relations.failure.${failure}`)} + )} +
    + + +
    + + ) +} diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx index 9cc46a5f..ac0eebc2 100644 --- a/apps/app/src/components/shell/SidebarNav.tsx +++ b/apps/app/src/components/shell/SidebarNav.tsx @@ -13,6 +13,7 @@ interface NavItem { export const NAV_ITEMS: readonly NavItem[] = [ { to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true }, { to: '/app/clients', icon: 'users', labelKey: 'shell.nav.clients' }, + { to: '/app/animals', icon: 'paw', labelKey: 'shell.nav.animals' }, { to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' }, { to: '/', diff --git a/apps/app/src/components/ui/Button.tsx b/apps/app/src/components/ui/Button.tsx index a5c1a3da..c7cdb8ef 100644 --- a/apps/app/src/components/ui/Button.tsx +++ b/apps/app/src/components/ui/Button.tsx @@ -1,9 +1,11 @@ -import type { ButtonHTMLAttributes, ReactNode } from 'react' +import type { ButtonHTMLAttributes, ReactNode, Ref } from 'react' export interface ButtonProps extends ButtonHTMLAttributes { variant?: 'primary' | 'secondary' | 'ghost' | 'danger' size?: 'sm' | 'md' | 'lg' children?: ReactNode + /** React 19 passes it as a prop; it reaches the