From a6346105f16250a1ff9dde4b32b5b20e5236612b Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 25 Oct 2026 19:15:35 +0100 Subject: [PATCH] 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.