From d9c3f852e23026ec9fa7bbb6e9bdfd53b0558860 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 23 Nov 2026 00:01:28 +0100 Subject: [PATCH] feat(domain): reserved cat-access category created by the core with an access The editor commands create cat-access when a detail_trigger enters it and refuse any other write (insert, rename, recolour, remove, a point, a zone or another access entering it): EditError::ReservedCategory. validate.rs unchanged; N-1 states stay usable. baseline_edits retired from the N-1 file. wasm gzip -9: 595873 B (budget 600000, was 595331). --- apps/app/src/editor/refusal.ts | 1 + apps/app/src/i18n/en.ts | 2 + apps/app/src/i18n/fr.ts | 2 + crates/core/src/domain/sheet/access.rs | 46 ++++ crates/core/src/domain/sheet/edit.rs | 38 +++- crates/core/src/domain/sheet/mod.rs | 1 + crates/core/tests/n1_access_category.rs | 111 +--------- crates/core/tests/sheet_access_category.rs | 239 +++++++++++++++++++++ 8 files changed, 330 insertions(+), 110 deletions(-) create mode 100644 crates/core/src/domain/sheet/access.rs create mode 100644 crates/core/tests/sheet_access_category.rs diff --git a/apps/app/src/editor/refusal.ts b/apps/app/src/editor/refusal.ts index 668e09b2..54385bd0 100644 --- a/apps/app/src/editor/refusal.ts +++ b/apps/app/src/editor/refusal.ts @@ -10,6 +10,7 @@ const EDIT_KINDS: ReadonlySet = new Set([ 'invalid_position', 'too_deep', 'has_dependents', + 'reserved_category', ]) /** diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 3e2a225f..0dc95274 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1515,6 +1515,8 @@ export const en: Dict = { 'This position does not exist in the list.', 'editor.refusal.core.too_deep': 'The tree is too deep (8 levels at most).', 'editor.refusal.core.has_dependents': 'Other elements still use this one.', + 'editor.refusal.core.reserved_category': + 'This category is reserved for detail-view accesses.', 'editor.refusal.core.other': 'The document check refuses this value ({kind}).', 'editor.element.sheet': 'Sheet', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 75a2deef..441bf096 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -1574,6 +1574,8 @@ export const fr: Dict = { "L'arbre est trop profond (8 niveaux au plus).", 'editor.refusal.core.has_dependents': "D'autres éléments utilisent encore celui-ci.", + 'editor.refusal.core.reserved_category': + 'Cette catégorie est réservée aux accès des vues détaillées.', 'editor.refusal.core.other': 'Le contrôle du document refuse cette valeur ({kind}).', 'editor.element.sheet': 'Fiche', diff --git a/crates/core/src/domain/sheet/access.rs b/crates/core/src/domain/sheet/access.rs new file mode 100644 index 00000000..37a67289 --- /dev/null +++ b/crates/core/src/domain/sheet/access.rs @@ -0,0 +1,46 @@ +//! The internal category of the detail-view accesses (owner 2026-11-22, board +//! `docs/design/v1-2-6-u2-detail-views/README.md`, « Conséquences » 1; V1-2.6 T10 option B +//! without the `role` key): an ordinary `{id, name, color}` category marked by its reserved id, +//! so every reader of schema v2 reads it. The editor commands create it when an access enters +//! it and never let a person insert, rename, recolour or remove it, nor give it to a point, a +//! zone or another access. Validation does not know it: N-1 documents stay valid. + +use super::schema::{AnatomicalSheetDocument, Annotation, AnnotationCategory, LocalizedText}; + +/// The reserved id: page ids are `cat-` and ten letters (`apps/app/src/editor/ids.ts`), the +/// curated ones are words, so neither can take it. +pub const ACCESS_CATEGORY_ID: &str = "cat-access"; + +pub fn is_access_category(id: &str) -> bool { + id == ACCESS_CATEGORY_ID +} + +/// What the core writes the first time an access enters the category (T10 names, no colour: +/// the layer draws it in `FALLBACK_COLOR`). +pub fn access_category() -> AnnotationCategory { + AnnotationCategory { + id: ACCESS_CATEGORY_ID.to_owned(), + name: LocalizedText { + fr: "Accès aux vues détaillées".to_owned(), + en: "Detail view access".to_owned(), + }, + color: None, + } +} + +/// Whether `annotation` is an access placed in the internal category. +pub fn enters_access_category(annotation: &Annotation) -> bool { + annotation.trigger().is_some() && is_access_category(annotation.category_id()) +} + +/// Appends the internal category when the document lacks it; an existing one (renamed or +/// recoloured by an earlier application) is kept as it is. +pub fn ensure_access_category(document: &mut AnatomicalSheetDocument) { + if !document + .categories + .iter() + .any(|c| is_access_category(&c.id)) + { + document.categories.push(access_category()); + } +} diff --git a/crates/core/src/domain/sheet/edit.rs b/crates/core/src/domain/sheet/edit.rs index 4025cb62..d0c455f1 100644 --- a/crates/core/src/domain/sheet/edit.rs +++ b/crates/core/src/domain/sheet/edit.rs @@ -31,6 +31,7 @@ use serde_json::Value; #[cfg(feature = "ts")] use ts_rs::TS; +use super::access::{ensure_access_category, enters_access_category, is_access_category}; use super::keys::ElementKey; use super::schema::{ AnatomicalSheetDocument, Annotation, AnnotationCategory, Attribution, FindingCategory, @@ -245,6 +246,8 @@ pub enum EditError { TooDeep, /// A removal while another element names this one (`dependents`, descendants aside). HasDependents, + /// A write of the internal access category other than an access entering it (`access.rs`). + ReservedCategory, } impl EditError { @@ -257,6 +260,7 @@ impl EditError { Self::InvalidPosition => "invalid_position", Self::TooDeep => "too_deep", Self::HasDependents => "has_dependents", + Self::ReservedCategory => "reserved_category", } } } @@ -356,12 +360,10 @@ fn insert_top( NewElement::Region(r) => { insert_new(&mut doc.vertebral_config.regions, r, |r| &r.code, position) } + NewElement::Category(c) if is_access_category(&c.id) => Err(EditError::ReservedCategory), NewElement::Category(c) => insert_new(&mut doc.categories, c, |c| &c.id, position), NewElement::View(v) => insert_new(&mut doc.views, v, SheetView::id, position), - NewElement::Annotation(mut a) => { - set_annotation_status(&mut a, ReviewStatus::ToConfirm); - insert_new(&mut doc.annotations, a, Annotation::id, position) - } + NewElement::Annotation(a) => insert_annotation(doc, a, position), NewElement::Zone(mut zone) => { check_new_categories(&zone.categories)?; zone.categories @@ -375,6 +377,25 @@ fn insert_top( } } +/// A new annotation, `to_confirm`; an access entering the internal category brings the +/// category with it, and nothing else may enter it. +fn insert_annotation( + doc: &mut AnatomicalSheetDocument, + mut annotation: Annotation, + position: Option, +) -> Edit { + if is_access_category(annotation.category_id()) && annotation.trigger().is_none() { + return Err(EditError::ReservedCategory); + } + let enters = enters_access_category(&annotation); + set_annotation_status(&mut annotation, ReviewStatus::ToConfirm); + insert_new(&mut doc.annotations, annotation, Annotation::id, position)?; + if enters { + ensure_access_category(doc); + } + Ok(()) +} + fn insert_category( doc: &mut AnatomicalSheetDocument, zone_id: &str, @@ -462,6 +483,9 @@ fn update(doc: &mut AnatomicalSheetDocument, key: &ElementKey, element: NewEleme (ElementKey::Region { code }, NewElement::Region(r)) => { replace_same(&mut doc.vertebral_config.regions, code, r, |r| &r.code) } + (ElementKey::Category { id }, NewElement::Category(_)) if is_access_category(id) => { + Err(EditError::ReservedCategory) + } (ElementKey::Category { id }, NewElement::Category(c)) => { replace_same(&mut doc.categories, id, c, |c| &c.id) } @@ -498,6 +522,9 @@ fn update_annotation(doc: &mut AnatomicalSheetDocument, id: &str, mut next: Anno } let at = position_of(&doc.annotations, |a| a.id() == id)?; let current = &doc.annotations[at]; + if is_access_category(next.category_id()) && !is_access_category(current.category_id()) { + return Err(EditError::ReservedCategory); + } let status = super::keys::annotation_status(current); set_annotation_status(&mut next, status); let changed = &next != current; @@ -569,6 +596,9 @@ fn update_node( fn remove(doc: &mut AnatomicalSheetDocument, key: &ElementKey) -> Edit { let at = locate(doc, key)?; + if matches!(key, ElementKey::Category { id } if is_access_category(id)) { + return Err(EditError::ReservedCategory); + } let named_elsewhere = dependents(doc, key) .iter() .any(|d| d.relation != Relation::Descendant); diff --git a/crates/core/src/domain/sheet/mod.rs b/crates/core/src/domain/sheet/mod.rs index 2ff9d7af..e66b94f5 100644 --- a/crates/core/src/domain/sheet/mod.rs +++ b/crates/core/src/domain/sheet/mod.rs @@ -1,6 +1,7 @@ //! The anatomical sheet: document contract, integrity rules, index, the loaded sheet of a //! session and what React reads of it. +pub mod access; pub mod caps; pub mod check; pub mod create; diff --git a/crates/core/tests/n1_access_category.rs b/crates/core/tests/n1_access_category.rs index 7b3f8692..9b6ba41e 100644 --- a/crates/core/tests/n1_access_category.rs +++ b/crates/core/tests/n1_access_category.rs @@ -1,9 +1,11 @@ //! N-1 characterisation of the internal access category (owner 2026-11-22, board //! `docs/design/v1-2-6-u2-detail-views/README.md`, « Conséquences » 1). Written and green on the //! core BEFORE the change: what that core does with a sheet carrying `cat-access` is what every -//! N-1 application does. `permanent` stays green for ever. `baseline_edits` records the N-1 -//! edits; at Task 2 they flip to refusals, and Task 5 replays this file at the baseline commit -//! on the current fixture (read by path: the replay copies that one file). +//! N-1 application does. `permanent` stays green for ever. The N-1 edits (rename, recolour, a +//! point in the category, removal once empty, a second category refused as a duplicate) are +//! recorded at `N1_BASE` (ledger), where they ran green. The current core refuses the first +//! four: `sheet_access_category.rs`. Task 5 replays this file at the baseline commit on the +//! current fixture (read by path: the replay copies that one file). #![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] mod common; @@ -56,11 +58,6 @@ fn issues(doc: &AnatomicalSheetDocument) -> Vec<(String, String)> { list } -fn access_category() -> Value { - json!({ "id": "cat-access", - "name": { "fr": "Accès aux vues détaillées", "en": "Detail view access" }, "color": null }) -} - fn forelimb_view() -> Value { json!({ "id": "view-forelimbaa", "kind": "detail", "name": { "fr": "Membre antérieur", "en": "Forelimb" }, "parent_view_id": "view-main", @@ -68,23 +65,6 @@ fn forelimb_view() -> Value { "view_box": { "min_x": 625, "min_y": 969, "width": 220, "height": 660 } }) } -fn forelimb_access() -> Value { - json!({ "id": "anno-forelimbaa", "kind": "detail_trigger", "view_id": "view-main", - "category_id": "cat-access", "laterality": "left", - "geometry": { "type": "polygon", - "points": [[625, 969], [845, 969], [845, 1629], [625, 1629]] }, - "review_status": "to_confirm", "color": null, "name": null, - "opens_view_id": "view-forelimbaa" }) -} - -fn a_point_in_the_access_category() -> Value { - json!({ "id": "anno-n1pointaa", "kind": "point", "view_id": "view-main", - "category_id": "cat-access", "laterality": "unpaired", - "geometry": { "type": "circle", "cx": 700, "cy": 1000, "r": 14 }, - "review_status": "to_confirm", "color": null, "name": { "fr": "P", "en": "P" }, - "finding_zone_id": null, "vertebral_region_code": null }) -} - mod permanent { use super::*; @@ -113,84 +93,3 @@ mod permanent { assert!(!is_publishable(&validate_sheet_document(&doc))); } } - -mod baseline_edits { - use super::*; - - /// At the N-1 baseline, the page could write the category itself: the fixture is the slice - /// plus three plain inserts. - #[test] - fn the_fixture_is_the_slice_plus_three_inserts() { - let built = apply_all( - &slice(), - vec![ - insert("category", access_category()), - insert("view", forelimb_view()), - insert("annotation", forelimb_access()), - ], - ) - .unwrap(); - assert_eq!( - serde_json::to_value(&built).unwrap(), - serde_json::to_value(fixture()).unwrap() - ); - } - - #[test] - fn an_n1_application_renames_and_recolours_it() { - let renamed = json!({ "id": "cat-access", "name": { "fr": "Navigation", "en": "Navigation" }, - "color": "#123456" }); - let done = apply_edit( - &fixture(), - command(json!({ "op": "update", - "key": { "kind": "category", "id": "cat-access" }, - "element": { "kind": "category", "value": renamed } })), - ); - let doc = done.unwrap(); - let reread: AnatomicalSheetDocument = - serde_json::from_value(serde_json::to_value(&doc).unwrap()).unwrap(); - assert_eq!(issues(&reread), issues(&slice())); - } - - #[test] - fn an_n1_application_puts_a_point_in_it() { - let doc = apply_edit( - &fixture(), - insert("annotation", a_point_in_the_access_category()), - ); - assert!(doc.is_ok()); - } - - #[test] - fn an_n1_application_cannot_remove_it_while_an_access_uses_it() { - let done = apply_edit( - &fixture(), - command(json!({ "op": "remove", - "key": { "kind": "category", "id": "cat-access" } })), - ); - assert_eq!(done.unwrap_err(), EditError::HasDependents); - } - - /// Uniqueness at N-1 too: a second category of that id is a duplicate key. - #[test] - fn an_n1_application_cannot_insert_a_second_one() { - let done = apply_edit(&fixture(), insert("category", access_category())); - assert_eq!(done.unwrap_err(), EditError::DuplicateKey); - } - - #[test] - fn an_n1_application_removes_it_once_empty() { - let done = apply_all( - &fixture(), - vec![ - command( - json!({ "op": "remove", "key": { "kind": "annotation", "id": "anno-forelimbaa" } }), - ), - command( - json!({ "op": "remove", "key": { "kind": "category", "id": "cat-access" } }), - ), - ], - ); - assert!(done.is_ok()); - } -} diff --git a/crates/core/tests/sheet_access_category.rs b/crates/core/tests/sheet_access_category.rs new file mode 100644 index 00000000..3d5ecfa8 --- /dev/null +++ b/crates/core/tests/sheet_access_category.rs @@ -0,0 +1,239 @@ +//! The internal access category (owner 2026-11-22, README « Conséquences » 1): created by the +//! core when an access enters it, never written by a person, N-1 states kept usable. +#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)] + +mod common; + +use faunosteo_core::domain::js::parse_json; +use faunosteo_core::domain::sheet::access::ACCESS_CATEGORY_ID; +use faunosteo_core::domain::sheet::edit::{EditCommand, EditError, apply_edit}; +use faunosteo_core::domain::sheet::{ + AnatomicalSheetDocument, is_publishable, validate_sheet_document, +}; +use faunosteo_core::facade::call; +use serde_json::{Value, json}; + +const FIXTURE: &str = "crates/core/tests/fixtures/n1/access-category.json"; +const SLICE: &str = "crates/core/tests/fixtures/horse-slice.json"; + +fn value_of(path: &str) -> Value { + parse_json(&common::repo_file(path)).unwrap() +} + +fn doc_of(value: Value) -> AnatomicalSheetDocument { + serde_json::from_value(value).unwrap() +} + +fn slice() -> AnatomicalSheetDocument { + doc_of(value_of(SLICE)["input"].clone()) +} + +fn fixture_value() -> Value { + value_of(FIXTURE) +} + +fn command(value: Value) -> EditCommand { + serde_json::from_value(value).unwrap() +} + +fn insert(kind: &str, value: Value) -> EditCommand { + command(json!({ "op": "insert", "element": { "kind": kind, "value": value } })) +} + +fn update(kind: &str, id: &str, value: Value) -> EditCommand { + command(json!({ "op": "update", "key": { "kind": kind, "id": id }, + "element": { "kind": kind, "value": value } })) +} + +fn remove(kind: &str, id: &str) -> EditCommand { + command(json!({ "op": "remove", "key": { "kind": kind, "id": id } })) +} + +fn element(list: &str, id: &str) -> Value { + let doc = fixture_value(); + let found = doc[list].as_array().unwrap().iter().find(|e| e["id"] == id); + found.unwrap().clone() +} + +fn access_count(doc: &AnatomicalSheetDocument) -> usize { + doc.categories + .iter() + .filter(|c| c.id == ACCESS_CATEGORY_ID) + .count() +} + +fn refused(doc: &AnatomicalSheetDocument, c: EditCommand) -> EditError { + apply_edit(doc, c).unwrap_err() +} + +#[test] +fn the_fixture_is_the_slice_plus_the_view_and_its_access() { + let with_view = apply_edit( + &slice(), + insert("view", element("views", "view-forelimbaa")), + ); + let built = apply_edit( + &with_view.unwrap(), + insert("annotation", element("annotations", "anno-forelimbaa")), + ); + let fixture = serde_json::to_value(doc_of(fixture_value())).unwrap(); + assert_eq!(serde_json::to_value(built.unwrap()).unwrap(), fixture); +} + +#[test] +fn a_second_access_never_duplicates_the_category() { + let mut second = element("annotations", "anno-forelimbaa"); + second["id"] = json!("anno-forelimbbb"); + let doc = apply_edit(&doc_of(fixture_value()), insert("annotation", second)).unwrap(); + assert_eq!(access_count(&doc), 1); +} + +#[test] +fn a_category_renamed_by_an_n1_application_is_kept() { + let mut value = fixture_value(); + value["categories"][4]["name"] = json!({ "fr": "Navigation", "en": "Navigation" }); + let mut second = element("annotations", "anno-forelimbaa"); + second["id"] = json!("anno-forelimbbb"); + let doc = apply_edit(&doc_of(value), insert("annotation", second)).unwrap(); + assert_eq!(doc.categories[4].name.fr, "Navigation"); + assert_eq!(access_count(&doc), 1); +} + +#[test] +fn a_category_removed_by_an_n1_application_comes_back_with_the_next_access() { + let mut value = fixture_value(); + value["annotations"].as_array_mut().unwrap().pop(); + value["categories"].as_array_mut().unwrap().pop(); + let doc = apply_edit( + &doc_of(value), + insert("annotation", element("annotations", "anno-forelimbaa")), + ) + .unwrap(); + let fixture = serde_json::to_value(doc_of(fixture_value())).unwrap(); + assert_eq!(serde_json::to_value(&doc).unwrap(), fixture); +} + +#[test] +fn the_page_never_inserts_renames_recolours_or_removes_it() { + let doc = doc_of(fixture_value()); + let category = element("categories", ACCESS_CATEGORY_ID); + let mut renamed = category.clone(); + renamed["name"]["fr"] = json!("Autre"); + let mut recoloured = category; + recoloured["color"] = json!("#123456"); + let reserved = EditError::ReservedCategory; + assert_eq!( + refused( + &slice(), + insert("category", element("categories", ACCESS_CATEGORY_ID)) + ), + reserved + ); + assert_eq!( + refused(&doc, update("category", ACCESS_CATEGORY_ID, renamed)), + reserved + ); + assert_eq!( + refused(&doc, update("category", ACCESS_CATEGORY_ID, recoloured)), + reserved + ); + assert_eq!( + refused(&doc, remove("category", ACCESS_CATEGORY_ID)), + reserved + ); + let empty = apply_edit(&doc, remove("annotation", "anno-forelimbaa")).unwrap(); + assert_eq!( + refused(&empty, remove("category", ACCESS_CATEGORY_ID)), + reserved + ); +} + +#[test] +fn moving_it_in_the_list_stays_allowed() { + let moved = apply_edit( + &doc_of(fixture_value()), + command(json!({ "op": "move", + "key": { "kind": "category", "id": ACCESS_CATEGORY_ID }, "position": 0 })), + ); + assert_eq!(moved.unwrap().categories[0].id, ACCESS_CATEGORY_ID); +} + +#[test] +fn a_point_a_zone_or_another_access_never_enters_it() { + let doc = doc_of(fixture_value()); + let mut point = element("annotations", "hip"); + point["id"] = json!("anno-newpointa"); + point["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!( + refused(&doc, insert("annotation", point)), + EditError::ReservedCategory + ); + let mut hip = element("annotations", "hip"); + hip["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!( + refused(&doc, update("annotation", "hip", hip)), + EditError::ReservedCategory + ); + let mut head = element("annotations", "head-trigger"); + head["category_id"] = json!(ACCESS_CATEGORY_ID); + assert_eq!( + refused(&doc, update("annotation", "head-trigger", head)), + EditError::ReservedCategory + ); +} + +#[test] +fn an_access_in_it_is_reshaped_and_an_n1_point_in_it_stays_editable() { + let mut access = element("annotations", "anno-forelimbaa"); + access["geometry"]["points"][0] = json!([630, 970]); + let doc = apply_edit( + &doc_of(fixture_value()), + update("annotation", "anno-forelimbaa", access), + ) + .unwrap(); + let mut value = serde_json::to_value(&doc).unwrap(); + let point = json!({ "id": "anno-n1pointaa", "kind": "point", "view_id": "view-main", + "category_id": ACCESS_CATEGORY_ID, "laterality": "unpaired", + "geometry": { "type": "circle", "cx": 700, "cy": 1000, "r": 14 }, + "review_status": "to_confirm", "color": null, "name": { "fr": "P", "en": "P" }, + "finding_zone_id": null, "vertebral_region_code": null }); + value["annotations"] + .as_array_mut() + .unwrap() + .push(point.clone()); + let with_point = doc_of(value); + let mut moved = point.clone(); + moved["geometry"]["cx"] = json!(710); + assert!(apply_edit(&with_point, update("annotation", "anno-n1pointaa", moved)).is_ok()); + let mut ordinary = point; + ordinary["category_id"] = json!("articulations"); + assert!( + apply_edit( + &with_point, + update("annotation", "anno-n1pointaa", ordinary) + ) + .is_ok() + ); +} + +/// Uniqueness where it is held (correction to the owner, SQL keeps the structure only): a +/// document that held two would fail the verdict before submission and publication. +#[test] +fn two_access_categories_never_pass_the_verdict() { + let mut value = fixture_value(); + let category = element("categories", ACCESS_CATEGORY_ID); + value["categories"].as_array_mut().unwrap().push(category); + let issues = validate_sheet_document(&doc_of(value)); + assert!(issues.iter().any(|i| i.code == "category.id.duplicate")); + assert!(!is_publishable(&issues)); +} + +#[test] +fn the_facade_names_the_refusal() { + let input = json!({ "document": value_of(SLICE)["input"], + "command": { "op": "insert", "element": { "kind": "category", + "value": element("categories", ACCESS_CATEGORY_ID) } } }); + let answer: Value = serde_json::from_str(&call("sheet.edit", &input.to_string())).unwrap(); + assert_eq!(answer["ok"], json!(false)); + assert_eq!(answer["kind"], json!("reserved_category")); +}