Merge feature/step-04-anatomical-sheet-model into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s
This commit is contained in:
commit
1cc70c3589
37 files changed
+4762
-36
No files matched your search
@@ -58,3 +58,12 @@ Friction: `supabase start` → "permission denied … /var/run/docker.sock"; dae
|
|||||||
Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude).
|
Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude).
|
||||||
Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect).
|
Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect).
|
||||||
Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK.
|
Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BLK-007 | 2026-10-08 | Per-schema ALTER DEFAULT PRIVILEGES REVOKE is a no-op → private helpers kept PUBLIC EXECUTE
|
||||||
|
|
||||||
|
Friction: Step 4 verifier + security gate both found every `private.*` function executable by `authenticated` (incl. definer helpers taking a caller-supplied actor: assign_platform_role, insert_sheet_draft).
|
||||||
|
Root: foundation ran `alter default privileges in schema private revoke execute on functions from public`; PostgreSQL adds per-schema defaults on top of the built-in PUBLIC EXECUTE, a per-schema REVOKE cannot remove it. Nothing reachable via API (PostgREST exposes public only, anon no USAGE on private) but the rule "EXECUTE revoked from public" was false.
|
||||||
|
Fix: explicit `revoke all on function private.f(args) from public` for every function (new migration 20261008110100 for the Step 3 helpers, inline for Step 4); pgTAP 001 census: anon executes nothing in private/audit, authenticated only the 7 policy predicates.
|
||||||
|
Status: resolved (commit on feature/step-04-anatomical-sheet-model).
|
||||||
@@ -255,3 +255,27 @@ Status: closed.
|
|||||||
|
|
||||||
CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). `schema-types.test.ts`: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no `using(true)` for every future public table. CI `db:types:check` diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit.
|
CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). `schema-types.test.ts`: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no `using(true)` for every future public table. CI `db:types:check` diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit.
|
||||||
Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed.
|
Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BDR-030 | 2026-10-08 | Step 4 split: model + persistence now, importer → official equine DRAFT next
|
||||||
|
|
||||||
|
User brief: no full equine import yet; first official horse sheet = draft, business content verified before publication. Plan Step 4 bundled model + importer. Split: Step 4 = packages/domain document + validation + migration + pgTAP + docs; Step 4b = legacy importer → draft + IMPORT-REPORT, publish on user go. packages/anatomy created at 4b.
|
||||||
|
Alt rejected: importer in same step → publishes seed v1 immutable before expert review (contradicts brief).
|
||||||
|
Status: closed (plan note added under Step 4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BDR-031 | 2026-10-08 | Canonical sheet document shape (schema_version 1)
|
||||||
|
|
||||||
|
Labels `{ fr, en }` objects (one LocalizedText, new locale = optional key) instead of name_fr/name_en pairs. Strict Zod objects (unknown key rejected). Structural records explicit `null`; finding tree nodes lean on input, `.default()` fills description/sources/children/requires_vet_referral (612 leaves). Views = tree (`parent_view_id`), detail `svg_asset_id` nullable = crop parent via `view_box` (C9). Annotation discriminated union point|zone|detail_trigger; `laterality` 4 values explicit (unpaired/bilateral/left/right); spine = `vertebral_region_code` → ordered `vertebral_config.regions` with free codes (C1/Q3); findings link = inline `finding_zone_id` (no separate map, no label matching); finding categories carry `kind` dysfunction|observation|anamnesis|custom; node ids unique among siblings so `(zone, path[])` addressing survives Step 5. Two tiers: shape (Zod, every save) vs integrity (`validateSheetDocument`, 17 coded rules, publish gate).
|
||||||
|
Alt rejected: name_fr/name_en flat (BDR-009 catalog style) → no locale extension; annotation_finding_map array → extra structure for a 1:N field; UUIDs as in-document ids → unreadable, legacy paths re-keyed.
|
||||||
|
Status: closed; category kind `observation` vs report Observation collision (C7) flagged to user.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## BDR-032 | 2026-10-08 | Sheet persistence: trigger-enforced immutability, SQL publish re-check, content-addressed assets
|
||||||
|
|
||||||
|
Tables species / anatomical_sheets / _versions / _assets. Published immutable via BEFORE UPDATE trigger (every role incl. owner; only published→deprecated with stamps); deprecated frozen; BEFORE DELETE trigger = preconditions (never published, never current, never base of active fork; reports join later) → no session flags, RPC just deletes. One draft per sheet (partial unique index, C8). Document↔row: CHECK `content->'schema_version' = to_jsonb(document_schema_version)`, trigger species match. `private.sheet_document_issues(jsonb)` re-checks the non-recursive error rules at publish + unknown asset ids → defense in depth, same codes as TS (BACKEND_ARCH "SQL doesn't re-implement Zod" kept for shape). Assets content-addressed (sha256, unique per sheet), Storage path `<sha256>.svg` by convention, fork = metadata copy + `remap_document_assets`. Draft autosave = column-level UPDATE (content, change_note) policy on own draft (unaudited by design); identity (name/slug/description) column policy; visibility via audited `set_sheet_visibility` RPC and draft deletion via `delete_sheet_version` after gate review (sharing + deletion = sensitive state); `last_version_number` counter (no number reuse); content ≤ 2 MiB, byte_size ≤ 20 MiB, reason ≤ 500; `require_actor` refuses deactivated profiles; authz before lookup (unknown id = same 42501); fork copies only referenced assets. can_use_sheet = active ∧ (public ∨ editor) until grants/follows. Official sheet = creator null + is_official, platform admins edit.
|
||||||
|
Alt rejected: session-flag delete bypass (hacky); Zod-equivalent validation only in TS (browser not a boundary); per-sheet asset storage copy on fork (needs worker job).
|
||||||
|
Status: closed; names (`anatomical_sheet_assets`, storage layout, official ownership) listed for user confirmation.
|
||||||
@@ -56,3 +56,11 @@ Method: `supabase start` (postgres 17.11.0.004), `supabase test db`, `gen types
|
|||||||
Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant.
|
Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant.
|
||||||
Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap.
|
Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap.
|
||||||
Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved.
|
Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved.
|
||||||
|
|
||||||
|
## EVAL-008 | 2026-10-08 | Step 4 sheet model — domain tests, pgTAP both engines, fresh verifier + security gates
|
||||||
|
|
||||||
|
Method: packages/domain 61 vitest (schema 29 + integrity 32, one per rule code); pgTAP 005 (127 checks) + 001 census on PGlite and real stack (`db reset`, `db test` 210/210, `gen types` diff clean); root check (typecheck, 356 tests, lint 0, build); fresh verifier (contract C1–C13) + security-auditor (semgrep 725 rules 0 findings + checklist).
|
||||||
|
Result: first gate pass → verifier ECARTS(5), security BLOCK(1): private EXECUTE not revoked (BLK-007), visibility change unaudited, 7 RPCs without non-editor denial test, doc/code mismatches, 75-line SQL function, `any` suppression in a test. All fixed same session: +32 pgTAP checks, hardening migration, visibility RPC, caps, authz-first, SQL check split in 4 functions, `set()/unset()` typed mutations. Second pass: fresh verifier (pending at write time).
|
||||||
|
Anomalies: 6 test-side fixes on first pgTAP run (RLS hides rows → "no change" asserts; data-modifying CTE; collation of `order by`; trigger name order decides errcode; audit list; pg_temp grants). Executor (opus) deviated usefully: RegionCode pattern separate from StableId.
|
||||||
|
Action: LRN-038/039/040, BLK-007. Keep the two-gate pass on every migration step.
|
||||||
|
|
||||||
@@ -178,3 +178,5 @@ SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domai
|
|||||||
Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof.
|
Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof.
|
||||||
- Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish.
|
- Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish.
|
||||||
- Step 3 validated by user (session 4). chore/supabase-cli-gitignore finished into develop. Step 4 (sheet model) started on feature/step-04-anatomical-sheet-model.
|
- Step 3 validated by user (session 4). chore/supabase-cli-gitignore finished into develop. Step 4 (sheet model) started on feature/step-04-anatomical-sheet-model.
|
||||||
|
- Step 4 (session 4): spec docs/development/ANATOMICAL_SHEET_MODEL.md; packages/domain (Zod doc strict, 17 integrity rules, 60 tests, opus executor); migration 20261008110000 (species, sheets, immutable versions, assets, 11 RPCs, RLS) + pgTAP 005 (95 checks); types regenerated on real stack (Docker now OK), pgTAP 176/176 real + PGlite; publishSheetVersion gate; docs synced. 5 commits on feature/step-04-anatomical-sheet-model. BDR-030/031/032, LRN-038/039. Verifier + security gates dispatched. Next: user validation, Step 4b importer → equine draft.
|
||||||
|
- Gates: verifier ECARTS(5) + security BLOCK(1) on first pass (private EXECUTE never revoked = BLK-007, foundation flaw). Fixed: hardening migration 20261008110100, explicit revokes + pgTAP census, set_sheet_visibility RPC, no direct draft DELETE, caps, authz-first, counter, asset copy scoped, SQL check split, url http(s) only. Real stack 210/210, root check green. Fresh verifier re-dispatched on the delta.
|
||||||
@@ -288,3 +288,24 @@ Apply: every migration; pin with pgTAP privilege checks.
|
|||||||
|
|
||||||
Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps.
|
Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps.
|
||||||
Apply: any dual-runner test setup (shim vs real); any CI diff on generated code.
|
Apply: any dual-runner test setup (shim vs real); any CI diff on generated code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRN-038 | 2026-10-08 | RLS filters, never raises: test "no change", and trigger guards under the owner role
|
||||||
|
|
||||||
|
API-role UPDATE/DELETE on a row hidden by policy touches 0 rows silently → `throws_ok` wrong; assert the row unchanged afterwards (`is((select content ...), expected)`). Trigger-level immutability must be proven with `reset role` (table owner bypasses RLS). pgTAP `is()` cannot wrap a data-modifying CTE (`with u as (update …)` must be top level) → plain statement then a read. Triggers fire alphabetically by name: when two BEFORE triggers reject, the first name's errcode surfaces (species check 23514 before guard 42501) → pick test inputs that isolate the guard.
|
||||||
|
Apply: every RLS + trigger pgTAP file.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRN-039 | 2026-10-08 | Dual-runner parity: pin collation, grant pg_temp fixtures to API roles
|
||||||
|
|
||||||
|
Real Supabase image sorts text with a locale collation (`anatomical_sheet_asset…` before `anatomical_sheet.archived`), PGlite with C → `results_eq` on `order by text` flaps; pin `order by col collate "C"`. pg_temp tables/functions created as postgres are invisible to `set local role authenticated` → `grant all on pg_temp.t to anon, authenticated; grant execute on function pg_temp.f(...)`. jsonb equality check beats `(x->>'k')::int = n` in a CHECK (no cast error on garbage).
|
||||||
|
Apply: any pgTAP file with fixtures read while impersonating; any ordered results_eq (extends LRN-037).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## LRN-040 | 2026-10-08 | Function privileges: revoke per function, pin with a pg_proc census
|
||||||
|
|
||||||
|
`alter default privileges in schema X revoke execute on functions from public` does nothing (BLK-007). Pattern: every migration ends with `revoke all on function private.f(args) from public` per function + explicit grants; a pgTAP census (`has_function_privilege('anon'|'authenticated', p.oid, 'execute')` over pg_proc of private/audit, compared to an allowlist via `string_agg(... order by proname::text collate "C")`) fails the next omission. `results_eq` over `name`-typed columns vs text literals raises "could not determine which collation" on PGlite → compare one aggregated string. Trigger functions that call other private functions must be `security definer` once EXECUTE is revoked (the invoking API role no longer holds it).
|
||||||
|
Apply: every Supabase migration; the census is the backstop.
|
||||||
@@ -61,7 +61,15 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
|
|||||||
- [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r
|
- [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r
|
||||||
- [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer
|
- [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer
|
||||||
- [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006
|
- [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006
|
||||||
- [ ] Step 4 — sheet model + importer (next, on validation; ∥ Step 3 per plan)
|
- [ ] Step 4 — canonical anatomical sheet model (2026-10-08, branch feature/step-04-anatomical-sheet-model). Scope re-split: model + validation + persistence + tests here; legacy importer → official equine DRAFT + import report = next step (user: no full import yet, draft verified before publication). Spec: docs/development/ANATOMICAL_SHEET_MODEL.md
|
||||||
|
- [x] 4.0 context + spec: business §2.6–2.9/§7/§16/§17.3/§23, OPEN_QUESTIONS C1/C2/C8/C9/Q3/Q5/Q9, audit 07; ANATOMICAL_SHEET_MODEL.md written
|
||||||
|
- [x] 4.1 packages/domain: AnatomicalSheetDocumentSchema (strict, localized {fr,en}, views tree, annotations union, finding tree with category kind), validateSheetDocument (integrity issues), assertPublishable, createEmptySheetDocument; fixture horse-slice; tests per rule + id-stability
|
||||||
|
- [x] 4.2 migration 20261008110000_anatomical_sheets: species (seed equine), enums, sheets/versions/assets, triggers (one draft, published immutable, delete preconditions, species match), helpers can_edit/can_use_sheet, sheet_document_issues, lifecycle RPCs (create/draft/publish/deprecate/delete/fork/archive/restore/delete sheet/register asset), privileges + RLS
|
||||||
|
- [x] 4.3 pgTAP 005_anatomical_sheets.sql: schema/privileges, lifecycle allowed path, immutability, fork provenance, deletion preconditions, denied paths (other user, anon, direct writes, official), invalid document refused at publish
|
||||||
|
- [x] 4.4 packages/supabase: database.types.ts regenerated (real stack), schema-types test extended (tables, enums list, functions); index.ts row aliases; publishSheetVersion service (domain validation before RPC) + test
|
||||||
|
- [x] 4.5 docs: SUPABASE.md layout/tests, CLAUDE.md folder map + conventions + scopes, packages/README, IMPLEMENTATION_PLAN Step 4 adjustment note, CHANGELOG
|
||||||
|
- [x] 4.6 verify: pnpm check green (61+17+278), db:reset + db:test 210/210 real stack, types in sync; verifier ECARTS(5) + security BLOCK(1) → all fixed (BLK-007 hardening migration, visibility RPC, +32 pgTAP, doc sync); BDR-030..032, LRN-038..040, EVAL-008
|
||||||
|
- [ ] Step 4b — legacy importer → official equine sheet as DRAFT (document.json + legacy-id-map + IMPORT-REPORT.md for business verification), publication after user validation
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ Versions follow [Semantic Versioning](https://semver.org/).
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added (SaaS migration, plan Steps 3–4)
|
||||||
|
|
||||||
|
- **Supabase foundation** — local stack (`supabase/config.toml`), migrations (schemas `private` / `audit`, `profiles`, platform roles with audited RPCs), pgTAP suite run on PGlite (`pnpm test:run`) and on the real stack (`pnpm db:test`), `@faunosteo/supabase` typed client + generated types. No UI change.
|
||||||
|
- **Anatomical sheet model** — `@faunosteo/domain`: canonical sheet document (views tree, annotations with stable ids and explicit laterality, ordered vertebral regions, typed finding categories, explicit annotation → finding zone links, FR/EN labels) with integrity validation; tables `species`, `anatomical_sheets`, `anatomical_sheet_versions` (published rows immutable, one draft per sheet, deletion preconditions), `anatomical_sheet_assets`; lifecycle RPCs (create, draft, publish, deprecate, delete, fork with provenance, archive, assets) audited and under RLS. Spec: `docs/development/ANATOMICAL_SHEET_MODEL.md`.
|
||||||
|
|
||||||
### Changed (SaaS migration, plan Step 2)
|
### Changed (SaaS migration, plan Step 2)
|
||||||
|
|
||||||
- **pnpm workspace** — the application moved to `apps/app` (`@faunosteo/app`) with `git mv`; root commands (`pnpm typecheck|test:run|lint|build|dev`) delegate to the packages. `packages/` reserved, empty. CI workflow added (`.gitea/workflows/ci.yml`).
|
- **pnpm workspace** — the application moved to `apps/app` (`@faunosteo/app`) with `git mv`; root commands (`pnpm typecheck|test:run|lint|build|dev`) delegate to the packages. `packages/` reserved, empty. CI workflow added (`.gitea/workflows/ci.yml`).
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ writes conclusion, and exports an A4 PDF. PDF carries the full JSON state as a n
|
|||||||
attachment so importing it restores the session for a follow-up.
|
attachment so importing it restores the session for a follow-up.
|
||||||
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
|
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
|
||||||
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
|
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
|
||||||
audit log exist; the UI does not use the client yet (local-only flows unchanged).
|
audit log exist; Step 4 added the canonical anatomical sheet model (`packages/domain`,
|
||||||
|
tables `species`, `anatomical_sheets` / `_versions` / `_assets`). The UI does not use
|
||||||
|
the client yet (local-only flows unchanged).
|
||||||
MVP species: equine only. Open-source MIT.
|
MVP species: equine only. Open-source MIT.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -43,8 +45,9 @@ MVP species: equine only. Open-source MIT.
|
|||||||
|
|
||||||
## Build commands
|
## Build commands
|
||||||
|
|
||||||
pnpm workspace: `apps/app` = the private application, `packages/supabase` =
|
pnpm workspace: `apps/app` = the private application, `packages/domain` = pure
|
||||||
Supabase access layer (see `docs/development/WORKSPACE.md`). Every command
|
Zod domain model (anatomical sheet document), `packages/supabase` = Supabase
|
||||||
|
access layer (see `docs/development/WORKSPACE.md`). Every command
|
||||||
below runs from the repository root and delegates to the packages.
|
below runs from the repository root and delegates to the packages.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -192,12 +195,15 @@ faunosteo/
|
|||||||
├─ eslint.config.js, index.html, package.json (@faunosteo/app)
|
├─ eslint.config.js, index.html, package.json (@faunosteo/app)
|
||||||
├─ tsconfig*.json, vite.config.ts, vitest.config.ts
|
├─ tsconfig*.json, vite.config.ts, vitest.config.ts
|
||||||
│ (end of apps/app)
|
│ (end of apps/app)
|
||||||
|
├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only)
|
||||||
|
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
|
||||||
|
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
|
||||||
├─ packages/supabase/ ← @faunosteo/supabase
|
├─ packages/supabase/ ← @faunosteo/supabase
|
||||||
│ ├─ src/{index,client,database.types}.ts ← typed browser client + generated types
|
│ ├─ src/{index,client,database.types,anatomical-sheets}.ts ← typed client, generated types, publish gate
|
||||||
│ └─ tests/{client.test.ts,db/} ← PGlite harness, shim, pgTAP runner, schema↔types test
|
│ └─ tests/{client,anatomical-sheets}.test.ts, tests/db/ ← PGlite harness, shim, pgTAP runner, schema↔types test
|
||||||
├─ supabase/
|
├─ supabase/
|
||||||
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
|
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
|
||||||
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles
|
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles, anatomical_sheets
|
||||||
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
|
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
|
||||||
├─ packages/README.md ← shared packages index
|
├─ packages/README.md ← shared packages index
|
||||||
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
|
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
|
||||||
@@ -320,6 +326,16 @@ Database (Supabase)
|
|||||||
- A migration is never edited once applied. Each migration ships its pgTAP file with
|
- A migration is never edited once applied. Each migration ships its pgTAP file with
|
||||||
allowed AND denied cases, and a regenerated `database.types.ts`.
|
allowed AND denied cases, and a regenerated `database.types.ts`.
|
||||||
- The browser holds the anon key only. `service_role` never appears in env.js, .env.example or code.
|
- The browser holds the anon key only. `service_role` never appears in env.js, .env.example or code.
|
||||||
|
- pgTAP files run on PGlite and on the real image: scope counts to fixture ids, pin `collate "C"` on text ordering.
|
||||||
|
|
||||||
|
### Anatomical sheet model (packages/domain + migration 20261008110000)
|
||||||
|
- `docs/development/ANATOMICAL_SHEET_MODEL.md` is the source of truth: document shape, issue codes, tables, RPCs.
|
||||||
|
- Ids are stable slugs never derived from labels; labels are `{ fr, en }` objects. Annotation → findings is the
|
||||||
|
explicit `finding_zone_id`; vertebral regions are ordered data with free codes. No label matching at runtime.
|
||||||
|
- A published version is immutable (trigger, every role). Change = new draft (`create_sheet_draft`) then
|
||||||
|
`publish_sheet_version`. Integrity rule codes are shared by `validateSheetDocument` (TS) and
|
||||||
|
`private.sheet_document_issues` (SQL); add a rule on both sides and in the spec table.
|
||||||
|
- Document schema change → bump `SHEET_DOCUMENT_SCHEMA_VERSION`, extend the SQL CHECK on `document_schema_version`.
|
||||||
|
|
||||||
### Component stubs
|
### Component stubs
|
||||||
- Scaffold stubs render <div>ComponentName placeholder</div>
|
- Scaffold stubs render <div>ComponentName placeholder</div>
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
|
|||||||
├─ src/lib/ id, dates, assert utilities
|
├─ src/lib/ id, dates, assert utilities
|
||||||
├─ src/styles/ Tailwind v4 CSS + design tokens
|
├─ src/styles/ Tailwind v4 CSS + design tokens
|
||||||
├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite)
|
├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite)
|
||||||
|
├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules
|
||||||
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
|
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
|
||||||
├─ supabase/ CLI config, SQL migrations, local seed, pgTAP tests
|
├─ supabase/ CLI config, SQL migrations, local seed, pgTAP tests
|
||||||
├─ docker/ entrypoint.sh + nginx.conf
|
├─ docker/ entrypoint.sh + nginx.conf
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
# Anatomical sheet model (Step 4)
|
||||||
|
|
||||||
|
Status: Step 4 deliverable, 2026-10-08. Source of truth for the canonical
|
||||||
|
"fiche anatomique": the JSON document, its validation rules, the PostgreSQL
|
||||||
|
tables that persist it, and the lifecycle rules (versions, copies, deletion).
|
||||||
|
Decisions it applies: business architecture §2.6–§2.9, §7, §16, §17.3,
|
||||||
|
§23.2; `OPEN_QUESTIONS.md` C1, C2, C8, C9, Q3, Q5, Q9 as decided on
|
||||||
|
2026-10-08 (equine only, two SVG assets, import anomalies land in a draft,
|
||||||
|
manual report points confirmed).
|
||||||
|
|
||||||
|
Out of scope here: the legacy importer and the official equine draft
|
||||||
|
(next step), the visual editor, cloud reports, community, booking.
|
||||||
|
|
||||||
|
## 1. Two layers
|
||||||
|
|
||||||
|
| Layer | Where | Role |
|
||||||
|
| ------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Canonical document | `packages/domain/src/anatomical-sheet/` (Zod) | The sheet content: views, annotations, finding tree, vertebral regions, translations. Self-describing (`schema_version`). |
|
||||||
|
| Relational identity | `supabase/migrations/20261008110000_anatomical_sheets.sql` | Who owns the sheet, visibility, versions and their status, provenance of copies, assets, audit. |
|
||||||
|
|
||||||
|
The database stores the document as JSONB in
|
||||||
|
`anatomical_sheet_versions.content`. Zod is the shape contract at the
|
||||||
|
application boundary; SQL checks what only SQL can know (species of the
|
||||||
|
parent sheet, assets registered for the sheet, immutability, numbering) plus
|
||||||
|
the referential rules of §3 at publication time, so a browser cannot publish
|
||||||
|
a dangling document.
|
||||||
|
|
||||||
|
## 2. Canonical document (schema_version 1)
|
||||||
|
|
||||||
|
Every id is a **stable id**: `^[a-z0-9][a-z0-9_-]{0,63}$`, never derived
|
||||||
|
from a label, never changed by a translation. Vertebral region codes are
|
||||||
|
the one exception: `^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$`, because the
|
||||||
|
practitioner reads them as-is (`C`, `T`, `L`, `S`, `Cd`). Labels are `LocalizedText`
|
||||||
|
objects `{ fr, en }` (both required) or `LocalizedOptionalText` `{ fr?, en? }`.
|
||||||
|
Adding a locale later means adding an optional key, not a new field family.
|
||||||
|
|
||||||
|
```text
|
||||||
|
AnatomicalSheetDocument
|
||||||
|
├─ schema_version: 1
|
||||||
|
├─ species_id: stable id (row of public.species)
|
||||||
|
├─ name: LocalizedText display name of the sheet
|
||||||
|
├─ description: LocalizedOptionalText
|
||||||
|
├─ scope_disclaimer: LocalizedOptionalText legal scope text shown once per session and in the PDF
|
||||||
|
├─ attribution: { authors: string[], license: string | null, notes: string | null }
|
||||||
|
├─ vertebral_config: { regions: VertebralRegion[] } ORDERED; codes free (C/T/L/S/Cd for the horse)
|
||||||
|
│ VertebralRegion = { code, name: LocalizedText, count ≥ 1 }
|
||||||
|
├─ categories: AnnotationCategory[] { id, name: LocalizedText, color: '#rrggbb' | null }
|
||||||
|
├─ views: SheetView[]
|
||||||
|
│ main: { id, kind: 'main', name, svg_asset_id: uuid | null, view_box: ViewBox | null }
|
||||||
|
│ detail: { id, kind: 'detail', name, parent_view_id, svg_asset_id: uuid | null, view_box: ViewBox | null }
|
||||||
|
│ ViewBox = { min_x, min_y, width > 0, height > 0 }
|
||||||
|
├─ annotations: Annotation[]
|
||||||
|
│ common: { id, view_id, category_id, laterality, geometry: Geometry | null }
|
||||||
|
│ point | zone: + { name: LocalizedText, finding_zone_id: id | null, vertebral_region_code: code | null }
|
||||||
|
│ detail_trigger: + { name: LocalizedText | null, opens_view_id }
|
||||||
|
│ laterality ∈ unpaired | bilateral | left | right
|
||||||
|
│ Geometry = circle { cx, cy, r } | polygon { points: [x, y][] ≥ 3 } | path { d }
|
||||||
|
└─ finding_zones: FindingZone[]
|
||||||
|
FindingZone = { id, name: LocalizedText, categories: FindingCategory[] }
|
||||||
|
FindingCategory = { id, kind: dysfunction | observation | anamnesis | custom, name, description?, children: FindingNode[] }
|
||||||
|
FindingNode = { id, name, description?, requires_vet_referral?, sources?, children? } (recursive)
|
||||||
|
SourceRef = { type: manual | journal | database | web, citation, url? }
|
||||||
|
```
|
||||||
|
|
||||||
|
Why these shapes:
|
||||||
|
|
||||||
|
- **Views are a tree**, not a `details.head` field. A detail view names its
|
||||||
|
parent; a `detail_trigger` annotation in the parent opens it. Nesting depth
|
||||||
|
is free (§7.3). `svg_asset_id` is nullable on a detail view: null means
|
||||||
|
"render the parent's asset with this `view_box`" (C9). The equine seed will
|
||||||
|
keep two assets (Q5), so both forms are exercised.
|
||||||
|
- **Laterality is explicit** on every annotation. `bilateral` = one drawing
|
||||||
|
stands for both sides, the report picks the side (today's behaviour);
|
||||||
|
`left` / `right` = the drawing shows one side; `unpaired` = no side.
|
||||||
|
Absence of attribute no longer carries meaning.
|
||||||
|
- **Spine regions are data.** `vertebral_config.regions` is an ordered list
|
||||||
|
with free codes (C1, Q3). An annotation that opens the vertebra picker
|
||||||
|
carries `vertebral_region_code`; no label parsing (`regionFromLabel` stays
|
||||||
|
in the importer).
|
||||||
|
- **Annotation → findings is one explicit field**, `finding_zone_id`. No
|
||||||
|
FR/EN matching at runtime (§23.2). Several annotations may share a zone;
|
||||||
|
a `detail_trigger` never has one (it is navigation, not an observation).
|
||||||
|
- **Finding categories carry a `kind`** so the three business buckets
|
||||||
|
(dysfonctions ostéopathiques, observations / motifs de consultation,
|
||||||
|
anamnèse / facteurs rapportés) are typed, and creators may add `custom`
|
||||||
|
ones (§7.4). Node ids are unique among siblings; a finding is referenced
|
||||||
|
by `(finding_zone_id, path[])` exactly as `Finding.path` does today, so
|
||||||
|
the Step 5 report adapter is a rename, not a re-keying.
|
||||||
|
- **Tree nodes are lean on input, total on output**: `description`,
|
||||||
|
`requires_vet_referral`, `sources`, `children` are optional in the JSON
|
||||||
|
and defaulted by the parser (612 leaves would otherwise carry four empty
|
||||||
|
keys each). Structural records (views, annotations) use explicit `null`.
|
||||||
|
- The parser is **strict**: unknown keys are rejected. A canonical document
|
||||||
|
must not silently carry fields no version of the schema defines.
|
||||||
|
|
||||||
|
### 2.1 Validation tiers
|
||||||
|
|
||||||
|
| Tier | Function | When |
|
||||||
|
| ---------- | ------------------------------------------ | ----------------------------------------------------------------------------- |
|
||||||
|
| Shape | `AnatomicalSheetDocumentSchema.parse()` | every save (draft included) |
|
||||||
|
| Integrity | `validateSheetDocument(doc): SheetIssue[]` | editor feedback; `publishable` = no issue with `severity: 'error'` |
|
||||||
|
| Relational | `publish_sheet_version()` in SQL | publication: species matches the sheet, assets exist, referential rules below |
|
||||||
|
|
||||||
|
`SheetIssue = { code, severity: 'error' | 'warning', path, message }`; the
|
||||||
|
path names the offending field (`annotations[0].category_id`), the later
|
||||||
|
entry for a duplicate, the item itself for `view.unreachable` and
|
||||||
|
`finding_zone.unreferenced`.
|
||||||
|
|
||||||
|
Integrity rules (error unless stated):
|
||||||
|
|
||||||
|
| Code | Rule |
|
||||||
|
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
||||||
|
| `view.main.count` | exactly one `main` view |
|
||||||
|
| `view.id.duplicate` | view ids unique |
|
||||||
|
| `view.parent.missing` / `view.parent.cycle` | detail parent exists; the parent chain reaches the main view |
|
||||||
|
| `view.unreachable` | every detail view is opened by ≥1 `detail_trigger` located in its parent view |
|
||||||
|
| `view.asset.missing` | the main view has an asset; a detail view without asset has a `view_box` |
|
||||||
|
| `annotation.id.duplicate` | annotation ids unique across the whole sheet (all views) |
|
||||||
|
| `annotation.view.missing` | `view_id` exists |
|
||||||
|
| `annotation.category.missing` | `category_id` exists |
|
||||||
|
| `annotation.opens_view.invalid` | trigger target exists, is `detail`, and its parent is the trigger's view |
|
||||||
|
| `annotation.finding_zone.missing` | `finding_zone_id` exists |
|
||||||
|
| `annotation.region.missing` | `vertebral_region_code` exists in `vertebral_config` |
|
||||||
|
| `annotation.no_findings` (warning) | point / zone without `finding_zone_id` |
|
||||||
|
| `region.code.duplicate`, `category.id.duplicate`, `finding_zone.id.duplicate` | uniqueness |
|
||||||
|
| `finding.id.duplicate` | node ids unique among siblings (per zone, per children array) |
|
||||||
|
| `finding_zone.unreferenced` (warning) | zone no annotation points to |
|
||||||
|
|
||||||
|
A draft may be saved with errors. Publishing a document with errors is
|
||||||
|
refused in TypeScript (`assertPublishable`) and in SQL:
|
||||||
|
`private.sheet_document_issues` re-checks every error-level rule except the
|
||||||
|
two recursive ones (parent cycle, sibling uniqueness) and reports
|
||||||
|
`document.shape` when an id-bearing collection is not an array;
|
||||||
|
`private.sheet_document_unknown_assets` adds `view.asset.unknown` when a
|
||||||
|
view points at an asset not registered for the sheet. Both run inside
|
||||||
|
`publish_sheet_version`.
|
||||||
|
|
||||||
|
## 3. Relational model
|
||||||
|
|
||||||
|
```text
|
||||||
|
public.species reference data, seeded by the migration (equine)
|
||||||
|
public.anatomical_sheets identity, owner, visibility, status, provenance, current version
|
||||||
|
public.anatomical_sheet_versions numbered versions, status draft | published | deprecated, content jsonb
|
||||||
|
public.anatomical_sheet_assets SVG files, content-addressed (sha256), per sheet
|
||||||
|
audit.audit_logs every lifecycle event (private.log_event)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `species`
|
||||||
|
|
||||||
|
`id text` (stable id), `name_fr`, `name_en`, `sort_order`, `active`. Read by
|
||||||
|
any authenticated user; no write path through the API (platform step later).
|
||||||
|
|
||||||
|
### `anatomical_sheets`
|
||||||
|
|
||||||
|
| Column | Notes |
|
||||||
|
| ------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||||
|
| `id uuid` | |
|
||||||
|
| `species_id` | FK species |
|
||||||
|
| `name text`, `slug text`, `description text` | slug `^[a-z0-9][a-z0-9-]{1,79}$`, unique per owner scope among non-deleted sheets |
|
||||||
|
| `creator_user_id uuid null` | null = platform-owned (official sheets, seeds) |
|
||||||
|
| `is_official boolean` | only a platform admin can create one; editable by platform admins |
|
||||||
|
| `visibility` | enum `sheet_visibility`: `private` \| `public` |
|
||||||
|
| `status` | enum `sheet_status`: `active` \| `archived` \| `deleted` (soft) |
|
||||||
|
| `based_on_sheet_id`, `based_on_version_id` | provenance of a copy (fork); FK `on delete set null` so the copy survives the source |
|
||||||
|
| `current_version_id` | latest published version (nullable while draft-only) |
|
||||||
|
| `last_version_number` | monotonic counter: a deleted version's number is never reused |
|
||||||
|
| `archived_at`, `deleted_at`, `created_at`, `updated_at` | |
|
||||||
|
|
||||||
|
### `anatomical_sheet_versions`
|
||||||
|
|
||||||
|
| Column | Notes |
|
||||||
|
| ----------------------------------------------------------- | --------------------------------------------------------------------------- |
|
||||||
|
| `id uuid`, `sheet_id` | |
|
||||||
|
| `version_number int` | unique per sheet, assigned by the server from the sheet's monotonic counter |
|
||||||
|
| `status` | enum `sheet_version_status`: `draft` \| `published` \| `deprecated` |
|
||||||
|
| `document_schema_version int` | CHECK = `content->>'schema_version'`; only `1` today |
|
||||||
|
| `content jsonb` | the canonical document; CHECK `jsonb_typeof = 'object'` and size ≤ 2 MiB |
|
||||||
|
| `change_note text` | what changed in this version |
|
||||||
|
| `created_by`, `published_by`, `deprecated_by` | profile ids, `on delete set null` |
|
||||||
|
| `published_at`, `deprecated_at`, `created_at`, `updated_at` | |
|
||||||
|
|
||||||
|
Rules enforced by triggers (every role, including the table owner):
|
||||||
|
|
||||||
|
- **One draft per sheet** (partial unique index, C8).
|
||||||
|
- **Published rows are immutable**: the only accepted UPDATE on a
|
||||||
|
`published` row is the transition to `deprecated` (status, `deprecated_at`,
|
||||||
|
`deprecated_by`); a change to any compared column (content, schema
|
||||||
|
version, number, sheet, note, authorship, timestamps) raises `42501` for
|
||||||
|
every role, table owner included. Through the API the row is simply
|
||||||
|
invisible to UPDATE (zero rows touched). A `deprecated` row is frozen.
|
||||||
|
- **Deletion preconditions** (BEFORE DELETE): never a `published` row; never
|
||||||
|
the `current_version_id` of its sheet; never a version a non-deleted sheet
|
||||||
|
is `based_on`; (reports: added when the table exists, §16). A `draft` has
|
||||||
|
no dependents and is dropped by its editor through `delete_sheet_version`.
|
||||||
|
- **Document ↔ row**: `content->>'species_id'` equals the sheet's species.
|
||||||
|
|
||||||
|
### `anatomical_sheet_assets`
|
||||||
|
|
||||||
|
`id uuid`, `sheet_id`, `sha256 text` (64 hex), `byte_size int`,
|
||||||
|
`content_type text` (`image/svg+xml` only for now), `file_name text`,
|
||||||
|
`created_by`, `created_at`. Unique `(sheet_id, sha256)`. Assets are
|
||||||
|
immutable and **content-addressed**: the bytes live in Storage under
|
||||||
|
`anatomical-sheet-assets/<sha256>.svg` (bucket and policies arrive with the
|
||||||
|
importer step; until then the path is a convention, not a row). Two sheets
|
||||||
|
with the same SVG share one object; a copy of a sheet copies only the
|
||||||
|
metadata rows its copied version references. Deleting an asset referenced by
|
||||||
|
a version is refused (FK restrict is not possible on a JSONB reference, so
|
||||||
|
`delete_sheet_asset` checks every version's views). Asset rows follow the
|
||||||
|
sheet's visibility, drafts included: the future Storage policy must
|
||||||
|
authorise through the sheet, never through a sha256 alone.
|
||||||
|
|
||||||
|
### 3.1 Lifecycle (RPCs, security definer, audited)
|
||||||
|
|
||||||
|
| RPC | Actor | Effect |
|
||||||
|
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `create_anatomical_sheet(species_id, name, slug, document, description, visibility, official)` | any active account; `official = true` needs platform admin | sheet + draft v1 |
|
||||||
|
| `create_sheet_draft(sheet_id, from_version_id, change_note)` | editor | new draft (next counter value), content copied from `from_version_id` (default: current version); refused if a draft exists |
|
||||||
|
| `publish_sheet_version(version_id)` | editor | draft → published; relational checks; sheet `current_version_id` ← version. Previous published versions stay `published` (historical reports keep rendering) |
|
||||||
|
| `deprecate_sheet_version(version_id, reason)` | editor | published → deprecated (not offered for new reports; still readable) |
|
||||||
|
| `delete_sheet_version(version_id)` | editor | physical delete, trigger preconditions |
|
||||||
|
| `fork_anatomical_sheet(source_version_id, name, slug, visibility)` | any user who can use the source | new sheet (`based_on_*` set, `creator = actor`), asset rows copied, draft v1 = source content with `svg_asset_id`s remapped. The source rows are not touched |
|
||||||
|
| `archive_anatomical_sheet(sheet_id)` / `restore_anatomical_sheet` | editor | status archived ↔ active; archived sheets are hidden from "use" but readable by their editor |
|
||||||
|
| `delete_anatomical_sheet(sheet_id)` | editor | soft delete; refused while a non-deleted copy derives from the sheet |
|
||||||
|
| `set_sheet_visibility(sheet_id, visibility)` | editor | private ↔ public, audited (sharing is sensitive state) |
|
||||||
|
| `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` | editor | asset row (idempotent on `(sheet, sha256)`) |
|
||||||
|
| `delete_sheet_asset(asset_id)` | editor | refused while any version references the asset |
|
||||||
|
|
||||||
|
Direct table access for `authenticated`: SELECT through the policies below;
|
||||||
|
UPDATE of `name` / `slug` / `description` on own sheets and of `content` /
|
||||||
|
`change_note` on **own draft** rows (the future editor autosaves with a
|
||||||
|
PATCH; the autosave itself is not audited, the publication is). Everything
|
||||||
|
else is RPC. Every RPC takes its actor from `auth.uid()`, refuses a
|
||||||
|
deactivated profile, checks `can_edit_sheet` before reading anything else
|
||||||
|
(unknown and foreign ids get the same `42501`), and calls
|
||||||
|
`private.log_event`.
|
||||||
|
|
||||||
|
### 3.2 Access helpers (`private`, security definer)
|
||||||
|
|
||||||
|
| Helper | True when |
|
||||||
|
| ------------------------------- | --------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `can_edit_sheet(uid, sheet_id)` | sheet not deleted and (creator = uid, or `is_official` and platform admin) |
|
||||||
|
| `can_use_sheet(uid, sheet_id)` | sheet `active` and (`public`, or `can_edit_sheet`), grants and follows plug in here at the community step |
|
||||||
|
|
||||||
|
Policies:
|
||||||
|
|
||||||
|
| Table | SELECT | INSERT / UPDATE / DELETE |
|
||||||
|
| --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ |
|
||||||
|
| `species` | authenticated, `active` rows | none |
|
||||||
|
| `anatomical_sheets` | `can_use_sheet` or `can_edit_sheet` | UPDATE `name`, `slug`, `description` for editors; everything else RPC |
|
||||||
|
| `anatomical_sheet_versions` | published / deprecated of usable sheets; drafts for editors | UPDATE `content`, `change_note` on own drafts; INSERT and DELETE via RPC |
|
||||||
|
| `anatomical_sheet_assets` | same visibility as the sheet | none (RPC) |
|
||||||
|
|
||||||
|
`anon` gets nothing. Every `private` function has EXECUTE revoked from
|
||||||
|
PUBLIC; `authenticated` executes only the policy predicates (the two above
|
||||||
|
plus the five platform-role predicates of Step 3); pgTAP 001 keeps a census. Public discovery views for the public site come
|
||||||
|
with the community step (§17.4).
|
||||||
|
|
||||||
|
## 4. What the model guarantees (acceptance criteria)
|
||||||
|
|
||||||
|
| Criterion | Where it is proven |
|
||||||
|
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| A sheet with several views and annotations explicitly linked to findings | `packages/domain/tests/fixtures/horse-slice.ts` (2 views, trigger, spine region, bilateral joint, 3 finding kinds); schema + integrity tests |
|
||||||
|
| Ids stable under translation | test: renaming every label leaves ids, references and `validateSheetDocument` output unchanged |
|
||||||
|
| Published versions immutable | pgTAP: UPDATE of content / status / number on a published row → `42501` for the table owner; zero rows touched through the API role |
|
||||||
|
| New version leaves old ones intact | pgTAP: v2 draft then publish; v1 row byte-identical, `current_version_id` moves |
|
||||||
|
| Copies keep provenance, source untouched | pgTAP: fork → `based_on_*` set, source rows and assets unchanged; editing the copy leaves the source unchanged |
|
||||||
|
| Validation detects inconsistencies | domain tests, one per rule (missing references, duplicate ids, invalid relations) + SQL `sheet_document_issues` |
|
||||||
|
| Security rules tested | pgTAP allowed + denied paths: other user, anon, direct writes, official sheets, archived/deleted sheets |
|
||||||
|
| Migrations reproducible | PGlite replays from zero in `pnpm test:run`; `pnpm db:reset` on the real stack |
|
||||||
|
| Previous tests pass | root `pnpm check` |
|
||||||
|
|
||||||
|
## 5. Decisions left to the user
|
||||||
|
|
||||||
|
1. **Follow = permission to use a public sheet** (§2.9) is not yet modelled:
|
||||||
|
today every authenticated user can use any public active sheet. Grants
|
||||||
|
and follows will narrow `can_use_sheet` at the community step.
|
||||||
|
2. **Who may create sheets**: any active account for now. Should creation
|
||||||
|
wait for professional verification (Step 7)?
|
||||||
|
3. **Deprecation policy**: publishing v2 does not deprecate v1. Should it,
|
||||||
|
automatically, or stay a manual act?
|
||||||
|
4. **Table name `anatomical_sheet_assets` and the content-addressed Storage
|
||||||
|
layout** (`<sha256>.svg`): confirm before the importer writes files.
|
||||||
|
5. **Official equine sheet owner**: platform-owned (`creator_user_id = null`,
|
||||||
|
`is_official = true`, edited by platform admins) or owned by the client's
|
||||||
|
account?
|
||||||
|
6. **Finding category kind naming**: `observation` collides with the report
|
||||||
|
"Observation" (OPEN_QUESTIONS C7). Alternative: `consultation_reason`.
|
||||||
|
7. **Server-side shape validation**: SQL re-checks references, sizes and the
|
||||||
|
species, not the full Zod shape (ids pattern, enums, unknown keys). A
|
||||||
|
client calling the RPC directly can publish a shape-invalid document to
|
||||||
|
its own sheet. Options: a plpgsql shape check, or publication through an
|
||||||
|
Edge Function running the Zod schema (community step at the latest).
|
||||||
|
8. **Account erasure**: `creator_user_id` is `on delete restrict` and the
|
||||||
|
immutability guard blocks `set null` on `published_by` of published rows,
|
||||||
|
so deleting an `auth.users` row that owns sheets fails by design until the
|
||||||
|
retention step (§16) defines reassignment or anonymisation.
|
||||||
@@ -138,6 +138,12 @@ Tests: importer reproduces the Step 1 mapping table exactly; every audit 07 spec
|
|||||||
Manual validation: open IMPORT-REPORT.md: 27 annotations, 26 mapped, 1 detail trigger, 5 spine zones with region codes C/T/L/S/Cd, 9 bilateral, 2 views; diff document.json against docs/faunosteo-audit/anatomical-sheet-example.json for sanity.
|
Manual validation: open IMPORT-REPORT.md: 27 annotations, 26 mapped, 1 detail trigger, 5 spine zones with region codes C/T/L/S/Cd, 9 bilateral, 2 views; diff document.json against docs/faunosteo-audit/anatomical-sheet-example.json for sanity.
|
||||||
Definition of Done: seed document committed; packages/domain and packages/anatomy have no DOM import outside anatomy/dom/*; no runtime code imports zoneMatch outside legacy/.
|
Definition of Done: seed document committed; packages/domain and packages/anatomy have no DOM import outside anatomy/dom/*; no runtime code imports zoneMatch outside legacy/.
|
||||||
Risks: subtle divergences between parser and importer on the detail trigger (no name, category kept); Horse_head.svg id space overlaps if a future file reuses ids (mitigated by per-view id scoping in the importer).
|
Risks: subtle divergences between parser and importer on the detail trigger (no name, category kept); Horse_head.svg id space overlaps if a future file reuses ids (mitigated by per-view id scoping in the importer).
|
||||||
|
Adjustment 2026-10-08 (user brief for Step 4): the step is split. Step 4 = model, validation,
|
||||||
|
persistence foundations and tests (packages/domain, migration 20261008110000_anatomical_sheets,
|
||||||
|
pgTAP 005, docs/development/ANATOMICAL_SHEET_MODEL.md). Step 4b = legacy importer producing the
|
||||||
|
official equine sheet as a DRAFT with an import report, published only after business review.
|
||||||
|
packages/anatomy is created at Step 4b. Labels use `{ fr, en }` objects, annotation→findings is
|
||||||
|
`finding_zone_id`, finding categories carry a `kind`; see the spec for the final field names.
|
||||||
```
|
```
|
||||||
|
|
||||||
```text
|
```text
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
# Supabase: local stack, migrations, tests
|
# Supabase: local stack, migrations, tests
|
||||||
|
|
||||||
Status: Step 3 deliverable, 2026-10-08. Covers the foundation only (profiles,
|
Status: Step 3 deliverable, extended at Step 4 (2026-10-08). Covers the
|
||||||
platform roles, audit log). Conventions: `BACKEND_ARCHITECTURE.md` §3–§9.
|
foundation (profiles, platform roles, audit log) and the anatomical sheet
|
||||||
|
tables (`ANATOMICAL_SHEET_MODEL.md`). Conventions: `BACKEND_ARCHITECTURE.md` §3–§9.
|
||||||
|
|
||||||
## 1. Layout
|
## 1. Layout
|
||||||
|
|
||||||
@@ -11,13 +12,18 @@ supabase/
|
|||||||
├─ migrations/ forward-only SQL, <timestamp>_<name>.sql
|
├─ migrations/ forward-only SQL, <timestamp>_<name>.sql
|
||||||
│ ├─ 20261008100000_foundation.sql schemas private/audit, updated_at, audit log
|
│ ├─ 20261008100000_foundation.sql schemas private/audit, updated_at, audit log
|
||||||
│ ├─ 20261008100100_profiles.sql profiles + auth.users trigger + RLS
|
│ ├─ 20261008100100_profiles.sql profiles + auth.users trigger + RLS
|
||||||
│ └─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs
|
│ ├─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs
|
||||||
|
│ ├─ 20261008110000_anatomical_sheets.sql species, sheets, immutable versions, assets, lifecycle RPCs
|
||||||
|
│ └─ 20261008110100_private_execute_hardening.sql EXECUTE revoked from PUBLIC on the Step 3 helpers
|
||||||
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
|
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
|
||||||
└─ tests/ pgTAP, one file per concern, allowed AND denied paths
|
└─ tests/ pgTAP, one file per concern, allowed AND denied paths
|
||||||
packages/supabase/
|
packages/supabase/
|
||||||
├─ src/client.ts createBrowserClient() (anon key, PKCE)
|
├─ src/client.ts createBrowserClient() (anon key, PKCE)
|
||||||
├─ src/database.types.ts `supabase gen types` output
|
├─ src/database.types.ts `supabase gen types` output
|
||||||
|
├─ src/anatomical-sheets.ts publishSheetVersion(): Zod + integrity gate before the RPC
|
||||||
└─ tests/db/ PGlite harness: runs the pgTAP files without Docker
|
└─ tests/db/ PGlite harness: runs the pgTAP files without Docker
|
||||||
|
packages/domain/
|
||||||
|
└─ src/anatomical-sheet/ canonical sheet document (Zod), validateSheetDocument, createEmptySheetDocument
|
||||||
```
|
```
|
||||||
|
|
||||||
## 2. Prerequisites
|
## 2. Prerequisites
|
||||||
@@ -46,23 +52,23 @@ pnpm db:reset # drop + replay every migration + seed from zero
|
|||||||
|
|
||||||
Local endpoints (`config.toml`):
|
Local endpoints (`config.toml`):
|
||||||
|
|
||||||
| Service | URL |
|
| Service | URL |
|
||||||
|---|---|
|
| --------------------------------------- | --------------------------------------------------------- |
|
||||||
| API (PostgREST, Auth, Storage) | `http://127.0.0.1:54321` |
|
| API (PostgREST, Auth, Storage) | `http://127.0.0.1:54321` |
|
||||||
| PostgreSQL | `postgresql://postgres:postgres@127.0.0.1:54322/postgres` |
|
| PostgreSQL | `postgresql://postgres:postgres@127.0.0.1:54322/postgres` |
|
||||||
| Studio | `http://127.0.0.1:54323` |
|
| Studio | `http://127.0.0.1:54323` |
|
||||||
| Mail catcher (confirmation / OTP mails) | `http://127.0.0.1:54324` |
|
| Mail catcher (confirmation / OTP mails) | `http://127.0.0.1:54324` |
|
||||||
|
|
||||||
`pnpm db:start` prints the `anon` and `service_role` keys. Only the anon key
|
`pnpm db:start` prints the `anon` and `service_role` keys. Only the anon key
|
||||||
ever reaches the browser.
|
ever reaches the browser.
|
||||||
|
|
||||||
Seed accounts (local only, password `LocalDev-only-password-1`):
|
Seed accounts (local only, password `LocalDev-only-password-1`):
|
||||||
|
|
||||||
| Email | Role |
|
| Email | Role |
|
||||||
|---|---|
|
| ----------------------- | ------------------------------------------- |
|
||||||
| `owner@faunosteo.local` | platform owner (bootstrapped by `seed.sql`) |
|
| `owner@faunosteo.local` | platform owner (bootstrapped by `seed.sql`) |
|
||||||
| `alice@faunosteo.local` | plain user |
|
| `alice@faunosteo.local` | plain user |
|
||||||
| `bob@faunosteo.local` | plain user |
|
| `bob@faunosteo.local` | plain user |
|
||||||
|
|
||||||
## 4. Writing a migration
|
## 4. Writing a migration
|
||||||
|
|
||||||
@@ -87,16 +93,20 @@ RLS enabled, no `using (true)` / `with check (true)` policy for `anon` or
|
|||||||
|
|
||||||
Two runners, one SQL source of truth (`supabase/tests/*.sql`, pgTAP):
|
Two runners, one SQL source of truth (`supabase/tests/*.sql`, pgTAP):
|
||||||
|
|
||||||
| Command | Engine | Needs Docker | What runs |
|
| Command | Engine | Needs Docker | What runs |
|
||||||
|---|---|---|---|
|
| -------------------------------------------- | ------------------------------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------ |
|
||||||
| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory |
|
| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory; publish gate |
|
||||||
| `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image |
|
| `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image |
|
||||||
|
|
||||||
`pnpm test:run` at the root runs the PGlite suite together with the app
|
`pnpm test:run` at the root runs the PGlite suite together with the app
|
||||||
suite. The shim (`packages/supabase/tests/db/supabase-shim.sql`) recreates
|
suite. The shim (`packages/supabase/tests/db/supabase-shim.sql`) recreates
|
||||||
the API roles, `auth.users`, `auth.uid()` and the permissive default
|
the API roles, `auth.users`, `auth.uid()` and the permissive default
|
||||||
privileges of Supabase so that a forgotten `revoke` fails a test.
|
privileges of Supabase so that a forgotten `revoke` fails a test.
|
||||||
|
|
||||||
|
Two parity traps met so far: counts must be scoped to fixture ids (the real
|
||||||
|
stack carries `seed.sql` rows), and `order by` on text must pin
|
||||||
|
`collate "C"` (the real image sorts with a locale collation, PGlite with C).
|
||||||
|
|
||||||
How a test impersonates a user (same technique in both runners):
|
How a test impersonates a user (same technique in both runners):
|
||||||
|
|
||||||
```sql
|
```sql
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ faunosteo/
|
|||||||
│ ├─ src/ public/ tests/ scripts/ index.html
|
│ ├─ src/ public/ tests/ scripts/ index.html
|
||||||
│ ├─ vite.config.ts vitest.config.ts tsconfig*.json eslint.config.js
|
│ ├─ vite.config.ts vitest.config.ts tsconfig*.json eslint.config.js
|
||||||
│ └─ package.json app dependencies and scripts
|
│ └─ package.json app dependencies and scripts
|
||||||
|
├─ packages/domain/ @faunosteo/domain: canonical anatomical sheet document (Zod) + integrity rules
|
||||||
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL tests
|
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL tests
|
||||||
├─ supabase/ Supabase CLI config, migrations, seed, pgTAP tests (docs/development/SUPABASE.md)
|
├─ supabase/ Supabase CLI config, migrations, seed, pgTAP tests (docs/development/SUPABASE.md)
|
||||||
├─ docker/ nginx.conf, entrypoint.sh (unchanged)
|
├─ docker/ nginx.conf, entrypoint.sh (unchanged)
|
||||||
|
|||||||
+3
-3
@@ -8,11 +8,11 @@ Planned packages and the step that creates each one:
|
|||||||
|
|
||||||
| Package | Content | Created at |
|
| Package | Content | Created at |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `@faunosteo/domain` | Zod schemas: report document, anatomical sheet document, species, entitlement capabilities | Step 4 (sheet model) |
|
| `@faunosteo/domain` | Zod schemas: anatomical sheet document + integrity rules (**created**, Step 4); report document, entitlement capabilities later | Step 4 (sheet model) |
|
||||||
| `@faunosteo/anatomy` | SVG convention parser, legacy importer, renderer helpers, spine logic | Step 4 |
|
| `@faunosteo/anatomy` | SVG convention parser, legacy importer, renderer helpers, spine logic | Step 4b (importer) |
|
||||||
| `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) |
|
| `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) |
|
||||||
| `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) |
|
| `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) |
|
||||||
| `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite | **created**, Step 3 |
|
| `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite, sheet publish gate | **created**, Step 3 |
|
||||||
| `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web |
|
| `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web |
|
||||||
| `@faunosteo/ui` | UI primitives and design tokens | only when public-web reuses them |
|
| `@faunosteo/ui` | UI primitives and design tokens | only when public-web reuses them |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import globals from 'globals'
|
||||||
|
import tseslint from 'typescript-eslint'
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{ ignores: ['node_modules/**'] },
|
||||||
|
{
|
||||||
|
files: ['**/*.ts'],
|
||||||
|
extends: [...tseslint.configs.recommended],
|
||||||
|
languageOptions: {
|
||||||
|
globals: { ...globals.node, ...globals.es2022 },
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'warn',
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{ argsIgnorePattern: '^_' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"name": "@faunosteo/domain",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Faunosteo pure domain model: canonical anatomical sheet document, Zod schemas and integrity rules",
|
||||||
|
"license": "MIT",
|
||||||
|
"type": "module",
|
||||||
|
"main": "./src/index.ts",
|
||||||
|
"types": "./src/index.ts",
|
||||||
|
"exports": {
|
||||||
|
".": "./src/index.ts",
|
||||||
|
"./anatomical-sheet": "./src/anatomical-sheet/index.ts"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||||
|
"test": "vitest",
|
||||||
|
"test:run": "vitest run",
|
||||||
|
"lint": "eslint . --max-warnings 0",
|
||||||
|
"build": "tsc -p tsconfig.json --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"zod": "^3.24.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^20.19.41",
|
||||||
|
"eslint": "^9.17.0",
|
||||||
|
"globals": "^15.14.0",
|
||||||
|
"typescript": "^5.7.2",
|
||||||
|
"typescript-eslint": "^8.19.0",
|
||||||
|
"vitest": "^3.2.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||||
|
type AnatomicalSheetDocument,
|
||||||
|
type LocalizedText,
|
||||||
|
} from './schema'
|
||||||
|
|
||||||
|
export interface NewSheetDocumentParams {
|
||||||
|
species_id: string
|
||||||
|
name: LocalizedText
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MAIN_VIEW_ID = 'view-main'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starting point of a new sheet: shape-valid so it can be saved as a draft
|
||||||
|
* at once, but not publishable until the main view gets its SVG asset.
|
||||||
|
*/
|
||||||
|
export function createEmptySheetDocument(
|
||||||
|
params: NewSheetDocumentParams,
|
||||||
|
): AnatomicalSheetDocument {
|
||||||
|
return AnatomicalSheetDocumentSchema.parse({
|
||||||
|
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||||
|
species_id: params.species_id,
|
||||||
|
name: params.name,
|
||||||
|
description: {},
|
||||||
|
scope_disclaimer: {},
|
||||||
|
attribution: { authors: [], license: null, notes: null },
|
||||||
|
vertebral_config: { regions: [] },
|
||||||
|
categories: [],
|
||||||
|
views: [
|
||||||
|
{
|
||||||
|
id: MAIN_VIEW_ID,
|
||||||
|
kind: 'main',
|
||||||
|
name: { fr: 'Vue principale', en: 'Main view' },
|
||||||
|
svg_asset_id: null,
|
||||||
|
view_box: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
annotations: [],
|
||||||
|
finding_zones: [],
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export * from './schema'
|
||||||
|
export * from './validate'
|
||||||
|
export * from './create'
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import { z } from 'zod'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Canonical anatomical sheet document, schema_version 1.
|
||||||
|
*
|
||||||
|
* Shape contract of docs/development/ANATOMICAL_SHEET_MODEL.md §2. Every
|
||||||
|
* object is strict: a canonical document must not silently carry fields no
|
||||||
|
* version of the schema defines. Cross-references (view ids, zone ids…) are
|
||||||
|
* checked by validateSheetDocument, not here, so a draft with dangling
|
||||||
|
* references can still be saved.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const SHEET_DOCUMENT_SCHEMA_VERSION = 1
|
||||||
|
|
||||||
|
/** Ids are never derived from labels, so translations never move them. */
|
||||||
|
export const STABLE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
|
||||||
|
|
||||||
|
export const StableIdSchema = z.string().regex(STABLE_ID_PATTERN)
|
||||||
|
|
||||||
|
/** Region codes are free (C, T, L, S, Cd for the horse), case included. */
|
||||||
|
export const RegionCodeSchema = z
|
||||||
|
.string()
|
||||||
|
.regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/)
|
||||||
|
|
||||||
|
export const LocalizedTextSchema = z
|
||||||
|
.object({ fr: z.string().min(1), en: z.string().min(1) })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const LocalizedOptionalTextSchema = z
|
||||||
|
.object({ fr: z.string().optional(), en: z.string().optional() })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const VertebralRegionSchema = z
|
||||||
|
.object({
|
||||||
|
code: RegionCodeSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
count: z.number().int().min(1),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const HexColorSchema = z.string().regex(/^#[0-9a-fA-F]{6}$/)
|
||||||
|
|
||||||
|
export const AnnotationCategorySchema = z
|
||||||
|
.object({
|
||||||
|
id: StableIdSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
color: HexColorSchema.nullable(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const CoordinateSchema = z.number().finite()
|
||||||
|
|
||||||
|
export const ViewBoxSchema = z
|
||||||
|
.object({
|
||||||
|
min_x: CoordinateSchema,
|
||||||
|
min_y: CoordinateSchema,
|
||||||
|
width: CoordinateSchema.positive(),
|
||||||
|
height: CoordinateSchema.positive(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
/** Null asset on a detail view means "parent asset cropped by view_box". */
|
||||||
|
const viewCommon = {
|
||||||
|
id: StableIdSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
svg_asset_id: z.string().uuid().nullable(),
|
||||||
|
view_box: ViewBoxSchema.nullable(),
|
||||||
|
}
|
||||||
|
|
||||||
|
const MainViewSchema = z
|
||||||
|
.object({ ...viewCommon, kind: z.literal('main') })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const DetailViewSchema = z
|
||||||
|
.object({
|
||||||
|
...viewCommon,
|
||||||
|
kind: z.literal('detail'),
|
||||||
|
parent_view_id: StableIdSchema,
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
/** Views form a tree: a detail names its parent, any depth. */
|
||||||
|
export const SheetViewSchema = z.discriminatedUnion('kind', [
|
||||||
|
MainViewSchema,
|
||||||
|
DetailViewSchema,
|
||||||
|
])
|
||||||
|
|
||||||
|
const CircleSchema = z
|
||||||
|
.object({
|
||||||
|
type: z.literal('circle'),
|
||||||
|
cx: CoordinateSchema,
|
||||||
|
cy: CoordinateSchema,
|
||||||
|
r: CoordinateSchema.positive(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const PolygonSchema = z
|
||||||
|
.object({
|
||||||
|
type: z.literal('polygon'),
|
||||||
|
points: z.array(z.tuple([CoordinateSchema, CoordinateSchema])).min(3),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const PathSchema = z
|
||||||
|
.object({ type: z.literal('path'), d: z.string().min(1) })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const GeometrySchema = z.discriminatedUnion('type', [
|
||||||
|
CircleSchema,
|
||||||
|
PolygonSchema,
|
||||||
|
PathSchema,
|
||||||
|
])
|
||||||
|
|
||||||
|
/** Explicit on every annotation: absence no longer carries meaning. */
|
||||||
|
export const LateralitySchema = z.enum([
|
||||||
|
'unpaired',
|
||||||
|
'bilateral',
|
||||||
|
'left',
|
||||||
|
'right',
|
||||||
|
])
|
||||||
|
|
||||||
|
const annotationCommon = {
|
||||||
|
id: StableIdSchema,
|
||||||
|
view_id: StableIdSchema,
|
||||||
|
category_id: StableIdSchema,
|
||||||
|
laterality: LateralitySchema,
|
||||||
|
geometry: GeometrySchema.nullable(),
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Observable annotations link to findings through one explicit field. */
|
||||||
|
const observableFields = {
|
||||||
|
...annotationCommon,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
finding_zone_id: StableIdSchema.nullable(),
|
||||||
|
vertebral_region_code: RegionCodeSchema.nullable(),
|
||||||
|
}
|
||||||
|
|
||||||
|
const PointAnnotationSchema = z
|
||||||
|
.object({ ...observableFields, kind: z.literal('point') })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const ZoneAnnotationSchema = z
|
||||||
|
.object({ ...observableFields, kind: z.literal('zone') })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
/** Navigation only: a trigger never carries findings. */
|
||||||
|
const DetailTriggerAnnotationSchema = z
|
||||||
|
.object({
|
||||||
|
...annotationCommon,
|
||||||
|
kind: z.literal('detail_trigger'),
|
||||||
|
name: LocalizedTextSchema.nullable(),
|
||||||
|
opens_view_id: StableIdSchema,
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const AnnotationSchema = z.discriminatedUnion('kind', [
|
||||||
|
PointAnnotationSchema,
|
||||||
|
ZoneAnnotationSchema,
|
||||||
|
DetailTriggerAnnotationSchema,
|
||||||
|
])
|
||||||
|
|
||||||
|
/** Documents are shared across users: only web links, never javascript: URLs. */
|
||||||
|
const HttpUrlSchema = z
|
||||||
|
.string()
|
||||||
|
.url()
|
||||||
|
.refine((url) => /^https?:\/\//i.test(url), 'http(s) URL expected')
|
||||||
|
|
||||||
|
export const SourceRefSchema = z
|
||||||
|
.object({
|
||||||
|
type: z.enum(['manual', 'journal', 'database', 'web']),
|
||||||
|
citation: z.string().min(1),
|
||||||
|
url: HttpUrlSchema.optional(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export type SourceRef = z.infer<typeof SourceRefSchema>
|
||||||
|
export type LocalizedText = z.infer<typeof LocalizedTextSchema>
|
||||||
|
export type LocalizedOptionalText = z.infer<typeof LocalizedOptionalTextSchema>
|
||||||
|
|
||||||
|
/** Parsed node: every optional key of the authoring form is filled in. */
|
||||||
|
export interface FindingNode {
|
||||||
|
id: string
|
||||||
|
name: LocalizedText
|
||||||
|
description: LocalizedOptionalText
|
||||||
|
requires_vet_referral: boolean
|
||||||
|
sources: SourceRef[]
|
||||||
|
children: FindingNode[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Authoring form: leaves stay lean, hundreds of them carry no empty keys. */
|
||||||
|
export interface FindingNodeInput {
|
||||||
|
id: string
|
||||||
|
name: LocalizedText
|
||||||
|
description?: LocalizedOptionalText
|
||||||
|
requires_vet_referral?: boolean
|
||||||
|
sources?: SourceRef[]
|
||||||
|
children?: FindingNodeInput[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const FindingNodeSchema: z.ZodType<
|
||||||
|
FindingNode,
|
||||||
|
z.ZodTypeDef,
|
||||||
|
FindingNodeInput
|
||||||
|
> = z.lazy(() =>
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
id: StableIdSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
description: LocalizedOptionalTextSchema.default({}),
|
||||||
|
requires_vet_referral: z.boolean().default(false),
|
||||||
|
sources: z.array(SourceRefSchema).default([]),
|
||||||
|
children: z.array(FindingNodeSchema).default([]),
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Typed business buckets; creators may add their own as 'custom'. */
|
||||||
|
export const FindingCategoryKindSchema = z.enum([
|
||||||
|
'dysfunction',
|
||||||
|
'observation',
|
||||||
|
'anamnesis',
|
||||||
|
'custom',
|
||||||
|
])
|
||||||
|
|
||||||
|
export const FindingCategorySchema = z
|
||||||
|
.object({
|
||||||
|
id: StableIdSchema,
|
||||||
|
kind: FindingCategoryKindSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
description: LocalizedOptionalTextSchema.default({}),
|
||||||
|
children: z.array(FindingNodeSchema),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const FindingZoneSchema = z
|
||||||
|
.object({
|
||||||
|
id: StableIdSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
categories: z.array(FindingCategorySchema),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const AttributionSchema = z
|
||||||
|
.object({
|
||||||
|
authors: z.array(z.string().min(1)),
|
||||||
|
license: z.string().min(1).nullable(),
|
||||||
|
notes: z.string().min(1).nullable(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
const VertebralConfigSchema = z
|
||||||
|
.object({ regions: z.array(VertebralRegionSchema) })
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export const AnatomicalSheetDocumentSchema = z
|
||||||
|
.object({
|
||||||
|
schema_version: z.literal(SHEET_DOCUMENT_SCHEMA_VERSION),
|
||||||
|
species_id: StableIdSchema,
|
||||||
|
name: LocalizedTextSchema,
|
||||||
|
description: LocalizedOptionalTextSchema,
|
||||||
|
scope_disclaimer: LocalizedOptionalTextSchema,
|
||||||
|
attribution: AttributionSchema,
|
||||||
|
vertebral_config: VertebralConfigSchema,
|
||||||
|
categories: z.array(AnnotationCategorySchema),
|
||||||
|
views: z.array(SheetViewSchema),
|
||||||
|
annotations: z.array(AnnotationSchema),
|
||||||
|
finding_zones: z.array(FindingZoneSchema),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
|
||||||
|
export type AnatomicalSheetDocument = z.output<
|
||||||
|
typeof AnatomicalSheetDocumentSchema
|
||||||
|
>
|
||||||
|
export type AnatomicalSheetDocumentInput = z.input<
|
||||||
|
typeof AnatomicalSheetDocumentSchema
|
||||||
|
>
|
||||||
|
export type VertebralRegion = z.infer<typeof VertebralRegionSchema>
|
||||||
|
export type AnnotationCategory = z.infer<typeof AnnotationCategorySchema>
|
||||||
|
export type ViewBox = z.infer<typeof ViewBoxSchema>
|
||||||
|
export type SheetView = z.infer<typeof SheetViewSchema>
|
||||||
|
export type Geometry = z.infer<typeof GeometrySchema>
|
||||||
|
export type Laterality = z.infer<typeof LateralitySchema>
|
||||||
|
export type Annotation = z.infer<typeof AnnotationSchema>
|
||||||
|
export type FindingCategoryKind = z.infer<typeof FindingCategoryKindSchema>
|
||||||
|
export type FindingCategory = z.output<typeof FindingCategorySchema>
|
||||||
|
export type FindingZone = z.output<typeof FindingZoneSchema>
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
import type {
|
||||||
|
AnatomicalSheetDocument,
|
||||||
|
Annotation,
|
||||||
|
FindingNode,
|
||||||
|
SheetView,
|
||||||
|
} from './schema'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Integrity tier of the sheet model (ANATOMICAL_SHEET_MODEL.md §2.1).
|
||||||
|
*
|
||||||
|
* The shape tier (Zod) accepts dangling references so drafts can be saved
|
||||||
|
* mid-edit; this tier lists every inconsistency for the editor and gates
|
||||||
|
* publication. Each rule is one function; codes are part of the contract
|
||||||
|
* shared with the SQL re-check (private.sheet_document_issues).
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type SheetIssueSeverity = 'error' | 'warning'
|
||||||
|
|
||||||
|
export interface SheetIssue {
|
||||||
|
code: string
|
||||||
|
severity: SheetIssueSeverity
|
||||||
|
path: string
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Rule = (doc: AnatomicalSheetDocument) => SheetIssue[]
|
||||||
|
|
||||||
|
type ObservableAnnotation = Exclude<Annotation, { kind: 'detail_trigger' }>
|
||||||
|
type TriggerAnnotation = Extract<Annotation, { kind: 'detail_trigger' }>
|
||||||
|
type DetailView = Extract<SheetView, { kind: 'detail' }>
|
||||||
|
|
||||||
|
/** A sibling level of the finding tree: categories or node children. */
|
||||||
|
interface FindingLevelItem {
|
||||||
|
id: string
|
||||||
|
children: readonly FindingNode[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function error(code: string, path: string, message: string): SheetIssue {
|
||||||
|
return { code, severity: 'error', path, message }
|
||||||
|
}
|
||||||
|
|
||||||
|
function warning(code: string, path: string, message: string): SheetIssue {
|
||||||
|
return { code, severity: 'warning', path, message }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexes of entries whose value already appeared earlier in the list. */
|
||||||
|
function repeatedIndexes(values: readonly string[]): number[] {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
const repeated: number[] = []
|
||||||
|
values.forEach((value, index) => {
|
||||||
|
if (seen.has(value)) repeated.push(index)
|
||||||
|
seen.add(value)
|
||||||
|
})
|
||||||
|
return repeated
|
||||||
|
}
|
||||||
|
|
||||||
|
function duplicateIssues(
|
||||||
|
values: readonly string[],
|
||||||
|
code: string,
|
||||||
|
pathOf: (index: number) => string,
|
||||||
|
): SheetIssue[] {
|
||||||
|
return repeatedIndexes(values).map((index) =>
|
||||||
|
error(code, pathOf(index), `Duplicate id "${values[index]}"`),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObservable(
|
||||||
|
annotation: Annotation,
|
||||||
|
): annotation is ObservableAnnotation {
|
||||||
|
return annotation.kind !== 'detail_trigger'
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTrigger(annotation: Annotation): annotation is TriggerAnnotation {
|
||||||
|
return annotation.kind === 'detail_trigger'
|
||||||
|
}
|
||||||
|
|
||||||
|
function viewsById(doc: AnatomicalSheetDocument): Map<string, SheetView> {
|
||||||
|
const byId = new Map<string, SheetView>()
|
||||||
|
for (const view of doc.views) if (!byId.has(view.id)) byId.set(view.id, view)
|
||||||
|
return byId
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rendering starts from a single root drawing. */
|
||||||
|
const checkMainViewCount: Rule = (doc) => {
|
||||||
|
const count = doc.views.filter((view) => view.kind === 'main').length
|
||||||
|
if (count === 1) return []
|
||||||
|
return [
|
||||||
|
error('view.main.count', 'views', `Expected 1 main view, found ${count}`),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkViewIdsUnique: Rule = (doc) =>
|
||||||
|
duplicateIssues(
|
||||||
|
doc.views.map((view) => view.id),
|
||||||
|
'view.id.duplicate',
|
||||||
|
(index) => `views[${index}].id`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkViewParentsExist: Rule = (doc) => {
|
||||||
|
const byId = viewsById(doc)
|
||||||
|
return doc.views.flatMap((view, index) =>
|
||||||
|
view.kind === 'detail' && !byId.has(view.parent_view_id)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'view.parent.missing',
|
||||||
|
`views[${index}].parent_view_id`,
|
||||||
|
`Parent view "${view.parent_view_id}" does not exist`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when the parent chain loops before reaching the main view. A
|
||||||
|
* missing parent ends the walk: that case is view.parent.missing.
|
||||||
|
*/
|
||||||
|
function loopsBeforeMain(view: DetailView, byId: Map<string, SheetView>) {
|
||||||
|
const visited = new Set<string>([view.id])
|
||||||
|
let current: SheetView = view
|
||||||
|
while (current.kind === 'detail') {
|
||||||
|
const parent = byId.get(current.parent_view_id)
|
||||||
|
if (!parent) return false
|
||||||
|
if (visited.has(parent.id)) return true
|
||||||
|
visited.add(parent.id)
|
||||||
|
current = parent
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkViewParentCycles: Rule = (doc) => {
|
||||||
|
const byId = viewsById(doc)
|
||||||
|
return doc.views.flatMap((view, index) =>
|
||||||
|
view.kind === 'detail' && loopsBeforeMain(view, byId)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'view.parent.cycle',
|
||||||
|
`views[${index}].parent_view_id`,
|
||||||
|
`Parent chain of "${view.id}" never reaches the main view`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isOpenedFromParent(
|
||||||
|
view: DetailView,
|
||||||
|
doc: AnatomicalSheetDocument,
|
||||||
|
): boolean {
|
||||||
|
return doc.annotations.some(
|
||||||
|
(annotation) =>
|
||||||
|
isTrigger(annotation) &&
|
||||||
|
annotation.opens_view_id === view.id &&
|
||||||
|
annotation.view_id === view.parent_view_id,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A detail view nobody can open is dead content for the practitioner. */
|
||||||
|
const checkViewsReachable: Rule = (doc) => {
|
||||||
|
const byId = viewsById(doc)
|
||||||
|
return doc.views.flatMap((view, index) =>
|
||||||
|
view.kind === 'detail' &&
|
||||||
|
byId.has(view.parent_view_id) &&
|
||||||
|
!isOpenedFromParent(view, doc)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'view.unreachable',
|
||||||
|
`views[${index}]`,
|
||||||
|
`No detail_trigger in "${view.parent_view_id}" opens "${view.id}"`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every view must have something to draw: its own asset or a crop. */
|
||||||
|
function viewAssetIssue(view: SheetView, index: number): SheetIssue[] {
|
||||||
|
if (view.svg_asset_id !== null) return []
|
||||||
|
if (view.kind === 'main') {
|
||||||
|
return [
|
||||||
|
error(
|
||||||
|
'view.asset.missing',
|
||||||
|
`views[${index}].svg_asset_id`,
|
||||||
|
`Main view "${view.id}" has no SVG asset`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
if (view.view_box !== null) return []
|
||||||
|
return [
|
||||||
|
error(
|
||||||
|
'view.asset.missing',
|
||||||
|
`views[${index}].view_box`,
|
||||||
|
`Detail view "${view.id}" has neither an asset nor a view_box`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkViewAssets: Rule = (doc) => doc.views.flatMap(viewAssetIssue)
|
||||||
|
|
||||||
|
/** Report points are keyed by annotation id across every view. */
|
||||||
|
const checkAnnotationIdsUnique: Rule = (doc) =>
|
||||||
|
duplicateIssues(
|
||||||
|
doc.annotations.map((annotation) => annotation.id),
|
||||||
|
'annotation.id.duplicate',
|
||||||
|
(index) => `annotations[${index}].id`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkAnnotationViews: Rule = (doc) => {
|
||||||
|
const byId = viewsById(doc)
|
||||||
|
return doc.annotations.flatMap((annotation, index) =>
|
||||||
|
byId.has(annotation.view_id)
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
error(
|
||||||
|
'annotation.view.missing',
|
||||||
|
`annotations[${index}].view_id`,
|
||||||
|
`View "${annotation.view_id}" does not exist`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkAnnotationCategories: Rule = (doc) => {
|
||||||
|
const ids = new Set(doc.categories.map((category) => category.id))
|
||||||
|
return doc.annotations.flatMap((annotation, index) =>
|
||||||
|
ids.has(annotation.category_id)
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
error(
|
||||||
|
'annotation.category.missing',
|
||||||
|
`annotations[${index}].category_id`,
|
||||||
|
`Category "${annotation.category_id}" does not exist`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A trigger opens a direct child of the view it is drawn in. */
|
||||||
|
function opensChildOfOwnView(
|
||||||
|
trigger: TriggerAnnotation,
|
||||||
|
byId: Map<string, SheetView>,
|
||||||
|
): boolean {
|
||||||
|
const target = byId.get(trigger.opens_view_id)
|
||||||
|
return target?.kind === 'detail' && target.parent_view_id === trigger.view_id
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkTriggerTargets: Rule = (doc) => {
|
||||||
|
const byId = viewsById(doc)
|
||||||
|
return doc.annotations.flatMap((annotation, index) =>
|
||||||
|
isTrigger(annotation) && !opensChildOfOwnView(annotation, byId)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'annotation.opens_view.invalid',
|
||||||
|
`annotations[${index}].opens_view_id`,
|
||||||
|
`"${annotation.opens_view_id}" is not a detail child of ` +
|
||||||
|
`"${annotation.view_id}"`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkAnnotationFindingZones: Rule = (doc) => {
|
||||||
|
const ids = new Set(doc.finding_zones.map((zone) => zone.id))
|
||||||
|
return doc.annotations.flatMap((annotation, index) =>
|
||||||
|
isObservable(annotation) &&
|
||||||
|
annotation.finding_zone_id !== null &&
|
||||||
|
!ids.has(annotation.finding_zone_id)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'annotation.finding_zone.missing',
|
||||||
|
`annotations[${index}].finding_zone_id`,
|
||||||
|
`Finding zone "${annotation.finding_zone_id}" does not exist`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkAnnotationRegions: Rule = (doc) => {
|
||||||
|
const codes = new Set(doc.vertebral_config.regions.map((r) => r.code))
|
||||||
|
return doc.annotations.flatMap((annotation, index) =>
|
||||||
|
isObservable(annotation) &&
|
||||||
|
annotation.vertebral_region_code !== null &&
|
||||||
|
!codes.has(annotation.vertebral_region_code)
|
||||||
|
? [
|
||||||
|
error(
|
||||||
|
'annotation.region.missing',
|
||||||
|
`annotations[${index}].vertebral_region_code`,
|
||||||
|
`Vertebral region "${annotation.vertebral_region_code}" ` +
|
||||||
|
'is not configured',
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Allowed in a draft, but a click on it would offer nothing to record. */
|
||||||
|
const checkAnnotationsHaveFindings: Rule = (doc) =>
|
||||||
|
doc.annotations.flatMap((annotation, index) =>
|
||||||
|
isObservable(annotation) && annotation.finding_zone_id === null
|
||||||
|
? [
|
||||||
|
warning(
|
||||||
|
'annotation.no_findings',
|
||||||
|
`annotations[${index}].finding_zone_id`,
|
||||||
|
`Annotation "${annotation.id}" is linked to no finding zone`,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkRegionCodesUnique: Rule = (doc) =>
|
||||||
|
duplicateIssues(
|
||||||
|
doc.vertebral_config.regions.map((region) => region.code),
|
||||||
|
'region.code.duplicate',
|
||||||
|
(index) => `vertebral_config.regions[${index}].code`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkCategoryIdsUnique: Rule = (doc) =>
|
||||||
|
duplicateIssues(
|
||||||
|
doc.categories.map((category) => category.id),
|
||||||
|
'category.id.duplicate',
|
||||||
|
(index) => `categories[${index}].id`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const checkFindingZoneIdsUnique: Rule = (doc) =>
|
||||||
|
duplicateIssues(
|
||||||
|
doc.finding_zones.map((zone) => zone.id),
|
||||||
|
'finding_zone.id.duplicate',
|
||||||
|
(index) => `finding_zones[${index}].id`,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Findings are addressed by (zone, path[]) as Finding.path does today, so
|
||||||
|
* ids only need to be unique among siblings, at every depth.
|
||||||
|
*/
|
||||||
|
function siblingIssues(
|
||||||
|
nodes: readonly FindingLevelItem[],
|
||||||
|
path: string,
|
||||||
|
): SheetIssue[] {
|
||||||
|
const own = duplicateIssues(
|
||||||
|
nodes.map((node) => node.id),
|
||||||
|
'finding.id.duplicate',
|
||||||
|
(index) => `${path}[${index}].id`,
|
||||||
|
)
|
||||||
|
const nested = nodes.flatMap((node, index) =>
|
||||||
|
siblingIssues(node.children, `${path}[${index}].children`),
|
||||||
|
)
|
||||||
|
return [...own, ...nested]
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkFindingSiblings: Rule = (doc) =>
|
||||||
|
doc.finding_zones.flatMap((zone, index) =>
|
||||||
|
siblingIssues(zone.categories, `finding_zones[${index}].categories`),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Allowed in a draft, but nothing on the drawing can reach this zone. */
|
||||||
|
const checkFindingZonesReferenced: Rule = (doc) => {
|
||||||
|
const referenced = new Set(
|
||||||
|
doc.annotations.filter(isObservable).map((a) => a.finding_zone_id),
|
||||||
|
)
|
||||||
|
return doc.finding_zones.flatMap((zone, index) =>
|
||||||
|
referenced.has(zone.id)
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
warning(
|
||||||
|
'finding_zone.unreferenced',
|
||||||
|
`finding_zones[${index}]`,
|
||||||
|
`No annotation points to finding zone "${zone.id}"`,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const RULES: readonly Rule[] = [
|
||||||
|
checkMainViewCount,
|
||||||
|
checkViewIdsUnique,
|
||||||
|
checkViewParentsExist,
|
||||||
|
checkViewParentCycles,
|
||||||
|
checkViewsReachable,
|
||||||
|
checkViewAssets,
|
||||||
|
checkAnnotationIdsUnique,
|
||||||
|
checkAnnotationViews,
|
||||||
|
checkAnnotationCategories,
|
||||||
|
checkTriggerTargets,
|
||||||
|
checkAnnotationFindingZones,
|
||||||
|
checkAnnotationRegions,
|
||||||
|
checkAnnotationsHaveFindings,
|
||||||
|
checkRegionCodesUnique,
|
||||||
|
checkCategoryIdsUnique,
|
||||||
|
checkFindingZoneIdsUnique,
|
||||||
|
checkFindingSiblings,
|
||||||
|
checkFindingZonesReferenced,
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Lists every integrity issue of a shape-valid document. */
|
||||||
|
export function validateSheetDocument(
|
||||||
|
doc: AnatomicalSheetDocument,
|
||||||
|
): SheetIssue[] {
|
||||||
|
return RULES.flatMap((rule) => rule(doc))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Warnings never block publication; errors always do. */
|
||||||
|
export function isPublishable(issues: readonly SheetIssue[]): boolean {
|
||||||
|
return !issues.some((issue) => issue.severity === 'error')
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SheetValidationError extends Error {
|
||||||
|
readonly issues: SheetIssue[]
|
||||||
|
|
||||||
|
constructor(issues: SheetIssue[]) {
|
||||||
|
const errors = issues.filter((issue) => issue.severity === 'error')
|
||||||
|
super(
|
||||||
|
`Sheet document is not publishable: ${errors.length} error(s), ` +
|
||||||
|
`first: ${errors[0]?.code ?? 'none'}`,
|
||||||
|
)
|
||||||
|
this.name = 'SheetValidationError'
|
||||||
|
this.issues = issues
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TypeScript-side publication gate, mirrored by SQL at publish time. */
|
||||||
|
export function assertPublishable(doc: AnatomicalSheetDocument): void {
|
||||||
|
const issues = validateSheetDocument(doc)
|
||||||
|
if (!isPublishable(issues)) throw new SheetValidationError(issues)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export * from './anatomical-sheet'
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
FindingNodeSchema,
|
||||||
|
StableIdSchema,
|
||||||
|
type AnatomicalSheetDocumentInput,
|
||||||
|
} from '../src'
|
||||||
|
import { horseSlice, horseSliceInput } from './fixtures/horse-slice'
|
||||||
|
|
||||||
|
type Tree = Record<string, unknown>
|
||||||
|
type Mutation = (doc: Tree) => void
|
||||||
|
|
||||||
|
/** Walks `path` inside a JSON tree; mutations break the typed shape on purpose. */
|
||||||
|
function at(doc: Tree, path: (string | number)[]): Tree {
|
||||||
|
return path.reduce<Tree>((node, key) => node[key] as Tree, doc)
|
||||||
|
}
|
||||||
|
|
||||||
|
function set(doc: Tree, path: (string | number)[], value: unknown): void {
|
||||||
|
at(doc, path.slice(0, -1))[String(path.at(-1))] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
function unset(doc: Tree, path: (string | number)[]): void {
|
||||||
|
delete at(doc, path.slice(0, -1))[String(path.at(-1))]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Applies a mutation to the lean fixture and reports whether it parses. */
|
||||||
|
function parsesAfter(mutate: Mutation): boolean {
|
||||||
|
const doc = horseSliceInput() as unknown as Tree
|
||||||
|
mutate(doc)
|
||||||
|
return AnatomicalSheetDocumentSchema.safeParse(doc).success
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AnatomicalSheetDocumentSchema', () => {
|
||||||
|
it('accepts the horse slice fixture', () => {
|
||||||
|
const result = AnatomicalSheetDocumentSchema.safeParse(horseSliceInput())
|
||||||
|
expect(result.success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts a parsed document again (output is valid input)', () => {
|
||||||
|
expect(AnatomicalSheetDocumentSchema.parse(horseSlice())).toEqual(
|
||||||
|
horseSlice(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
const rejections: Array<[string, Mutation]> = [
|
||||||
|
['an unknown top-level key', (d) => set(d, ['extra'], true)],
|
||||||
|
['an unknown nested key', (d) => set(d, ['views', 0, 'zoom'], 2)],
|
||||||
|
[
|
||||||
|
'a stable id with spaces',
|
||||||
|
(d) => set(d, ['annotations', 0, 'id'], 'Hip Joint'),
|
||||||
|
],
|
||||||
|
['a stable id with an accent', (d) => set(d, ['categories', 0, 'id'], 'É')],
|
||||||
|
['an empty stable id', (d) => set(d, ['finding_zones', 0, 'id'], '')],
|
||||||
|
['schema_version 2', (d) => set(d, ['schema_version'], 2)],
|
||||||
|
[
|
||||||
|
'a non-uuid svg_asset_id',
|
||||||
|
(d) => set(d, ['views', 0, 'svg_asset_id'], 'horse'),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a polygon with 2 points',
|
||||||
|
(d) =>
|
||||||
|
set(
|
||||||
|
d,
|
||||||
|
['annotations', 1, 'geometry', 'points'],
|
||||||
|
[
|
||||||
|
[0, 0],
|
||||||
|
[1, 1],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a circle with r 0',
|
||||||
|
(d) => set(d, ['annotations', 0, 'geometry', 'r'], 0),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a region count of 0',
|
||||||
|
(d) => set(d, ['vertebral_config', 'regions', 0, 'count'], 0),
|
||||||
|
],
|
||||||
|
['a missing en label', (d) => unset(d, ['name', 'en'])],
|
||||||
|
[
|
||||||
|
'a detail view without parent_view_id',
|
||||||
|
(d) => unset(d, ['views', 1, 'parent_view_id']),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a detail_trigger with finding_zone_id',
|
||||||
|
(d) => set(d, ['annotations', 3, 'finding_zone_id'], 'hip'),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a javascript: source url',
|
||||||
|
(d) =>
|
||||||
|
set(
|
||||||
|
d,
|
||||||
|
[
|
||||||
|
'finding_zones',
|
||||||
|
0,
|
||||||
|
'categories',
|
||||||
|
2,
|
||||||
|
'children',
|
||||||
|
0,
|
||||||
|
'sources',
|
||||||
|
0,
|
||||||
|
'url',
|
||||||
|
],
|
||||||
|
'javascript:alert(1)',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a finding category kind foo',
|
||||||
|
(d) => set(d, ['finding_zones', 0, 'categories', 0, 'kind'], 'foo'),
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
it.each(rejections)('rejects %s', (_label, mutate) => {
|
||||||
|
expect(parsesAfter(mutate)).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('StableIdSchema', () => {
|
||||||
|
it.each(['hip', 'c7-t1', 'view_main', '0'])('accepts %s', (id) => {
|
||||||
|
expect(StableIdSchema.safeParse(id).success).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each(['Hip Joint', 'É', '', '-hip', 'a'.repeat(65)])(
|
||||||
|
'rejects %j',
|
||||||
|
(id) => {
|
||||||
|
expect(StableIdSchema.safeParse(id).success).toBe(false)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('FindingNodeSchema defaults', () => {
|
||||||
|
it('fills the optional keys of a lean node, recursively', () => {
|
||||||
|
const node = FindingNodeSchema.parse({
|
||||||
|
id: 'articular',
|
||||||
|
name: { fr: 'Articulaire', en: 'Articular' },
|
||||||
|
children: [{ id: 'flexion', name: { fr: 'Flexion', en: 'Flexion' } }],
|
||||||
|
})
|
||||||
|
expect(node.description).toEqual({})
|
||||||
|
expect(node.requires_vet_referral).toBe(false)
|
||||||
|
expect(node.sources).toEqual([])
|
||||||
|
expect(node.children[0]).toEqual({
|
||||||
|
id: 'flexion',
|
||||||
|
name: { fr: 'Flexion', en: 'Flexion' },
|
||||||
|
description: {},
|
||||||
|
requires_vet_referral: false,
|
||||||
|
sources: [],
|
||||||
|
children: [],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps explicit values of the fixture', () => {
|
||||||
|
const doc = horseSlice()
|
||||||
|
const lameness = doc.finding_zones[0].categories[1].children[0]
|
||||||
|
expect(lameness.requires_vet_referral).toBe(true)
|
||||||
|
const trauma = doc.finding_zones[0].categories[2].children[0]
|
||||||
|
expect(trauma.sources).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not add default keys to the lean input', () => {
|
||||||
|
const input: AnatomicalSheetDocumentInput = horseSliceInput()
|
||||||
|
const leaf = input.finding_zones[2].categories[0].children[0]
|
||||||
|
expect(Object.keys(leaf)).toEqual(['id', 'name'])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,426 @@
|
|||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
SheetValidationError,
|
||||||
|
assertPublishable,
|
||||||
|
createEmptySheetDocument,
|
||||||
|
isPublishable,
|
||||||
|
validateSheetDocument,
|
||||||
|
type AnatomicalSheetDocument,
|
||||||
|
type Annotation,
|
||||||
|
type SheetView,
|
||||||
|
} from '../src'
|
||||||
|
import { HORSE_MAIN_ASSET_ID, horseSlice } from './fixtures/horse-slice'
|
||||||
|
|
||||||
|
/** [code, path] pairs: what each rule test pins down. */
|
||||||
|
function issuesOf(doc: AnatomicalSheetDocument): Array<[string, string]> {
|
||||||
|
return validateSheetDocument(doc).map((issue) => [issue.code, issue.path])
|
||||||
|
}
|
||||||
|
|
||||||
|
function mutated(
|
||||||
|
mutate: (doc: AnatomicalSheetDocument) => void,
|
||||||
|
): AnatomicalSheetDocument {
|
||||||
|
const doc = horseSlice()
|
||||||
|
mutate(doc)
|
||||||
|
return doc
|
||||||
|
}
|
||||||
|
|
||||||
|
function point(id: string, fields: Partial<Annotation> = {}): Annotation {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
kind: 'point',
|
||||||
|
view_id: 'view-main',
|
||||||
|
category_id: 'articulations',
|
||||||
|
laterality: 'bilateral',
|
||||||
|
geometry: null,
|
||||||
|
name: { fr: id, en: id },
|
||||||
|
finding_zone_id: 'hip',
|
||||||
|
vertebral_region_code: null,
|
||||||
|
...fields,
|
||||||
|
} as Annotation
|
||||||
|
}
|
||||||
|
|
||||||
|
function trigger(id: string, viewId: string, opensViewId: string) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
kind: 'detail_trigger',
|
||||||
|
view_id: viewId,
|
||||||
|
category_id: 'cadrans-du-crane',
|
||||||
|
laterality: 'unpaired',
|
||||||
|
geometry: null,
|
||||||
|
name: null,
|
||||||
|
opens_view_id: opensViewId,
|
||||||
|
} satisfies Annotation
|
||||||
|
}
|
||||||
|
|
||||||
|
function detailView(id: string, parentId: string) {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
kind: 'detail',
|
||||||
|
name: { fr: id, en: id },
|
||||||
|
parent_view_id: parentId,
|
||||||
|
svg_asset_id: HORSE_MAIN_ASSET_ID,
|
||||||
|
view_box: null,
|
||||||
|
} satisfies SheetView
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('validateSheetDocument on the horse slice', () => {
|
||||||
|
it('reports no error and no warning', () => {
|
||||||
|
expect(validateSheetDocument(horseSlice())).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('integrity rules (one mutation per code)', () => {
|
||||||
|
it('view.main.count', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views.push({ ...d.views[0], id: 'view-alt' })
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([['view.main.count', 'views']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.main.count with no main view', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views = d.views.filter((view) => view.kind !== 'main')
|
||||||
|
})
|
||||||
|
const codes = issuesOf(doc).map(([code]) => code)
|
||||||
|
expect(codes).toContain('view.main.count')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.id.duplicate', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views.push(structuredClone(d.views[1]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([['view.id.duplicate', 'views[2].id']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.parent.missing', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views.push(detailView('view-orphan', 'view-ghost'))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['view.parent.missing', 'views[2].parent_view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.parent.cycle (terminates on a two-view loop)', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views.push(detailView('view-a', 'view-b'))
|
||||||
|
d.views.push(detailView('view-b', 'view-a'))
|
||||||
|
d.annotations.push(trigger('open-a', 'view-b', 'view-a'))
|
||||||
|
d.annotations.push(trigger('open-b', 'view-a', 'view-b'))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['view.parent.cycle', 'views[2].parent_view_id'],
|
||||||
|
['view.parent.cycle', 'views[3].parent_view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.parent.cycle on a self-parent', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views.push(detailView('view-self', 'view-self'))
|
||||||
|
d.annotations.push(trigger('open-self', 'view-self', 'view-self'))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['view.parent.cycle', 'views[2].parent_view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.unreachable', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations = d.annotations.filter((a) => a.id !== 'head-trigger')
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([['view.unreachable', 'views[1]']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.asset.missing on the main view', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views[0].svg_asset_id = null
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['view.asset.missing', 'views[0].svg_asset_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('view.asset.missing on a detail view without asset nor view_box', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views[1].view_box = null
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([['view.asset.missing', 'views[1].view_box']])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.id.duplicate (across views)', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push({ ...structuredClone(d.annotations[4]) })
|
||||||
|
d.annotations[6].view_id = 'view-main'
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.id.duplicate', 'annotations[6].id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.view.missing', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(point('ghost', { view_id: 'view-ghost' }))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.view.missing', 'annotations[6].view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.category.missing', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations[0].category_id = 'os'
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.category.missing', 'annotations[0].category_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.opens_view.invalid when the target is not a child', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(trigger('loop', 'view-head', 'view-head'))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.opens_view.invalid', 'annotations[6].opens_view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.opens_view.invalid when the target is main or absent', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(trigger('to-main', 'view-main', 'view-main'))
|
||||||
|
d.annotations.push(trigger('to-ghost', 'view-main', 'view-ghost'))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.opens_view.invalid', 'annotations[6].opens_view_id'],
|
||||||
|
['annotation.opens_view.invalid', 'annotations[7].opens_view_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.finding_zone.missing', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(point('stifle', { finding_zone_id: 'stifle' }))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.finding_zone.missing', 'annotations[6].finding_zone_id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.region.missing', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
const cervical = d.annotations[1]
|
||||||
|
if (cervical.kind === 'detail_trigger') throw new Error('fixture')
|
||||||
|
cervical.vertebral_region_code = 'Q'
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.region.missing', 'annotations[1].vertebral_region_code'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('annotation.no_findings is a warning', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(point('mandible', { finding_zone_id: null }))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['annotation.no_findings', 'annotations[6].finding_zone_id'],
|
||||||
|
])
|
||||||
|
expect(validateSheetDocument(doc)[0].severity).toBe('warning')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('region.code.duplicate', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
const regions = d.vertebral_config.regions
|
||||||
|
regions.push(structuredClone(regions[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['region.code.duplicate', 'vertebral_config.regions[5].code'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('category.id.duplicate', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.categories.push(structuredClone(d.categories[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['category.id.duplicate', 'categories[4].id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finding_zone.id.duplicate', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.finding_zones.push(structuredClone(d.finding_zones[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['finding_zone.id.duplicate', 'finding_zones[5].id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finding.id.duplicate among finding categories', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
const categories = d.finding_zones[0].categories
|
||||||
|
categories.push(structuredClone(categories[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['finding.id.duplicate', 'finding_zones[0].categories[3].id'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finding.id.duplicate among nested children', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
const articular = d.finding_zones[0].categories[0].children[0]
|
||||||
|
articular.children.push(structuredClone(articular.children[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
[
|
||||||
|
'finding.id.duplicate',
|
||||||
|
'finding_zones[0].categories[0].children[0].children[2].id',
|
||||||
|
],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finding ids may repeat across different sibling arrays', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
const hip = d.finding_zones[0].categories
|
||||||
|
hip[1].children.push(structuredClone(hip[0].children[0]))
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('finding_zone.unreferenced is a warning', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.finding_zones.push({
|
||||||
|
id: 'stifle',
|
||||||
|
name: { fr: 'Grasset', en: 'Stifle' },
|
||||||
|
categories: [],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
expect(issuesOf(doc)).toEqual([
|
||||||
|
['finding_zone.unreferenced', 'finding_zones[5]'],
|
||||||
|
])
|
||||||
|
expect(validateSheetDocument(doc)[0].severity).toBe('warning')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('publication gate', () => {
|
||||||
|
it('accepts the fixture', () => {
|
||||||
|
expect(isPublishable(validateSheetDocument(horseSlice()))).toBe(true)
|
||||||
|
expect(() => assertPublishable(horseSlice())).not.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('accepts a document with warnings only', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.annotations.push(point('mandible', { finding_zone_id: null }))
|
||||||
|
})
|
||||||
|
expect(validateSheetDocument(doc)).toHaveLength(1)
|
||||||
|
expect(isPublishable(validateSheetDocument(doc))).toBe(true)
|
||||||
|
expect(() => assertPublishable(doc)).not.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a document with an error, exposing the issues', () => {
|
||||||
|
const doc = mutated((d) => {
|
||||||
|
d.views[0].svg_asset_id = null
|
||||||
|
})
|
||||||
|
expect(isPublishable(validateSheetDocument(doc))).toBe(false)
|
||||||
|
let caught: unknown
|
||||||
|
try {
|
||||||
|
assertPublishable(doc)
|
||||||
|
} catch (thrown) {
|
||||||
|
caught = thrown
|
||||||
|
}
|
||||||
|
expect(caught).toBeInstanceOf(SheetValidationError)
|
||||||
|
const codes = (caught as SheetValidationError).issues.map((i) => i.code)
|
||||||
|
expect(codes).toEqual(['view.asset.missing'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('createEmptySheetDocument', () => {
|
||||||
|
const empty = () =>
|
||||||
|
createEmptySheetDocument({
|
||||||
|
species_id: 'equine',
|
||||||
|
name: { fr: 'Nouvelle fiche', en: 'New sheet' },
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is valid for the shape tier', () => {
|
||||||
|
expect(AnatomicalSheetDocumentSchema.safeParse(empty()).success).toBe(true)
|
||||||
|
expect(empty().views).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
id: 'view-main',
|
||||||
|
kind: 'main',
|
||||||
|
svg_asset_id: null,
|
||||||
|
view_box: null,
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('is not publishable: the main view has no asset', () => {
|
||||||
|
const issues = validateSheetDocument(empty())
|
||||||
|
expect(issues.map((issue) => issue.code)).toEqual(['view.asset.missing'])
|
||||||
|
expect(() => assertPublishable(empty())).toThrow(SheetValidationError)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/** True for a { fr?, en? } label object, the only thing a translator edits. */
|
||||||
|
function isLabel(value: unknown): value is Record<string, string> {
|
||||||
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
const keys = Object.keys(value)
|
||||||
|
return keys.length > 0 && keys.every((key) => key === 'fr' || key === 'en')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rewrites every label with arbitrary strings, leaving all else intact. */
|
||||||
|
function mapLabels(
|
||||||
|
value: unknown,
|
||||||
|
rewrite: (label: Record<string, string>) => unknown,
|
||||||
|
): unknown {
|
||||||
|
if (isLabel(value)) return rewrite(value)
|
||||||
|
if (Array.isArray(value)) return value.map((v) => mapLabels(v, rewrite))
|
||||||
|
if (value === null || typeof value !== 'object') return value
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(value).map(([k, v]) => [k, mapLabels(v, rewrite)]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every id and reference: values of keys named id, *_id or code. */
|
||||||
|
function collectIds(value: unknown, out: string[] = []): string[] {
|
||||||
|
if (Array.isArray(value)) value.forEach((v) => collectIds(v, out))
|
||||||
|
else if (value !== null && typeof value === 'object') {
|
||||||
|
for (const [key, v] of Object.entries(value)) {
|
||||||
|
const isRef = key === 'id' || key.endsWith('_id') || key.endsWith('code')
|
||||||
|
if (isRef && typeof v === 'string') out.push(`${key}=${v}`)
|
||||||
|
else collectIds(v, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ID stability under translation', () => {
|
||||||
|
it('keeps ids, references and validation output when labels change', () => {
|
||||||
|
const original = horseSlice()
|
||||||
|
let counter = 0
|
||||||
|
const relabeled = AnatomicalSheetDocumentSchema.parse(
|
||||||
|
mapLabels(original, (label) =>
|
||||||
|
Object.fromEntries(
|
||||||
|
Object.keys(label).map((locale) => [locale, `x${counter++}`]),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
expect(counter).toBeGreaterThan(50)
|
||||||
|
expect(JSON.stringify(relabeled)).not.toEqual(JSON.stringify(original))
|
||||||
|
expect(collectIds(relabeled)).toEqual(collectIds(original))
|
||||||
|
const strip = () => null
|
||||||
|
expect(mapLabels(relabeled, strip)).toEqual(mapLabels(original, strip))
|
||||||
|
expect(validateSheetDocument(relabeled)).toEqual(
|
||||||
|
validateSheetDocument(original),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps validation output identical on a broken document too', () => {
|
||||||
|
const broken = mutated((d) => {
|
||||||
|
d.annotations[0].category_id = 'os'
|
||||||
|
d.views[1].view_box = null
|
||||||
|
})
|
||||||
|
const relabeled = mapLabels(broken, () => ({ fr: 'a', en: 'b' }))
|
||||||
|
expect(validateSheetDocument(relabeled as AnatomicalSheetDocument)).toEqual(
|
||||||
|
validateSheetDocument(broken),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
+443
@@ -0,0 +1,443 @@
|
|||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
type AnatomicalSheetDocument,
|
||||||
|
type AnatomicalSheetDocumentInput,
|
||||||
|
type FindingNodeInput,
|
||||||
|
} from '../../src'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reduced equine sheet built from the real assets: labels come from
|
||||||
|
* apps/app/public/species/equine/{Horse,Horse_head}.svg and from
|
||||||
|
* apps/app/src/domain/species/equine/pathologies.json. It exercises two
|
||||||
|
* views (one cropped detail), a trigger, a spine region, a bilateral joint,
|
||||||
|
* the three finding kinds, a two-level tree, a vet referral and a source.
|
||||||
|
* It references every finding zone, so it validates with zero issues.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const HORSE_MAIN_ASSET_ID = '3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8'
|
||||||
|
|
||||||
|
function leaf(id: string, fr: string, en: string): FindingNodeInput {
|
||||||
|
return { id, name: { fr, en } }
|
||||||
|
}
|
||||||
|
|
||||||
|
const ANAMNESIS = {
|
||||||
|
id: 'anamnesis',
|
||||||
|
kind: 'anamnesis',
|
||||||
|
name: {
|
||||||
|
fr: 'Anamnèse / facteurs rapportés',
|
||||||
|
en: 'Anamnesis / reported factors',
|
||||||
|
},
|
||||||
|
description: {
|
||||||
|
fr: "Facteurs rapportés par le propriétaire lors de l'anamnèse",
|
||||||
|
},
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const OBSERVATIONS_NAME = {
|
||||||
|
fr: 'Observations / motifs de consultation',
|
||||||
|
en: 'Observations / consultation reasons',
|
||||||
|
}
|
||||||
|
|
||||||
|
const DYSFUNCTIONS_NAME = {
|
||||||
|
fr: 'Dysfonctions ostéopathiques',
|
||||||
|
en: 'Osteopathic dysfunctions',
|
||||||
|
}
|
||||||
|
|
||||||
|
const TRAUMA = leaf(
|
||||||
|
'trauma-direct',
|
||||||
|
'Traumatisme rapporté (choc, chute)',
|
||||||
|
'Reported trauma (blow, fall)',
|
||||||
|
)
|
||||||
|
|
||||||
|
const STRESS = leaf(
|
||||||
|
'stress-context',
|
||||||
|
'Contexte de stress / changement',
|
||||||
|
'Stress / change context',
|
||||||
|
)
|
||||||
|
|
||||||
|
const HIP_ZONE = {
|
||||||
|
id: 'hip',
|
||||||
|
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'hip-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
name: DYSFUNCTIONS_NAME,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
id: 'articular',
|
||||||
|
name: {
|
||||||
|
fr: 'Restrictions de mobilité articulaire',
|
||||||
|
en: 'Articular mobility restrictions',
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'restriction-flexion',
|
||||||
|
'Restriction en flexion',
|
||||||
|
'Flexion restriction',
|
||||||
|
),
|
||||||
|
leaf(
|
||||||
|
'restriction-extension',
|
||||||
|
'Restriction en extension',
|
||||||
|
'Extension restriction',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'hip-observations',
|
||||||
|
kind: 'observation',
|
||||||
|
name: OBSERVATIONS_NAME,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
...leaf(
|
||||||
|
'limb-lameness',
|
||||||
|
'Boiterie rapportée (membre concerné)',
|
||||||
|
'Reported lameness (affected limb)',
|
||||||
|
),
|
||||||
|
requires_vet_referral: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...ANAMNESIS,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
...TRAUMA,
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
type: 'manual',
|
||||||
|
citation: 'Legacy equine catalog (pathologies.json)',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
|
||||||
|
|
||||||
|
const CERVICAL_ZONE = {
|
||||||
|
id: 'cervical',
|
||||||
|
name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' },
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'cervical-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
name: DYSFUNCTIONS_NAME,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
id: 'muscular',
|
||||||
|
name: {
|
||||||
|
fr: 'Tensions musculaires paravertébrales',
|
||||||
|
en: 'Paravertebral muscle tensions',
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
leaf('splenius-tension', 'Tension du splénius', 'Splenius tension'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cervical-observations',
|
||||||
|
kind: 'observation',
|
||||||
|
name: OBSERVATIONS_NAME,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
...leaf(
|
||||||
|
'stumbling-proprioceptive',
|
||||||
|
'Trébuchements / déficit proprioceptif rapporté',
|
||||||
|
'Reported stumbling / proprioceptive deficit',
|
||||||
|
),
|
||||||
|
requires_vet_referral: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ ...ANAMNESIS, children: [TRAUMA] },
|
||||||
|
],
|
||||||
|
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
|
||||||
|
|
||||||
|
const C7_T1_ZONE = {
|
||||||
|
id: 'c7-t1',
|
||||||
|
name: {
|
||||||
|
fr: 'Charnière C7-T1 (cervico-thoracique)',
|
||||||
|
en: 'C7-T1 (Cervicothoracic)',
|
||||||
|
},
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'c7-t1-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
name: DYSFUNCTIONS_NAME,
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'restriction-rotation',
|
||||||
|
'Restriction en rotation',
|
||||||
|
'Rotation restriction',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'c7-t1-observations',
|
||||||
|
kind: 'observation',
|
||||||
|
name: OBSERVATIONS_NAME,
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'base-neck-stiffness',
|
||||||
|
"Raideur de la base de l'encolure",
|
||||||
|
'Base-of-neck stiffness',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ ...ANAMNESIS, children: [STRESS] },
|
||||||
|
],
|
||||||
|
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
|
||||||
|
|
||||||
|
const ATM_ZONE = {
|
||||||
|
id: 'atm',
|
||||||
|
name: {
|
||||||
|
fr: 'Articulation Temporo-Mandibulaire (ATM)',
|
||||||
|
en: 'Temporomandibular Joint (TMJ)',
|
||||||
|
},
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'atm-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
name: {
|
||||||
|
fr: "Dysfonctions ostéopathiques de l'ATM",
|
||||||
|
en: 'Osteopathic TMJ dysfunctions',
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
leaf('masseter-tension', 'Tension du masséter', 'Masseter tension'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'atm-observations',
|
||||||
|
kind: 'observation',
|
||||||
|
name: OBSERVATIONS_NAME,
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'bit-defense',
|
||||||
|
'Réactions de défense au mors',
|
||||||
|
'Defense reactions to bit',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...ANAMNESIS,
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'dental-context',
|
||||||
|
'Suite de soin dentaire récent',
|
||||||
|
'Post recent dental care',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
|
||||||
|
|
||||||
|
const SPHENOID_ZONE = {
|
||||||
|
id: 'sphenoid',
|
||||||
|
name: { fr: 'Sphénoïde', en: 'Sphenoid' },
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'ssb-dysfunctions',
|
||||||
|
kind: 'dysfunction',
|
||||||
|
name: DYSFUNCTIONS_NAME,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
id: 'physiological',
|
||||||
|
name: {
|
||||||
|
fr: 'Lésions physiologiques (SSB)',
|
||||||
|
en: 'Physiological lesions (SBS)',
|
||||||
|
},
|
||||||
|
children: [
|
||||||
|
leaf('torsion-right', 'Torsion droite', 'Right torsion'),
|
||||||
|
leaf('torsion-left', 'Torsion gauche', 'Left torsion'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sphenoid-observations',
|
||||||
|
kind: 'observation',
|
||||||
|
name: OBSERVATIONS_NAME,
|
||||||
|
children: [
|
||||||
|
leaf(
|
||||||
|
'post-trauma-head',
|
||||||
|
'Suite de traumatisme crânien',
|
||||||
|
'Post head trauma',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ ...ANAMNESIS, children: [TRAUMA, STRESS] },
|
||||||
|
],
|
||||||
|
} satisfies AnatomicalSheetDocumentInput['finding_zones'][number]
|
||||||
|
|
||||||
|
const HORSE_SLICE_INPUT: AnatomicalSheetDocumentInput = {
|
||||||
|
schema_version: 1,
|
||||||
|
species_id: 'equine',
|
||||||
|
name: { fr: 'Cheval (extrait)', en: 'Horse (slice)' },
|
||||||
|
description: {
|
||||||
|
fr: 'Extrait de la fiche équine pour les tests du modèle',
|
||||||
|
en: 'Equine sheet slice for model tests',
|
||||||
|
},
|
||||||
|
scope_disclaimer: {
|
||||||
|
fr:
|
||||||
|
"Les éléments listés correspondent au périmètre légal de l'ostéopathie " +
|
||||||
|
'animale : dysfonctions ostéopathiques palpées, observations cliniques ' +
|
||||||
|
"et motifs de consultation. Aucun diagnostic médical n'est posé. " +
|
||||||
|
'Toute pathologie organique relève du vétérinaire.',
|
||||||
|
},
|
||||||
|
attribution: { authors: ['Faunosteo'], license: 'MIT', notes: null },
|
||||||
|
vertebral_config: {
|
||||||
|
regions: [
|
||||||
|
{ code: 'C', name: { fr: 'Cervicales', en: 'Cervical' }, count: 7 },
|
||||||
|
{ code: 'T', name: { fr: 'Thoraciques', en: 'Thoracic' }, count: 18 },
|
||||||
|
{ code: 'L', name: { fr: 'Lombaires', en: 'Lumbar' }, count: 6 },
|
||||||
|
{ code: 'S', name: { fr: 'Sacrées', en: 'Sacral' }, count: 5 },
|
||||||
|
{ code: 'Cd', name: { fr: 'Caudales', en: 'Caudal' }, count: 18 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
categories: [
|
||||||
|
{
|
||||||
|
id: 'articulations',
|
||||||
|
name: { fr: 'Articulations', en: 'Joints' },
|
||||||
|
color: '#ff9500',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'zone-colonne',
|
||||||
|
name: { fr: 'Zone colonne', en: 'Spine zone' },
|
||||||
|
color: '#e100ff',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'charnieres-vertebrales',
|
||||||
|
name: { fr: 'Charnières vertébrales', en: 'Vertebral junctions' },
|
||||||
|
color: '#ff0000',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cadrans-du-crane',
|
||||||
|
name: { fr: 'Cadrans du crâne', en: 'Skull quadrants' },
|
||||||
|
color: '#1baa08',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
views: [
|
||||||
|
{
|
||||||
|
id: 'view-main',
|
||||||
|
kind: 'main',
|
||||||
|
name: { fr: 'Cheval entier', en: 'Whole horse' },
|
||||||
|
svg_asset_id: HORSE_MAIN_ASSET_ID,
|
||||||
|
view_box: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'view-head',
|
||||||
|
kind: 'detail',
|
||||||
|
name: { fr: 'Tête', en: 'Head' },
|
||||||
|
parent_view_id: 'view-main',
|
||||||
|
svg_asset_id: null,
|
||||||
|
view_box: { min_x: 60, min_y: 100, width: 500, height: 380 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
annotations: [
|
||||||
|
{
|
||||||
|
id: 'hip',
|
||||||
|
kind: 'point',
|
||||||
|
view_id: 'view-main',
|
||||||
|
category_id: 'articulations',
|
||||||
|
laterality: 'bilateral',
|
||||||
|
geometry: { type: 'circle', cx: 1516, cy: 695, r: 34 },
|
||||||
|
name: { fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' },
|
||||||
|
finding_zone_id: 'hip',
|
||||||
|
vertebral_region_code: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cervical-vertebrae',
|
||||||
|
kind: 'zone',
|
||||||
|
view_id: 'view-main',
|
||||||
|
category_id: 'zone-colonne',
|
||||||
|
laterality: 'unpaired',
|
||||||
|
geometry: {
|
||||||
|
type: 'polygon',
|
||||||
|
points: [
|
||||||
|
[468, 276],
|
||||||
|
[489, 216],
|
||||||
|
[558, 248],
|
||||||
|
[586, 339],
|
||||||
|
[552, 461],
|
||||||
|
[524, 370],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
name: { fr: 'Vertèbres cervicales', en: 'Cervical Vertebrae' },
|
||||||
|
finding_zone_id: 'cervical',
|
||||||
|
vertebral_region_code: 'C',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'hinge-c7-t1',
|
||||||
|
kind: 'point',
|
||||||
|
view_id: 'view-main',
|
||||||
|
category_id: 'charnieres-vertebrales',
|
||||||
|
laterality: 'unpaired',
|
||||||
|
geometry: { type: 'circle', cx: 840.17, cy: 399.08, r: 30 },
|
||||||
|
name: {
|
||||||
|
fr: 'Charnière C7-T1 (cervico-thoracique)',
|
||||||
|
en: 'C7-T1 (Cervicothoracic)',
|
||||||
|
},
|
||||||
|
finding_zone_id: 'c7-t1',
|
||||||
|
vertebral_region_code: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'head-trigger',
|
||||||
|
kind: 'detail_trigger',
|
||||||
|
view_id: 'view-main',
|
||||||
|
category_id: 'cadrans-du-crane',
|
||||||
|
laterality: 'unpaired',
|
||||||
|
geometry: {
|
||||||
|
type: 'polygon',
|
||||||
|
points: [
|
||||||
|
[454, 332],
|
||||||
|
[429, 202],
|
||||||
|
[349, 154],
|
||||||
|
[234, 279],
|
||||||
|
[164, 384],
|
||||||
|
[234, 468],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
name: null,
|
||||||
|
opens_view_id: 'view-head',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'atm',
|
||||||
|
kind: 'point',
|
||||||
|
view_id: 'view-head',
|
||||||
|
category_id: 'articulations',
|
||||||
|
laterality: 'bilateral',
|
||||||
|
geometry: { type: 'circle', cx: 384.94, cy: 314.02, r: 27 },
|
||||||
|
name: {
|
||||||
|
fr: 'Articulation Temporo-Mandibulaire (ATM)',
|
||||||
|
en: 'Temporomandibular Joint (TMJ)',
|
||||||
|
},
|
||||||
|
finding_zone_id: 'atm',
|
||||||
|
vertebral_region_code: null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'sphenoid',
|
||||||
|
kind: 'point',
|
||||||
|
view_id: 'view-head',
|
||||||
|
category_id: 'cadrans-du-crane',
|
||||||
|
laterality: 'unpaired',
|
||||||
|
geometry: { type: 'circle', cx: 299, cy: 298, r: 27 },
|
||||||
|
name: { fr: 'Sphénoïde', en: 'Sphenoid' },
|
||||||
|
finding_zone_id: 'sphenoid',
|
||||||
|
vertebral_region_code: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
finding_zones: [HIP_ZONE, CERVICAL_ZONE, C7_T1_ZONE, ATM_ZONE, SPHENOID_ZONE],
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lean authoring form, as a creator or the importer would write it. */
|
||||||
|
export function horseSliceInput(): AnatomicalSheetDocumentInput {
|
||||||
|
return structuredClone(HORSE_SLICE_INPUT)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parsed (total) document; a fresh copy so tests can mutate it freely. */
|
||||||
|
export function horseSlice(): AnatomicalSheetDocument {
|
||||||
|
return AnatomicalSheetDocumentSchema.parse(horseSliceInput())
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"noImplicitReturns": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"types": ["node", "vitest/globals"],
|
||||||
|
"noEmit": true
|
||||||
|
},
|
||||||
|
"include": ["src", "tests"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: 'node',
|
||||||
|
globals: true,
|
||||||
|
include: ['tests/**/*.test.ts'],
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"build": "tsc -p tsconfig.json --noEmit"
|
"build": "tsc -p tsconfig.json --noEmit"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@faunosteo/domain": "workspace:*",
|
||||||
"@supabase/supabase-js": "^2.100.0"
|
"@supabase/supabase-js": "^2.100.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import {
|
||||||
|
AnatomicalSheetDocumentSchema,
|
||||||
|
assertPublishable,
|
||||||
|
} from '@faunosteo/domain'
|
||||||
|
import type { FaunosteoClient } from './client'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publication gate on the client side: the full Zod shape and every
|
||||||
|
* integrity rule run before the RPC, so the editor gets the complete issue
|
||||||
|
* list. The database re-checks the referential rules on its own
|
||||||
|
* (private.sheet_document_issues); this call never replaces that guard.
|
||||||
|
*/
|
||||||
|
export async function publishSheetVersion(
|
||||||
|
client: FaunosteoClient,
|
||||||
|
versionId: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const draft = await client
|
||||||
|
.from('anatomical_sheet_versions')
|
||||||
|
.select('content')
|
||||||
|
.eq('id', versionId)
|
||||||
|
.single()
|
||||||
|
if (draft.error) throw draft.error
|
||||||
|
|
||||||
|
assertPublishable(AnatomicalSheetDocumentSchema.parse(draft.data.content))
|
||||||
|
|
||||||
|
const published = await client.rpc('publish_sheet_version', {
|
||||||
|
version_id: versionId,
|
||||||
|
})
|
||||||
|
if (published.error) throw published.error
|
||||||
|
return published.data
|
||||||
|
}
|
||||||
@@ -9,6 +9,233 @@ export type Json =
|
|||||||
export type Database = {
|
export type Database = {
|
||||||
public: {
|
public: {
|
||||||
Tables: {
|
Tables: {
|
||||||
|
anatomical_sheet_assets: {
|
||||||
|
Row: {
|
||||||
|
byte_size: number
|
||||||
|
content_type: string
|
||||||
|
created_at: string
|
||||||
|
created_by: string | null
|
||||||
|
file_name: string
|
||||||
|
id: string
|
||||||
|
sha256: string
|
||||||
|
sheet_id: string
|
||||||
|
}
|
||||||
|
ComputedFields: never
|
||||||
|
Insert: {
|
||||||
|
byte_size: number
|
||||||
|
content_type?: string
|
||||||
|
created_at?: string
|
||||||
|
created_by?: string | null
|
||||||
|
file_name: string
|
||||||
|
id?: string
|
||||||
|
sha256: string
|
||||||
|
sheet_id: string
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
byte_size?: number
|
||||||
|
content_type?: string
|
||||||
|
created_at?: string
|
||||||
|
created_by?: string | null
|
||||||
|
file_name?: string
|
||||||
|
id?: string
|
||||||
|
sha256?: string
|
||||||
|
sheet_id?: string
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_assets_created_by_fkey'
|
||||||
|
columns: ['created_by']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'profiles'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_assets_sheet_id_fkey'
|
||||||
|
columns: ['sheet_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'anatomical_sheets'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
anatomical_sheet_versions: {
|
||||||
|
Row: {
|
||||||
|
change_note: string
|
||||||
|
content: NonNullable<Json>
|
||||||
|
created_at: string
|
||||||
|
created_by: string | null
|
||||||
|
deprecated_at: string | null
|
||||||
|
deprecated_by: string | null
|
||||||
|
document_schema_version: number
|
||||||
|
id: string
|
||||||
|
published_at: string | null
|
||||||
|
published_by: string | null
|
||||||
|
sheet_id: string
|
||||||
|
status: Database['public']['Enums']['sheet_version_status']
|
||||||
|
updated_at: string
|
||||||
|
version_number: number
|
||||||
|
}
|
||||||
|
ComputedFields: never
|
||||||
|
Insert: {
|
||||||
|
change_note?: string
|
||||||
|
content: NonNullable<Json>
|
||||||
|
created_at?: string
|
||||||
|
created_by?: string | null
|
||||||
|
deprecated_at?: string | null
|
||||||
|
deprecated_by?: string | null
|
||||||
|
document_schema_version: number
|
||||||
|
id?: string
|
||||||
|
published_at?: string | null
|
||||||
|
published_by?: string | null
|
||||||
|
sheet_id: string
|
||||||
|
status?: Database['public']['Enums']['sheet_version_status']
|
||||||
|
updated_at?: string
|
||||||
|
version_number: number
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
change_note?: string
|
||||||
|
content?: NonNullable<Json>
|
||||||
|
created_at?: string
|
||||||
|
created_by?: string | null
|
||||||
|
deprecated_at?: string | null
|
||||||
|
deprecated_by?: string | null
|
||||||
|
document_schema_version?: number
|
||||||
|
id?: string
|
||||||
|
published_at?: string | null
|
||||||
|
published_by?: string | null
|
||||||
|
sheet_id?: string
|
||||||
|
status?: Database['public']['Enums']['sheet_version_status']
|
||||||
|
updated_at?: string
|
||||||
|
version_number?: number
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_versions_created_by_fkey'
|
||||||
|
columns: ['created_by']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'profiles'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_versions_deprecated_by_fkey'
|
||||||
|
columns: ['deprecated_by']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'profiles'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_versions_published_by_fkey'
|
||||||
|
columns: ['published_by']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'profiles'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheet_versions_sheet_id_fkey'
|
||||||
|
columns: ['sheet_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'anatomical_sheets'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
anatomical_sheets: {
|
||||||
|
Row: {
|
||||||
|
archived_at: string | null
|
||||||
|
based_on_sheet_id: string | null
|
||||||
|
based_on_version_id: string | null
|
||||||
|
created_at: string
|
||||||
|
creator_user_id: string | null
|
||||||
|
current_version_id: string | null
|
||||||
|
deleted_at: string | null
|
||||||
|
description: string
|
||||||
|
id: string
|
||||||
|
is_official: boolean
|
||||||
|
last_version_number: number
|
||||||
|
name: string
|
||||||
|
slug: string
|
||||||
|
species_id: string
|
||||||
|
status: Database['public']['Enums']['sheet_status']
|
||||||
|
updated_at: string
|
||||||
|
visibility: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
ComputedFields: never
|
||||||
|
Insert: {
|
||||||
|
archived_at?: string | null
|
||||||
|
based_on_sheet_id?: string | null
|
||||||
|
based_on_version_id?: string | null
|
||||||
|
created_at?: string
|
||||||
|
creator_user_id?: string | null
|
||||||
|
current_version_id?: string | null
|
||||||
|
deleted_at?: string | null
|
||||||
|
description?: string
|
||||||
|
id?: string
|
||||||
|
is_official?: boolean
|
||||||
|
last_version_number?: number
|
||||||
|
name: string
|
||||||
|
slug: string
|
||||||
|
species_id: string
|
||||||
|
status?: Database['public']['Enums']['sheet_status']
|
||||||
|
updated_at?: string
|
||||||
|
visibility?: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
archived_at?: string | null
|
||||||
|
based_on_sheet_id?: string | null
|
||||||
|
based_on_version_id?: string | null
|
||||||
|
created_at?: string
|
||||||
|
creator_user_id?: string | null
|
||||||
|
current_version_id?: string | null
|
||||||
|
deleted_at?: string | null
|
||||||
|
description?: string
|
||||||
|
id?: string
|
||||||
|
is_official?: boolean
|
||||||
|
last_version_number?: number
|
||||||
|
name?: string
|
||||||
|
slug?: string
|
||||||
|
species_id?: string
|
||||||
|
status?: Database['public']['Enums']['sheet_status']
|
||||||
|
updated_at?: string
|
||||||
|
visibility?: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
Relationships: [
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheets_based_on_sheet_id_fkey'
|
||||||
|
columns: ['based_on_sheet_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'anatomical_sheets'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheets_based_on_version_fkey'
|
||||||
|
columns: ['based_on_version_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'anatomical_sheet_versions'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheets_creator_user_id_fkey'
|
||||||
|
columns: ['creator_user_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'profiles'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheets_current_version_fkey'
|
||||||
|
columns: ['current_version_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'anatomical_sheet_versions'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
foreignKeyName: 'anatomical_sheets_species_id_fkey'
|
||||||
|
columns: ['species_id']
|
||||||
|
isOneToOne: false
|
||||||
|
referencedRelation: 'species'
|
||||||
|
referencedColumns: ['id']
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
profile_roles: {
|
profile_roles: {
|
||||||
Row: {
|
Row: {
|
||||||
granted_at: string
|
granted_at: string
|
||||||
@@ -108,11 +335,76 @@ export type Database = {
|
|||||||
}
|
}
|
||||||
Relationships: []
|
Relationships: []
|
||||||
}
|
}
|
||||||
|
species: {
|
||||||
|
Row: {
|
||||||
|
active: boolean
|
||||||
|
created_at: string
|
||||||
|
id: string
|
||||||
|
name_en: string
|
||||||
|
name_fr: string
|
||||||
|
sort_order: number
|
||||||
|
}
|
||||||
|
ComputedFields: never
|
||||||
|
Insert: {
|
||||||
|
active?: boolean
|
||||||
|
created_at?: string
|
||||||
|
id: string
|
||||||
|
name_en: string
|
||||||
|
name_fr: string
|
||||||
|
sort_order?: number
|
||||||
|
}
|
||||||
|
Update: {
|
||||||
|
active?: boolean
|
||||||
|
created_at?: string
|
||||||
|
id?: string
|
||||||
|
name_en?: string
|
||||||
|
name_fr?: string
|
||||||
|
sort_order?: number
|
||||||
|
}
|
||||||
|
Relationships: []
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Views: {
|
Views: {
|
||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
}
|
}
|
||||||
Functions: {
|
Functions: {
|
||||||
|
archive_anatomical_sheet: { Args: { sheet_id: string }; Returns: string }
|
||||||
|
create_anatomical_sheet: {
|
||||||
|
Args: {
|
||||||
|
description?: string
|
||||||
|
document: Json
|
||||||
|
name: string
|
||||||
|
official?: boolean
|
||||||
|
slug: string
|
||||||
|
species_id: string
|
||||||
|
visibility?: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
|
create_sheet_draft: {
|
||||||
|
Args: {
|
||||||
|
change_note?: string
|
||||||
|
from_version_id?: string
|
||||||
|
sheet_id: string
|
||||||
|
}
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
|
delete_anatomical_sheet: { Args: { sheet_id: string }; Returns: string }
|
||||||
|
delete_sheet_asset: { Args: { asset_id: string }; Returns: string }
|
||||||
|
delete_sheet_version: { Args: { version_id: string }; Returns: string }
|
||||||
|
deprecate_sheet_version: {
|
||||||
|
Args: { reason?: string; version_id: string }
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
|
fork_anatomical_sheet: {
|
||||||
|
Args: {
|
||||||
|
name: string
|
||||||
|
slug: string
|
||||||
|
source_version_id: string
|
||||||
|
visibility?: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
grant_platform_role: {
|
grant_platform_role: {
|
||||||
Args: {
|
Args: {
|
||||||
role: Database['public']['Enums']['platform_role']
|
role: Database['public']['Enums']['platform_role']
|
||||||
@@ -120,6 +412,17 @@ export type Database = {
|
|||||||
}
|
}
|
||||||
Returns: string
|
Returns: string
|
||||||
}
|
}
|
||||||
|
publish_sheet_version: { Args: { version_id: string }; Returns: string }
|
||||||
|
register_sheet_asset: {
|
||||||
|
Args: {
|
||||||
|
byte_size: number
|
||||||
|
file_name: string
|
||||||
|
sha256: string
|
||||||
|
sheet_id: string
|
||||||
|
}
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
|
restore_anatomical_sheet: { Args: { sheet_id: string }; Returns: string }
|
||||||
revoke_platform_role: {
|
revoke_platform_role: {
|
||||||
Args: {
|
Args: {
|
||||||
reason?: string
|
reason?: string
|
||||||
@@ -128,9 +431,19 @@ export type Database = {
|
|||||||
}
|
}
|
||||||
Returns: string
|
Returns: string
|
||||||
}
|
}
|
||||||
|
set_sheet_visibility: {
|
||||||
|
Args: {
|
||||||
|
sheet_id: string
|
||||||
|
visibility: Database['public']['Enums']['sheet_visibility']
|
||||||
|
}
|
||||||
|
Returns: string
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Enums: {
|
Enums: {
|
||||||
platform_role: 'owner' | 'admin' | 'moderator' | 'support'
|
platform_role: 'owner' | 'admin' | 'moderator' | 'support'
|
||||||
|
sheet_status: 'active' | 'archived' | 'deleted'
|
||||||
|
sheet_version_status: 'draft' | 'published' | 'deprecated'
|
||||||
|
sheet_visibility: 'private' | 'public'
|
||||||
}
|
}
|
||||||
CompositeTypes: {
|
CompositeTypes: {
|
||||||
[_ in never]: never
|
[_ in never]: never
|
||||||
@@ -259,6 +572,9 @@ export const Constants = {
|
|||||||
public: {
|
public: {
|
||||||
Enums: {
|
Enums: {
|
||||||
platform_role: ['owner', 'admin', 'moderator', 'support'],
|
platform_role: ['owner', 'admin', 'moderator', 'support'],
|
||||||
|
sheet_status: ['active', 'archived', 'deleted'],
|
||||||
|
sheet_version_status: ['draft', 'published', 'deprecated'],
|
||||||
|
sheet_visibility: ['private', 'public'],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
} as const
|
} as const
|
||||||
@@ -21,3 +21,19 @@ export type Profile = Tables<'profiles'>
|
|||||||
export type ProfileRole = Tables<'profile_roles'>
|
export type ProfileRole = Tables<'profile_roles'>
|
||||||
/** owner | admin | moderator | support. Not a professional status. */
|
/** owner | admin | moderator | support. Not a professional status. */
|
||||||
export type PlatformRole = Enums<'platform_role'>
|
export type PlatformRole = Enums<'platform_role'>
|
||||||
|
export { publishSheetVersion } from './anatomical-sheets'
|
||||||
|
|
||||||
|
/** Row of public.species. */
|
||||||
|
export type Species = Tables<'species'>
|
||||||
|
/** Row of public.anatomical_sheets. */
|
||||||
|
export type AnatomicalSheet = Tables<'anatomical_sheets'>
|
||||||
|
/** Row of public.anatomical_sheet_versions (content = canonical document). */
|
||||||
|
export type AnatomicalSheetVersion = Tables<'anatomical_sheet_versions'>
|
||||||
|
/** Row of public.anatomical_sheet_assets. */
|
||||||
|
export type AnatomicalSheetAsset = Tables<'anatomical_sheet_assets'>
|
||||||
|
/** private | public. */
|
||||||
|
export type SheetVisibility = Enums<'sheet_visibility'>
|
||||||
|
/** active | archived | deleted. */
|
||||||
|
export type SheetStatus = Enums<'sheet_status'>
|
||||||
|
/** draft | published | deprecated. */
|
||||||
|
export type SheetVersionStatus = Enums<'sheet_version_status'>
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { publishSheetVersion } from '../src'
|
||||||
|
import type { FaunosteoClient } from '../src'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stub of the two client calls publishSheetVersion makes. The real RPC is
|
||||||
|
* covered by supabase/tests/005_anatomical_sheets.sql; here the point is the
|
||||||
|
* order of the gate: no RPC call unless the document is publishable.
|
||||||
|
*/
|
||||||
|
function stubClient(content: unknown) {
|
||||||
|
const rpcCalls: unknown[] = []
|
||||||
|
const client = {
|
||||||
|
from: () => ({
|
||||||
|
select: () => ({
|
||||||
|
eq: () => ({
|
||||||
|
single: async () => ({ data: { content }, error: null }),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
rpc: async (name: string, args: unknown) => {
|
||||||
|
rpcCalls.push([name, args])
|
||||||
|
return { data: 'published-id', error: null }
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return { client: client as unknown as FaunosteoClient, rpcCalls }
|
||||||
|
}
|
||||||
|
|
||||||
|
const publishable = {
|
||||||
|
schema_version: 1,
|
||||||
|
species_id: 'equine',
|
||||||
|
name: { fr: 'Test', en: 'Test' },
|
||||||
|
description: {},
|
||||||
|
scope_disclaimer: {},
|
||||||
|
attribution: { authors: [], license: null, notes: null },
|
||||||
|
vertebral_config: { regions: [] },
|
||||||
|
categories: [],
|
||||||
|
views: [
|
||||||
|
{
|
||||||
|
id: 'view-main',
|
||||||
|
kind: 'main',
|
||||||
|
name: { fr: 'Vue', en: 'View' },
|
||||||
|
svg_asset_id: '11111111-1111-4111-8111-111111111111',
|
||||||
|
view_box: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
annotations: [],
|
||||||
|
finding_zones: [],
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('publishSheetVersion', () => {
|
||||||
|
it('calls the RPC once the document passes shape and integrity checks', async () => {
|
||||||
|
const { client, rpcCalls } = stubClient(publishable)
|
||||||
|
await expect(publishSheetVersion(client, 'v1')).resolves.toBe(
|
||||||
|
'published-id',
|
||||||
|
)
|
||||||
|
expect(rpcCalls).toEqual([['publish_sheet_version', { version_id: 'v1' }]])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a document with integrity errors before any RPC', async () => {
|
||||||
|
const { client, rpcCalls } = stubClient({
|
||||||
|
...publishable,
|
||||||
|
views: [{ ...publishable.views[0], svg_asset_id: null }],
|
||||||
|
})
|
||||||
|
await expect(publishSheetVersion(client, 'v1')).rejects.toThrow(
|
||||||
|
/view\.asset\.missing/,
|
||||||
|
)
|
||||||
|
expect(rpcCalls).toEqual([])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('refuses a document that does not match the schema', async () => {
|
||||||
|
const { client, rpcCalls } = stubClient({ schema_version: 2 })
|
||||||
|
await expect(publishSheetVersion(client, 'v1')).rejects.toThrow()
|
||||||
|
expect(rpcCalls).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -20,6 +20,51 @@ type ColumnMap = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const expectedColumns = {
|
const expectedColumns = {
|
||||||
|
anatomical_sheet_assets: [
|
||||||
|
'byte_size',
|
||||||
|
'content_type',
|
||||||
|
'created_at',
|
||||||
|
'created_by',
|
||||||
|
'file_name',
|
||||||
|
'id',
|
||||||
|
'sha256',
|
||||||
|
'sheet_id',
|
||||||
|
],
|
||||||
|
anatomical_sheet_versions: [
|
||||||
|
'change_note',
|
||||||
|
'content',
|
||||||
|
'created_at',
|
||||||
|
'created_by',
|
||||||
|
'deprecated_at',
|
||||||
|
'deprecated_by',
|
||||||
|
'document_schema_version',
|
||||||
|
'id',
|
||||||
|
'published_at',
|
||||||
|
'published_by',
|
||||||
|
'sheet_id',
|
||||||
|
'status',
|
||||||
|
'updated_at',
|
||||||
|
'version_number',
|
||||||
|
],
|
||||||
|
anatomical_sheets: [
|
||||||
|
'archived_at',
|
||||||
|
'based_on_sheet_id',
|
||||||
|
'based_on_version_id',
|
||||||
|
'created_at',
|
||||||
|
'creator_user_id',
|
||||||
|
'current_version_id',
|
||||||
|
'deleted_at',
|
||||||
|
'description',
|
||||||
|
'id',
|
||||||
|
'is_official',
|
||||||
|
'last_version_number',
|
||||||
|
'name',
|
||||||
|
'slug',
|
||||||
|
'species_id',
|
||||||
|
'status',
|
||||||
|
'updated_at',
|
||||||
|
'visibility',
|
||||||
|
],
|
||||||
profile_roles: [
|
profile_roles: [
|
||||||
'granted_at',
|
'granted_at',
|
||||||
'granted_by',
|
'granted_by',
|
||||||
@@ -43,6 +88,7 @@ const expectedColumns = {
|
|||||||
'timezone',
|
'timezone',
|
||||||
'updated_at',
|
'updated_at',
|
||||||
],
|
],
|
||||||
|
species: ['active', 'created_at', 'id', 'name_en', 'name_fr', 'sort_order'],
|
||||||
} as const satisfies ColumnMap
|
} as const satisfies ColumnMap
|
||||||
|
|
||||||
// Compile-time: a column present in the type but absent from the list is an error.
|
// Compile-time: a column present in the type but absent from the list is an error.
|
||||||
@@ -59,8 +105,28 @@ type FunctionArgs = {
|
|||||||
string)[]
|
string)[]
|
||||||
}
|
}
|
||||||
const expectedFunctionArgs = {
|
const expectedFunctionArgs = {
|
||||||
|
archive_anatomical_sheet: ['sheet_id'],
|
||||||
|
create_anatomical_sheet: [
|
||||||
|
'description',
|
||||||
|
'document',
|
||||||
|
'name',
|
||||||
|
'official',
|
||||||
|
'slug',
|
||||||
|
'species_id',
|
||||||
|
'visibility',
|
||||||
|
],
|
||||||
|
create_sheet_draft: ['change_note', 'from_version_id', 'sheet_id'],
|
||||||
|
delete_anatomical_sheet: ['sheet_id'],
|
||||||
|
delete_sheet_asset: ['asset_id'],
|
||||||
|
delete_sheet_version: ['version_id'],
|
||||||
|
deprecate_sheet_version: ['reason', 'version_id'],
|
||||||
|
fork_anatomical_sheet: ['name', 'slug', 'source_version_id', 'visibility'],
|
||||||
grant_platform_role: ['role', 'target_user_id'],
|
grant_platform_role: ['role', 'target_user_id'],
|
||||||
|
publish_sheet_version: ['version_id'],
|
||||||
|
register_sheet_asset: ['byte_size', 'file_name', 'sha256', 'sheet_id'],
|
||||||
|
restore_anatomical_sheet: ['sheet_id'],
|
||||||
revoke_platform_role: ['reason', 'role', 'target_user_id'],
|
revoke_platform_role: ['reason', 'role', 'target_user_id'],
|
||||||
|
set_sheet_visibility: ['sheet_id', 'visibility'],
|
||||||
} as const satisfies FunctionArgs
|
} as const satisfies FunctionArgs
|
||||||
|
|
||||||
type MissingArgs = {
|
type MissingArgs = {
|
||||||
@@ -78,6 +144,10 @@ interface ColumnRow {
|
|||||||
interface NameRow {
|
interface NameRow {
|
||||||
name: string
|
name: string
|
||||||
}
|
}
|
||||||
|
interface EnumRow {
|
||||||
|
name: string
|
||||||
|
labels: string[]
|
||||||
|
}
|
||||||
interface FunctionRow {
|
interface FunctionRow {
|
||||||
name: string
|
name: string
|
||||||
args: string[]
|
args: string[]
|
||||||
@@ -122,17 +192,23 @@ describe('database.types.ts matches the migrated schema', () => {
|
|||||||
expect(actual).toEqual(expected)
|
expect(actual).toEqual(expected)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('lists the enum labels in order', async () => {
|
it('lists every public enum with its labels in order', async () => {
|
||||||
const { rows } = await db.query<NameRow>(
|
const { rows } = await db.query<EnumRow>(
|
||||||
`select e.enumlabel as name
|
`select t.typname as name,
|
||||||
|
array_agg(e.enumlabel order by e.enumsortorder) as labels
|
||||||
from pg_enum e join pg_type t on t.oid = e.enumtypid
|
from pg_enum e join pg_type t on t.oid = e.enumtypid
|
||||||
join pg_namespace n on n.oid = t.typnamespace
|
join pg_namespace n on n.oid = t.typnamespace
|
||||||
where n.nspname = 'public' and t.typname = 'platform_role'
|
where n.nspname = 'public'
|
||||||
order by e.enumsortorder`,
|
group by t.typname order by t.typname`,
|
||||||
)
|
)
|
||||||
expect(rows.map((r) => r.name)).toEqual([
|
const actual = Object.fromEntries(rows.map((r) => [r.name, r.labels]))
|
||||||
...Constants.public.Enums.platform_role,
|
const expected = Object.fromEntries(
|
||||||
])
|
Object.entries(Constants.public.Enums).map(([name, labels]) => [
|
||||||
|
name,
|
||||||
|
[...labels],
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
expect(actual).toEqual(expected)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('lists exactly the public functions and their argument names', async () => {
|
it('lists exactly the public functions and their argument names', async () => {
|
||||||
|
|||||||
Generated
+28
@@ -97,8 +97,36 @@ importers:
|
|||||||
specifier: ^3.2.7
|
specifier: ^3.2.7
|
||||||
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)
|
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)
|
||||||
|
|
||||||
|
packages/domain:
|
||||||
|
dependencies:
|
||||||
|
zod:
|
||||||
|
specifier: ^3.24.1
|
||||||
|
version: 3.25.76
|
||||||
|
devDependencies:
|
||||||
|
'@types/node':
|
||||||
|
specifier: ^20.19.41
|
||||||
|
version: 20.19.41
|
||||||
|
eslint:
|
||||||
|
specifier: ^9.17.0
|
||||||
|
version: 9.39.4(jiti@2.7.0)
|
||||||
|
globals:
|
||||||
|
specifier: ^15.14.0
|
||||||
|
version: 15.15.0
|
||||||
|
typescript:
|
||||||
|
specifier: ^5.7.2
|
||||||
|
version: 5.9.3
|
||||||
|
typescript-eslint:
|
||||||
|
specifier: ^8.19.0
|
||||||
|
version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3)
|
||||||
|
vitest:
|
||||||
|
specifier: ^3.2.7
|
||||||
|
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)
|
||||||
|
|
||||||
packages/supabase:
|
packages/supabase:
|
||||||
dependencies:
|
dependencies:
|
||||||
|
'@faunosteo/domain':
|
||||||
|
specifier: workspace:*
|
||||||
|
version: link:../domain
|
||||||
'@supabase/supabase-js':
|
'@supabase/supabase-js':
|
||||||
specifier: ^2.100.0
|
specifier: ^2.100.0
|
||||||
version: 2.117.3
|
version: 2.117.3
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
|||||||
|
-- Harden EXECUTE on the private helpers created by the foundation, profiles
|
||||||
|
-- and platform-roles migrations.
|
||||||
|
--
|
||||||
|
-- The foundation ran `alter default privileges in schema private revoke
|
||||||
|
-- execute on functions from public`. PostgreSQL applies per-schema default
|
||||||
|
-- privileges on top of the built-in defaults; a per-schema REVOKE cannot
|
||||||
|
-- remove the built-in EXECUTE for PUBLIC. Every function created since kept
|
||||||
|
-- it. Nothing was reachable through the API (PostgREST exposes `public`
|
||||||
|
-- only and anon has no USAGE on `private`), but the project rule is
|
||||||
|
-- "EXECUTE revoked from public, granted only to the roles that evaluate
|
||||||
|
-- it". This migration makes it true; pgTAP 001 pins it with a census.
|
||||||
|
|
||||||
|
revoke all on function private.set_updated_at() from public;
|
||||||
|
revoke all on function private.reset_phone_verification() from public;
|
||||||
|
revoke all on function private.handle_new_auth_user() from public;
|
||||||
|
revoke all on function audit.reject_mutation() from public;
|
||||||
|
|
||||||
|
-- Role predicates keep their explicit grant to authenticated (policies).
|
||||||
|
revoke all on function private.has_platform_role(uuid, public.platform_role[]) from public;
|
||||||
|
revoke all on function private.is_platform_owner(uuid) from public;
|
||||||
|
revoke all on function private.is_platform_admin(uuid) from public;
|
||||||
|
revoke all on function private.is_platform_moderator(uuid) from public;
|
||||||
|
revoke all on function private.is_support(uuid) from public;
|
||||||
|
|
||||||
|
-- Owner-context helpers: RPCs and privileged SQL sessions only.
|
||||||
|
revoke all on function private.can_manage_platform_role(uuid, public.platform_role) from public;
|
||||||
|
revoke all on function private.assign_platform_role(uuid, uuid, public.platform_role) from public;
|
||||||
|
revoke all on function private.withdraw_platform_role(uuid, uuid, public.platform_role, text) from public;
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
-- Schema contract: objects exist, RLS is on, API roles start from zero.
|
-- Schema contract: objects exist, RLS is on, API roles start from zero.
|
||||||
begin;
|
begin;
|
||||||
select plan(24);
|
select plan(26);
|
||||||
|
|
||||||
-- Schemas
|
-- Schemas
|
||||||
select has_schema('private', 'schema private exists');
|
select has_schema('private', 'schema private exists');
|
||||||
@@ -51,5 +51,20 @@ select ok(not has_column_privilege('authenticated', 'public.profiles', 'active',
|
|||||||
select ok(not has_schema_privilege('anon', 'private', 'usage'), 'anon has no usage on schema private');
|
select ok(not has_schema_privilege('anon', 'private', 'usage'), 'anon has no usage on schema private');
|
||||||
select ok(not has_function_privilege('anon', 'public.grant_platform_role(uuid, public.platform_role)', 'execute'), 'anon cannot execute grant_platform_role');
|
select ok(not has_function_privilege('anon', 'public.grant_platform_role(uuid, public.platform_role)', 'execute'), 'anon cannot execute grant_platform_role');
|
||||||
|
|
||||||
|
-- Private helpers: EXECUTE revoked from everyone except the predicates the policies evaluate.
|
||||||
|
-- (has_function_privilege is true for any role while proacl is null, i.e. the built-in PUBLIC default.)
|
||||||
|
select is(
|
||||||
|
(select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||||
|
where n.nspname in ('private', 'audit') and has_function_privilege('anon', p.oid, 'execute')),
|
||||||
|
0::bigint, 'anon can execute nothing in private/audit'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select string_agg(p.proname::text, ',' order by p.proname::text collate "C")
|
||||||
|
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||||
|
where n.nspname in ('private', 'audit') and has_function_privilege('authenticated', p.oid, 'execute')),
|
||||||
|
'can_edit_sheet,can_use_sheet,has_platform_role,is_platform_admin,is_platform_moderator,is_platform_owner,is_support',
|
||||||
|
'authenticated executes only the policy predicates in private'
|
||||||
|
);
|
||||||
|
|
||||||
select * from finish();
|
select * from finish();
|
||||||
rollback;
|
rollback;
|
||||||
@@ -0,0 +1,637 @@
|
|||||||
|
-- Anatomical sheets: schema contract, lifecycle (allowed path), immutability,
|
||||||
|
-- copies with provenance, deletion preconditions, invalid documents, every
|
||||||
|
-- denied path (other user, anon, direct writes, official sheets).
|
||||||
|
-- Counts are scoped to fixture ids: the real stack also carries seed rows.
|
||||||
|
begin;
|
||||||
|
select plan(127);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Fixtures
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
insert into auth.users (id, email) values
|
||||||
|
('20000000-0000-0000-0000-000000000001', 'root-sheets@test.local'),
|
||||||
|
('20000000-0000-0000-0000-00000000000a', 'alice-sheets@test.local'),
|
||||||
|
('20000000-0000-0000-0000-00000000000b', 'bob-sheets@test.local');
|
||||||
|
select private.assign_platform_role(null, '20000000-0000-0000-0000-000000000001', 'owner');
|
||||||
|
|
||||||
|
-- A small but complete document: two views (detail without its own asset),
|
||||||
|
-- a trigger, a bilateral joint, a spine zone, one finding zone.
|
||||||
|
create function pg_temp.sheet_doc(p_asset uuid)
|
||||||
|
returns jsonb
|
||||||
|
language sql
|
||||||
|
as $$
|
||||||
|
select jsonb_build_object(
|
||||||
|
'schema_version', 1,
|
||||||
|
'species_id', 'equine',
|
||||||
|
'name', jsonb_build_object('fr', 'Cheval test', 'en', 'Test horse'),
|
||||||
|
'description', '{}'::jsonb,
|
||||||
|
'scope_disclaimer', '{}'::jsonb,
|
||||||
|
'attribution', jsonb_build_object('authors', '[]'::jsonb, 'license', null, 'notes', null),
|
||||||
|
'vertebral_config', jsonb_build_object('regions', jsonb_build_array(
|
||||||
|
jsonb_build_object('code', 'C', 'name', jsonb_build_object('fr', 'Cervicales', 'en', 'Cervical'), 'count', 7)
|
||||||
|
)),
|
||||||
|
'categories', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'articulations', 'name', jsonb_build_object('fr', 'Articulations', 'en', 'Joints'), 'color', null)
|
||||||
|
),
|
||||||
|
'views', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'view-main', 'kind', 'main',
|
||||||
|
'name', jsonb_build_object('fr', 'Vue principale', 'en', 'Main view'),
|
||||||
|
'svg_asset_id', p_asset, 'view_box', null),
|
||||||
|
jsonb_build_object('id', 'view-head', 'kind', 'detail', 'parent_view_id', 'view-main',
|
||||||
|
'name', jsonb_build_object('fr', 'Tête', 'en', 'Head'),
|
||||||
|
'svg_asset_id', null,
|
||||||
|
'view_box', jsonb_build_object('min_x', 60, 'min_y', 100, 'width', 500, 'height', 380))
|
||||||
|
),
|
||||||
|
'annotations', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'hip', 'kind', 'point', 'view_id', 'view-main', 'category_id', 'articulations',
|
||||||
|
'laterality', 'bilateral', 'geometry', null,
|
||||||
|
'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip joint'),
|
||||||
|
'finding_zone_id', 'hip', 'vertebral_region_code', null),
|
||||||
|
jsonb_build_object('id', 'cervical', 'kind', 'zone', 'view_id', 'view-main', 'category_id', 'articulations',
|
||||||
|
'laterality', 'unpaired', 'geometry', null,
|
||||||
|
'name', jsonb_build_object('fr', 'Vertèbres cervicales', 'en', 'Cervical vertebrae'),
|
||||||
|
'finding_zone_id', null, 'vertebral_region_code', 'C'),
|
||||||
|
jsonb_build_object('id', 'head-trigger', 'kind', 'detail_trigger', 'view_id', 'view-main',
|
||||||
|
'category_id', 'articulations', 'laterality', 'unpaired', 'geometry', null,
|
||||||
|
'name', null, 'opens_view_id', 'view-head')
|
||||||
|
),
|
||||||
|
'finding_zones', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'hip', 'name', jsonb_build_object('fr', 'Hanche', 'en', 'Hip'),
|
||||||
|
'categories', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'hip-dysfunctions', 'kind', 'dysfunction',
|
||||||
|
'name', jsonb_build_object('fr', 'Dysfonctions', 'en', 'Dysfunctions'),
|
||||||
|
'children', jsonb_build_array(
|
||||||
|
jsonb_build_object('id', 'articular', 'name', jsonb_build_object('fr', 'Articulaire', 'en', 'Articular'))
|
||||||
|
))
|
||||||
|
))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
$$;
|
||||||
|
|
||||||
|
create table pg_temp.ids (key text primary key, id uuid not null);
|
||||||
|
create function pg_temp.id(p_key text) returns uuid language sql stable
|
||||||
|
as $$ select id from pg_temp.ids where key = p_key $$;
|
||||||
|
-- The fixtures are read while impersonating the API roles.
|
||||||
|
grant all on pg_temp.ids to anon, authenticated;
|
||||||
|
grant execute on function pg_temp.id(text), pg_temp.sheet_doc(uuid) to anon, authenticated;
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 1. Schema contract
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
select has_table('public', 'species', 'table species exists');
|
||||||
|
select has_table('public', 'anatomical_sheets', 'table anatomical_sheets exists');
|
||||||
|
select has_table('public', 'anatomical_sheet_versions', 'table anatomical_sheet_versions exists');
|
||||||
|
select has_table('public', 'anatomical_sheet_assets', 'table anatomical_sheet_assets exists');
|
||||||
|
select enum_has_labels('public', 'sheet_visibility', array['private', 'public'], 'sheet_visibility labels');
|
||||||
|
select enum_has_labels('public', 'sheet_status', array['active', 'archived', 'deleted'], 'sheet_status labels');
|
||||||
|
select enum_has_labels('public', 'sheet_version_status', array['draft', 'published', 'deprecated'], 'sheet_version_status labels');
|
||||||
|
select is(
|
||||||
|
(select count(*) from public.species where id = 'equine' and active), 1::bigint,
|
||||||
|
'species equine is seeded by the migration'
|
||||||
|
);
|
||||||
|
select ok(
|
||||||
|
(select bool_and(relrowsecurity) from pg_class
|
||||||
|
where oid in ('public.species'::regclass, 'public.anatomical_sheets'::regclass,
|
||||||
|
'public.anatomical_sheet_versions'::regclass, 'public.anatomical_sheet_assets'::regclass)),
|
||||||
|
'RLS enabled on the four tables'
|
||||||
|
);
|
||||||
|
select ok(not has_table_privilege('anon', 'public.anatomical_sheets', 'select'), 'anon cannot select sheets');
|
||||||
|
select ok(not has_table_privilege('anon', 'public.anatomical_sheet_versions', 'select'), 'anon cannot select versions');
|
||||||
|
select ok(not has_table_privilege('anon', 'public.species', 'select'), 'anon cannot select species');
|
||||||
|
select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'insert'), 'authenticated cannot insert sheets directly');
|
||||||
|
select ok(not has_table_privilege('authenticated', 'public.anatomical_sheets', 'delete'), 'authenticated cannot delete sheets directly');
|
||||||
|
select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'status', 'update'), 'authenticated cannot update sheets.status');
|
||||||
|
select ok(not has_column_privilege('authenticated', 'public.anatomical_sheets', 'is_official', 'update'), 'authenticated cannot update sheets.is_official');
|
||||||
|
select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'insert'), 'authenticated cannot insert versions directly');
|
||||||
|
select ok(not has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'status', 'update'), 'authenticated cannot update versions.status');
|
||||||
|
select ok(has_column_privilege('authenticated', 'public.anatomical_sheet_versions', 'content', 'update'), 'authenticated may update versions.content (RLS: own draft)');
|
||||||
|
select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_assets', 'insert'), 'authenticated cannot insert assets directly');
|
||||||
|
select ok(
|
||||||
|
not (has_column_privilege('authenticated', 'public.anatomical_sheets', 'visibility', 'update')
|
||||||
|
or has_column_privilege('authenticated', 'public.anatomical_sheets', 'creator_user_id', 'update')
|
||||||
|
or has_column_privilege('authenticated', 'public.anatomical_sheets', 'current_version_id', 'update')
|
||||||
|
or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_sheet_id', 'update')
|
||||||
|
or has_column_privilege('authenticated', 'public.anatomical_sheets', 'based_on_version_id', 'update')
|
||||||
|
or has_column_privilege('authenticated', 'public.anatomical_sheets', 'species_id', 'update')),
|
||||||
|
'visibility, ownership, provenance, current version and species are not user-updatable'
|
||||||
|
);
|
||||||
|
select ok(not has_table_privilege('authenticated', 'public.anatomical_sheet_versions', 'delete'), 'authenticated cannot delete versions directly (RPC only)');
|
||||||
|
select is(
|
||||||
|
(select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
||||||
|
where n.nspname = 'public' and p.prokind = 'f'
|
||||||
|
and not exists (select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e')
|
||||||
|
and has_function_privilege('anon', p.oid, 'execute')),
|
||||||
|
0::bigint, 'anon can execute no public RPC'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 2. Alice creates a private sheet (draft v1), registers an asset, publishes
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
set local role authenticated;
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
insert into pg_temp.ids select 'sheet', public.create_anatomical_sheet(
|
||||||
|
'equine', 'Mon cheval', 'mon-cheval', pg_temp.sheet_doc(null), 'perso'
|
||||||
|
);
|
||||||
|
select results_eq(
|
||||||
|
$$ select creator_user_id, status::text, visibility::text, current_version_id, is_official
|
||||||
|
from public.anatomical_sheets where id = pg_temp.id('sheet') $$,
|
||||||
|
$$ values ('20000000-0000-0000-0000-00000000000a'::uuid, 'active', 'private', null::uuid, false) $$,
|
||||||
|
'created sheet: creator alice, active, private, no current version'
|
||||||
|
);
|
||||||
|
insert into pg_temp.ids select 'v1', id from public.anatomical_sheet_versions
|
||||||
|
where sheet_id = pg_temp.id('sheet') and version_number = 1;
|
||||||
|
select is(
|
||||||
|
(select status::text from public.anatomical_sheet_versions where id = pg_temp.id('v1')),
|
||||||
|
'draft', 'version 1 is a draft'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('unicorn', 'x', 'x-x', pg_temp.sheet_doc(null)) $$,
|
||||||
|
'P0002', null, 'unknown species is refused'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('equine', 'Dup', 'mon-cheval', pg_temp.sheet_doc(null)) $$,
|
||||||
|
'23505', null, 'slug is unique per owner'
|
||||||
|
);
|
||||||
|
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('equine', 'Bad', 'bad-doc', '{"schema_version":"abc","species_id":"equine"}'::jsonb) $$,
|
||||||
|
'23514', null, 'a non-numeric schema_version is refused'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_build_object('schema_version', 1, 'species_id', 'equine', 'pad', repeat('x', 2200000))
|
||||||
|
where id = pg_temp.id('v1') $$,
|
||||||
|
'23514', null, 'a document over 2 MiB is refused'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Publishing a draft whose main view has no asset is refused with the rule code
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'23514', 'document not publishable: view.asset.missing', 'publish refuses a main view without asset'
|
||||||
|
);
|
||||||
|
|
||||||
|
insert into pg_temp.ids select 'asset', public.register_sheet_asset(
|
||||||
|
pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
public.register_sheet_asset(pg_temp.id('sheet'), repeat('a', 64), 142400, 'Horse.svg'),
|
||||||
|
pg_temp.id('asset'), 'registering the same sha256 again returns the same asset'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Draft autosave: direct UPDATE of content through the policy
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = pg_temp.sheet_doc(pg_temp.id('asset')), change_note = 'asset wired'
|
||||||
|
where id = pg_temp.id('v1');
|
||||||
|
select is(
|
||||||
|
(select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('v1')),
|
||||||
|
pg_temp.id('asset')::text, 'editor updated the draft content in place'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Unknown asset uuid is refused at publish
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = pg_temp.sheet_doc('ffffffff-ffff-ffff-ffff-ffffffffffff')
|
||||||
|
where id = pg_temp.id('v1');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'23514', null, 'publish refuses a view pointing at an asset not registered for the sheet'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1');
|
||||||
|
|
||||||
|
-- Document species must match the sheet species (trigger)
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{species_id}', '"canine"')
|
||||||
|
where id = pg_temp.id('v1') $$,
|
||||||
|
'23514', null, 'a document for another species is refused'
|
||||||
|
);
|
||||||
|
-- Dangling references are refused at publish
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,finding_zone_id}', '"nowhere"')
|
||||||
|
where id = pg_temp.id('v1');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'23514', 'document not publishable: annotation.finding_zone.missing',
|
||||||
|
'publish refuses an annotation pointing at a missing finding zone'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,id}', '"hip"')
|
||||||
|
where id = pg_temp.id('v1');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'23514', 'document not publishable: annotation.id.duplicate',
|
||||||
|
'publish refuses duplicate annotation ids'
|
||||||
|
);
|
||||||
|
create function pg_temp.publish_issue(p_doc jsonb) returns text language plpgsql as $$
|
||||||
|
begin
|
||||||
|
update public.anatomical_sheet_versions set content = p_doc where id = pg_temp.id('v1');
|
||||||
|
perform public.publish_sheet_version(pg_temp.id('v1'));
|
||||||
|
return 'published';
|
||||||
|
exception when check_violation then
|
||||||
|
return sqlerrm;
|
||||||
|
end $$;
|
||||||
|
grant execute on function pg_temp.publish_issue(jsonb) to authenticated;
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,0,kind}', '"detail"')),
|
||||||
|
'document not publishable: view.main.count, view.parent.missing', 'SQL gate: no main view'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(pg_temp.sheet_doc(pg_temp.id('asset')) #- '{annotations,2}'),
|
||||||
|
'document not publishable: view.unreachable', 'SQL gate: detail view without trigger'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,parent_view_id}', '"nowhere"')),
|
||||||
|
'document not publishable: view.parent.missing, annotation.opens_view.invalid', 'SQL gate: dangling parent view'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views,1,id}', '"view-main"')),
|
||||||
|
'document not publishable: view.unreachable, view.id.duplicate, annotation.opens_view.invalid', 'SQL gate: duplicate view id'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,view_id}', '"nowhere"')),
|
||||||
|
'document not publishable: annotation.view.missing', 'SQL gate: annotation on a missing view'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,0,category_id}', '"nowhere"')),
|
||||||
|
'document not publishable: annotation.category.missing', 'SQL gate: missing category'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,1,vertebral_region_code}', '"Z"')),
|
||||||
|
'document not publishable: annotation.region.missing', 'SQL gate: unknown vertebral region'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{annotations,2,opens_view_id}', '"view-main"')),
|
||||||
|
'document not publishable: view.unreachable, annotation.opens_view.invalid', 'SQL gate: trigger opening a non-child view'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{vertebral_config,regions}',
|
||||||
|
'[{"code":"C","name":{"fr":"a","en":"a"},"count":7},{"code":"C","name":{"fr":"b","en":"b"},"count":7}]')),
|
||||||
|
'document not publishable: region.code.duplicate', 'SQL gate: duplicate region code'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{finding_zones}',
|
||||||
|
'[{"id":"hip","name":{"fr":"a","en":"a"},"categories":[]},{"id":"hip","name":{"fr":"b","en":"b"},"categories":[]}]')),
|
||||||
|
'document not publishable: finding_zone.id.duplicate', 'SQL gate: duplicate finding zone id'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
pg_temp.publish_issue(jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{views}', '"not-an-array"')),
|
||||||
|
'document not publishable: document.shape', 'SQL gate: views not an array'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = pg_temp.sheet_doc(pg_temp.id('asset')) where id = pg_temp.id('v1');
|
||||||
|
|
||||||
|
select lives_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'alice publishes version 1'
|
||||||
|
);
|
||||||
|
select results_eq(
|
||||||
|
$$ select status::text, published_by, published_at is not null
|
||||||
|
from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$,
|
||||||
|
$$ values ('published', '20000000-0000-0000-0000-00000000000a'::uuid, true) $$,
|
||||||
|
'version 1 is published by alice'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')),
|
||||||
|
pg_temp.id('v1'), 'sheet current version is v1'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.publish_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'55000', null, 'publishing twice is refused'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 3. Published rows are immutable (editor, then table owner)
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- Through the API role the policies hide published rows from UPDATE/DELETE:
|
||||||
|
-- the statement touches zero rows instead of raising.
|
||||||
|
update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v1');
|
||||||
|
select is(
|
||||||
|
(select content from public.anatomical_sheet_versions where id = pg_temp.id('v1')),
|
||||||
|
pg_temp.sheet_doc(pg_temp.id('asset')), 'editor UPDATE of published content touches no row'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions set change_note = 'x' where id = pg_temp.id('v1');
|
||||||
|
select is(
|
||||||
|
(select change_note from public.anatomical_sheet_versions where id = pg_temp.id('v1')),
|
||||||
|
'asset wired', 'editor UPDATE of a published change note touches no row'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$,
|
||||||
|
'42501', null, 'editor has no DELETE privilege on versions (RPC only)'
|
||||||
|
);
|
||||||
|
reset role;
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions
|
||||||
|
set content = pg_temp.sheet_doc(pg_temp.id('asset')) || '{"name":{"fr":"X","en":"X"}}'
|
||||||
|
where id = pg_temp.id('v1') $$,
|
||||||
|
'42501', null, 'even the table owner cannot change published content'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions set status = 'draft' where id = pg_temp.id('v1') $$,
|
||||||
|
'42501', null, 'a published version cannot go back to draft'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions set version_number = 9 where id = pg_temp.id('v1') $$,
|
||||||
|
'42501', null, 'version_number is immutable'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ delete from public.anatomical_sheet_versions where id = pg_temp.id('v1') $$,
|
||||||
|
'55000', null, 'owner role cannot delete a published version either'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 4. New version leaves the old one intact
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
set local role authenticated;
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
create table pg_temp.v1_snapshot as
|
||||||
|
select * from public.anatomical_sheet_versions where id = pg_temp.id('v1');
|
||||||
|
|
||||||
|
insert into pg_temp.ids select 'v2', public.create_sheet_draft(pg_temp.id('sheet'), null, 'second edition');
|
||||||
|
select results_eq(
|
||||||
|
$$ select version_number, status::text, change_note, content = (select content from pg_temp.v1_snapshot)
|
||||||
|
from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$,
|
||||||
|
$$ values (2, 'draft', 'second edition', true) $$,
|
||||||
|
'draft v2 starts from the current version content'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_sheet_draft(pg_temp.id('sheet')) $$,
|
||||||
|
'23505', null, 'one draft per sheet'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_set(pg_temp.sheet_doc(pg_temp.id('asset')), '{name,fr}', '"Cheval v2"')
|
||||||
|
where id = pg_temp.id('v2');
|
||||||
|
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('v2')) $$, 'alice publishes v2');
|
||||||
|
select is(
|
||||||
|
(select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')),
|
||||||
|
pg_temp.id('v2'), 'current version moved to v2'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select count(*) from public.anatomical_sheet_versions v, pg_temp.v1_snapshot s
|
||||||
|
where v.id = s.id and v.content = s.content and v.status = s.status
|
||||||
|
and v.published_at = s.published_at and v.version_number = s.version_number
|
||||||
|
and v.change_note = s.change_note),
|
||||||
|
1::bigint, 'v1 row is byte-identical after v2 was published'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_sheet_version(pg_temp.id('v2')) $$,
|
||||||
|
'55000', null, 'the current version cannot be deleted'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_sheet_version(pg_temp.id('v1')) $$,
|
||||||
|
'55000', null, 'a published version cannot be deleted before deprecation'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 5. Bob: private sheet invisible; public sheet usable; copy keeps provenance
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'bob does not see the private sheet');
|
||||||
|
select is((select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its versions');
|
||||||
|
select is((select count(*) from public.anatomical_sheet_assets where sheet_id = pg_temp.id('sheet')), 0::bigint, 'bob does not see its assets');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie', 'copie-bob') $$,
|
||||||
|
'42501', null, 'bob cannot copy a private sheet'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_sheet_draft(pg_temp.id('sheet')) $$,
|
||||||
|
'42501', null, 'bob cannot open a draft on alice sheet'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheets set name = 'hijack' where id = pg_temp.id('sheet');
|
||||||
|
select throws_ok(
|
||||||
|
$$ insert into public.anatomical_sheets (species_id, name, slug, creator_user_id)
|
||||||
|
values ('equine', 'direct', 'direct', '20000000-0000-0000-0000-00000000000b') $$,
|
||||||
|
'42501', null, 'bob cannot insert a sheet row directly'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ insert into public.anatomical_sheet_versions (sheet_id, version_number, document_schema_version, content)
|
||||||
|
values (pg_temp.id('sheet'), 9, 1, pg_temp.sheet_doc(null)) $$,
|
||||||
|
'42501', null, 'bob cannot insert a version row directly'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- alice makes the sheet public through the identity-column policy
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob update on alice sheet changed nothing');
|
||||||
|
select lives_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'public') $$, 'alice makes the sheet public (audited RPC)');
|
||||||
|
insert into pg_temp.ids select 'v3', public.create_sheet_draft(pg_temp.id('sheet'), null, 'work in progress');
|
||||||
|
insert into pg_temp.ids select 'asset-unused', public.register_sheet_asset(
|
||||||
|
pg_temp.id('sheet'), repeat('b', 64), 1000, 'Unused.svg'
|
||||||
|
);
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'bob sees the public sheet');
|
||||||
|
select results_eq(
|
||||||
|
$$ select version_number from public.anatomical_sheet_versions where sheet_id = pg_temp.id('sheet') order by 1 $$,
|
||||||
|
$$ values (1), (2) $$,
|
||||||
|
'bob sees the published versions, not the draft'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v3') and content = '{}'::jsonb),
|
||||||
|
0::bigint, 'bob cannot read the draft'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions set content = '{"schema_version":1}'::jsonb where id = pg_temp.id('v3');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.fork_anatomical_sheet(pg_temp.id('v3'), 'Copie', 'copie-bob') $$,
|
||||||
|
'42501', null, 'a draft cannot be copied (hidden from non-editors)'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheets set name = 'hijack-public' where id = pg_temp.id('sheet');
|
||||||
|
select is((select name from public.anatomical_sheets where id = pg_temp.id('sheet')), 'Mon cheval', 'bob cannot rename a public sheet he does not edit');
|
||||||
|
-- Every editor-gated RPC refuses a non-editor, even on a public sheet
|
||||||
|
select throws_ok($$ select public.publish_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot publish');
|
||||||
|
select throws_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'x') $$, '42501', null, 'non-editor cannot deprecate');
|
||||||
|
select throws_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, '42501', null, 'non-editor cannot delete a version');
|
||||||
|
select throws_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot archive');
|
||||||
|
select throws_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot restore');
|
||||||
|
select throws_ok($$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$, '42501', null, 'non-editor cannot delete a sheet');
|
||||||
|
select throws_ok($$ select public.set_sheet_visibility(pg_temp.id('sheet'), 'private') $$, '42501', null, 'non-editor cannot change visibility');
|
||||||
|
select throws_ok($$ select public.register_sheet_asset(pg_temp.id('sheet'), repeat('c', 64), 10, 'x.svg') $$, '42501', null, 'non-editor cannot register an asset');
|
||||||
|
select throws_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, '42501', null, 'non-editor cannot delete an asset');
|
||||||
|
select throws_ok($$ select public.publish_sheet_version(gen_random_uuid()) $$, '42501', null, 'unknown version gets the same answer as a foreign one');
|
||||||
|
-- A platform admin is not an editor of a personal sheet
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
|
||||||
|
select throws_ok($$ select public.create_sheet_draft(pg_temp.id('sheet')) $$, '42501', null, 'platform owner cannot edit a personal sheet');
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
create table pg_temp.source_snapshot as
|
||||||
|
select s.updated_at as sheet_updated_at, s.current_version_id, v.content, v.updated_at as version_updated_at,
|
||||||
|
(select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) as asset_count
|
||||||
|
from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id
|
||||||
|
where s.id = pg_temp.id('sheet');
|
||||||
|
|
||||||
|
insert into pg_temp.ids select 'fork', public.fork_anatomical_sheet(pg_temp.id('v2'), 'Copie de Bob', 'copie-bob');
|
||||||
|
select results_eq(
|
||||||
|
$$ select creator_user_id, based_on_sheet_id, based_on_version_id, species_id, visibility::text, is_official
|
||||||
|
from public.anatomical_sheets where id = pg_temp.id('fork') $$,
|
||||||
|
$$ values ('20000000-0000-0000-0000-00000000000b'::uuid, pg_temp.id('sheet'), pg_temp.id('v2'), 'equine', 'private', false) $$,
|
||||||
|
'copy records provenance (source sheet + version) and belongs to bob'
|
||||||
|
);
|
||||||
|
insert into pg_temp.ids select 'fork-v1', id from public.anatomical_sheet_versions where sheet_id = pg_temp.id('fork');
|
||||||
|
insert into pg_temp.ids select 'fork-asset', id from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork');
|
||||||
|
select results_eq(
|
||||||
|
$$ select version_number, status::text, created_by from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1') $$,
|
||||||
|
$$ values (1, 'draft', '20000000-0000-0000-0000-00000000000b'::uuid) $$,
|
||||||
|
'copy starts as draft v1 owned by bob'
|
||||||
|
);
|
||||||
|
select results_eq(
|
||||||
|
$$ select sha256, byte_size, id <> pg_temp.id('asset') from public.anatomical_sheet_assets where sheet_id = pg_temp.id('fork') $$,
|
||||||
|
$$ values (repeat('a', 64), 142400, true) $$,
|
||||||
|
'only the asset referenced by the copied version is copied (same content, new id)'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select content -> 'views' -> 0 ->> 'svg_asset_id' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')),
|
||||||
|
pg_temp.id('fork-asset')::text, 'copied document points at the copied asset'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select content #- '{views,0,svg_asset_id}' from public.anatomical_sheet_versions where id = pg_temp.id('fork-v1')),
|
||||||
|
(select content #- '{views,0,svg_asset_id}' from pg_temp.source_snapshot),
|
||||||
|
'copied document is otherwise identical to the source'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- bob edits his copy; the source stays untouched
|
||||||
|
update public.anatomical_sheet_versions
|
||||||
|
set content = jsonb_set(content, '{name,fr}', '"Ma copie"') where id = pg_temp.id('fork-v1');
|
||||||
|
select lives_ok($$ select public.publish_sheet_version(pg_temp.id('fork-v1')) $$, 'bob publishes his copy');
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
select is(
|
||||||
|
(select count(*) from public.anatomical_sheets s join public.anatomical_sheet_versions v on v.id = s.current_version_id,
|
||||||
|
pg_temp.source_snapshot snap
|
||||||
|
where s.id = pg_temp.id('sheet') and s.updated_at = snap.sheet_updated_at and s.current_version_id = snap.current_version_id
|
||||||
|
and v.content = snap.content and v.updated_at = snap.version_updated_at
|
||||||
|
and (select count(*) from public.anatomical_sheet_assets where sheet_id = s.id) = snap.asset_count),
|
||||||
|
1::bigint, 'source sheet, version and assets are unchanged by the copy and its edits'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 6. Deprecation, deletion preconditions, archive, soft delete
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
select lives_ok($$ select public.deprecate_sheet_version(pg_temp.id('v2'), 'superseded') $$, 'alice deprecates v2');
|
||||||
|
select results_eq(
|
||||||
|
$$ select status::text, deprecated_by from public.anatomical_sheet_versions where id = pg_temp.id('v2') $$,
|
||||||
|
$$ values ('deprecated', '20000000-0000-0000-0000-00000000000a'::uuid) $$,
|
||||||
|
'v2 is deprecated'
|
||||||
|
);
|
||||||
|
select is(
|
||||||
|
(select current_version_id from public.anatomical_sheets where id = pg_temp.id('sheet')),
|
||||||
|
pg_temp.id('v1'), 'current version falls back to the latest published one (v1)'
|
||||||
|
);
|
||||||
|
update public.anatomical_sheet_versions set content = '{}'::jsonb where id = pg_temp.id('v2');
|
||||||
|
select is(
|
||||||
|
(select content ->> 'schema_version' from public.anatomical_sheet_versions where id = pg_temp.id('v2')),
|
||||||
|
'1', 'a deprecated version is hidden from editor UPDATE'
|
||||||
|
);
|
||||||
|
reset role;
|
||||||
|
select throws_ok(
|
||||||
|
$$ update public.anatomical_sheet_versions set change_note = 'late edit' where id = pg_temp.id('v2') $$,
|
||||||
|
'42501', null, 'a deprecated version is frozen for the table owner too'
|
||||||
|
);
|
||||||
|
set local role authenticated;
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_sheet_version(pg_temp.id('v2')) $$,
|
||||||
|
'55000', null, 'v2 cannot be deleted while bob copy derives from it'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_anatomical_sheet(pg_temp.id('sheet')) $$,
|
||||||
|
'55000', null, 'the sheet cannot be deleted while a copy is active'
|
||||||
|
);
|
||||||
|
select lives_ok($$ select public.archive_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice archives the sheet');
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 1::bigint, 'the editor still reads her archived sheet');
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('sheet')), 0::bigint, 'an archived sheet is no longer usable by others');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_sheet_version(pg_temp.id('fork-v1')) $$,
|
||||||
|
'55000', null, 'bob cannot delete the published version of his copy'
|
||||||
|
);
|
||||||
|
select lives_ok($$ select public.delete_anatomical_sheet(pg_temp.id('fork')) $$, 'bob soft-deletes his copy');
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('fork')), 0::bigint, 'a deleted sheet is invisible to its creator');
|
||||||
|
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
select lives_ok($$ select public.restore_anatomical_sheet(pg_temp.id('sheet')) $$, 'alice restores the sheet');
|
||||||
|
select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v2')) $$, 'deprecated v2 is deleted once no active copy depends on it');
|
||||||
|
select is((select count(*) from public.anatomical_sheet_versions where id = pg_temp.id('v2')), 0::bigint, 'v2 row is gone');
|
||||||
|
select lives_ok($$ select public.delete_sheet_version(pg_temp.id('v3')) $$, 'editor drops her own draft through the RPC');
|
||||||
|
insert into pg_temp.ids select 'v4', public.create_sheet_draft(pg_temp.id('sheet'), null, 'after deletion');
|
||||||
|
select is(
|
||||||
|
(select version_number from public.anatomical_sheet_versions where id = pg_temp.id('v4')),
|
||||||
|
4, 'a deleted version number is never reused'
|
||||||
|
);
|
||||||
|
select lives_ok($$ select public.delete_sheet_asset(pg_temp.id('asset-unused')) $$, 'an unreferenced asset can be deleted');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.delete_sheet_asset(pg_temp.id('asset')) $$,
|
||||||
|
'55000', null, 'an asset referenced by a version cannot be deleted'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 7. Deactivated account
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
reset role;
|
||||||
|
update public.profiles set active = false where id = '20000000-0000-0000-0000-00000000000b';
|
||||||
|
set local role authenticated;
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('equine', 'Nope', 'nope', pg_temp.sheet_doc(null)) $$,
|
||||||
|
'42501', null, 'a deactivated account cannot write'
|
||||||
|
);
|
||||||
|
reset role;
|
||||||
|
update public.profiles set active = true where id = '20000000-0000-0000-0000-00000000000b';
|
||||||
|
set local role authenticated;
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 8. Official sheets: platform admins only
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('equine', 'Officielle', 'officielle', pg_temp.sheet_doc(null), '', 'public', true) $$,
|
||||||
|
'42501', null, 'a plain user cannot create an official sheet'
|
||||||
|
);
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
|
||||||
|
insert into pg_temp.ids select 'official', public.create_anatomical_sheet(
|
||||||
|
'equine', 'Faunosteo / Cheval', 'faunosteo-cheval', pg_temp.sheet_doc(null), 'Fiche officielle', 'public', true
|
||||||
|
);
|
||||||
|
select results_eq(
|
||||||
|
$$ select creator_user_id, is_official, visibility::text from public.anatomical_sheets where id = pg_temp.id('official') $$,
|
||||||
|
$$ values (null::uuid, true, 'public') $$,
|
||||||
|
'official sheet is platform-owned'
|
||||||
|
);
|
||||||
|
select set_config('request.jwt.claims', '{"sub":"20000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
|
||||||
|
select is((select count(*) from public.anatomical_sheets where id = pg_temp.id('official')), 1::bigint, 'alice sees the public official sheet');
|
||||||
|
select is(
|
||||||
|
(select count(*) from public.anatomical_sheet_versions where sheet_id = pg_temp.id('official')),
|
||||||
|
0::bigint, 'alice does not see the official draft'
|
||||||
|
);
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_sheet_draft(pg_temp.id('official')) $$,
|
||||||
|
'42501', null, 'alice cannot edit the official sheet'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 9. Anonymous
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
set local role anon;
|
||||||
|
select set_config('request.jwt.claims', '', true);
|
||||||
|
select throws_ok($$ select * from public.species $$, '42501', null, 'anon cannot read species');
|
||||||
|
select throws_ok($$ select * from public.anatomical_sheets $$, '42501', null, 'anon cannot read sheets');
|
||||||
|
select throws_ok(
|
||||||
|
$$ select public.create_anatomical_sheet('equine', 'x', 'x-x', '{}'::jsonb) $$,
|
||||||
|
'42501', null, 'anon cannot call create_anatomical_sheet'
|
||||||
|
);
|
||||||
|
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
-- 10. Audit trail
|
||||||
|
-- ---------------------------------------------------------------------------
|
||||||
|
reset role;
|
||||||
|
select results_eq(
|
||||||
|
$$ select action from audit.audit_logs
|
||||||
|
where resource_id in (pg_temp.id('sheet'), pg_temp.id('v1'), pg_temp.id('v2'), pg_temp.id('v3'), pg_temp.id('fork'),
|
||||||
|
pg_temp.id('asset'), pg_temp.id('asset-unused'))
|
||||||
|
group by action order by action collate "C" $$,
|
||||||
|
$$ values ('anatomical_sheet.archived'), ('anatomical_sheet.created'), ('anatomical_sheet.deleted'),
|
||||||
|
('anatomical_sheet.forked'), ('anatomical_sheet.restored'), ('anatomical_sheet.visibility_changed'),
|
||||||
|
('anatomical_sheet_asset.deleted'), ('anatomical_sheet_asset.registered'),
|
||||||
|
('anatomical_sheet_version.created'), ('anatomical_sheet_version.deleted'),
|
||||||
|
('anatomical_sheet_version.deprecated'), ('anatomical_sheet_version.published') $$,
|
||||||
|
'every lifecycle step left an audit event'
|
||||||
|
);
|
||||||
|
|
||||||
|
select * from finish();
|
||||||
|
rollback;
|
||||||
Reference in new issue
Block a user