feat(app): application on the canonical sheet — report v3 store with v2 draft migration, bundled SheetProvider (SHEET_BUNDLE), annotation layer rendered from the document, zone interaction service, pickers and cards on the sheet index, PDF v3 export with v2 archive import; legacy registry, matchers, editors and assets removed

This commit is contained in:
bchanot committed 2026-10-10 11:36:14 +02:00
1 parent 0a17e390cf
commit ce2ec26112
114 files changed
+3560 -14637

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
import {
REPORT_VERSION,
type Observation,
type Report,
} from '@faunosteo/domain'
import { loadSheetIndex } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
/** The bundled reference draft (vitest runs the sheet-bundle plugin in draft mode). */
export async function loadTestSheet(): Promise<SheetIndex> {
const index = await loadSheetIndex('equine')
if (!index) throw new Error('bundled sheet missing: run pnpm import:equine')
return index
}
export function emptyObservation(id = 'obs-1'): Observation {
return { id, zones: [], findings: [], freeTextFindings: [], comment: '' }
}
export function minimalReport(
sheet: SheetIndex,
patch: Partial<Report> = {},
): Report {
return {
version: REPORT_VERSION,
id: 'r1',
createdAt: '2026-10-10T10:00:00Z',
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
sheet: sheet.sheet.ref,
observations: [],
conclusion: '',
recommendations: '',
localAnnotations: [],
...patch,
}
}
-72
View File
@@ -1,72 +0,0 @@
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'
const HERE = dirname(fileURLToPath(import.meta.url))
const HORSE_PATH = resolve(HERE, '../../public/species/equine/Horse.svg')
const HEAD_PATH = resolve(HERE, '../../public/species/equine/Horse_head.svg')
function loadSvg(path: string): SVGSVGElement {
const raw = readFileSync(path, 'utf8')
const doc = new DOMParser().parseFromString(raw, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}
describe('real Horse.svg', () => {
const map = parseSvgBones(loadSvg(HORSE_PATH))
it('parses 18 unique annotations', () => {
expect(map.size).toBe(18)
})
it('contains 5 zone-colonne annotations (cervical / thoracic / lumbar / sacral / caudal)', () => {
const spine = [...map.values()].filter(
(b) => b.category === 'zone-colonne',
)
expect(spine.length).toBe(5)
})
it('contains exactly one opens-detail trigger pointing at the head SVG', () => {
const triggers = [...map.values()].filter((b) => b.opensDetail === 'head')
expect(triggers.length).toBe(1)
})
it('contains 9 articulations', () => {
const arts = [...map.values()].filter(
(b) => b.category === 'articulations',
)
expect(arts.length).toBe(9)
})
it('contains 3 vertebral hinges', () => {
const ch = [...map.values()].filter(
(b) => b.category === 'charni-res-vert-brales',
)
expect(ch.length).toBe(3)
})
})
describe('real Horse_head.svg', () => {
const map = parseSvgBones(loadSvg(HEAD_PATH))
it('parses 9 unique annotations', () => {
expect(map.size).toBe(9)
})
it('contains 5 cadrans-du-cr-ne annotations', () => {
const cadrans = [...map.values()].filter(
(b) => b.category === 'cadrans-du-cr-ne',
)
expect(cadrans.length).toBe(5)
})
it('contains 2 articulations (ATM + SSB equivalents)', () => {
const arts = [...map.values()].filter(
(b) => b.category === 'articulations',
)
expect(arts.length).toBe(2)
})
})
@@ -1,99 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
parseSvgBones,
getBoneIdFromEvent,
} from '@/anatomy/svgConvention'
import { SvgConventionError } from '@/anatomy/types'
function svgFromString(s: string): SVGSVGElement {
const doc = new DOMParser().parseFromString(s, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}
const FIXTURE = `
<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="point-shoulder" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulations" />
<circle data-anno-id="point-shoulder" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulations" />
<polygon data-anno-id="zone-cervical" data-anno-name-fr="Vertèbres cervicales"
data-anno-name-en="Cervical Vertebrae" data-anno-category="zone-colonne"
data-anno-special="vertebral-precision" />
<polygon data-anno-id="zone-head" data-anno-category="os" data-anno-opens-detail="head" />
<polygon data-anno-id="zone-future" data-anno-name-fr="Catégorie inédite"
data-anno-category="something-new-the-parser-has-never-seen" />
<circle data-anno-id="point-knee" data-anno-name-fr="Genou" data-anno-name-en="Knee"
data-anno-category="articulations" data-anno-lateral="bilateral" />
</svg>`
describe('parseSvgBones', () => {
it('groups multiple elements sharing the same data-anno-id', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
const shoulder = map.get('point-shoulder')
expect(shoulder).toBeDefined()
expect(shoulder?.fr).toBe('Épaule')
expect(shoulder?.en).toBe('Shoulder')
expect(shoulder?.category).toBe('articulations')
expect(shoulder?.els.length).toBe(2)
})
it('captures opensDetail when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-head')?.opensDetail).toBe('head')
})
it('captures data-anno-special when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-cervical')?.special).toBe('vertebral-precision')
expect(map.get('point-shoulder')?.special).toBeUndefined()
})
it('allows annotations without data-anno-name-fr/en (trigger-only zones)', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
const trigger = map.get('zone-head')
expect(trigger?.fr).toBe('')
expect(trigger?.en).toBe('')
})
it('accepts any string as data-anno-category (no hardcoded enum)', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('zone-future')?.category).toBe(
'something-new-the-parser-has-never-seen',
)
})
it('captures data-anno-lateral when present', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-knee')?.lateral).toBe('bilateral')
})
it('leaves lateral undefined when attribute absent', () => {
const map = parseSvgBones(svgFromString(FIXTURE))
expect(map.get('point-shoulder')?.lateral).toBeUndefined()
})
})
describe('parseSvgBones validation', () => {
it('throws on missing data-anno-category', () => {
const bad = `<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="x" />
</svg>`
expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError)
})
it('throws on empty data-anno-id', () => {
const bad = `<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="" data-anno-category="anything" />
</svg>`
expect(() => parseSvgBones(svgFromString(bad))).toThrow(SvgConventionError)
})
})
describe('getBoneIdFromEvent', () => {
it('returns null when no anno in ancestry', () => {
const div = document.createElement('div')
const evt = new Event('click')
Object.defineProperty(evt, 'target', { value: div })
expect(getBoneIdFromEvent(evt)).toBeNull()
})
})
@@ -1,23 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { loadSvg } from '@/anatomy/svgLoader'
const SVG = '<svg xmlns="http://www.w3.org/2000/svg"><g data-anno-id="x"/></svg>'
describe('loadSvg', () => {
beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => ({
ok: true,
text: async () => SVG,
})) as unknown as typeof fetch)
})
it('returns an SVGSVGElement', async () => {
const root = await loadSvg('/whatever.svg')
expect(root.tagName.toLowerCase()).toBe('svg')
})
it('throws on non-ok response', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404, text: async () => '' })) as unknown as typeof fetch)
await expect(loadSvg('/missing.svg')).rejects.toThrow()
})
})
-169
View File
@@ -1,169 +0,0 @@
/**
* 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<string, RawZone>
}
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 <zone>-dysfunctions / <zone>-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<string, number>()
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<string, string[]>()
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])
})
})
@@ -1,293 +0,0 @@
/**
* 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<string, string> = {
'/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<Report, 'id' | 'createdAt' | 'version'>)
}
const zonesOf = (i = 0) => useReportStore.getState().report!.observations[i].zones
const activeIndex = () => useReportStore.getState().activeObservationIndex
async function mount() {
const utils = render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
// 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(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
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()
})
})
@@ -1,127 +0,0 @@
/**
* Characterisation (Step 1): dictionary keys the runtime builds dynamically
* (severity.<fr value>, vertebra.region.<code>, 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(
<MemoryRouter>
<NewReportRoute />
</MemoryRouter>,
)
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' })
})
@@ -1,146 +0,0 @@
/**
* 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<string, string>
en: Record<string, string>
}
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(/<script[^>]+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)
})
})
-250
View File
@@ -1,250 +0,0 @@
/**
* 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<string, string> = {
'/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 <FEFF004600610075006E006F007300740065006F002000730074006100740065002000760032>')
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')
})
})
@@ -1,115 +0,0 @@
/**
* 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')
})
})
@@ -1,222 +0,0 @@
/**
* 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<string, Bone> {
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<string, string> = {
'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 }] })
})
})
@@ -1,39 +1,110 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { beforeAll, describe, expect, it, vi, afterEach } from 'vitest'
import { cleanup, render, waitFor } from '@testing-library/react'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
import { buildViewSvg, parseDrawing, sanitizeSvg } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
vi.mock('@/anatomy/svgLoader', () => ({
loadSvg: vi.fn(async () => {
const doc = new DOMParser().parseFromString(
`<svg xmlns="http://www.w3.org/2000/svg">
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulation" class="bone osteo articulation hitbox bone-epaule" />
<circle data-anno-id="epaule" data-anno-name-fr="Épaule" data-anno-name-en="Shoulder"
data-anno-category="articulation" class="bone osteo articulation visible bone-epaule" />
</svg>`,
'image/svg+xml',
)
return doc.documentElement as unknown as SVGSVGElement
}),
}))
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
afterEach(cleanup)
beforeEach(() => vi.clearAllMocks())
describe('AnatomyCanvas', () => {
it('renders the loaded SVG inline', async () => {
render(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={() => {}} />)
await waitFor(() =>
expect(document.querySelector('[data-anno-id="epaule"]')).not.toBeNull(),
describe('buildViewSvg', () => {
it('frames the main view on the asset box and the head view on its crop of the same drawing', () => {
const main = buildViewSvg(sheet, 'main', new Map())
const head = buildViewSvg(sheet, 'head', new Map())
expect(main.getAttribute('viewBox')).toBe('0 0 2073.4 1629.4')
expect(head.getAttribute('viewBox')).toBe('60 100 500 380')
expect(main.querySelectorAll('path').length).toBe(
head.querySelectorAll('path').length,
)
expect(main.querySelectorAll('[data-layer="annotations"]')).toHaveLength(1)
expect(main.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(2)
expect(head.querySelectorAll('[data-anno-id="hip"]')).toHaveLength(0)
expect(head.querySelectorAll('[data-anno-id="atm"]')).toHaveLength(2)
expect(main.hasAttribute('width')).toBe(false)
})
it('calls onZoneClick with the clicked bone id', async () => {
const onZoneClick = vi.fn()
render(<AnatomyCanvas src="/x.svg" boneStates={new Map()} onZoneClick={onZoneClick} />)
await waitFor(() => screen.getByTestId('anatomy-canvas'))
;(document.querySelector('[data-anno-id="epaule"]') as Element).dispatchEvent(
new Event('click', { bubbles: true }),
it('applies states as data-state on the generated markers', () => {
const svg = buildViewSvg(sheet, 'main', new Map([['stifle', 'current']]))
const marked = Array.from(
svg.querySelectorAll('[data-state="current"]'),
).map((el) => el.getAttribute('data-anno-id'))
expect(marked).toEqual(['stifle', 'stifle'])
})
it('sanitises scripts, embedded documents and handlers out of an asset', () => {
const root = parseDrawing(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"><script>alert(1)</script><g onclick="x()"><a href="javascript:void(0)"><path d="M0 0"/></a></g><foreignObject/></svg>',
)
await waitFor(() => expect(onZoneClick).toHaveBeenCalledWith('epaule'))
sanitizeSvg(root)
expect(root.querySelector('script')).toBeNull()
expect(root.querySelector('foreignObject')).toBeNull()
expect(root.querySelector('g')!.hasAttribute('onclick')).toBe(false)
expect(root.querySelector('a')!.hasAttribute('href')).toBe(false)
expect(root.querySelector('path')).not.toBeNull()
expect(() => parseDrawing('<not svg')).toThrow()
})
})
describe('AnatomyCanvas', () => {
it('renders the view and delegates clicks on the generated markers to onZoneClick with the view id', async () => {
const onZoneClick = vi.fn()
const { container } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={onZoneClick}
/>,
)
await waitFor(() =>
expect(
container.querySelector('[data-anno-id="head-trigger"]'),
).not.toBeNull(),
)
const hip = container.querySelector('circle[data-anno-id="hip"]')!
hip.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledWith('hip', 'main')
container
.querySelector('path')!
.dispatchEvent(new Event('click', { bubbles: true }))
expect(onZoneClick).toHaveBeenCalledTimes(1)
})
it('restyles in place when the states change', async () => {
const { container, rerender } = render(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
await waitFor(() =>
expect(container.querySelector('[data-anno-id="hip"]')).not.toBeNull(),
)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map([['hip', 'current']])}
onZoneClick={() => undefined}
/>,
)
expect(
container.querySelectorAll('[data-anno-id="hip"][data-state="current"]'),
).toHaveLength(2)
rerender(
<AnatomyCanvas
index={sheet}
viewId="main"
states={new Map()}
onZoneClick={() => undefined}
/>,
)
expect(container.querySelectorAll('[data-state="current"]')).toHaveLength(0)
})
})
@@ -1,298 +1,112 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import {
beforeAll,
describe,
expect,
it,
vi,
afterEach,
beforeEach,
} from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Finding } from '@faunosteo/domain'
import FindingsTreePicker from '@/components/observation/FindingsTreePicker'
import type { ZoneFindings } from '@/domain/schema/findings'
import type { Finding } from '@/domain/schema/observation'
import { useLocaleStore } from '@/state/localeStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
beforeEach(() => {
// Navigator-detected default may land on EN in happy-dom; force FR so the
// FR-label assertions in this file remain stable regardless of the runner's
// navigator.language.
useLocaleStore.setState({ locale: 'fr' })
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
const TREE: ZoneFindings = {
id: 'sphenoid',
name_fr: 'Sphénoïde',
name_en: 'Sphenoid',
categories: [
{
id: 'dysfunctions',
name_fr: 'Dysfonctions',
name_en: 'Dysfunctions',
children: [
{
id: 'flexion',
name_fr: 'Flexion',
name_en: 'Flexion',
description_fr: 'Description test',
},
{
id: 'extension',
name_fr: 'Extension',
name_en: 'Extension',
requires_vet_referral: true,
},
],
},
],
}
describe('FindingsTreePicker', () => {
it('renders the zone name in the initial breadcrumb', () => {
describe('FindingsTreePicker on a sheet finding zone', () => {
it('drills down the hip zone and selects a leaf as a v3 finding with snapshots and side', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={() => {}}
/>,
)
expect(screen.getByText('Sphénoïde')).toBeInTheDocument()
})
it('drills into a category and shows leaves', async () => {
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={() => {}}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
expect(screen.getByLabelText('Flexion')).toBeInTheDocument()
expect(screen.getByLabelText('Extension')).toBeInTheDocument()
})
it('emits a Finding with snapshot labels on leaf select', async () => {
const onChange = vi.fn<(next: Finding[]) => void>()
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
zone={sheet.findingZone('hip')!}
side="left"
selected={[]}
onChange={onChange}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
await userEvent.click(screen.getByLabelText('Flexion'))
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange.mock.calls[0][0]).toEqual([
expect(screen.getByText('Hanche (coxo-fémorale)')).toBeInTheDocument()
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Dysfonctions ostéopathiques',
}),
)
await user.click(
screen.getByRole('button', {
name: 'Ouvrir Restrictions de mobilité articulaire',
}),
)
await user.click(
screen.getByRole('checkbox', { name: 'Restriction en flexion' }),
)
expect(onChange).toHaveBeenCalledWith([
{
zoneId: 'sphenoid',
path: ['dysfunctions', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
side: 'left',
},
])
})
it('flags vet-referral leaves with requiresVetReferral on selection', async () => {
const onChange = vi.fn<(next: Finding[]) => void>()
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={onChange}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
await userEvent.click(screen.getByLabelText('Extension'))
expect(onChange.mock.calls[0][0][0].requiresVetReferral).toBe(true)
})
it('deselects a previously selected leaf', async () => {
const onChange = vi.fn<(next: Finding[]) => void>()
it('shows descriptions in the active locale, the vet marker, counts, and unselects', async () => {
const user = userEvent.setup()
useLocaleStore.setState({ locale: 'en' })
const selected: Finding[] = [
{
zoneId: 'sphenoid',
path: ['dysfunctions', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'hypermobility'],
labelFrSnapshot: 'x',
labelEnSnapshot: 'x',
requiresVetReferral: true,
},
]
const onChange = vi.fn()
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
zone={sheet.findingZone('hip')!}
selected={selected}
onChange={onChange}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
await userEvent.click(screen.getByLabelText('Flexion'))
expect(screen.getByLabelText('1 finding selected')).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'Open Osteopathic dysfunctions' }),
)
await user.click(
screen.getByRole('button', {
name: 'Open Articular mobility restrictions',
}),
)
expect(
screen.getByText(/Perceived laxity may indicate a ligament injury/),
).toBeInTheDocument()
expect(
screen.getAllByLabelText('Refer to a veterinarian').length,
).toBeGreaterThan(0)
const box = screen.getByRole('checkbox', {
name: 'Hypermobility / perceived laxity',
})
expect(box).toBeChecked()
await user.click(box)
expect(onChange).toHaveBeenCalledWith([])
})
it('navigates back to parent via the Retour button', async () => {
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={() => {}}
/>,
await user.click(
screen.getByRole('button', { name: 'Back to previous level' }),
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
expect(screen.getByLabelText('Flexion')).toBeInTheDocument()
await userEvent.click(screen.getByLabelText('Retour au niveau précédent'))
expect(screen.getByLabelText('Ouvrir Dysfonctions')).toBeInTheDocument()
})
})
const DEEP_TREE: ZoneFindings = {
id: 'atm',
name_fr: 'ATM',
name_en: 'TMJ',
categories: [
{
id: 'dysf',
name_fr: 'Dysfonctions ostéopathiques de l\'ATM',
name_en: 'Osteopathic dysfunctions of the TMJ',
children: [
{
id: 'tensions',
name_fr: 'Tensions des muscles masticateurs',
name_en: 'Masticatory muscle tensions',
children: [
{
id: 'temporal',
name_fr: 'Tension du temporal',
name_en: 'Temporal tension',
},
{
id: 'pterygo',
name_fr: 'Tension des ptérygoïdiens',
name_en: 'Pterygoid tension',
},
{
id: 'masseter',
name_fr: 'Tension des masséters',
name_en: 'Masseter tension',
},
],
},
{
id: 'capsule',
name_fr: 'Dysfonction capsulaire',
name_en: 'Capsular dysfunction',
children: [
{ id: 'cap-ant', name_fr: 'Antérieure', name_en: 'Anterior' },
{ id: 'cap-post', name_fr: 'Postérieure', name_en: 'Posterior' },
],
},
],
},
],
}
describe('FindingsTreePicker selection counts on intermediate nodes', () => {
const selected: Finding[] = [
{
zoneId: 'atm',
path: ['dysf', 'tensions', 'temporal'],
labelFrSnapshot: 'Tension du temporal',
labelEnSnapshot: 'Temporal tension',
},
{
zoneId: 'atm',
path: ['dysf', 'tensions', 'pterygo'],
labelFrSnapshot: 'Tension des ptérygoïdiens',
labelEnSnapshot: 'Pterygoid tension',
},
]
it('shows a count badge of 2 on the top-level category when two descendant leaves are selected', () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
// Root view: only the top-level "Dysfonctions..." category is visible.
expect(
screen.getByLabelText('2 constats sélectionnés'),
screen.getByRole('button', {
name: 'Open Articular mobility restrictions',
}),
).toBeInTheDocument()
})
it('shows a count badge of 2 on the sub-category one level deeper', async () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
await userEvent.click(
screen.getByLabelText('Ouvrir Dysfonctions ostéopathiques de l\'ATM'),
)
// Now we see "Tensions des muscles masticateurs" (2 leaves selected)
// and "Dysfonction capsulaire" (0 leaves selected — no badge).
expect(
screen.getByLabelText('2 constats sélectionnés'),
).toBeInTheDocument()
})
it('does not show a badge for siblings without selected descendants', async () => {
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={selected}
onChange={() => {}}
/>,
)
await userEvent.click(
screen.getByLabelText('Ouvrir Dysfonctions ostéopathiques de l\'ATM'),
)
// Capsular dysfunction has no selections — the button should not carry a badge label.
const capsular = screen.getByLabelText('Ouvrir Dysfonction capsulaire')
expect(capsular.textContent ?? '').not.toMatch(/\d/)
})
it('shows a singular badge label for exactly one selection', () => {
const oneSelected: Finding[] = [selected[0]]
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={oneSelected}
onChange={() => {}}
/>,
)
expect(
screen.getByLabelText('1 constat sélectionné'),
).toBeInTheDocument()
})
it('ignores selections from other zones when counting', () => {
const cross: Finding[] = [
{
zoneId: 'sphenoid',
path: ['dysf', 'tensions', 'temporal'],
labelFrSnapshot: 'Tension du temporal',
labelEnSnapshot: 'Temporal tension',
},
]
render(
<FindingsTreePicker
zoneId="atm"
tree={DEEP_TREE}
selected={cross}
onChange={() => {}}
/>,
)
// No badge should appear on the ATM tree — the lone selected finding
// belongs to a different zone.
expect(
screen.queryByLabelText(/constat sélectionné/),
).not.toBeInTheDocument()
})
})
@@ -11,8 +11,14 @@ beforeEach(() => {
describe('LanguageSwitcher', () => {
it('reflects the active locale via aria-pressed', () => {
render(<LanguageSwitcher />)
expect(screen.getByRole('button', { name: /français/i })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByRole('button', { name: /english/i })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('button', { name: /français/i })).toHaveAttribute(
'aria-pressed',
'true',
)
expect(screen.getByRole('button', { name: /english/i })).toHaveAttribute(
'aria-pressed',
'false',
)
})
it('clicking EN updates the store', async () => {
@@ -1,104 +1,87 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import {
beforeAll,
describe,
expect,
it,
vi,
afterEach,
beforeEach,
} from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import VertebraPicker from '@/components/observation/VertebraPicker'
import { regionFromLabel } from '@/lib/spineZones'
import { EQUINE_VERTEBRAL_FORMULA } from '@/domain/species/equine/vertebrae'
import { useLocaleStore } from '@/state/localeStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
describe('VertebraPicker', () => {
it('renders region tabs based on the formula', () => {
render(
<VertebraPicker
open
onClose={() => {}}
onConfirm={() => {}}
initial={[]}
formula={EQUINE_VERTEBRAL_FORMULA}
title="Vertèbres cervicales"
/>,
)
expect(screen.getByRole('tab', { name: /Cervicales/ })).toBeInTheDocument()
expect(screen.getByRole('tab', { name: /Thoraciques/ })).toBeInTheDocument()
})
function mount(initialRegion?: string, onConfirm = vi.fn()) {
render(
<VertebraPicker
open
onClose={() => undefined}
onConfirm={onConfirm}
initial={[{ region: 'C', index: 3 }]}
regions={sheet.regions()}
title="Vertèbres"
initialRegion={initialRegion}
/>,
)
return onConfirm
}
it('toggles a chip and confirms', async () => {
const onConfirm = vi.fn()
render(
<VertebraPicker
open
onClose={() => {}}
onConfirm={onConfirm}
initial={[]}
formula={EQUINE_VERTEBRAL_FORMULA}
title="Vertèbres thoraciques"
/>,
)
await userEvent.click(screen.getByRole('tab', { name: /Thoraciques/ }))
await userEvent.click(screen.getByRole('button', { name: 'T12' }))
await userEvent.click(screen.getByRole('button', { name: 'Valider' }))
expect(onConfirm).toHaveBeenCalledWith([{ region: 'T', index: 12 }])
})
it('preselects the tab matching initialRegion', () => {
render(
<VertebraPicker
open
onClose={() => {}}
onConfirm={() => {}}
initial={[]}
formula={EQUINE_VERTEBRAL_FORMULA}
title="Vertèbres lombaires"
initialRegion="L"
/>,
)
expect(screen.getByRole('tab', { name: /Lombaires/ })).toHaveAttribute(
describe('VertebraPicker on the sheet regions', () => {
it('shows one tab per region of the sheet, named from the document, opening on the asked region', () => {
mount('L')
const tabs = screen.getAllByRole('tab').map((t) => t.textContent)
expect(tabs).toEqual([
'Cervicales',
'Thoraciques',
'Lombaires',
'Sacrales',
'Caudales',
])
expect(screen.getByRole('tab', { name: 'Lombaires' })).toHaveAttribute(
'aria-selected',
'true',
)
expect(screen.getByText('L6')).toBeInTheDocument()
expect(screen.queryByText('L7')).toBeNull()
})
it('opens on initialRegion even when other regions are pre-selected', () => {
render(
<VertebraPicker
open
onClose={() => {}}
onConfirm={() => {}}
initial={[{ region: 'S', index: 2 }]}
formula={EQUINE_VERTEBRAL_FORMULA}
title="Vertèbres cervicales"
initialRegion="C"
/>,
)
expect(screen.getByRole('tab', { name: /Cervicales/ })).toHaveAttribute(
'aria-selected',
'true',
it('shows the usual count and extends to the documented maximum (D6)', async () => {
const user = userEvent.setup()
mount('Cd')
expect(screen.getByText('Cd18')).toBeInTheDocument()
expect(screen.queryByText('Cd21')).toBeNull()
await user.click(
screen.getByRole('button', { name: "Afficher jusqu'à 21" }),
)
expect(screen.getByText('Cd21')).toBeInTheDocument()
expect(
screen.getByText(/Nombre usuel : 18 ; variation documentée : 15 à 21/),
).toBeInTheDocument()
await user.click(screen.getByRole('tab', { name: 'Cervicales' }))
expect(screen.queryByRole('button', { name: /Afficher jusqu/ })).toBeNull()
})
})
describe('regionFromLabel', () => {
it('matches FR roots (accent-insensitive)', () => {
expect(regionFromLabel('Vertèbres cervicales')).toBe('C')
expect(regionFromLabel('Vertèbres thoraciques')).toBe('T')
expect(regionFromLabel('Vertèbres lombaires')).toBe('L')
expect(regionFromLabel('Vertèbres sacrales')).toBe('S')
expect(regionFromLabel('Vertèbres caudales')).toBe('Cd')
})
it('matches EN roots', () => {
expect(regionFromLabel('Cervical Vertebrae')).toBe('C')
expect(regionFromLabel('Thoracic Vertebrae')).toBe('T')
expect(regionFromLabel('Lumbar Vertebrae')).toBe('L')
expect(regionFromLabel('Coccygeal Vertebrae')).toBe('Cd')
})
it('returns undefined when no root matches', () => {
expect(regionFromLabel('Épaule')).toBeUndefined()
expect(regionFromLabel('')).toBeUndefined()
it('toggles vertebrae and confirms the selection across regions', async () => {
const user = userEvent.setup()
const onConfirm = mount('C')
await user.click(screen.getByText('C5'))
await user.click(screen.getByRole('tab', { name: 'Thoraciques' }))
await user.click(screen.getByText('T2'))
await user.click(screen.getByRole('button', { name: 'Valider' }))
expect(onConfirm).toHaveBeenCalledWith([
{ region: 'C', index: 3 },
{ region: 'C', index: 5 },
{ region: 'T', index: 2 },
])
})
})
-120
View File
@@ -1,120 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
findSpineZoneId,
collectSpineVertebrae,
syncSpineZones,
} from '@/lib/spineZones'
import type { Bone } from '@/anatomy/types'
import type { ObservationZone, Vertebra } from '@/domain/schema/observation'
function spine(id: string, fr: string, en: string): Bone {
return { id, fr, en, category: 'zone-colonne', special: 'vertebral-precision', els: [] }
}
const BONES = new Map<string, Bone>([
['z-c', spine('z-c', 'Vertèbres cervicales', 'Cervical Vertebrae')],
['z-t', spine('z-t', 'Vertèbres thoraciques', 'Thoracic Vertebrae')],
['z-l', spine('z-l', 'Vertèbres lombaires', 'Lumbar Vertebrae')],
['z-s', spine('z-s', 'Vertèbres sacrales', 'Sacral Vertebrae')],
['z-cd', spine('z-cd', 'Vertèbres caudales', 'Coccygeal Vertebrae')],
['z-shoulder', { id: 'z-shoulder', fr: 'Épaule', en: 'Shoulder', category: 'zone', els: [] }],
])
const v = (region: Vertebra['region'], index: number): Vertebra => ({ region, index })
describe('findSpineZoneId', () => {
it('maps each region to its spine zone', () => {
expect(findSpineZoneId('C', BONES)).toBe('z-c')
expect(findSpineZoneId('T', BONES)).toBe('z-t')
expect(findSpineZoneId('L', BONES)).toBe('z-l')
expect(findSpineZoneId('S', BONES)).toBe('z-s')
expect(findSpineZoneId('Cd', BONES)).toBe('z-cd')
})
it('returns undefined when no spine zone exists for a region', () => {
const only = new Map([['z-l', BONES.get('z-l')!]])
expect(findSpineZoneId('C', only)).toBeUndefined()
})
})
describe('collectSpineVertebrae', () => {
it('unions vertebrae across all spine zones', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-l', vertebrae: [v('L', 1), v('L', 2)] },
{ boneId: 'z-c', vertebrae: [v('C', 3)] },
]
expect(collectSpineVertebrae(zones, BONES)).toEqual([v('L', 1), v('L', 2), v('C', 3)])
})
it('lists the priority zone vertebrae first', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-c', vertebrae: [v('C', 3)] },
{ boneId: 'z-l', vertebrae: [v('L', 1)] },
]
expect(collectSpineVertebrae(zones, BONES, 'z-l')).toEqual([v('L', 1), v('C', 3)])
})
it('ignores non-spine zones and dedups', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-shoulder' },
{ boneId: 'z-l', vertebrae: [v('L', 1), v('L', 1)] },
]
expect(collectSpineVertebrae(zones, BONES)).toEqual([v('L', 1)])
})
})
describe('syncSpineZones', () => {
it('keeps same-region vertebrae on the existing zone', () => {
const zones: ObservationZone[] = [{ boneId: 'z-l' }]
const next = syncSpineZones(zones, [v('L', 1), v('L', 2)], BONES)
expect(next).toEqual([{ boneId: 'z-l', vertebrae: [v('L', 1), v('L', 2)] }])
})
it('spawns a new zone for a newly picked region', () => {
const zones: ObservationZone[] = [{ boneId: 'z-l' }]
const next = syncSpineZones(zones, [v('L', 1), v('C', 3)], BONES)
expect(next).toHaveLength(2)
expect(next[0]).toEqual({ boneId: 'z-l', vertebrae: [v('L', 1)] })
expect(next[1]).toEqual({ boneId: 'z-c', vertebrae: [v('C', 3)] })
})
it('replaces a region authoritatively (deselection sticks)', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-l', vertebrae: [v('L', 1), v('L', 2)] },
{ boneId: 'z-c', vertebrae: [v('C', 2), v('C', 3)] },
]
const next = syncSpineZones(zones, [v('L', 1), v('C', 3)], BONES)
expect(next).toHaveLength(2)
expect(next[0].vertebrae).toEqual([v('L', 1)])
expect(next[1].vertebrae).toEqual([v('C', 3)])
})
it('prunes a spine zone whose region dropped to zero', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-l', vertebrae: [v('L', 1)] },
{ boneId: 'z-c', vertebrae: [v('C', 1)] },
]
const next = syncSpineZones(zones, [v('C', 1)], BONES)
expect(next).toEqual([{ boneId: 'z-c', vertebrae: [v('C', 1)] }])
})
it('preserves non-spine zones untouched', () => {
const zones: ObservationZone[] = [
{ boneId: 'z-shoulder' },
{ boneId: 'z-l', vertebrae: [v('L', 1)] },
]
const next = syncSpineZones(zones, [v('L', 2)], BONES)
expect(next).toEqual([
{ boneId: 'z-shoulder' },
{ boneId: 'z-l', vertebrae: [v('L', 2)] },
])
})
it('drops vertebrae of a region with no spine zone in the SVG', () => {
const noCervical = new Map(BONES)
noCervical.delete('z-c')
const zones: ObservationZone[] = [{ boneId: 'z-l', vertebrae: [v('L', 1)] }]
const next = syncSpineZones(zones, [v('L', 1), v('C', 2)], noCervical)
expect(next).toEqual([{ boneId: 'z-l', vertebrae: [v('L', 1)] }])
})
})
-154
View File
@@ -1,154 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
normalizeLabel,
levenshtein,
scorePair,
matchZoneFindings,
} from '@/lib/zoneMatch'
import type { ZoneFindings } from '@/domain/schema/findings'
const ZONES: ZoneFindings[] = [
{
id: 'sphenoid',
name_fr: 'Sphénoïde',
name_en: 'Sphenoid',
categories: [],
},
{
id: 'ssb',
name_fr: 'Synchondrose Sphéno-Basilaire (SSB)',
name_en: 'Spheno-Basilar Synchondrosis (SBS)',
categories: [],
},
{
id: 'atm',
name_fr: 'Articulation Temporo-Mandibulaire (ATM)',
name_en: 'Temporomandibular Joint (TMJ)',
categories: [],
},
]
describe('normalizeLabel', () => {
it('lowercases, strips accents and non-alphanumerics', () => {
expect(normalizeLabel('Sphénoïde')).toBe('sphenoide')
})
it('strips parens and whitespace', () => {
expect(normalizeLabel('Articulation Temporo-Mandibulaire (ATM)')).toBe(
'articulationtemporomandibulaireatm',
)
})
it('keeps short bare labels intact', () => {
expect(normalizeLabel('(ATM)')).toBe('atm')
})
it('returns empty string for nullish inputs', () => {
expect(normalizeLabel(undefined)).toBe('')
expect(normalizeLabel(null)).toBe('')
expect(normalizeLabel('')).toBe('')
})
})
describe('levenshtein', () => {
it('returns 0 for identical strings', () => {
expect(levenshtein('abc', 'abc')).toBe(0)
})
it('handles classic textbook case', () => {
expect(levenshtein('kitten', 'sitting')).toBe(3)
})
it('returns length when one string is empty', () => {
expect(levenshtein('', 'abc')).toBe(3)
expect(levenshtein('abc', '')).toBe(3)
})
it('costs 1 per single-char typo', () => {
expect(levenshtein('sphenoide', 'sphenoid')).toBe(1)
expect(levenshtein('shenoide', 'sphenoide')).toBe(1)
})
})
describe('scorePair', () => {
it('scores exact normalized matches at 0', () => {
expect(scorePair('Sphenoid', 'Sphénoïde')).toBeGreaterThan(-1)
expect(scorePair('Sphenoid', 'sphenoid')).toBe(0)
})
it('scores substring matches at 1', () => {
expect(scorePair('(ATM)', 'Articulation Temporo-Mandibulaire (ATM)')).toBe(1)
})
it('routes a substring hit ("sphenoide" contains "sphenoid") to score 1', () => {
expect(scorePair('sphenoide', 'sphenoid')).toBe(1)
})
it('routes a pure-edit typo to Levenshtein scoring (2+d)', () => {
expect(scorePair('shenoide', 'sphenoid')).toBeGreaterThanOrEqual(2)
expect(scorePair('shenoide', 'sphenoid')).toBeLessThanOrEqual(5)
})
it('returns infinity for unrelated strings', () => {
expect(scorePair('Sphenoid', 'Synchondrose Sphéno-Basilaire (SSB)')).toBe(
Number.POSITIVE_INFINITY,
)
})
it('rejects empty inputs', () => {
expect(scorePair('', 'Sphenoid')).toBe(Number.POSITIVE_INFINITY)
expect(scorePair('Sphenoid', '')).toBe(Number.POSITIVE_INFINITY)
})
})
describe('matchZoneFindings', () => {
it('matches the SVG Sphenoid bone to the sphenoid zone via EN exact', () => {
const z = matchZoneFindings({ fr: 'Sphénoïde', en: 'Sphenoid' }, ZONES)
expect(z?.id).toBe('sphenoid')
})
it('matches the SVG SSB bone to the ssb zone via EN exact', () => {
const z = matchZoneFindings(
{ fr: 'Synchondrose Sphéno-Basilaire (SSB)', en: 'Spheno-Basilar Synchondrosis (SBS)' },
ZONES,
)
expect(z?.id).toBe('ssb')
})
it('matches the SVG ATM bone to the atm zone', () => {
const z = matchZoneFindings(
{ fr: 'Articulation Temporo-Mandibulaire (ATM)', en: 'Temporomandibular Joint (TMJ)' },
ZONES,
)
expect(z?.id).toBe('atm')
})
it('matches via FR-only labels when EN is empty', () => {
const z = matchZoneFindings({ fr: 'Sphénoïde', en: '' }, ZONES)
expect(z?.id).toBe('sphenoid')
})
it('matches abbreviation typed alone via substring', () => {
const z = matchZoneFindings({ fr: '(ATM)', en: '' }, ZONES)
expect(z?.id).toBe('atm')
})
it('tolerates small typos via Levenshtein', () => {
expect(matchZoneFindings({ fr: '', en: 'sphenoide' }, ZONES)?.id).toBe('sphenoid')
expect(matchZoneFindings({ fr: '', en: 'shenoide' }, ZONES)?.id).toBe('sphenoid')
expect(matchZoneFindings({ fr: '', en: 'sphenoi' }, ZONES)?.id).toBe('sphenoid')
})
it('returns undefined for clearly unrelated zones', () => {
expect(matchZoneFindings({ fr: 'Hanche (coxo-fémorale)', en: 'Hip joint' }, ZONES)).toBeUndefined()
expect(matchZoneFindings({ fr: 'hyoïde', en: 'Hyoid' }, ZONES)).toBeUndefined()
})
it('does not collapse Sphenoid into the SSB zone', () => {
expect(matchZoneFindings({ fr: 'Sphénoïde', en: 'Sphenoid' }, ZONES)?.id).toBe('sphenoid')
})
it('returns undefined when the catalog is empty', () => {
expect(matchZoneFindings({ fr: 'Sphénoïde', en: 'Sphenoid' }, [])).toBeUndefined()
})
})
@@ -10,7 +10,9 @@ async function deflate(data: Uint8Array): Promise<Uint8Array> {
describe('inflateFlate decompression cap', () => {
it('inflates a normal-size payload', async () => {
const payload = new TextEncoder().encode(JSON.stringify({ version: 2, hello: 'world' }))
const payload = new TextEncoder().encode(
JSON.stringify({ version: 2, hello: 'world' }),
)
const out = await inflateFlate(await deflate(payload))
expect(out).not.toBeNull()
expect(new TextDecoder().decode(out!)).toContain('hello')
+20 -21
View File
@@ -1,33 +1,30 @@
import { describe, it, expect } from 'vitest'
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { attachReportJson, extractReportJson } from '@/pdf/attachment'
import type { Report } from '@/domain/schema/report'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const report: Report = {
version: 2,
id: 'r1',
createdAt: '2026-05-18T10:00:00Z',
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: 'tout va bien',
recommendations: 'continuer',
}
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('PDF attachment roundtrip', () => {
it('attaches and extracts the report JSON', async () => {
it('attaches and extracts the v3 report JSON', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await attachReportJson(doc, report)
await attachReportJson(
doc,
minimalReport(sheet, { conclusion: 'tout va bien' }),
)
const bytes = await doc.save()
const reopened = await PDFDocument.load(bytes)
const out = await extractReportJson(reopened)
expect(out.conclusion).toBe('tout va bien')
expect(out.animal.name).toBe('Mistral')
expect(out.version).toBe(2)
const out = await extractReportJson(reopened, sheet.sheet.migrationMap)
expect(out.report.conclusion).toBe('tout va bien')
expect(out.report.animal.name).toBe('Mistral')
expect(out.report.version).toBe(3)
expect(out.migrated).toBe(false)
})
it('throws on PDFs without the attachment', async () => {
@@ -35,6 +32,8 @@ describe('PDF attachment roundtrip', () => {
doc.addPage()
const bytes = await doc.save()
const reopened = await PDFDocument.load(bytes)
await expect(extractReportJson(reopened)).rejects.toThrow()
await expect(
extractReportJson(reopened, sheet.sheet.migrationMap),
).rejects.toThrow()
})
})
+302 -102
View File
@@ -1,112 +1,312 @@
import { describe, it, expect, vi } from 'vitest'
import { AFRelationship, PDFDocument } from 'pdf-lib'
/**
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the v3 pipeline on
* the bundled sheet (drawn strings from the document, attachment v3,
* roundtrip FR/EN) and the import of the frozen v2 archive PDFs, migrated
* without silent loss.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterAll,
} from 'vitest'
import { PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation } from '@faunosteo/domain'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { embedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: async () => new Uint8Array([137, 80, 78, 71]) }))
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => ONE_PX_PNG),
}))
const report: Report = {
version: 2,
id: 'r1',
createdAt: '2026-05-18T10:00:00Z',
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: 'ok',
recommendations: '',
const HERE = dirname(fileURLToPath(import.meta.url))
const fixture = (name: string) =>
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
let sheet: SheetIndex
let drawn: string[] = []
const realFetch = globalThis.fetch
beforeAll(async () => {
sheet = await loadTestSheet()
globalThis.fetch = (async () =>
new Response('not found', { status: 404 })) as typeof fetch
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => {
globalThis.fetch = realFetch
})
beforeEach(() => {
drawn = []
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
this: PDFPage,
text: string,
) {
drawn.push(text)
} as never)
})
/** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */
function fullObservation(): Observation {
return {
id: 'obs-full',
zones: [
{ annotationId: 'c7-t1', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
{ annotationId: 'hip', viewId: 'main', side: 'right' },
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'atm', viewId: 'head' },
],
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'Fixation de la charnière',
labelEnSnapshot: 'Junction fixation',
},
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
side: 'left',
},
{
findingZoneId: 'atm',
path: ['atm-consultation-reasons', 'headshaking'],
labelFrSnapshot: 'Headshaking (secouement de tête)',
labelEnSnapshot: 'Headshaking',
requiresVetReferral: true,
unresolved: true,
},
],
freeTextFindings: ['Sensibilité au garrot'],
severity: 'moderate',
comment: 'note',
}
}
describe('PDF roundtrip', () => {
it('rejects unrelated PDF bytes with ImportError', async () => {
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 226, 227, 207, 211, 10])
await expect(importReportFromPdf(fake)).rejects.toThrow(ImportError)
})
it('roundtrips a minimal report (no observations)', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('roundtrips a report exported with locale=fr', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('roundtrips a report exported with locale=en', async () => {
const bytes = await exportReportToPdf(report, { locale: 'en' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('FR and EN exports both produce non-empty byte streams', async () => {
// pdf-lib subsets fonts (LRN-016), so plain-text grep over the bytes
// is unreliable. The imported JSON is the strongest invariant — the
// locale lives outside the Report, so both imports return the same
// payload while the static label snapshots differ inside the PDF.
const fr = await exportReportToPdf(report, { locale: 'fr' })
const en = await exportReportToPdf(report, { locale: 'en' })
expect(fr.byteLength).toBeGreaterThan(0)
expect(en.byteLength).toBeGreaterThan(0)
const frImported = await importReportFromPdf(fr)
const enImported = await importReportFromPdf(en)
expect(frImported.animal.name).toBe(enImported.animal.name)
expect(frImported.version).toBe(enImported.version)
})
it('vet-referral marker is encodable by the body font (regression: WinAnsi cannot encode U+26A0)', async () => {
// observationPage prefixes vet-referral leaves with a marker that
// is rendered using the WinAnsi-encoded StandardFonts.Helvetica.
// The previous "⚠ " marker (U+26A0) threw `WinAnsi cannot encode "⚠"`
// the moment the text-height estimator measured the leaf label.
// Guard against re-introducing a non-WinAnsi marker by exercising
// the same path: load the body font and measure a label that
// carries the prefix.
const doc = await PDFDocument.create()
const fonts = await embedFonts(doc)
expect(() =>
fonts.bodyRegular.widthOfTextAtSize('(!) Difficulté de déglutition', 10),
).not.toThrow()
})
it('rejects a legacy v1 PDF with a version-specific message', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const legacyPayload = {
version: 1,
id: 'legacy',
createdAt: '2025-12-01T00:00:00Z',
date: '2025-12-01',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
const bytes = new TextEncoder().encode(JSON.stringify(legacyPayload))
await doc.attach(bytes, 'osteo-report.json', {
mimeType: 'application/json',
description: 'Osteo Report state v1',
afRelationship: AFRelationship.Data,
describe('export on a full v3 report (FR)', () => {
it('produces one page per observation plus the conclusion, labels from the sheet', async () => {
const report = minimalReport(sheet, {
observations: [fullObservation()],
conclusion: 'ok',
})
const pdfBytes = await doc.save()
try {
await importReportFromPdf(pdfBytes)
throw new Error('expected rejection')
} catch (err) {
expect(err).toBeInstanceOf(ImportError)
const e = err as ImportError
expect(e.kind).toBe('incompatible_version')
expect(e.foundVersion).toBe(1)
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getPageCount()).toBe(2)
const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!)
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)')
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('(!) Headshaking (secouement de tête)')
expect(drawn).toContain(fr['severity.moderate']!)
expect(drawn).toContain(fr['pdf.view.general']!)
expect(drawn).toContain(
`${fr['pdf.view.detail_prefix']}TÊTE (VUE LATÉRALE GAUCHE)`,
)
})
it('attaches v3 and roundtrips in both locales', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportReportToPdf(report, sheet, { locale })
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(out.migrated).toBe(false)
expect(out.report).toEqual(report)
}
})
it('highlights the observation zones of a view and hides the other markers', () => {
const svg = highlightedViewSvg(sheet, 'main', fullObservation())
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
expect(svg).toContain('url(#osteo-halo)')
expect(svg).toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
const head = highlightedViewSvg(sheet, 'head', fullObservation())
expect(head).toContain('viewBox="60 100 500 380"')
expect(head).not.toContain('osteo-halo')
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await importReportFromPdf(
fixture('report-v2.full.pdf'),
sheet.sheet.migrationMap,
)
expect(out.migrated).toBe(true)
const { report } = out
expect(report.version).toBe(3)
expect(report.sheet).toEqual(sheet.sheet.ref)
expect(report.animal.name).toBe('Mistral')
const zones = report.observations.flatMap((o) => o.zones)
expect(
zones.map(
(z) => `${z.annotationId}@${z.viewId}${z.side ? ':' + z.side : ''}`,
),
).toEqual(
expect.arrayContaining([
'c7-t1@main',
'hip@main:left',
'hip@main:right',
'cervical@main',
'atm@head',
]),
)
expect(zones.every((z) => !z.unresolved)).toBe(true)
const findings = report.observations.flatMap((o) => o.findings)
const moved = findings.find((f) =>
f.path.includes('stumbling-proprioceptive'),
)!
expect(moved.path[0]).toBe('cervical-consultation-reasons')
expect(moved.unresolved).toBeUndefined()
const headshaking = findings.find((f) => f.path.includes('headshaking'))!
expect(headshaking.path).toEqual([
'atm-consultation-reasons',
'headshaking',
])
expect(findings.some((f) => f.unresolved)).toBe(false)
expect(out.unresolvedFindings).toBe(0)
expect(report.observations.map((o) => o.severity)).toEqual(
expect.arrayContaining(['moderate', 'severe']),
)
// Re-export and re-import: stable.
const again = await importReportFromPdf(
await exportReportToPdf(report, sheet, { locale: 'fr' }),
sheet.sheet.migrationMap,
)
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
})
it('keeps a v2 finding whose node was removed and a zone whose id is unknown, both flagged', async () => {
const v2 = {
...JSON.parse(
readFileSync(
resolve(HERE, '../fixtures/report-v2.minimal.json'),
'utf8',
),
),
observations: [
{
id: 'o-legacy',
zones: [
{ boneId: 'point-mpbyphay', detailSourceId: 'head' },
{ boneId: 'point-gone' },
],
findings: [
{
zoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
labelFrSnapshot: 'Suture sphéno-zygomatique',
labelEnSnapshot: 'Sphenozygomatic suture',
},
],
freeTextFindings: [],
comment: '',
severity: 'légère',
},
],
}
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify(v2)),
'osteo-report.json',
{ mimeType: 'application/json' },
)
const out = await importReportFromPdf(
await doc.save(),
sheet.sheet.migrationMap,
)
const [obs] = out.report.observations
expect(obs!.zones).toEqual([
expect.objectContaining({
annotationId: 'ssb',
viewId: 'head',
labelFrSnapshot: 'Synchondrose Sphéno-Basilaire (SSB)',
}),
expect.objectContaining({
annotationId: 'point-gone',
viewId: 'main',
unresolved: true,
}),
])
expect(obs!.findings[0]).toMatchObject({
findingZoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
unresolved: true,
labelFrSnapshot: 'Suture sphéno-zygomatique',
})
expect(obs!.severity).toBe('mild')
expect(out.unresolvedFindings).toBe(1)
expect(out.unresolvedZones).toBe(1)
// The migrated document is a valid v3 document: exporting it again keeps the flags.
const again = await importReportFromPdf(
await exportReportToPdf(out.report, sheet, { locale: 'en' }),
sheet.sheet.migrationMap,
)
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
})
it('migrates the minimal v2 report', async () => {
const out = await importReportFromPdf(
fixture('report-v2.minimal.pdf'),
sheet.sheet.migrationMap,
)
expect(out.report.version).toBe(3)
expect(out.report.observations).toEqual([])
expect(out.unresolvedFindings + out.unresolvedZones).toBe(0)
})
it('refuses unknown versions and unrelated PDFs with typed errors', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify({ version: 7 })),
'osteo-report.json',
{ mimeType: 'application/json' },
)
await expect(
importReportFromPdf(await doc.save(), sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'incompatible_version', foundVersion: 7 })
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(
importReportFromPdf(fake, sheet.sheet.migrationMap),
).rejects.toThrow(ImportError)
})
})
+9 -14
View File
@@ -39,12 +39,10 @@ describe('rasterizeSvg', () => {
canvas.toBlob = ((cb: BlobCallback) => {
cb(new Blob([PNG_BYTES], { type: 'image/png' }))
}) as HTMLCanvasElement['toBlob']
vi.spyOn(document, 'createElement').mockImplementation(
((tag: string) =>
tag === 'canvas'
? canvas
: ({}) as HTMLElement) as typeof document.createElement,
)
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
@@ -67,14 +65,11 @@ describe('rasterizeSvg', () => {
cb(null)
}) as HTMLCanvasElement['toBlob']
canvas.toDataURL = () =>
'data:image/png;base64,' +
Buffer.from(PNG_BYTES).toString('base64')
vi.spyOn(document, 'createElement').mockImplementation(
((tag: string) =>
tag === 'canvas'
? canvas
: ({}) as HTMLElement) as typeof document.createElement,
)
'data:image/png;base64,' + Buffer.from(PNG_BYTES).toString('base64')
vi.spyOn(document, 'createElement').mockImplementation(((tag: string) =>
tag === 'canvas'
? canvas
: ({} as HTMLElement)) as typeof document.createElement)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
@@ -1,96 +0,0 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { buildZoneLabels } from '@/pdf/export'
import type { Report } from '@/domain/schema/report'
const HERE = dirname(fileURLToPath(import.meta.url))
const HORSE_SVG = readFileSync(
resolve(HERE, '../../public/species/equine/Horse.svg'),
'utf8',
)
const HEAD_SVG = readFileSync(
resolve(HERE, '../../public/species/equine/Horse_head.svg'),
'utf8',
)
const realFetch = globalThis.fetch
let detailFetchShouldFail = false
beforeAll(() => {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = String(input)
if (url.endsWith('/Horse.svg')) {
return new Response(HORSE_SVG, {
status: 200,
headers: { 'content-type': 'image/svg+xml' },
})
}
if (url.endsWith('/Horse_head.svg')) {
if (detailFetchShouldFail) {
return new Response('not found', { status: 404 })
}
return new Response(HEAD_SVG, {
status: 200,
headers: { 'content-type': 'image/svg+xml' },
})
}
return new Response('not found', { status: 404 })
}) as typeof fetch
})
afterAll(() => {
globalThis.fetch = realFetch
})
const baseReport: Report = {
version: 2,
id: 'r1',
createdAt: '2026-05-20T10:00:00Z',
date: '2026-05-20',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
describe('buildZoneLabels', () => {
it('maps detail-popup boneIds to their FR + EN labels', async () => {
detailFetchShouldFail = false
const labels = await buildZoneLabels(baseReport)
const atm = labels.get('point-mpbyo7zq')
expect(atm?.fr).toBe('Articulation Temporo-Mandibulaire (ATM)')
expect(atm?.en).toBe('Temporomandibular Joint (TMJ)')
const sphenoid = labels.get('point-mpbymcln')
expect(sphenoid?.fr).toBe('Sphénoïde')
expect(sphenoid?.en).toBe('Sphenoid')
})
it('maps main-SVG boneIds to their FR + EN labels', async () => {
detailFetchShouldFail = false
const labels = await buildZoneLabels(baseReport)
expect(labels.size).toBeGreaterThan(0)
const pairs = Array.from(labels.values())
expect(pairs.some((p) => p.fr.includes('Vertèbres'))).toBe(true)
expect(pairs.some((p) => p.en.includes('Vertebrae'))).toBe(true)
})
it('keeps the main labels even when the detail SVG fetch fails', async () => {
detailFetchShouldFail = true
const labels = await buildZoneLabels(baseReport)
expect(labels.get('point-mpbymcln')).toBeUndefined()
const pairs = Array.from(labels.values())
expect(pairs.some((p) => p.fr.includes('Vertèbres'))).toBe(true)
})
it('returns an empty map for an unknown species', async () => {
const labels = await buildZoneLabels({
...baseReport,
animal: { speciesId: 'cat', name: 'X' },
})
expect(labels.size).toBe(0)
})
})
@@ -0,0 +1,198 @@
/**
* The editor route on the bundled sheet: the click chain end to end (DOM
* click on a generated marker → service → store), the detail view by its
* localized name, the sheet status line, the disclaimer once per session.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
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 EditorRoute from '@/app/routes/EditorRoute'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore
.getState()
.hydrateReport(
minimalReport(sheet, {
observations: [
{
id: 'o1',
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
const zonesOf = (i = 0) =>
useReportStore.getState().report!.observations[i]!.zones
async function mount() {
const utils = render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
await waitFor(() =>
expect(
document.querySelector('[data-anno-id="head-trigger"]'),
).not.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 }))
}
describe('EditorRoute on the canonical sheet', () => {
it('shows the sheet status line and toggles a plain zone on the active observation', async () => {
await mount()
expect(screen.getByTestId('sheet-status').textContent).toBe(
fr['sheet.status.draft'],
)
clickZone('c7-t1')
expect(zonesOf()).toEqual([
{
annotationId: 'c7-t1',
viewId: 'main',
labelFrSnapshot: 'Charnière C7-T1 (cervico-thoracique)',
labelEnSnapshot: 'C7-T1 junction (cervicothoracic)',
},
])
clickZone('c7-t1')
expect(zonesOf()).toEqual([])
})
it('a click with no active observation only activates the last one', async () => {
useReportStore.getState().setActiveObservation(-1)
await mount()
clickZone('c7-t1')
expect(useReportStore.getState().activeObservationIndex).toBe(0)
expect(zonesOf()).toEqual([])
})
it('a bilateral zone opens the side picker and adds the chosen side; both sides then clear on re-click', async () => {
const user = userEvent.setup()
await mount()
clickZone('hip')
const dialog = await screen.findByRole('dialog', {
name: 'Hanche (coxo-fémorale)',
})
await user.click(
within(dialog).getByRole('button', { name: fr['lateral.both'] }),
)
expect(zonesOf().map((z) => z.side)).toEqual(['left', 'right'])
clickZone('hip')
expect(zonesOf()).toEqual([])
})
it('a spine zone is added and opens the vertebra picker; confirming syncs vertebrae by region', async () => {
const user = userEvent.setup()
await mount()
clickZone('cervical')
const dialog = await screen.findByRole('dialog', {
name: /Vertèbres cervicales/,
})
expect(zonesOf()[0]!.annotationId).toBe('cervical')
expect(
within(dialog).getByRole('tab', { name: 'Cervicales' }),
).toHaveAttribute('aria-selected', 'true')
await user.click(within(dialog).getByText('C3'))
await user.click(within(dialog).getByRole('tab', { name: 'Lombaires' }))
await user.click(within(dialog).getByText('L2'))
await user.click(
within(dialog).getByRole('button', { name: fr['common.confirm'] }),
)
expect(zonesOf().map((z) => [z.annotationId, z.vertebrae])).toEqual([
['cervical', [{ region: 'C', index: 3 }]],
['lumbar', [{ region: 'L', index: 2 }]],
])
})
it('the head trigger opens the detail view by its name and its zones carry the head view id', async () => {
await mount()
clickZone('head-trigger')
const dialog = await screen.findByRole('dialog', {
name: 'Tête (vue latérale gauche)',
})
await waitFor(() =>
expect(dialog.querySelector('[data-anno-id="atm"]')).not.toBeNull(),
)
expect(dialog.querySelector('svg')!.getAttribute('viewBox')).toBe(
'60 100 500 380',
)
clickZone('atm', dialog)
expect(zonesOf()).toEqual([
expect.objectContaining({ annotationId: 'atm', viewId: 'head' }),
])
expect(
screen.getByRole('dialog', { name: 'Tête (vue latérale gauche)' }),
).toBeInTheDocument()
})
it('shows the scope disclaimer once per session, from the sheet', async () => {
sessionStorage.removeItem(DISCLAIMER_FLAG)
const user = userEvent.setup()
await mount()
const dialog = await screen.findByRole('dialog', {
name: fr['editor.disclaimer_title'],
})
expect(dialog.textContent).toContain('R. 243-6')
await user.click(
within(dialog).getByRole('button', { name: fr['common.understood'] }),
)
expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1')
})
it('restores the per-tab draft when the store is empty, migrating a v2 one', async () => {
const report = useReportStore.getState().report!
useReportStore.setState({ report: null })
sessionStorage.setItem(
'osteo:draft',
JSON.stringify({ ...report, version: 3 }),
)
await mount()
expect(useReportStore.getState().report?.id).toBe(report.id)
})
})
@@ -1,157 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
ObservationSchema,
VertebraSchema,
SeveritySchema,
FindingSchema,
LateralSideSchema,
ObservationZoneSchema,
} from '@/domain/schema/observation'
describe('SeveritySchema', () => {
it('accepts the three documented values', () => {
expect(SeveritySchema.parse('légère')).toBe('légère')
expect(SeveritySchema.parse('modérée')).toBe('modérée')
expect(SeveritySchema.parse('sévère')).toBe('sévère')
})
it('rejects unknown severity', () => {
expect(() => SeveritySchema.parse('critique')).toThrow()
})
})
describe('VertebraSchema', () => {
it('accepts a region+index pair', () => {
expect(VertebraSchema.parse({ region: 'T', index: 12 })).toEqual({
region: 'T',
index: 12,
})
})
it('rejects index 0', () => {
expect(() => VertebraSchema.parse({ region: 'C', index: 0 })).toThrow()
})
it('rejects unknown region', () => {
expect(() => VertebraSchema.parse({ region: 'X', index: 1 })).toThrow()
})
})
describe('FindingSchema', () => {
const base = {
zoneId: 'sphenoid',
path: ['sphenoid-dysfunctions', 'physiological', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
}
it('accepts a minimal finding', () => {
expect(() => FindingSchema.parse(base)).not.toThrow()
})
it('accepts the optional vet-referral flag', () => {
expect(() =>
FindingSchema.parse({ ...base, requiresVetReferral: true }),
).not.toThrow()
})
it('rejects an empty path', () => {
expect(() => FindingSchema.parse({ ...base, path: [] })).toThrow()
})
it('rejects an empty zoneId', () => {
expect(() => FindingSchema.parse({ ...base, zoneId: '' })).toThrow()
})
})
describe('LateralSideSchema', () => {
it('accepts left and right', () => {
expect(LateralSideSchema.parse('left')).toBe('left')
expect(LateralSideSchema.parse('right')).toBe('right')
})
it('rejects unknown side', () => {
expect(() => LateralSideSchema.parse('both')).toThrow()
expect(() => LateralSideSchema.parse('')).toThrow()
})
})
describe('ObservationZoneSchema with side', () => {
it('accepts a zone without side (unpaired)', () => {
expect(() => ObservationZoneSchema.parse({ boneId: 'sternum' })).not.toThrow()
})
it('accepts a zone with side left', () => {
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'left' })
expect(parsed.side).toBe('left')
})
it('accepts a zone with side right', () => {
const parsed = ObservationZoneSchema.parse({ boneId: 'knee', side: 'right' })
expect(parsed.side).toBe('right')
})
it('accepts two zones with same boneId but different sides', () => {
const obs = {
id: 'obs-1',
zones: [
{ boneId: 'knee', side: 'left' },
{ boneId: 'knee', side: 'right' },
],
findings: [],
freeTextFindings: [],
comment: '',
}
expect(() => ObservationSchema.parse(obs)).not.toThrow()
})
})
describe('ObservationSchema', () => {
const baseObs = {
id: 'obs-1',
zones: [{ boneId: 'epaule' }],
findings: [],
freeTextFindings: [],
comment: '',
}
it('accepts a minimal observation', () => {
expect(() => ObservationSchema.parse(baseObs)).not.toThrow()
})
it('accepts a spine-zone observation with precise vertebrae', () => {
const obs = {
...baseObs,
zones: [
{
boneId: 'thoracic-vertebrae-spine-zone',
vertebrae: [
{ region: 'T', index: 12 },
{ region: 'T', index: 13 },
],
},
],
}
expect(() => ObservationSchema.parse(obs)).not.toThrow()
})
it('accepts an observation with findings and free-text additions', () => {
const obs = {
...baseObs,
findings: [
{
zoneId: 'sphenoid',
path: ['sphenoid-dysfunctions', 'physiological', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
},
],
freeTextFindings: ['note libre'],
}
expect(() => ObservationSchema.parse(obs)).not.toThrow()
})
it('rejects empty id', () => {
expect(() => ObservationSchema.parse({ ...baseObs, id: '' })).toThrow()
})
})
-53
View File
@@ -1,53 +0,0 @@
import { describe, it, expect } from 'vitest'
import { ReportSchema } from '@/domain/schema/report'
const minimal = {
version: 2 as const,
id: 'r1',
createdAt: '2026-05-18T10:00:00Z',
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
describe('ReportSchema', () => {
it('accepts a minimal valid report', () => {
expect(() => ReportSchema.parse(minimal)).not.toThrow()
})
it('accepts nextAppointment kind=date', () => {
expect(() =>
ReportSchema.parse({
...minimal,
nextAppointment: { kind: 'date', date: '2026-06-08' },
}),
).not.toThrow()
})
it('accepts nextAppointment kind=period', () => {
expect(() =>
ReportSchema.parse({
...minimal,
nextAppointment: { kind: 'period', text: 'dans 3 semaines' },
}),
).not.toThrow()
})
it('rejects legacy v1 reports', () => {
expect(() => ReportSchema.parse({ ...minimal, version: 1 })).toThrow()
})
it('rejects unknown future versions', () => {
expect(() => ReportSchema.parse({ ...minimal, version: 3 })).toThrow()
})
it('rejects empty practitioner.name', () => {
expect(() =>
ReportSchema.parse({ ...minimal, practitioner: { name: '' } }),
).toThrow()
})
})
@@ -0,0 +1,214 @@
/**
* Replaces char.clickChain (Step 1) one-to-one: every branch of the legacy
* zone-click chain, now decided by the pure service on the bundled sheet's
* annotations, with outcomes in Report v3 shape.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import type { Annotation } from '@faunosteo/domain'
import type { SheetIndex } from '@/services/sheetIndex'
import {
addSides,
collectVertebrae,
decideZoneClick,
ensureZone,
refOf,
removeAllSides,
removeZoneAt,
sidesPresent,
syncVertebrae,
toggleZone,
} from '@/services/zoneInteraction'
import { emptyObservation, loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
const a = (id: string): Annotation => {
const annotation = sheet.annotation(id)
if (!annotation) throw new Error(`no annotation ${id}`)
return annotation
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('decideZoneClick', () => {
it('opens the detail view for the trigger, even without an active observation', () => {
expect(decideZoneClick(a('head-trigger'), undefined)).toEqual({
kind: 'open_view',
viewId: 'head',
})
expect(decideZoneClick(a('head-trigger'), emptyObservation())).toEqual({
kind: 'open_view',
viewId: 'head',
})
})
it('only activates a fallback observation when none is active', () => {
expect(decideZoneClick(a('c7-t1'), undefined)).toEqual({
kind: 'activate_fallback',
})
expect(decideZoneClick(undefined, emptyObservation())).toEqual({
kind: 'ignore',
})
})
it('always opens the vertebra picker on a spine zone', () => {
const obs = toggleZone(emptyObservation(), a('cervical'))
expect(decideZoneClick(a('cervical'), emptyObservation())).toEqual({
kind: 'open_vertebra_picker',
})
expect(decideZoneClick(a('cervical'), obs)).toEqual({
kind: 'open_vertebra_picker',
})
})
it('routes bilateral zones through the side picker, or clears both sides', () => {
const hip = a('hip')
expect(decideZoneClick(hip, emptyObservation())).toEqual({
kind: 'open_laterality_picker',
})
const left = addSides(emptyObservation(), hip, ['left'])
expect(decideZoneClick(hip, left)).toEqual({
kind: 'open_laterality_picker',
})
const both = addSides(left, hip, ['right'])
expect(decideZoneClick(hip, both)).toEqual({ kind: 'remove_both_sides' })
})
it('toggles plain zones; the ten bilateral annotations and the 18 others split as the sheet says', () => {
expect(decideZoneClick(a('c7-t1'), emptyObservation())).toEqual({
kind: 'toggle',
})
const observable = sheet.sheet.document.annotations.filter(
(x) => x.kind !== 'detail_trigger',
)
const decisions = observable.map(
(x) => decideZoneClick(x, emptyObservation()).kind,
)
expect(
decisions.filter((k) => k === 'open_laterality_picker'),
).toHaveLength(10)
expect(decisions.filter((k) => k === 'open_vertebra_picker')).toHaveLength(
5,
)
expect(decisions.filter((k) => k === 'toggle')).toHaveLength(12)
})
})
describe('reducers', () => {
it('toggleZone adds a zone with snapshots then removes it', () => {
const added = toggleZone(emptyObservation(), a('c7-t1'))
expect(added.zones).toEqual([
{
annotationId: 'c7-t1',
viewId: 'main',
labelFrSnapshot: 'Charnière C7-T1 (cervico-thoracique)',
labelEnSnapshot: 'C7-T1 junction (cervicothoracic)',
},
])
expect(toggleZone(added, a('c7-t1')).zones).toEqual([])
})
it('ensureZone keeps an existing zone and reports its index', () => {
const base = toggleZone(
toggleZone(emptyObservation(), a('c7-t1')),
a('cervical'),
)
expect(ensureZone(base, a('cervical')).index).toBe(1)
const { observation, index } = ensureZone(emptyObservation(), a('cervical'))
expect(index).toBe(0)
expect(observation.zones[0]!.annotationId).toBe('cervical')
})
it('addSides appends only the missing sides and never removes one', () => {
const hip = a('hip')
const left = addSides(emptyObservation(), hip, ['left'])
expect(sidesPresent(left, refOf(hip))).toEqual(['left'])
const same = addSides(left, hip, ['left'])
expect(same).toBe(left)
const both = addSides(left, hip, ['left', 'right'])
expect(both.zones.map((z) => z.side)).toEqual(['left', 'right'])
expect(removeAllSides(both, refOf(hip)).zones).toEqual([])
})
it('removeZoneAt removes one zone by index and keeps findings (BDR-019 wart kept, D5)', () => {
const obs = {
...toggleZone(emptyObservation(), a('c7-t1')),
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'F',
labelEnSnapshot: 'F',
},
],
}
const out = removeZoneAt(obs, 0)
expect(out.zones).toEqual([])
expect(out.findings).toHaveLength(1)
})
it('detail-view zones are distinct from main-view zones with the same id', () => {
const atm = a('atm')
const obs = toggleZone(emptyObservation(), atm)
expect(obs.zones[0]).toMatchObject({ annotationId: 'atm', viewId: 'head' })
expect(decideZoneClick(atm, obs)).toEqual({ kind: 'toggle' })
})
})
describe('vertebrae (BDR-019 sync, region codes from the sheet)', () => {
it('collects vertebrae across spine zones, the priority zone first', () => {
const obs = {
...emptyObservation(),
zones: [
{
annotationId: 'thoracic',
viewId: 'main',
vertebrae: [{ region: 'T', index: 2 }],
},
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'c7-t1', viewId: 'main' },
],
}
expect(collectVertebrae(obs, sheet, 1)).toEqual([
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
{ region: 'T', index: 2 },
])
})
it('replaces per region, prunes emptied zones and spawns zones for new regions', () => {
const base = ensureZone(emptyObservation(), a('cervical')).observation
const out = syncVertebrae(
base,
[
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
{ region: 'Cd', index: 20 },
],
sheet,
'main',
)
expect(out.zones.map((z) => z.annotationId)).toEqual(['lumbar', 'caudal'])
expect(out.zones[0]!.vertebrae).toEqual([
{ region: 'L', index: 3 },
{ region: 'L', index: 4 },
])
expect(out.zones[0]!.labelFrSnapshot).toBe('Vertèbres lombaires')
const cleared = syncVertebrae(out, [], sheet, 'main')
expect(cleared.zones).toEqual([])
})
it('keeps non-spine zones untouched and ignores unknown regions', () => {
const base = toggleZone(emptyObservation(), a('c7-t1'))
const out = syncVertebrae(base, [{ region: 'XX', index: 1 }], sheet, 'main')
expect(out.zones).toEqual(base.zones)
})
})
+113
View File
@@ -0,0 +1,113 @@
/**
* Replaces anatomy.horse / char.svgCatalogLink: the bundled reference sheet
* loads, validates, and indexes as the canonical document says.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import { bundledSheetProvider } from '@/sheets/provider'
import {
buildSheetIndex,
isObservable,
pickLabel,
type SheetIndex,
} from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('bundled sheet provider', () => {
it('returns the equine draft with its reference, assets and migration map', async () => {
const loaded = await bundledSheetProvider.getReferenceSheet('equine')
expect(loaded).not.toBeNull()
expect(loaded!.status).toBe('draft')
expect(loaded!.speciesId).toBe('equine')
expect(loaded!.ref.documentSha256).toMatch(/^[0-9a-f]{64}$/)
expect(loaded!.ref.versionId).toBeNull()
expect(loaded!.migrationMap.sheet).toEqual(loaded!.ref)
expect(Object.keys(loaded!.assets)).toHaveLength(1)
expect(loaded!.assets[loaded!.document.views[0]!.svg_asset_id!]).toContain(
'<svg',
)
expect(await bundledSheetProvider.getReferenceSheet('canine')).toBeNull()
})
})
describe('sheet index', () => {
it('exposes the views, 28 annotations (27 observable), 27 finding zones and 5 regions', () => {
const { document } = sheet.sheet
expect(sheet.mainView.id).toBe('main')
expect(sheet.view('head')).toMatchObject({
kind: 'detail',
parent_view_id: 'main',
svg_asset_id: null,
})
expect(document.annotations).toHaveLength(28)
expect(document.annotations.filter(isObservable)).toHaveLength(27)
expect(sheet.annotationsOfView('head')).toHaveLength(9)
expect(sheet.annotationsOfView('main')).toHaveLength(19)
expect(document.finding_zones).toHaveLength(27)
expect(sheet.regions().map((r) => r.code)).toEqual([
'C',
'T',
'L',
'S',
'Cd',
])
expect(sheet.region('Cd')).toMatchObject({
count: 18,
count_range: { min: 15, max: 21 },
})
})
it('links every observable annotation to an existing finding zone, the trigger to the head view', () => {
for (const a of sheet.sheet.document.annotations) {
if (!isObservable(a)) {
expect(a.opens_view_id).toBe('head')
continue
}
expect(a.finding_zone_id, a.id).not.toBeNull()
expect(sheet.findingZone(a.finding_zone_id!), a.id).toBeDefined()
}
expect(sheet.spineAnnotation('C', 'main')?.id).toBe('cervical')
expect(sheet.spineAnnotation('C', 'head')).toBeUndefined()
expect(sheet.isSpine('cervical')).toBe(true)
expect(sheet.isSpine('hip')).toBe(false)
expect(sheet.isSpine('head-trigger')).toBe(false)
})
it('resolves finding paths and reports absent ones', () => {
expect(
sheet.nodeAt('hip', [
'hip-dysfunctions',
'articular',
'restriction-flexion',
])?.name.fr,
).toBe('Restriction en flexion')
expect(sheet.nodeAt('hip', ['hip-dysfunctions'])?.name.fr).toBe(
'Dysfonctions ostéopathiques',
)
expect(
sheet.nodeAt('cervical', [
'cervical-observations',
'stumbling-proprioceptive',
]),
).toBeUndefined()
expect(sheet.nodeAt('nowhere', ['x'])).toBeUndefined()
expect(sheet.nodeAt('hip', [])).toBeUndefined()
})
it('names annotations and triggers in both locales', () => {
expect(pickLabel(sheet.name(sheet.annotation('hip')!), 'fr')).toBe(
'Hanche (coxo-fémorale)',
)
expect(pickLabel(sheet.name(sheet.annotation('hip')!), 'en')).toBe(
'Hip joint',
)
expect(pickLabel(sheet.name(sheet.annotation('head-trigger')!), 'en')).toBe(
'Head (left lateral view)',
)
expect(buildSheetIndex(sheet.sheet).mainView).toEqual(sheet.mainView)
})
})
+9 -14
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { ReportSchema } from '@/domain/schema/report'
import { ReportSchema } from '@faunosteo/domain'
import { generateId } from '@/lib/id'
import { todayIso, nowIso } from '@/lib/dates'
import { assert } from '@/lib/assert'
@@ -12,37 +12,32 @@ describe('skeleton smoke test', () => {
})
it('todayIso returns an ISO date string', () => {
const today = todayIso()
expect(today).toMatch(/^\d{4}-\d{2}-\d{2}$/)
expect(todayIso()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
})
it('nowIso returns an ISO timestamp string', () => {
const now = nowIso()
expect(now).toMatch(/^\d{4}-\d{2}-\d{2}T/)
expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T/)
})
it('ReportSchema parses a valid minimal report', () => {
const validReport = {
version: 2 as const,
it('ReportSchema parses a valid minimal v3 report', () => {
const result = ReportSchema.safeParse({
version: 3,
id: generateId(),
createdAt: nowIso(),
date: todayIso(),
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
sheet: { sheetId: 's', versionId: null, documentSha256: 'a'.repeat(64) },
observations: [],
conclusion: '',
recommendations: '',
}
const result = ReportSchema.safeParse(validReport)
})
expect(result.success).toBe(true)
})
it('ReportSchema rejects a report missing required fields', () => {
const invalid = { version: 1, id: '' }
const result = ReportSchema.safeParse(invalid)
expect(result.success).toBe(false)
expect(ReportSchema.safeParse({ version: 1, id: '' }).success).toBe(false)
})
it('assert passes when condition is truthy', () => {
@@ -1,52 +0,0 @@
import { describe, it, expect } from 'vitest'
import EQUINE_FINDINGS from '@/domain/species/equine/pathologies'
import {
SpeciesFindingsSchema,
type FindingNode,
} from '@/domain/schema/findings'
function walkLeaves(node: FindingNode, fn: (leaf: FindingNode) => void): void {
if (!node.children || node.children.length === 0) {
fn(node)
return
}
for (const child of node.children) walkLeaves(child, fn)
}
describe('equine findings tree', () => {
it('parses against SpeciesFindingsSchema', () => {
expect(() => SpeciesFindingsSchema.parse(EQUINE_FINDINGS)).not.toThrow()
})
it('species id matches the registry id', () => {
expect(EQUINE_FINDINGS.species.id).toBe('equine')
})
it('scope_disclaimer is non-empty', () => {
expect(EQUINE_FINDINGS.scope_disclaimer.length).toBeGreaterThan(0)
})
it('has at least one zone with at least one category with at least one leaf', () => {
const zoneIds = Object.keys(EQUINE_FINDINGS.zones)
expect(zoneIds.length).toBeGreaterThanOrEqual(1)
const someZone = EQUINE_FINDINGS.zones[zoneIds[0]]
expect(someZone.categories.length).toBeGreaterThanOrEqual(1)
let leafCount = 0
walkLeaves(someZone.categories[0], () => {
leafCount += 1
})
expect(leafCount).toBeGreaterThanOrEqual(1)
})
it('every leaf carries both FR and EN labels', () => {
const missing: string[] = []
for (const zone of Object.values(EQUINE_FINDINGS.zones)) {
for (const category of zone.categories) {
walkLeaves(category, (leaf) => {
if (!leaf.name_fr || !leaf.name_en) missing.push(leaf.id)
})
}
}
expect(missing).toEqual([])
})
})
@@ -1,24 +0,0 @@
import { describe, it, expect } from 'vitest'
import { getSpecies, getAllSpecies } from '@/domain/species/registry'
describe('species registry', () => {
it('returns the equine manifest', () => {
const eq = getSpecies('equine')
expect(eq).toBeDefined()
expect(eq?.labelFr).toBe('Cheval')
expect(eq?.labelEn).toBe('Horse')
expect(eq?.mainSvg).toBe('/species/equine/Horse.svg')
expect(eq?.details.head).toBe('/species/equine/Horse_head.svg')
expect(eq?.vertebralFormula).toEqual({ C: 7, T: 18, L: 6, S: 5, Cd: 18 })
})
it('returns undefined for unknown species', () => {
expect(getSpecies('martian')).toBeUndefined()
})
it('lists at least the equine species', () => {
const all = getAllSpecies()
expect(all.length).toBeGreaterThanOrEqual(1)
expect(all.find((s) => s.id === 'equine')).toBeDefined()
})
})
@@ -1,35 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useReportStore } from '@/state/reportStore'
const STORAGE_KEY = 'osteo:draft'
const draft = {
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
beforeEach(() => {
useReportStore.getState().reset()
sessionStorage.clear()
})
describe('reportStore sessionStorage mirror', () => {
it('mirrors the report on every change', () => {
useReportStore.getState().initReport(draft)
const raw = sessionStorage.getItem(STORAGE_KEY)
expect(raw).not.toBeNull()
const parsed = JSON.parse(raw!)
expect(parsed.practitioner.name).toBe('Dr. Dupont')
})
it('clears the mirror on reset', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().reset()
expect(sessionStorage.getItem(STORAGE_KEY)).toBeNull()
})
})
@@ -1,58 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
const draft = {
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
/** Fresh module instance = simulated page load. */
async function freshStore() {
const mod = await import('@/state/reportStore')
return mod.useReportStore
}
beforeEach(() => {
vi.resetModules()
sessionStorage.clear()
})
describe('reportStore draft restore', () => {
it('restores the sessionStorage draft on store init (page refresh)', async () => {
const store1 = await freshStore()
store1.getState().initReport(draft)
const saved = store1.getState().report!
vi.resetModules() // simulate refresh: new module, sessionStorage intact
const store2 = await freshStore()
expect(store2.getState().report).not.toBeNull()
expect(store2.getState().report!.id).toBe(saved.id)
expect(store2.getState().report!.animal.name).toBe('Mistral')
})
it('starts empty when the stored draft is invalid', async () => {
sessionStorage.setItem('osteo:draft', '{"version":999,"garbage":true}')
const store = await freshStore()
expect(store.getState().report).toBeNull()
})
it('starts empty when no draft exists', async () => {
const store = await freshStore()
expect(store.getState().report).toBeNull()
})
it('clears the draft after reset (no resurrection on next load)', async () => {
const store1 = await freshStore()
store1.getState().initReport(draft)
store1.getState().reset()
vi.resetModules()
const store2 = await freshStore()
expect(store2.getState().report).toBeNull()
})
})
@@ -1,56 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useReportStore } from '@/state/reportStore'
const draft = {
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
beforeEach(() => {
useReportStore.getState().reset()
})
describe('reportStore identity setters', () => {
it('setPractitioner replaces the practitioner block', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().setPractitioner({
name: 'Dr. Curie',
cabinet: 'Clinique du Pré',
contact: 'contact@example.test',
})
const p = useReportStore.getState().report!.practitioner
expect(p.name).toBe('Dr. Curie')
expect(p.cabinet).toBe('Clinique du Pré')
expect(p.contact).toBe('contact@example.test')
})
it('setAnimal replaces the animal block', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().setAnimal({
speciesId: 'equine',
name: 'Tempête',
breed: 'Pur-sang',
})
const a = useReportStore.getState().report!.animal
expect(a.name).toBe('Tempête')
expect(a.breed).toBe('Pur-sang')
})
it('setOwner replaces the owner block', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().setOwner({ name: 'Marie Petit' })
expect(useReportStore.getState().report!.owner.name).toBe('Marie Petit')
})
it('setters are no-ops when no report is loaded', () => {
useReportStore.getState().setPractitioner({ name: 'Ghost' })
useReportStore.getState().setAnimal({ speciesId: 'equine', name: 'Ghost' })
useReportStore.getState().setOwner({ name: 'Ghost' })
expect(useReportStore.getState().report).toBeNull()
})
})
+129 -94
View File
@@ -1,120 +1,155 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useReportStore } from '@/state/reportStore'
/**
* Replaces state.reportStore / state.reportStore.restore / .setters /
* state.draftMirror: the v3 store, its actions, the sessionStorage mirror
* and the migration of a v2 draft on restore.
*/
import { beforeAll, beforeEach, describe, expect, it } from 'vitest'
import {
createReportStore,
useReportStore,
emptyObservation,
} from '@/state/reportStore'
import { DRAFT_KEY, sessionStoragePersistence } from '@/state/persistence'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import fullV2 from '../fixtures/report-v2.full.json'
const draft = {
date: '2026-05-18',
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
sessionStorage.clear()
useReportStore.setState({ report: null, activeObservationIndex: 0 })
})
const draft = () => ({
date: '2026-10-10',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
beforeEach(() => {
useReportStore.getState().reset()
})
describe('reportStore.initReport', () => {
it('sets a report with version=2, id, and createdAt', () => {
useReportStore.getState().initReport(draft)
const r = useReportStore.getState().report!
expect(r.version).toBe(2)
expect(r.id.length).toBeGreaterThan(0)
expect(r.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/)
expect(r.practitioner.name).toBe('Dr. Dupont')
})
it('seeds a single empty observation when the draft has none', () => {
useReportStore.getState().initReport(draft)
const r = useReportStore.getState().report!
expect(r.observations.length).toBe(1)
expect(r.observations[0].zones).toEqual([])
expect(r.observations[0].comment).toBe('')
})
it('resets activeObservationIndex to 0', () => {
useReportStore.getState().initReport(draft)
describe('initReport', () => {
it('stamps version 3, id, createdAt, the sheet ref and one empty observation', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
const report = useReportStore.getState().report!
expect(report.version).toBe(3)
expect(report.id).toBeTruthy()
expect(report.createdAt).toMatch(/^\d{4}-/)
expect(report.sheet).toEqual(sheet.sheet.ref)
expect(report.observations).toHaveLength(1)
expect(report.localAnnotations).toEqual([])
expect(useReportStore.getState().activeObservationIndex).toBe(0)
})
})
describe('reportStore.reset', () => {
it('clears the report', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().reset()
describe('observation actions', () => {
it('adds, updates, moves and removes observations, keeping the active index sane', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.addObservation()
expect(useReportStore.getState().report!.observations).toHaveLength(2)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
const [first, second] = useReportStore.getState().report!.observations
s.updateObservation(1, { ...second!, comment: 'note' })
s.moveObservationUp(1)
expect(
useReportStore.getState().report!.observations.map((o) => o.id),
).toEqual([second!.id, first!.id])
s.moveObservationDown(0)
expect(
useReportStore.getState().report!.observations.map((o) => o.id),
).toEqual([first!.id, second!.id])
s.moveObservationUp(0)
s.moveObservationDown(1)
s.removeObservation(1)
expect(useReportStore.getState().report!.observations).toHaveLength(1)
expect(useReportStore.getState().activeObservationIndex).toBe(0)
s.setActiveObservation(-1)
expect(useReportStore.getState().activeObservationIndex).toBe(-1)
})
it('setters replace identity, conclusion and appointment; nextAppointment can be cleared', () => {
const s = useReportStore.getState()
s.initReport(draft(), sheet.sheet.ref)
s.setPractitioner({ name: 'Dr. X' })
s.setAnimal({ speciesId: 'equine', name: 'Y' })
s.setOwner({ name: 'Z' })
s.setConclusion('c')
s.setRecommendations('r')
s.setNextAppointment({ kind: 'date', date: '2026-11-01' })
const r = useReportStore.getState().report!
expect([
r.practitioner.name,
r.animal.name,
r.owner.name,
r.conclusion,
r.recommendations,
]).toEqual(['Dr. X', 'Y', 'Z', 'c', 'r'])
expect(r.nextAppointment).toEqual({ kind: 'date', date: '2026-11-01' })
s.setNextAppointment(undefined)
expect('nextAppointment' in useReportStore.getState().report!).toBe(false)
s.reset()
expect(useReportStore.getState().report).toBeNull()
})
it('every action is a no-op without a report', () => {
const s = useReportStore.getState()
s.addObservation()
s.updateObservation(0, emptyObservation())
s.setConclusion('x')
expect(useReportStore.getState().report).toBeNull()
})
})
describe('reportStore.addObservation', () => {
it('appends an empty observation and sets it active', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().addObservation()
const s = useReportStore.getState()
expect(s.report!.observations.length).toBe(2)
expect(s.activeObservationIndex).toBe(1)
describe('sessionStorage mirror and restore', () => {
it('mirrors every change under osteo:draft and removes it on reset', () => {
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
useReportStore.getState().reset()
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
})
})
describe('reportStore.updateObservation', () => {
it('replaces the observation at the given index', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().addObservation()
const next = {
...useReportStore.getState().report!.observations[0],
comment: 'patate',
}
useReportStore.getState().updateObservation(0, next)
expect(useReportStore.getState().report!.observations[0].comment).toBe('patate')
})
})
describe('reportStore.removeObservation', () => {
it('drops the observation at the given index', () => {
const store = useReportStore.getState()
store.initReport(draft) // seeds 1
store.addObservation()
store.addObservation()
store.removeObservation(0)
expect(useReportStore.getState().report!.observations.length).toBe(2)
})
it('restores a v3 draft, and migrates a v2 draft left by the previous version', () => {
const v3 = minimalReport(sheet, { conclusion: 'kept' })
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(v3))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
expect(useReportStore.getState().report?.conclusion).toBe('kept')
it('clamps activeObservationIndex within bounds', () => {
const store = useReportStore.getState()
store.initReport(draft) // seeds 1
store.addObservation()
store.addObservation() // total 3
store.setActiveObservation(2)
store.removeObservation(2)
expect(useReportStore.getState().activeObservationIndex).toBe(1)
useReportStore.setState({ report: null })
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(fullV2))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
const restored = useReportStore.getState().report!
expect(restored.version).toBe(3)
expect(
restored.observations.flatMap((o) => o.zones).map((z) => z.annotationId),
).toContain('hip')
expect(JSON.parse(sessionStorage.getItem(DRAFT_KEY)!).version).toBe(3)
})
})
describe('reportStore.move up/down', () => {
it('moveObservationUp swaps with previous', () => {
const s = useReportStore.getState()
s.initReport(draft)
s.addObservation()
s.addObservation()
const idA = useReportStore.getState().report!.observations[0].id
const idB = useReportStore.getState().report!.observations[1].id
s.moveObservationUp(1)
const after = useReportStore.getState().report!.observations
expect(after[0].id).toBe(idB)
expect(after[1].id).toBe(idA)
it('ignores an unreadable draft and does not replace an open report', () => {
sessionStorage.setItem(DRAFT_KEY, '{not json')
expect(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ version: 1 }))
expect(sessionStoragePersistence.load(sheet.sheet.migrationMap)).toBeNull()
useReportStore.getState().initReport(draft(), sheet.sheet.ref)
const before = useReportStore.getState().report
sessionStorage.setItem(DRAFT_KEY, JSON.stringify(minimalReport(sheet)))
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
expect(useReportStore.getState().report).toBe(before)
})
it('moveObservationDown swaps with next', () => {
const s = useReportStore.getState()
s.initReport(draft)
s.addObservation()
s.addObservation()
const idA = useReportStore.getState().report!.observations[0].id
const idB = useReportStore.getState().report!.observations[1].id
s.moveObservationDown(0)
const after = useReportStore.getState().report!.observations
expect(after[0].id).toBe(idB)
expect(after[1].id).toBe(idA)
it('createReportStore accepts another persistence adapter', () => {
const saved: unknown[] = []
const store = createReportStore({
load: () => null,
save: (r) => saved.push(r),
})
store.getState().initReport(draft(), sheet.sheet.ref)
expect(saved.at(-1)).toMatchObject({ version: 3 })
})
})