From e84cbaf884bf061c879589421a63cdec8c995fbf Mon Sep 17 00:00:00 2001 From: bchanot Date: Thu, 8 Oct 2026 21:41:39 +0200 Subject: [PATCH] test(tests): add characterisation suite of the current app (step 1) Seven files, 91 cases, on the real SVGs and catalog: catalog invariants, SVG <-> catalog mapping table, pathology-editor matcher parity, click chain through the DOM, full PDF export/import, schema and persistence, i18n and species. Two golden Report v2 fixtures. No application file changed. Report: docs/development/CHARACTERIZATION_REPORT.md. 271/271 green. --- .claude/tasks/TODO.md | 8 + docs/development/CHARACTERIZATION_REPORT.md | 89 ++++++ tests/fixtures/README.md | 12 + tests/fixtures/report-v2.full.json | 89 ++++++ tests/fixtures/report-v2.minimal.json | 12 + tests/unit/char.catalog.test.ts | 169 +++++++++++ tests/unit/char.clickChain.test.tsx | 293 ++++++++++++++++++++ tests/unit/char.i18nSpecies.test.tsx | 127 +++++++++ tests/unit/char.pathologyEditor.test.ts | 146 ++++++++++ tests/unit/char.pdfFull.test.ts | 250 +++++++++++++++++ tests/unit/char.schemaPersistence.test.ts | 115 ++++++++ tests/unit/char.svgCatalogLink.test.ts | 222 +++++++++++++++ 12 files changed, 1532 insertions(+) create mode 100644 docs/development/CHARACTERIZATION_REPORT.md create mode 100644 tests/fixtures/README.md create mode 100644 tests/fixtures/report-v2.full.json create mode 100644 tests/fixtures/report-v2.minimal.json create mode 100644 tests/unit/char.catalog.test.ts create mode 100644 tests/unit/char.clickChain.test.tsx create mode 100644 tests/unit/char.i18nSpecies.test.tsx create mode 100644 tests/unit/char.pathologyEditor.test.ts create mode 100644 tests/unit/char.pdfFull.test.ts create mode 100644 tests/unit/char.schemaPersistence.test.ts create mode 100644 tests/unit/char.svgCatalogLink.test.ts diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 517aa2ea..c8c389ef 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -44,6 +44,14 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo --- +## SaaS migration (plan: docs/development/IMPLEMENTATION_PLAN.md) + +- [x] Step 0 — preparation docs in docs/development/ (2026-10-08, validated) +- [x] Step 1 — characterisation tests: 7 files / 91 cases, 2 golden fixtures, docs/development/CHARACTERIZATION_REPORT.md; 271/271, typecheck, lint, build green (2026-10-08, branch feature/step-01-characterisation-tests, awaiting validation) +- [ ] Step 2 — monorepo workspace (next, on validation) + +--- + ## Phase A — DONE (kept for reference) - [x] Scaffold (deps, configs, Docker, schemas, stubs) diff --git a/docs/development/CHARACTERIZATION_REPORT.md b/docs/development/CHARACTERIZATION_REPORT.md new file mode 100644 index 00000000..a58353c9 --- /dev/null +++ b/docs/development/CHARACTERIZATION_REPORT.md @@ -0,0 +1,89 @@ +# Characterisation report (plan Step 1) + +Status: done 2026-10-08, branch `feature/step-01-characterisation-tests`. +Scope: a tested photograph of the current application before any SaaS +transformation. No file under `src/`, `public/`, `scripts/`, `docker/` was +changed. Commands run on this host: Node 24.21.0, pnpm 10.13.1 (corepack), +dependencies installed from the lockfile. + +## 1. Results + +| Command | Result | +|---|---| +| `pnpm test:run` | 39 files, 271 tests green (180 pre-existing + 91 new) | +| `pnpm typecheck` | 0 errors | +| `pnpm lint` | 0 errors, 0 warnings | +| `pnpm build` | OK (chunk-size warning pre-existing) | + +## 2. Files added + +| File | Cases | Characterises | +|---|---|---| +| `tests/fixtures/report-v2.full.json` | fixture | Golden Report v2 with every zone kind (plain hinge, bilateral both sides, spine with vertebrae, detail-popup), catalog findings with vet flag and side, free text, severity, comment, conclusion, recommendations, dated next appointment. Real `data-anno-id` and catalog paths. | +| `tests/fixtures/report-v2.minimal.json` | fixture | Smallest valid v2 report. | +| `tests/fixtures/README.md` | doc | Fixture contract: never edited to make a test pass. | +| `tests/unit/char.catalog.test.ts` | 13 | `pathologies.json`: byte parity of the two copies, Zod acceptance, schema_version, species, the 26 zone keys in order, `zone.id === key`, 3 categories per zone, root-category id convention with the **known** `sphenoid → ssb-dysfunctions` anomaly, 792 nodes / 612 leaves / depth 3 / 228+384, 41 vet flags all on leaves, 62 `description_fr`, 0 `description_en`, 0 `sources`, sibling-only id uniqueness (26× `anamnesis`, 11× `amplitude-asymmetry`), three `anamnesis` content variants (8/9/9 zones). | +| `tests/unit/char.svgCatalogLink.test.ts` | 18 | Raw attribute census of both SVGs (48/48/18/47/47/18/5/1), five category slugs, 27 distinct ids, `Horse_head.svg` = same drawing + different viewBox, the full 26-row mapping table annotation → catalog zone with score 0 in EN and FR, trigger unmatched, no orphan zone, substring rule unreachable, the two FR pairs inside the fuzzy tolerance (distances 5 and 3), opens-detail ↔ manifest coherence, spine helpers on the real file (region → polygon id, spawn, collect order, detail-sourced exclusion). | +| `tests/unit/char.pathologyEditor.test.ts` | 8 | The inline matcher of `public/pathology-editor.html` evaluated from the file and compared to `zoneMatch.ts` on all 27 annotations + edge labels (LRN-026 parity test), `generateId` slug rules, 76/76 inline translation keys disjoint from the app dictionary, shared `osteo:locale` key, hard-coded `SPECIES_CONFIG` pointing at existing files, zero `src/` imports, noindex, no Zod. | +| `tests/unit/char.clickChain.test.tsx` | 12 | `EditorRoute` through the DOM on the real SVGs: disclaimer once per session (`osteo:disclaimer-shown`), plain toggle add/remove and `data-state="current"`, collapsed-card fallback (click re-activates the last observation and is lost), detail trigger opens the modal and is never a zone, zones clicked in the modal carry `detailSourceId: 'head'`, spine click adds + opens the picker on the right tab and never toggles off, cancel leaves a zone without vertebrae, picker spawns another region and prunes to zero, bilateral left / right / both and "both present → clear both", ✕ removal keeps orphan findings (**known**, BDR-019), one picker per (catalog zone, side) and raw-id badge for the unnamed trigger. | +| `tests/unit/char.pdfFull.test.ts` | 15 | Export of the full fixture: page count, title/author metadata, re-fetch of SVGs and logos at export time, ZONES as bullet rows with `(C3, C4)` / `(Gauche)` suffixes, one `CONSTATS — ` section per (zone, side) with snapshot labels and the `(!)` marker, free findings / severity / comment / view captions, conclusion page and header identity on every page, EN variant with identical attachment, deep-equal roundtrip, attachment dictionaries (`/F (osteo-report.json)`, `/AFRelationship /Data`, `/Desc` UTF-16 "Faunosteo state v2", `/Subtype /application#2Fjson`, Flate), pdf-lib 1.17.1 has no `getAttachments` so the traversal is the production path, `incompatible_version` with `foundVersion 3`, foreign attachment and Zod-invalid attachment both reported as `no_attachment` (**known**), orphan finding printed under its zone, unknown ids printed raw. | +| `tests/unit/char.schemaPersistence.test.ts` | 13 | Zod: fixtures accepted unchanged, unknown keys stripped, version literal 2, unbounded vertebra index (C99), French severity enum, orphan findings accepted, unknown species accepted, duplicate boneId with sides / detail. Persistence: full fixture mirrored to and restored from `osteo:draft`, `hydrateReport` does not revalidate, `initReport` shape, `osteo:lastPractitioner`, `osteo:locale`. | +| `tests/unit/char.i18nSpecies.test.tsx` | 12 | Dynamic keys (`severity.*`, `vertebra.region.*`, `home.import.error_*` with `{version}`, `pdf.section.*`/`pdf.view.*`), 71 `svg_editor.*` keys, label fallbacks, registry = equine only with the committed formula, catalog loader species id, `NewReportRoute` select defaults to equine with one option, scaffold script quirks (`schema_version '1.1'`, T13 default). | + +Pre-existing tests reused as-is: all 32 files (180 cases). They already +cover: SVG parser rules and counts (`anatomy.*`), zoneMatch on a synthetic +catalog, spineZones on synthetic bones, VertebraPicker, FindingsTreePicker, +schemas, store actions and draft mirror, practitioner cache, locale, +dictionary parity, minimal PDF roundtrip, attachment extraction and the 16 MiB +inflate cap, `buildZoneLabels`, `rasterizeSvg`, UI primitives. + +## 3. Behaviours characterised (summary) + +- Report: schema acceptance boundary, store init/hydrate, persistence keys, draft restore. +- Anatomy: real SVG attributes and categories, id spaces, parser output, spine region inference and sync on real data. +- Findings: catalog structure, counts, conventions, anomalies, SVG ↔ catalog link table, matcher behaviour and fragile pairs. +- Pathology editor: matcher parity, id generation, translations, config, isolation. +- Click chain: every branch of `onZoneClick` and the three pickers' effect on the store. +- PDF: full export text, pages, attachment format, import error kinds, degradation on missing assets. +- i18n: dynamic keys, fallbacks, dictionary surface tied to legacy tools. +- Special cases: detail trigger, orphan findings, disclaimer flag, unbounded vertebra index, unknown species, foreign attachments. + +## 4. Behaviours NOT characterised, and why + +| Area | Reason | Where it will be covered | +|---|---|---| +| SVG editor (`SvgEditorRoute.tsx`, 1858 lines) | Vanilla DOM inside a `useEffect`, state in the DOM, drag/mouse geometry depends on `getScreenCTM` which happy-dom does not implement. Testing it would require rewriting it (forbidden in this step). | Replaced by the merged editor (plan Step 17); its operations are listed in audit 03 §2 and become reference tests of the new model. | +| Pathology editor DOM behaviour (tree add/edit/delete, dirty flag, download) | 1700 lines of imperative DOM in an IIFE with no export; only the pure functions were extracted by text. | Merged editor findings panel (Step 17). | +| Real rasterisation (`rasterizeSvg` on the real SVG) | No canvas in happy-dom; a 1×1 PNG stub is used. The existing `pdf.svgToPng` test covers the function with mocks. | Playwright raster hash at the PDF step (Step 6) or later e2e. | +| Visual PDF layout (positions, wrapping, pagination) | Only drawn strings are captured, not coordinates. | PDF golden comparison by extracted text stays; layout is a visual QA item. | +| Vertex-level SVG geometry | `cx/cy/points` are never read by the app; no behaviour to pin. | Importer tests (Step 4) when geometry becomes data. | +| `window.alert` on export failure, download anchor click | Side effects of the route; no value in pinning. | e2e. | +| Browser e2e (real routing, file input import, download) | No Playwright in the repo; adding it is tooling work outside this step. | See §6. | + +## 5. Problems discovered (none fixed, by rule) + +1. **Host tooling**: this machine had no `pnpm` and no `node_modules`; CLAUDE.md says pnpm is at `~/.local/bin/pnpm`, which does not exist. Node is 24.21.0, not 20. Used `corepack prepare pnpm@10.13.1` (the Dockerfile pin). CLAUDE.md note is stale. +2. **Import error cause lost**: a Zod-invalid attachment and a foreign JSON attachment both surface as `no_attachment` (audit 08 B.2, pinned as known). +3. **ZONES rendering**: the ' · ' joined value is split back into bullet rows by the renderer; harmless, but the dictionary-level `pdf.empty` fallback is printed when an observation has findings but no zone. +4. **Fuzzy tolerance**: the FR pairs fetlock ant./post. and sacral/caudal are inside the Levenshtein threshold (5 ≤ 7, 3 ≤ 4); unreachable today only because EN labels are exact. +5. **Scaffold script** writes `schema_version '1.1'` and a mixed formula (known, script slated for removal). +6. **README** still says 174 tests (actual before this step: 180). Not edited in this step to keep the diff to tests and docs; corrected at Step 2 with the workspace move. + +## 6. To cover in a future e2e suite + +- Full flow: `/` → `/new` → `/editor` → zones of each kind → findings → export → download → re-import from `/`. +- Session persistence across a real reload (sessionStorage) and language switch mid-edit. +- Detail modal interactions with real pointer events (tooltip hidden on the trigger). +- PDF opened in a viewer: attachment visible, pages readable, raster images present. +- Mobile viewport layout of the editor. + +## 7. Known obsolescence + +Tests in `char.clickChain.test.tsx` and `char.pdfFull.test.ts` are written +against the current route and export signatures. Plan Step 5 (zone service, +document v3) and Step 6 (PDF v3) will replace them one-to-one; each deleted +test must name its replacement in the commit message (TEST_STRATEGY.md §6). +`char.pathologyEditor.test.ts` and the `svg_editor.*` key count die with the +legacy editors (Step 17). `char.catalog.test.ts` and +`char.svgCatalogLink.test.ts` become the oracle of the legacy importer +(Step 4) and survive as long as the seed files exist. diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md new file mode 100644 index 00000000..61f198d5 --- /dev/null +++ b/tests/fixtures/README.md @@ -0,0 +1,12 @@ +# Test fixtures + +Golden inputs frozen for the characterisation tests (plan Step 1). They describe +the Report v2 document as the current application produces it. + +| File | Content | +|---|---| +| `report-v2.full.json` | One report exercising every zone kind the editor can produce: plain hinge point, bilateral joint with both sides, spine zone with vertebrae, detail-popup zone, catalog findings (with and without vet referral and side), free text, severity, comment, conclusion, recommendations, dated next appointment. `boneId` values are the real `data-anno-id` of `public/species/equine/*.svg`; `zoneId`/`path` values exist in `pathologies.json`. | +| `report-v2.minimal.json` | Smallest valid v2 report (no observations). | + +Do not edit these files to make a test pass: they are the behavioural oracle for +the Report v2 → v3 adapter and for PDF regression. Add a new fixture instead. diff --git a/tests/fixtures/report-v2.full.json b/tests/fixtures/report-v2.full.json new file mode 100644 index 00000000..b331d170 --- /dev/null +++ b/tests/fixtures/report-v2.full.json @@ -0,0 +1,89 @@ +{ + "version": 2, + "id": "fixture-full-v2", + "createdAt": "2026-06-01T09:00:00.000Z", + "date": "2026-06-01", + "practitioner": { + "name": "Dr. Claire Dupont", + "cabinet": "Cabinet Équi-Ostéo", + "contact": "claire@example.test", + "siret": "12345678901234" + }, + "animal": { + "speciesId": "equine", + "name": "Mistral", + "breed": "Selle Français", + "age": "9 ans" + }, + "owner": { "name": "Jean Martin" }, + "observations": [ + { + "id": "obs-1", + "zones": [ + { "boneId": "point-mpbwyyc9" }, + { "boneId": "point-mpbwtst0", "side": "left" }, + { "boneId": "point-mpbwtst0", "side": "right" } + ], + "findings": [ + { + "zoneId": "c7-t1", + "path": ["c7-t1-dysfunctions", "segmental", "fixation"], + "labelFrSnapshot": "Fixation de la charnière", + "labelEnSnapshot": "Junction fixation" + }, + { + "zoneId": "hip", + "path": ["hip-dysfunctions", "articular", "restriction-flexion"], + "labelFrSnapshot": "Restriction en flexion", + "labelEnSnapshot": "Flexion restriction", + "side": "left" + } + ], + "freeTextFindings": ["Sensibilité au garrot"], + "severity": "modérée", + "comment": "Réagit à la palpation du garrot." + }, + { + "id": "obs-2", + "zones": [ + { + "boneId": "zone-mpbx5hx2", + "vertebrae": [ + { "region": "C", "index": 3 }, + { "region": "C", "index": 4 } + ] + } + ], + "findings": [ + { + "zoneId": "cervical", + "path": ["cervical-observations", "stumbling-proprioceptive"], + "labelFrSnapshot": "Trébuchements / déficit proprioceptif rapporté", + "labelEnSnapshot": "Reported stumbling / proprioceptive deficit", + "requiresVetReferral": true + } + ], + "freeTextFindings": [], + "severity": "sévère", + "comment": "" + }, + { + "id": "obs-3", + "zones": [{ "boneId": "point-mpbyo7zq", "detailSourceId": "head" }], + "findings": [ + { + "zoneId": "atm", + "path": ["atm-observations", "headshaking"], + "labelFrSnapshot": "Headshaking (secouement de tête)", + "labelEnSnapshot": "Headshaking", + "requiresVetReferral": true + } + ], + "freeTextFindings": [], + "comment": "Vue détail tête." + } + ], + "conclusion": "Dysfonction cervico-thoracique avec compensation du bassin.", + "recommendations": "Repos 3 jours puis reprise progressive.", + "nextAppointment": { "kind": "date", "date": "2026-07-01" } +} diff --git a/tests/fixtures/report-v2.minimal.json b/tests/fixtures/report-v2.minimal.json new file mode 100644 index 00000000..1028c40b --- /dev/null +++ b/tests/fixtures/report-v2.minimal.json @@ -0,0 +1,12 @@ +{ + "version": 2, + "id": "fixture-minimal-v2", + "createdAt": "2026-06-01T09:00:00.000Z", + "date": "2026-06-01", + "practitioner": { "name": "Dr. Dupont" }, + "animal": { "speciesId": "equine", "name": "Mistral" }, + "owner": { "name": "Jean Martin" }, + "observations": [], + "conclusion": "", + "recommendations": "" +} diff --git a/tests/unit/char.catalog.test.ts b/tests/unit/char.catalog.test.ts new file mode 100644 index 00000000..596fe0a8 --- /dev/null +++ b/tests/unit/char.catalog.test.ts @@ -0,0 +1,169 @@ +/** + * Characterisation (Step 1): the equine findings catalog as it exists today. + * Pins the facts of docs/faunosteo-audit/05-findings-editor.md §2.4 so that + * the future legacy importer (plan Step 4) can be checked against them, and + * so that any deliberate business correction shows up as a test change. + * + * Reads the files directly (no Zod) to count what is really on disk. + */ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { SpeciesFindingsSchema } from '@/domain/schema/findings' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const SRC_PATH = resolve(HERE, '../../src/domain/species/equine/pathologies.json') +const PUBLIC_PATH = resolve(HERE, '../../public/species/equine/pathologies.json') + +interface RawNode { + id: string + name_fr?: string + name_en?: string + description_fr?: string + description_en?: string + requires_vet_referral?: boolean + sources?: unknown[] + children?: RawNode[] +} +interface RawZone { id: string; name_fr: string; name_en: string; categories: RawNode[] } +interface RawCatalog { + schema_version: string + scope_disclaimer: string + species: { id: string; name_fr: string; name_en: string } + zones: Record +} + +const srcText = readFileSync(SRC_PATH, 'utf8') +const catalog = JSON.parse(srcText) as RawCatalog +const zoneKeys = Object.keys(catalog.zones) + +function walk(nodes: RawNode[], depth: number, visit: (n: RawNode, depth: number) => void) { + for (const n of nodes) { + visit(n, depth) + if (n.children) walk(n.children, depth + 1, visit) + } +} + +function allNodes(): Array<{ node: RawNode; depth: number; zone: string }> { + const out: Array<{ node: RawNode; depth: number; zone: string }> = [] + for (const key of zoneKeys) { + walk(catalog.zones[key].categories, 1, (node, depth) => out.push({ node, depth, zone: key })) + } + return out +} + +const isLeaf = (n: RawNode) => !n.children || n.children.length === 0 + +describe('catalog copies (src vs public)', () => { + it('the two pathologies.json copies are byte-identical (manual sync, no script)', () => { + const publicText = readFileSync(PUBLIC_PATH, 'utf8') + const md5 = (s: string) => createHash('md5').update(s).digest('hex') + expect(md5(publicText)).toBe(md5(srcText)) + }) + + it('the bundled copy passes the Zod schema (boot-time contract)', () => { + expect(() => SpeciesFindingsSchema.parse(catalog)).not.toThrow() + }) +}) + +describe('catalog shape (audit 05 §2.4)', () => { + it('declares schema_version "2.0" and species equine / Cheval / Horse', () => { + expect(catalog.schema_version).toBe('2.0') + expect(catalog.species).toEqual({ id: 'equine', name_fr: 'Cheval', name_en: 'Horse' }) + expect(catalog.scope_disclaimer.length).toBeGreaterThan(50) + }) + + it('has exactly 26 zones in cranio-caudal insertion order', () => { + expect(zoneKeys).toEqual([ + 'parietal', 'frontal', 'sphenoid', 'temporal', 'occipital', 'ssb', 'atm', 'hyoid', + 'c0-c1', 'cervical', 'c7-t1', 'shoulder', 'elbow', 'fore-fetlock', 'fore-sesamoids', + 'thoracic', 't18-l1', 'lumbar', 'l6-s1', 'sacral', 'sacroiliac', 'hip', 'stifle', + 'hock', 'hind-fetlock', 'caudal', + ]) + }) + + it('every zone.id equals its record key (convention, not enforced by Zod)', () => { + for (const key of zoneKeys) expect(catalog.zones[key].id).toBe(key) + }) + + it('every zone has exactly 3 root categories, the third always "anamnesis"', () => { + for (const key of zoneKeys) { + const cats = catalog.zones[key].categories + expect(cats, key).toHaveLength(3) + expect(cats[2].id, key).toBe('anamnesis') + } + }) + + it('root category ids follow -dysfunctions / -observations, except the known sphenoid anomaly', () => { + const anomalies: string[] = [] + for (const key of zoneKeys) { + const [dys, obs] = catalog.zones[key].categories + if (dys.id !== `${key}-dysfunctions`) anomalies.push(`${key}:${dys.id}`) + if (obs.id !== `${key}-observations`) anomalies.push(`${key}:${obs.id}`) + } + // KNOWN: sphenoid reuses the ssb category id (audit 05 §2.4). The business + // correction is deferred to the editor before the first official version + // (OPEN_QUESTIONS Q9); the importer must NOT silently fix it. + expect(anomalies).toEqual(['sphenoid:ssb-dysfunctions']) + }) + + it('counts 792 nodes, 612 leaves, max depth 3, 228 leaves at depth 2 and 384 at depth 3', () => { + const nodes = allNodes() + expect(nodes).toHaveLength(792) + const leaves = nodes.filter((n) => isLeaf(n.node)) + expect(leaves).toHaveLength(612) + expect(Math.max(...nodes.map((n) => n.depth))).toBe(3) + expect(leaves.filter((n) => n.depth === 2)).toHaveLength(228) + expect(leaves.filter((n) => n.depth === 3)).toHaveLength(384) + }) + + it('flags 41 vet-referral nodes, all of them leaves', () => { + const flagged = allNodes().filter((n) => n.node.requires_vet_referral === true) + expect(flagged).toHaveLength(41) + expect(flagged.every((n) => isLeaf(n.node))).toBe(true) + }) + + it('carries 62 description_fr, 0 description_en, 0 sources (CLAUDE.md "≥1 source" rule not met)', () => { + const nodes = allNodes() + expect(nodes.filter((n) => typeof n.node.description_fr === 'string')).toHaveLength(62) + expect(nodes.filter((n) => typeof n.node.description_en === 'string')).toHaveLength(0) + expect(nodes.filter((n) => Array.isArray(n.node.sources))).toHaveLength(0) + }) + + it('every node has non-empty name_fr and name_en', () => { + for (const { node, zone } of allNodes()) { + expect(node.name_fr, `${zone}/${node.id}`).toBeTruthy() + expect(node.name_en, `${zone}/${node.id}`).toBeTruthy() + } + }) + + it('node ids are unique among siblings only (same id reused across zones)', () => { + const idCount = new Map() + for (const { node } of allNodes()) idCount.set(node.id, (idCount.get(node.id) ?? 0) + 1) + expect(idCount.get('anamnesis')).toBe(26) + expect(idCount.get('trauma-direct')).toBe(26) + expect(idCount.get('no-identified-cause')).toBe(26) + expect(idCount.get('amplitude-asymmetry')).toBe(11) + // sibling uniqueness holds everywhere + const checkSiblings = (nodes: RawNode[], where: string) => { + const ids = nodes.map((n) => n.id) + expect(new Set(ids).size, where).toBe(ids.length) + for (const n of nodes) if (n.children) checkSiblings(n.children, `${where}/${n.id}`) + } + for (const key of zoneKeys) checkSiblings(catalog.zones[key].categories, key) + }) + + it('anamnesis exists in exactly three content variants (vertebral / appendicular / head)', () => { + const variants = new Map() + for (const key of zoneKeys) { + const anam = catalog.zones[key].categories[2] + const sig = (anam.children ?? []).map((c) => c.id).join(',') + variants.set(sig, [...(variants.get(sig) ?? []), key]) + } + expect(variants.size).toBe(3) + const groups = [...variants.values()].map((g) => g.length).sort((a, b) => a - b) + expect(groups).toEqual([8, 9, 9]) + }) +}) diff --git a/tests/unit/char.clickChain.test.tsx b/tests/unit/char.clickChain.test.tsx new file mode 100644 index 00000000..086ac20c --- /dev/null +++ b/tests/unit/char.clickChain.test.tsx @@ -0,0 +1,293 @@ +/** + * Characterisation (Step 1): the zone-click chain of EditorRoute + * (onZoneClick → detail / fallback / spine / bilateral / toggle), the + * disclaimer-once-per-session rule, the zone removal and the pickers' + * integration with the store. Exercised through the rendered route on the + * real Horse.svg / Horse_head.svg, with loadSvg mocked to read the files. + * + * Limitation: the chain lives inside the route component (audit 13 §4, no + * unit seam). These tests go through the DOM; plan Step 5 extracts the + * chain into a service and will replace them with unit tests one-to-one. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { render, screen, waitFor, within, cleanup } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import EditorRoute from '@/app/routes/EditorRoute' +import { useReportStore } from '@/state/reportStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import minimal from '../fixtures/report-v2.minimal.json' +import type { Report } from '@/domain/schema/report' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const FILES: Record = { + '/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'), + '/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'), +} + +vi.mock('@/anatomy/svgLoader', () => ({ + loadSvg: vi.fn(async (path: string) => { + const text = FILES[path] + if (!text) throw new Error(`unexpected path ${path}`) + const doc = new DOMParser().parseFromString(text, 'image/svg+xml') + return doc.documentElement as unknown as SVGSVGElement + }), +})) + +const HINGE = 'point-mpbwyyc9' // Charnière C7-T1, plain point +const HIP = 'point-mpbwtst0' // bilateral +const CERVICAL = 'zone-mpbx5hx2' // vertebral-precision +const TRIGGER = 'zone-mpby55kd' // opens-detail=head +const ATM = 'point-mpbyo7zq' // in Horse_head.svg + +const DISCLAIMER_FLAG = 'osteo:disclaimer-shown' + +function seedReport(observations: Report['observations'] = []) { + useReportStore.setState({ report: null, activeObservationIndex: 0 }) + useReportStore.getState().initReport({ + ...(minimal as Report), + observations, + } as Omit) +} + +const zonesOf = (i = 0) => useReportStore.getState().report!.observations[i].zones +const activeIndex = () => useReportStore.getState().activeObservationIndex + +async function mount() { + const utils = render( + + + , + ) + // Main SVG rendered and parsed (bones map ready once the trigger exists). + await waitFor(() => expect(document.querySelector(`[data-anno-id="${TRIGGER}"]`)).not.toBeNull()) + // Give the bones state effect a tick so onZoneClick resolves ids. + await waitFor(() => expect(screen.queryByRole('dialog', { name: fr['editor.disclaimer_title'] })).toBeNull()) + return utils +} + +function clickZone(id: string, scope: ParentNode = document) { + const els = scope.querySelectorAll(`[data-anno-id="${id}"]`) + expect(els.length, id).toBeGreaterThan(0) + els[0].dispatchEvent(new Event('click', { bubbles: true })) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + sessionStorage.clear() + sessionStorage.setItem(DISCLAIMER_FLAG, '1') + window.scrollTo = vi.fn() as unknown as typeof window.scrollTo + seedReport() +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +describe('disclaimer', () => { + it('shows the catalog scope_disclaimer once per session and records the flag', async () => { + sessionStorage.removeItem(DISCLAIMER_FLAG) + render( + + + , + ) + const dialog = await screen.findByRole('dialog', { name: fr['editor.disclaimer_title'] }) + expect(dialog.textContent).toContain('Aucun diagnostic médical') + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.understood'] })) + expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1') + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + }) +}) + +describe('plain zone (toggle)', () => { + it('adds the zone on first click and removes it on second click', async () => { + await mount() + clickZone(HINGE) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }])) + clickZone(HINGE) + await waitFor(() => expect(zonesOf()).toEqual([])) + }) + + it('highlights the zone of the active observation with data-state="current"', async () => { + await mount() + clickZone(HINGE) + await waitFor(() => + expect(document.querySelector(`[data-anno-id="${HINGE}"]`)?.getAttribute('data-state')).toBe('current'), + ) + }) +}) + +describe('no active observation (fallback)', () => { + it('re-activates the last observation and drops the click (user must click again)', async () => { + await mount() + // Collapse the only card through the UI (sets activeObservationIndex to -1). + await userEvent.click(screen.getByRole('button', { name: `${fr['observation.collapse_aria']} 1` })) + await waitFor(() => expect(activeIndex()).toBe(-1)) + clickZone(HINGE) + await waitFor(() => expect(activeIndex()).toBe(0)) + expect(zonesOf()).toEqual([]) + clickZone(HINGE) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }])) + }) +}) + +describe('detail trigger', () => { + it('opens the detail modal, never adds the trigger as a zone, and zones clicked inside carry detailSourceId', async () => { + await mount() + clickZone(TRIGGER) + const dialog = await screen.findByRole('dialog', { name: `${fr['editor.detail_title_prefix']}head` }) + expect(zonesOf()).toEqual([]) + await waitFor(() => expect(dialog.querySelector(`[data-anno-id="${ATM}"]`)).not.toBeNull()) + clickZone(ATM, dialog) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: ATM, detailSourceId: 'head' }])) + // Toggle off from inside the modal uses the same (boneId, detailSourceId) identity. + clickZone(ATM, dialog) + await waitFor(() => expect(zonesOf()).toEqual([])) + }) +}) + +describe('spine zone (vertebral-precision)', () => { + it('adds the zone, opens the picker on the matching region, and never toggles off on re-click', async () => { + await mount() + clickZone(CERVICAL) + const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ }) + expect(zonesOf()).toEqual([{ boneId: CERVICAL }]) + expect(within(dialog).getByRole('tab', { name: fr['vertebra.region.C'] })).toHaveAttribute('aria-selected', 'true') + await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] })) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] }])) + + clickZone(CERVICAL) + await screen.findByRole('dialog', { name: /Préciser les vertèbres/ }) + expect(zonesOf()).toHaveLength(1) + }) + + it('cancelling the picker leaves a spine zone without vertebrae', async () => { + await mount() + clickZone(CERVICAL) + const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ }) + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] })) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + expect(zonesOf()).toEqual([{ boneId: CERVICAL }]) + }) + + it('picking another region in the picker spawns that region zone and pruning to zero removes a zone', async () => { + await mount() + clickZone(CERVICAL) + let dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ }) + await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) + await userEvent.click(within(dialog).getByRole('tab', { name: fr['vertebra.region.L'] })) + await userEvent.click(within(dialog).getByRole('button', { name: 'L2' })) + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] })) + await waitFor(() => + expect(zonesOf()).toEqual([ + { boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] }, + { boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }, + ]), + ) + clickZone(CERVICAL) + dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ }) + await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) // uncheck + await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] })) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }])) + }) +}) + +describe('bilateral zone', () => { + it('asks for a side, adds one zone per side, and clears both when both are present', async () => { + await mount() + clickZone(HIP) + let dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' }) + await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.left'] })) + await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HIP, side: 'left' }])) + + clickZone(HIP) + dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' }) + expect(within(dialog).getByRole('button', { name: fr['lateral.left'] })).toBeDisabled() + await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.right'] })) + await waitFor(() => + expect(zonesOf()).toEqual([ + { boneId: HIP, side: 'left' }, + { boneId: HIP, side: 'right' }, + ]), + ) + + clickZone(HIP) + await waitFor(() => expect(zonesOf()).toEqual([])) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('"both" adds the missing sides only', async () => { + await mount() + clickZone(HIP) + const dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' }) + await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.both'] })) + await waitFor(() => + expect(zonesOf()).toEqual([ + { boneId: HIP, side: 'left' }, + { boneId: HIP, side: 'right' }, + ]), + ) + }) +}) + +describe('zone removal and orphan findings', () => { + it('KNOWN: removing a zone via ✕ keeps the findings attached to its catalog zone', async () => { + seedReport([ + { + id: 'obs-a', + zones: [{ boneId: HINGE }], + findings: [ + { + zoneId: 'c7-t1', + path: ['c7-t1-dysfunctions', 'segmental', 'fixation'], + labelFrSnapshot: 'Fixation de la charnière', + labelEnSnapshot: 'Junction fixation', + }, + ], + freeTextFindings: [], + comment: '', + }, + ]) + await mount() + const remove = await screen.findByRole('button', { + name: `${fr['observation.remove_zone']} Charnière C7-T1 (cervico-thoracique)`, + }) + await userEvent.click(remove) + await waitFor(() => expect(zonesOf()).toEqual([])) + expect(useReportStore.getState().report!.observations[0].findings).toHaveLength(1) + }) + + it('shows one findings picker per (catalog zone, side) resolved by label match', async () => { + seedReport([ + { + id: 'obs-b', + zones: [ + { boneId: HIP, side: 'left' }, + { boneId: HIP, side: 'right' }, + { boneId: HINGE }, + { boneId: TRIGGER }, + ], + findings: [], + freeTextFindings: [], + comment: '', + }, + ]) + await mount() + await screen.findByRole('button', { name: /Hanche \(coxo-fémorale\) \(Gauche\)/ }) + screen.getByRole('button', { name: /Hanche \(coxo-fémorale\) \(Droite\)/ }) + screen.getByRole('button', { name: /^Charnière C7-T1 \(cervico-thoracique\)$/ }) + // The trigger has no label and no catalog zone: exactly 3 pickers, and its + // badge falls back to the raw boneId. + expect(document.querySelectorAll('[aria-controls^="findings-zone-"]')).toHaveLength(3) + expect( + screen.getByRole('button', { name: `${fr['observation.remove_zone']} ${TRIGGER}` }), + ).toBeInTheDocument() + }) +}) diff --git a/tests/unit/char.i18nSpecies.test.tsx b/tests/unit/char.i18nSpecies.test.tsx new file mode 100644 index 00000000..c3062d32 --- /dev/null +++ b/tests/unit/char.i18nSpecies.test.tsx @@ -0,0 +1,127 @@ +/** + * Characterisation (Step 1): dictionary keys the runtime builds dynamically + * (severity., vertebra.region., import error kinds, PDF + * section labels), label fallbacks, the species registry and the + * scaffold script quirks (audit 12 §1). + */ +import { describe, it, expect, beforeEach } from 'vitest' +import { render, screen } from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { fr } from '@/i18n/fr' +import { en } from '@/i18n/en' +import { pickLocaleLabel } from '@/i18n/pickLocaleLabel' +import { boneLabel } from '@/anatomy/labels' +import { SeveritySchema, VertebralRegionSchema } from '@/domain/schema/observation' +import { getAllSpecies, getSpecies, speciesLabel } from '@/domain/species/registry' +import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae' +import NewReportRoute from '@/app/routes/NewReportRoute' +import { useLocaleStore } from '@/state/localeStore' + +const HERE = dirname(fileURLToPath(import.meta.url)) + +describe('dynamic dictionary keys', () => { + it('has a severity.* key for every stored severity value, in both dicts', () => { + for (const s of SeveritySchema.options) { + expect(fr[`severity.${s}`]).toBeTruthy() + expect(en[`severity.${s}`]).toBeTruthy() + } + }) + + it('has a vertebra.region.* key for every region code', () => { + for (const r of VertebralRegionSchema.options) { + expect(fr[`vertebra.region.${r}`]).toBeTruthy() + expect(en[`vertebra.region.${r}`]).toBeTruthy() + } + }) + + it('has one message per ImportError kind plus a generic one, with a {version} placeholder', () => { + for (const k of ['invalid_pdf', 'no_attachment', 'incompatible_version', 'generic']) { + expect(fr[`home.import.error_${k}`]).toBeTruthy() + expect(en[`home.import.error_${k}`]).toBeTruthy() + } + expect(fr['home.import.error_incompatible_version']).toContain('{version}') + expect(en['home.import.error_incompatible_version']).toContain('{version}') + }) + + it('exposes the PDF section and view labels used by the renderer', () => { + for (const k of [ + 'pdf.section.zones', 'pdf.section.findings_prefix', 'pdf.section.free_findings', + 'pdf.section.severity', 'pdf.section.comment', 'pdf.section.conclusion', + 'pdf.section.recommendations', 'pdf.section.next_appointment', 'pdf.view.general', + 'pdf.view.detail_prefix', 'pdf.empty', 'pdf.title.suffix.bilan', 'pdf.subject', + ]) { + expect(fr[k], k).toBeTruthy() + expect(en[k], k).toBeTruthy() + } + expect(fr['pdf.section.findings_prefix']).toBe('CONSTATS — ') + }) + + it('carries 71 svg_editor.* keys that die with the SVG editor', () => { + expect(Object.keys(fr).filter((k) => k.startsWith('svg_editor.'))).toHaveLength(71) + }) +}) + +describe('label fallbacks', () => { + it('pickLocaleLabel falls back to the other language, then to the fallback', () => { + expect(pickLocaleLabel('FR', 'EN', 'fr')).toBe('FR') + expect(pickLocaleLabel('', 'EN', 'fr')).toBe('EN') + expect(pickLocaleLabel('FR', '', 'en')).toBe('FR') + expect(pickLocaleLabel('', '', 'en', 'id')).toBe('id') + expect(pickLocaleLabel(undefined, undefined, 'fr')).toBe('') + }) + + it('boneLabel returns the raw fallback for an unknown bone', () => { + expect(boneLabel(undefined, 'fr', 'point-x')).toBe('point-x') + }) +}) + +describe('species registry', () => { + it('registers exactly one species, equine, with the committed manifest values', () => { + expect(getAllSpecies().map((s) => s.id)).toEqual(['equine']) + const eq = getSpecies('equine')! + expect(speciesLabel(eq, 'fr')).toBe('Cheval') + expect(speciesLabel(eq, 'en')).toBe('Horse') + expect(eq.vertebralFormula).toEqual({ C: 7, T: 18, L: 6, S: 5, Cd: 18 }) + expect(EQUINE_VERTEBRAL_FORMULA).toEqual(eq.vertebralFormula) + }) + + it('the catalog loader resolves the same species id as the manifest', async () => { + const m = await getSpecies('equine')!.findings() + expect(m.default.species.id).toBe('equine') + }) + + it('NewReportRoute defaults the species select to equine', () => { + useLocaleStore.setState({ locale: 'fr' }) + render( + + + , + ) + const select = screen.getByRole('combobox') as HTMLSelectElement + expect(select.value).toBe('equine') + expect(select.options).toHaveLength(1) + }) +}) + +describe('scaffold script quirks (audit 12 §1, kept as-is, script slated for removal)', () => { + const src = readFileSync(resolve(HERE, '../../scripts/scaffold-species.mjs'), 'utf8') + + it("writes schema_version '1.1' while the horse catalog is at '2.0'", () => { + expect(src).toContain("schema_version: '1.1'") + }) + + it('defaults the vertebral formula to C7 T13 L6 S5 Cd18 (mixed canine/equine)', () => { + expect(src).toMatch(/askPositiveInt\('\s*cervical \(C\)', 7\)/) + expect(src).toMatch(/askPositiveInt\('\s*thoracic \(T\)', 13\)/) + expect(src).toMatch(/askPositiveInt\('\s*lumbar \(L\)', 6\)/) + expect(src).toMatch(/askPositiveInt\('\s*sacral \(S\)', 5\)/) + expect(src).toMatch(/askPositiveInt\('\s*caudal \(Cd\)', 18\)/) + }) +}) + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) +}) diff --git a/tests/unit/char.pathologyEditor.test.ts b/tests/unit/char.pathologyEditor.test.ts new file mode 100644 index 00000000..006fb20d --- /dev/null +++ b/tests/unit/char.pathologyEditor.test.ts @@ -0,0 +1,146 @@ +/** + * Characterisation (Step 1): public/pathology-editor.html, the standalone + * findings editor. Its JavaScript is extracted by text and evaluated so that + * the inline matcher, id generator, translations and species config are + * pinned without touching the file (BDR-020/021, LRN-026). + * + * Limitation: the DOM-editing behaviour (tree add/edit/delete, dirty flag, + * download) is not executed here; it is described in + * docs/faunosteo-audit/05-findings-editor.md §3.5 and will be re-specified + * as tests of the merged editor (plan Step 17). + */ +import { describe, it, expect } from 'vitest' +import { existsSync, readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { parseSvgBones } from '@/anatomy/svgConvention' +import { matchZoneFindings, normalizeLabel, scorePair } from '@/lib/zoneMatch' +import FINDINGS from '@/domain/species/equine/pathologies' +import { fr } from '@/i18n/fr' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const ROOT = resolve(HERE, '../..') +const HTML = readFileSync(resolve(ROOT, 'public/pathology-editor.html'), 'utf8') + +function slice(from: string, to: string): string { + const a = HTML.indexOf(from) + const b = HTML.indexOf(to, a) + if (a < 0 || b < 0) throw new Error(`markers not found: ${from} … ${to}`) + return HTML.slice(a, b) +} + +type Zone = { id: string; name_fr: string; name_en: string } +interface InlineApi { + normalizeLabel: (s: string) => string + scorePair: (a: string, b: string) => number + matchZone: (fr: string, en: string, zones: Zone[]) => Zone | null + generateId: (en: string, fr: string, existing: string[]) => string +} + +const matcherSrc = slice('function normalizeLabel(s)', '// ── Node stats ──') +const inline = new Function( + `${matcherSrc}; return { normalizeLabel, scorePair, matchZone, generateId };`, +)() as InlineApi + +const translationsSrc = slice('var TRANSLATIONS = ', '\n };') + '\n };' +const TRANSLATIONS = new Function(`${translationsSrc} return TRANSLATIONS;`)() as { + fr: Record + en: Record +} + +const configSrc = slice('var SPECIES_CONFIG = ', '\n ];') + '\n ];' +const SPECIES_CONFIG = new Function(`${configSrc} return SPECIES_CONFIG;`)() as Array<{ + id: string + labelKey: string + jsonPath: string + views: Array<{ labelKey: string; svgPath: string }> +}> + +function bones(file: string) { + const text = readFileSync(resolve(ROOT, 'public/species/equine', file), 'utf8') + const doc = new DOMParser().parseFromString(text, 'image/svg+xml') + return parseSvgBones(doc.documentElement as unknown as SVGSVGElement) +} + +const zones = Object.values(FINDINGS.zones) + +describe('inline matcher parity with src/lib/zoneMatch.ts', () => { + const labels: Array<{ fr: string; en: string }> = [ + ...[...bones('Horse.svg').values(), ...bones('Horse_head.svg').values()].map((b) => ({ fr: b.fr, en: b.en })), + { fr: 'Hanche', en: 'Hip' }, + { fr: 'ATM', en: 'TMJ' }, + { fr: 'Sphenoide', en: 'Sphenoidd' }, + { fr: 'Vertèbres sacrales', en: '' }, + { fr: '', en: '' }, + { fr: 'Boulet ant. (métacarpo-phalangien)', en: 'Fore fetlok' }, + ] + + it('returns the same zone for every real annotation and edge label', () => { + for (const l of labels) { + const app = matchZoneFindings(l, zones)?.id + const editor = inline.matchZone(l.fr, l.en, zones)?.id + expect(editor ?? undefined, `${l.fr} / ${l.en}`).toBe(app) + } + }) + + it('normalizes and scores identically', () => { + for (const s of ['Sphénoïde', 'Charnière C0-C1 (occipito-atloïdienne)', 'Temporomandibular Joint (TMJ)', '']) { + expect(inline.normalizeLabel(s)).toBe(normalizeLabel(s)) + } + expect(inline.scorePair('Hip', 'Hip joint')).toBe(scorePair('Hip', 'Hip joint')) + expect(inline.scorePair('Sphenoidd', 'Sphenoid')).toBe(scorePair('Sphenoidd', 'Sphenoid')) + expect(inline.scorePair('', 'x')).toBe(scorePair('', 'x')) + }) +}) + +describe('inline id generator', () => { + it('slugs name_en first, then name_fr, strips accents, suffixes -2 on sibling collision', () => { + expect(inline.generateId('Flexion restriction', 'Restriction en flexion', [])).toBe('flexion-restriction') + expect(inline.generateId('', 'Tension du splénius', [])).toBe('tension-du-splenius') + expect(inline.generateId('Hip', '', ['hip'])).toBe('hip-2') + expect(inline.generateId('Hip', '', ['hip', 'hip-2'])).toBe('hip-3') + expect(inline.generateId('', '', [])).toBe('node') + expect(inline.generateId(' -- ', '', [])).toBe('node') + }) +}) + +describe('inline translations and config', () => { + it('fr and en share the same key set (76 keys), independent from the app dictionary', () => { + const frKeys = Object.keys(TRANSLATIONS.fr).sort() + const enKeys = Object.keys(TRANSLATIONS.en).sort() + expect(frKeys).toEqual(enKeys) + expect(frKeys).toHaveLength(76) + // No shared key space with src/i18n (different naming scheme) + expect(frKeys.filter((k) => k in fr)).toEqual([]) + }) + + it('shares only the locale storage key with the app', () => { + expect(HTML).toContain("localStorage.getItem('osteo:locale')") + expect(HTML).toContain("localStorage.setItem('osteo:locale'") + }) + + it('hard-codes a single species (equine) with two views and the public JSON copy', () => { + expect(SPECIES_CONFIG).toHaveLength(1) + const [equine] = SPECIES_CONFIG + expect(equine.id).toBe('equine') + expect(equine.jsonPath).toBe('/species/equine/pathologies.json') + expect(equine.views.map((v) => v.svgPath)).toEqual([ + '/species/equine/Horse.svg', + '/species/equine/Horse_head.svg', + ]) + for (const p of [equine.jsonPath, ...equine.views.map((v) => v.svgPath)]) { + expect(existsSync(resolve(ROOT, 'public', p.slice(1))), p).toBe(true) + } + }) + + it('imports nothing from src/ and declares noindex', () => { + expect(HTML).not.toMatch(/from\s+['"]\.\.?\/src/) + expect(HTML).not.toMatch(/]+src=/) + expect(HTML).toMatch(/name="robots"\s+content="noindex,\s*nofollow"/) + }) + + it('validates only three top-level keys of the loaded JSON (no Zod)', () => { + expect(HTML).toMatch(/schema_version/) + expect(HTML).not.toMatch(/zod/i) + }) +}) diff --git a/tests/unit/char.pdfFull.test.ts b/tests/unit/char.pdfFull.test.ts new file mode 100644 index 00000000..c9664e94 --- /dev/null +++ b/tests/unit/char.pdfFull.test.ts @@ -0,0 +1,250 @@ +/** + * Characterisation (Step 1): the full PDF pipeline on the golden fixture + * (every zone kind, findings with vet flag and side, free text, severity, + * comment, conclusion, next appointment): page count, drawn text, attachment + * roundtrip, import error kinds, and the attachment fallback path. + * + * Text is captured by spying on PDFPage.drawText (pdf-lib has no text + * extraction). Rasterization is replaced by a 1×1 PNG: happy-dom has no + * canvas. SVG fetches are served from the committed files; logo fetches 404 + * on purpose to pin the "PDF without logos" degradation. + */ +import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest' +import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { exportReportToPdf } from '@/pdf/export' +import { importReportFromPdf, ImportError } from '@/pdf/import' +import { fr } from '@/i18n/fr' +import { en } from '@/i18n/en' +import full from '../fixtures/report-v2.full.json' +import type { Report } from '@/domain/schema/report' + +const ONE_PX_PNG = Uint8Array.from( + Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', + ), +) +vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: vi.fn(async () => ONE_PX_PNG) })) + +const HERE = dirname(fileURLToPath(import.meta.url)) +const FILES: Record = { + '/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'), + '/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'), +} +const fetched: string[] = [] +const realFetch = globalThis.fetch + +beforeAll(() => { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input) + fetched.push(url) + const text = FILES[url] + if (text) return new Response(text, { status: 200, headers: { 'content-type': 'image/svg+xml' } }) + return new Response('not found', { status: 404 }) + }) as typeof fetch + vi.spyOn(console, 'warn').mockImplementation(() => undefined) +}) +afterAll(() => { + globalThis.fetch = realFetch +}) + +const report = full as Report +let drawn: string[] = [] + +beforeEach(() => { + drawn = [] + fetched.length = 0 + vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (this: PDFPage, text: string) { + drawn.push(text) + } as never) +}) + +/** Rebuilds wrapped values: lines are drawn one by one, joined by a space. */ +const joined = () => drawn.join(' ').replace(/\s+/g, ' ') + +describe('export on the full fixture (FR)', () => { + it('produces one page per observation plus a conclusion page', async () => { + const bytes = await exportReportToPdf(report, { locale: 'fr' }) + const doc = await PDFDocument.load(bytes) + expect(doc.getPageCount()).toBe(report.observations.length + 1) + expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`) + expect(doc.getAuthor()).toBe('Dr. Claire Dupont') + }) + + it('re-fetches the SVGs from public/ and the logos at export time (external dependencies)', async () => { + await exportReportToPdf(report, { locale: 'fr' }) + const svgFetches = fetched.filter((u) => u.endsWith('.svg') && u.includes('/species/')) + // buildZoneLabels (2) + one colorized view per rendered image (general ×2, head ×1) + expect(svgFetches.filter((u) => u.endsWith('Horse.svg')).length).toBeGreaterThanOrEqual(3) + expect(svgFetches.filter((u) => u.endsWith('Horse_head.svg')).length).toBeGreaterThanOrEqual(2) + expect(fetched.some((u) => u.includes('/assets/') && u.endsWith('.png'))).toBe(true) + }) + + it('draws the ZONES section as bullet rows with vertebrae and side suffixes', async () => { + await exportReportToPdf(report, { locale: 'fr' }) + expect(drawn).toContain(fr['pdf.section.zones']) + const zonesIdx = drawn.indexOf(fr['pdf.section.zones']) + // The ' · ' joined value is split back into one row per zone with a bullet glyph. + expect(drawn.slice(zonesIdx + 1, zonesIdx + 6)).toEqual([ + 'Charnière C7-T1 (cervico-thoracique)', + '•', + 'Hanche (coxo-fémorale) (Gauche)', + '•', + 'Hanche (coxo-fémorale) (Droite)', + ]) + expect(drawn).toContain('Vertèbres cervicales (C3, C4)') + expect(drawn).toContain('Articulation Temporo-Mandibulaire (ATM)') + }) + + it('draws one CONSTATS section per (catalog zone, side) with snapshot labels and the (!) vet marker', async () => { + await exportReportToPdf(report, { locale: 'fr' }) + const prefix = fr['pdf.section.findings_prefix'] + expect(drawn).toContain(`${prefix}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`) + expect(drawn).toContain(`${prefix}HANCHE (COXO-FÉMORALE) (GAUCHE)`) + expect(drawn).toContain(`${prefix}VERTÈBRES CERVICALES`) + expect(drawn).toContain(`${prefix}ARTICULATION TEMPORO-MANDIBULAIRE (ATM)`) + expect(drawn).toContain('Fixation de la charnière') + expect(drawn).toContain('Restriction en flexion') + expect(drawn.some((l) => l.startsWith('(!) Trébuchements'))).toBe(true) + expect(drawn).toContain('(!) Headshaking (secouement de tête)') + }) + + it('draws free findings, severity, comment, and the view captions', async () => { + await exportReportToPdf(report, { locale: 'fr' }) + expect(drawn).toContain(fr['pdf.section.free_findings']) + expect(drawn).toContain('Sensibilité au garrot') + expect(drawn).toContain(fr['pdf.section.severity']) + expect(drawn).toContain(fr['severity.modérée']) + expect(drawn).toContain(fr['severity.sévère']) + expect(drawn).toContain(fr['pdf.section.comment']) + expect(drawn).toContain('Réagit à la palpation du garrot.') + expect(drawn.filter((l) => l === fr['pdf.view.general'])).toHaveLength(2) + expect(drawn).toContain(`${fr['pdf.view.detail_prefix']}HEAD`) + }) + + it('draws the conclusion page and the header identity on every page', async () => { + await exportReportToPdf(report, { locale: 'fr' }) + expect(drawn).toContain(fr['pdf.section.conclusion']) + expect(drawn).toContain(fr['pdf.section.recommendations']) + expect(drawn).toContain(fr['pdf.section.next_appointment']) + expect(joined()).toContain('Dysfonction cervico-thoracique avec compensation du bassin.') + expect(drawn.filter((l) => l === 'Dr. Claire Dupont').length).toBe(4) + expect(drawn.filter((l) => l.includes('12345678901234')).length).toBe(4) + }) + + it('uses the EN snapshots and dictionary when locale=en, same attachment bytes', async () => { + const frBytes = await exportReportToPdf(report, { locale: 'fr' }) + const frDrawn = [...drawn] + drawn = [] + const enBytes = await exportReportToPdf(report, { locale: 'en' }) + expect(drawn).toContain(en['pdf.section.zones']) + expect(drawn).toContain(`${en['pdf.section.findings_prefix']}HIP JOINT (LEFT)`) + expect(drawn).toContain('Junction fixation') + expect(drawn).toContain('(!) Headshaking') + expect(frDrawn).not.toContain('Junction fixation') + const a = await importReportFromPdf(frBytes) + const b = await importReportFromPdf(enBytes) + expect(a).toEqual(b) + }) +}) + +describe('roundtrip and import', () => { + it('re-imports the full fixture unchanged (deep equality)', async () => { + const bytes = await exportReportToPdf(report, { locale: 'fr' }) + const imported = await importReportFromPdf(bytes) + expect(imported).toEqual(report) + }) + + it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, description "Faunosteo state v2"', async () => { + const bytes = await exportReportToPdf(report, { locale: 'fr' }) + const doc = await PDFDocument.load(bytes) + const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o)) + const filespec = objects.find((s) => s.includes('/Type /Filespec'))! + expect(filespec).toContain('/F (osteo-report.json)') + expect(filespec).toContain('/AFRelationship /Data') + // /Desc is a UTF-16BE hex string: "Faunosteo state v2" + expect(filespec).toContain('/Desc ') + const embedded = objects.find((s) => s.includes('/Type /EmbeddedFile'))! + expect(embedded).toContain('/Subtype /application#2Fjson') + expect(embedded).toContain('/Filter /FlateDecode') + expect(objects.some((s) => s.includes('/EmbeddedFiles'))).toBe(true) + }) + + it('pdf-lib 1.17.1 has no getAttachments: the object-traversal fallback IS the import path', async () => { + expect(typeof (PDFDocument.prototype as unknown as { getAttachments?: unknown }).getAttachments).toBe('undefined') + }) + + it('reports incompatible_version with the found version for a v3 attachment', async () => { + const doc = await PDFDocument.create() + doc.addPage() + await doc.attach(new TextEncoder().encode(JSON.stringify({ ...report, version: 3 })), 'osteo-report.json', { + mimeType: 'application/json', + afRelationship: AFRelationship.Data, + }) + const err = await importReportFromPdf(await doc.save()).catch((e) => e) + expect(err).toBeInstanceOf(ImportError) + expect((err as ImportError).kind).toBe('incompatible_version') + expect((err as ImportError).foundVersion).toBe(3) + }) + + it('KNOWN: a foreign JSON attachment is picked up by the traversal and fails as no_attachment', async () => { + const doc = await PDFDocument.create() + doc.addPage() + await doc.attach(new TextEncoder().encode('{"hello":1}'), 'other.json', { + mimeType: 'application/json', + afRelationship: AFRelationship.Data, + }) + const err = await importReportFromPdf(await doc.save()).catch((e) => e) + expect(err).toBeInstanceOf(ImportError) + expect((err as ImportError).kind).toBe('no_attachment') + }) + + it('KNOWN: a Zod-invalid report attachment is also reported as no_attachment (cause lost)', async () => { + const doc = await PDFDocument.create() + doc.addPage() + const broken = { ...report, practitioner: { name: '' } } + await doc.attach(new TextEncoder().encode(JSON.stringify(broken)), 'osteo-report.json', { + mimeType: 'application/json', + afRelationship: AFRelationship.Data, + }) + const err = await importReportFromPdf(await doc.save()).catch((e) => e) + expect((err as ImportError).kind).toBe('no_attachment') + }) + + it('an orphan finding (zone removed) is still printed under its catalog zone', async () => { + const orphaned: Report = { + ...report, + observations: [{ ...report.observations[0], zones: [] }], + } + await exportReportToPdf(orphaned, { locale: 'fr' }) + expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`) + expect(drawn).toContain(fr['pdf.empty']) + }) + + it('an unknown boneId is printed raw and an unknown zoneId is printed raw', async () => { + const stale: Report = { + ...report, + observations: [ + { + ...report.observations[0], + zones: [{ boneId: 'point-gone' }], + findings: [ + { + zoneId: 'zone-gone', + path: ['x'], + labelFrSnapshot: 'Snapshot FR', + labelEnSnapshot: 'Snapshot EN', + }, + ], + }, + ], + } + await exportReportToPdf(stale, { locale: 'fr' }) + expect(drawn).toContain('point-gone') + expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`) + expect(drawn).toContain('Snapshot FR') + }) +}) diff --git a/tests/unit/char.schemaPersistence.test.ts b/tests/unit/char.schemaPersistence.test.ts new file mode 100644 index 00000000..db921dc9 --- /dev/null +++ b/tests/unit/char.schemaPersistence.test.ts @@ -0,0 +1,115 @@ +/** + * Characterisation (Step 1): what the Report v2 schema accepts or rejects, + * what the browser persistence keeps, and the storage keys the SaaS + * migration must read (plan Step 14 one-time draft import). + */ +import { describe, it, expect, beforeEach } from 'vitest' +import { ReportSchema } from '@/domain/schema/report' +import { ObservationSchema, VertebraSchema, SeveritySchema } from '@/domain/schema/observation' +import { readPersistedDraft, useReportStore } from '@/state/reportStore' +import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache' +import { useLocaleStore } from '@/state/localeStore' +import full from '../fixtures/report-v2.full.json' +import minimal from '../fixtures/report-v2.minimal.json' +import type { Report } from '@/domain/schema/report' + +describe('Report v2 schema on the golden fixtures', () => { + it('accepts both fixtures unchanged', () => { + expect(ReportSchema.parse(full)).toEqual(full) + expect(ReportSchema.parse(minimal)).toEqual(minimal) + }) + + it('strips unknown keys silently (forward-compat fields are lost on reimport)', () => { + const parsed = ReportSchema.parse({ ...minimal, futureField: 1, animal: { ...minimal.animal, chip: 'x' } }) + expect(parsed).toEqual(minimal) + }) + + it('rejects version 1 and 3, accepts only the literal 2', () => { + expect(ReportSchema.safeParse({ ...minimal, version: 1 }).success).toBe(false) + expect(ReportSchema.safeParse({ ...minimal, version: 3 }).success).toBe(false) + }) + + it('does not bound vertebra indexes by the species formula (C99 accepted)', () => { + expect(VertebraSchema.safeParse({ region: 'C', index: 99 }).success).toBe(true) + expect(VertebraSchema.safeParse({ region: 'X', index: 1 }).success).toBe(false) + expect(VertebraSchema.safeParse({ region: 'C', index: 0 }).success).toBe(false) + }) + + it('stores severities as French enum values', () => { + expect(SeveritySchema.options).toEqual(['légère', 'modérée', 'sévère']) + }) + + it('accepts findings whose zoneId matches no zone of the observation (orphans)', () => { + const obs = { ...full.observations[0], zones: [] } + expect(ObservationSchema.safeParse(obs).success).toBe(true) + }) + + it('accepts a speciesId that no manifest registers (checked only at render time)', () => { + expect(ReportSchema.safeParse({ ...minimal, animal: { speciesId: 'dragon', name: 'X' } }).success).toBe(true) + }) + + it('accepts two zones with the same boneId and different sides, and the same boneId from main and detail', () => { + const obs = { + ...minimal, + observations: [ + { + id: 'o', + zones: [ + { boneId: 'a', side: 'left' }, + { boneId: 'a', side: 'right' }, + { boneId: 'a', detailSourceId: 'head' }, + ], + findings: [], + freeTextFindings: [], + comment: '', + }, + ], + } + expect(ReportSchema.safeParse(obs).success).toBe(true) + }) +}) + +describe('browser persistence', () => { + beforeEach(() => { + sessionStorage.clear() + localStorage.clear() + useReportStore.setState({ report: null, activeObservationIndex: 0 }) + }) + + it('mirrors the full fixture to sessionStorage["osteo:draft"] and restores it unchanged', () => { + useReportStore.getState().hydrateReport(full as Report) + const raw = sessionStorage.getItem('osteo:draft') + expect(raw).not.toBeNull() + expect(JSON.parse(raw!)).toEqual(full) + expect(readPersistedDraft()).toEqual(full) + }) + + it('hydrateReport does not revalidate (an invalid report can enter the store, the draft is then unreadable)', () => { + const broken = { ...(minimal as Report), version: 7 } as unknown as Report + useReportStore.getState().hydrateReport(broken) + expect(useReportStore.getState().report?.version).toBe(7) + expect(readPersistedDraft()).toBeNull() + }) + + it('initReport creates one empty observation, a uuid id and version 2', () => { + const { observations, ...draft } = minimal as Report + void observations + useReportStore.getState().initReport({ ...draft, observations: [] } as never) + const r = useReportStore.getState().report! + expect(r.version).toBe(2) + expect(r.id).toMatch(/^[0-9a-f-]{36}$/) + expect(r.observations).toHaveLength(1) + expect(r.observations[0]).toMatchObject({ zones: [], findings: [], freeTextFindings: [], comment: '' }) + }) + + it('caches the practitioner block under localStorage["osteo:lastPractitioner"]', () => { + writeCachedPractitioner(full.practitioner) + expect(JSON.parse(localStorage.getItem('osteo:lastPractitioner')!)).toEqual(full.practitioner) + expect(readCachedPractitioner()).toEqual(full.practitioner) + }) + + it('persists the locale under localStorage["osteo:locale"] (shared with pathology-editor.html)', () => { + useLocaleStore.getState().setLocale('en') + expect(localStorage.getItem('osteo:locale')).toBe('en') + }) +}) diff --git a/tests/unit/char.svgCatalogLink.test.ts b/tests/unit/char.svgCatalogLink.test.ts new file mode 100644 index 00000000..f5082176 --- /dev/null +++ b/tests/unit/char.svgCatalogLink.test.ts @@ -0,0 +1,222 @@ +/** + * Characterisation (Step 1): the real SVG assets, their attributes, the + * SVG ↔ catalog link computed by zoneMatch, the opens-detail ↔ manifest + * contract and the spine helpers on the real Horse.svg. + * Oracle: docs/faunosteo-audit/06-svg-findings-link.md §4 (full table). + */ +import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, resolve } from 'node:path' +import { parseSvgBones } from '@/anatomy/svgConvention' +import { matchZoneFindings, scorePair, levenshtein, normalizeLabel } from '@/lib/zoneMatch' +import { + regionFromLabel, + findSpineZoneId, + collectSpineVertebrae, + syncSpineZones, +} from '@/lib/spineZones' +import { getSpecies } from '@/domain/species/registry' +import FINDINGS from '@/domain/species/equine/pathologies' +import type { Bone } from '@/anatomy/types' + +const HERE = dirname(fileURLToPath(import.meta.url)) +const HORSE_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8') +const HEAD_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8') + +function parse(text: string): Map { + const doc = new DOMParser().parseFromString(text, 'image/svg+xml') + return parseSvgBones(doc.documentElement as unknown as SVGSVGElement) +} + +const horse = parse(HORSE_TEXT) +const head = parse(HEAD_TEXT) +const zones = Object.values(FINDINGS.zones) + +/** Expected mapping, audit 06 §4. Trigger zone-mpby55kd is intentionally absent. */ +const EXPECTED: Record = { + 'point-mpbwrkp0': 'hind-fetlock', + 'point-mpbwsi9q': 'hock', + 'point-mpbwt4fa': 'stifle', + 'point-mpbwtst0': 'hip', + 'point-mpbwugty': 'sacroiliac', + 'point-mpbwv4xy': 'shoulder', + 'point-mpbwvpvt': 'elbow', + 'point-mpbwwaru': 'fore-fetlock', + 'point-mpbwwxvn': 'fore-sesamoids', + 'point-mpbwxnb4': 'l6-s1', + 'point-mpbwyd9i': 't18-l1', + 'point-mpbwyyc9': 'c7-t1', + 'zone-mpbx00jq': 'caudal', + 'zone-mpbx0xnp': 'sacral', + 'zone-mpbx1rm9': 'lumbar', + 'zone-mpbx2rpe': 'thoracic', + 'zone-mpbx5hx2': 'cervical', + 'point-mpbykomv': 'parietal', + 'point-mpbylh35': 'frontal', + 'point-mpbymcln': 'sphenoid', + 'point-mpbyn2k3': 'temporal', + 'point-mpbynls5': 'occipital', + 'point-mpbyo7zq': 'atm', + 'point-mpbyphay': 'ssb', + 'point-mpbyq841': 'hyoid', + 'point-mpbyqxbg': 'c0-c1', +} + +describe('SVG attribute census (raw text, audit 03 §10.H)', () => { + const count = (attr: string) => + (HORSE_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length + + (HEAD_TEXT.match(new RegExp(`${attr}="`, 'g')) ?? []).length + + it('counts data-anno-* attributes across both files', () => { + expect(count('data-anno-id')).toBe(48) + expect(count('data-anno-category')).toBe(48) + expect(count('data-anno-category-name')).toBe(18) + expect(count('data-anno-name-fr')).toBe(47) + expect(count('data-anno-name-en')).toBe(47) + expect(count('data-anno-lateral')).toBe(18) + expect(count('data-anno-special')).toBe(5) + expect(count('data-anno-opens-detail')).toBe(1) + }) + + it('uses only five category slugs, two of them with degraded accents', () => { + const cats = new Set([...horse.values(), ...head.values()].map((b) => b.category)) + expect([...cats].sort()).toEqual([ + 'articulations', 'cadrans-du-cr-ne', 'charni-res-vert-brales', 'os', 'zone-colonne', + ]) + }) + + it('lateral is always "bilateral", special always "vertebral-precision"', () => { + const all = [...horse.values(), ...head.values()] + expect(all.filter((b) => b.lateral).every((b) => b.lateral === 'bilateral')).toBe(true) + expect(all.filter((b) => b.lateral)).toHaveLength(9) + expect(all.filter((b) => b.special).every((b) => b.special === 'vertebral-precision')).toBe(true) + expect(all.filter((b) => b.special)).toHaveLength(5) + }) + + it('main and detail id spaces do not overlap (27 distinct ids)', () => { + const ids = new Set([...horse.keys(), ...head.keys()]) + expect(ids.size).toBe(horse.size + head.size) + expect(ids.size).toBe(27) + }) + + it('Horse_head.svg is the same drawing as Horse.svg with a different viewBox', () => { + expect(HORSE_TEXT).toMatch(/viewBox="0 0 2073\.4 1629\.4"/) + expect(HEAD_TEXT).toMatch(/viewBox="60 100 500 380"/) + const body = (t: string) => t.split('\n').slice(2, 703).join('\n') + expect(body(HEAD_TEXT)).toBe(body(HORSE_TEXT)) + }) +}) + +describe('SVG ↔ catalog link (audit 06 §4)', () => { + it('maps the 26 named annotations to their catalog zone, exact EN and FR match', () => { + const all = new Map([...horse, ...head]) + for (const [id, zoneId] of Object.entries(EXPECTED)) { + const bone = all.get(id) + expect(bone, id).toBeDefined() + const tree = matchZoneFindings({ fr: bone!.fr, en: bone!.en }, zones) + expect(tree?.id, id).toBe(zoneId) + expect(scorePair(bone!.en, tree!.name_en), `${id} EN`).toBe(0) + expect(scorePair(bone!.fr, tree!.name_fr), `${id} FR`).toBe(0) + } + }) + + it('leaves the detail trigger unmatched (no FR/EN name)', () => { + const trigger = horse.get('zone-mpby55kd')! + expect(trigger.fr).toBe('') + expect(trigger.en).toBe('') + expect(trigger.opensDetail).toBe('head') + expect(trigger.category).toBe('articulations') + expect(matchZoneFindings({ fr: trigger.fr, en: trigger.en }, zones)).toBeUndefined() + }) + + it('leaves no catalog zone orphaned', () => { + const matched = new Set(Object.values(EXPECTED)) + expect(matched.size).toBe(26) + expect(zones.map((z) => z.id).filter((id) => !matched.has(id))).toEqual([]) + }) + + it('no normalized EN or FR zone name is a substring of another (substring rule unreachable today)', () => { + for (const lang of ['name_en', 'name_fr'] as const) { + const norms = zones.map((z) => normalizeLabel(z[lang])) + for (let i = 0; i < norms.length; i += 1) + for (let j = 0; j < norms.length; j += 1) + if (i !== j) expect(norms[i].includes(norms[j]), `${lang} ${zones[i].id} ⊃ ${zones[j].id}`).toBe(false) + } + }) + + it('KNOWN: two FR pairs are within the fuzzy tolerance and would collide if EN ever diverged', () => { + const d = (a: string, b: string) => levenshtein(normalizeLabel(a), normalizeLabel(b)) + const fetlock = d('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)') + const spine = d('Vertèbres sacrales', 'Vertèbres caudales') + expect(fetlock).toBe(5) + expect(spine).toBe(3) + expect(scorePair('Boulet ant. (métacarpo-phalangien)', 'Boulet post. (métatarso-phalangien)')).toBe(2 + 5) + expect(scorePair('Vertèbres sacrales', 'Vertèbres caudales')).toBe(2 + 3) + }) +}) + +describe('opens-detail ↔ species manifest', () => { + const species = getSpecies('equine')! + + it('every opens-detail value is a key of species.details, and every key has one trigger', () => { + const triggers = [...horse.values()].filter((b) => b.opensDetail).map((b) => b.opensDetail!) + expect(triggers).toEqual(['head']) + for (const key of triggers) expect(species.details[key]).toBeDefined() + expect(Object.keys(species.details)).toEqual(['head']) + }) + + it('the detail SVG carries no trigger of its own (one level of detail)', () => { + expect([...head.values()].some((b) => b.opensDetail)).toBe(false) + }) + + it('manifest paths point at the two committed files', () => { + expect(species.mainSvg).toBe('/species/equine/Horse.svg') + expect(species.details.head).toBe('/species/equine/Horse_head.svg') + }) +}) + +describe('spine helpers on the real Horse.svg', () => { + it('resolves each region to its zone-colonne polygon by label', () => { + expect(findSpineZoneId('C', horse)).toBe('zone-mpbx5hx2') + expect(findSpineZoneId('T', horse)).toBe('zone-mpbx2rpe') + expect(findSpineZoneId('L', horse)).toBe('zone-mpbx1rm9') + expect(findSpineZoneId('S', horse)).toBe('zone-mpbx0xnp') + expect(findSpineZoneId('Cd', horse)).toBe('zone-mpbx00jq') + }) + + it('KNOWN: hinge labels also resolve to a region, but hinges have no special so it is never used', () => { + expect(regionFromLabel(horse.get('point-mpbwyyc9')!.fr)).toBe('C') + expect(horse.get('point-mpbwyyc9')!.special).toBeUndefined() + }) + + it('spawns a lumbar zone from scratch and keeps a joint zone untouched', () => { + const next = syncSpineZones([{ boneId: 'point-mpbwtst0', side: 'left' }], [{ region: 'L', index: 2 }], horse) + expect(next).toEqual([ + { boneId: 'point-mpbwtst0', side: 'left' }, + { boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }, + ]) + }) + + it('collects vertebrae across spine zones with the clicked zone first', () => { + const zonesSel = [ + { boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C' as const, index: 3 }] }, + { boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L' as const, index: 1 }] }, + ] + expect(collectSpineVertebrae(zonesSel, horse, 'zone-mpbx1rm9')).toEqual([ + { region: 'L', index: 1 }, + { region: 'C', index: 3 }, + ]) + }) + + it('detail-sourced zones never count as spine zones', () => { + const next = syncSpineZones( + [{ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' }], + [{ region: 'C', index: 1 }], + horse, + ) + // passes through untouched, then a fresh cervical zone is spawned + expect(next[0]).toEqual({ boneId: 'zone-mpbx5hx2', detailSourceId: 'head' }) + expect(next[1]).toEqual({ boneId: 'zone-mpbx5hx2', vertebrae: [{ region: 'C', index: 1 }] }) + }) +})