chore(workspace): move the app to apps/app under a pnpm workspace (step 2)

144 files moved with git mv (pure renames). Root package.json delegates
dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and
pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager,
root devDependency, engine-strict). Dockerfile builds @faunosteo/app on
node:24-alpine and copies apps/app/dist; nginx and runtime config
unchanged. CI workflow for Gitea Actions. packages/ reserved (README only).
Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan.
271/271 tests, typecheck, lint, build green from the root.
This commit is contained in:
bchanot committed 2026-10-08 21:51:13 +02:00
1 parent c8d48ab4cc
commit 8673475293
164 files changed
+348 -128

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
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)
})
})
@@ -0,0 +1,99 @@
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()
})
})
@@ -0,0 +1,23 @@
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
@@ -0,0 +1,169 @@
/**
* Characterisation (Step 1): the equine findings catalog as it exists today.
* Pins the facts of docs/faunosteo-audit/05-findings-editor.md §2.4 so that
* the future legacy importer (plan Step 4) can be checked against them, and
* so that any deliberate business correction shows up as a test change.
*
* Reads the files directly (no Zod) to count what is really on disk.
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { createHash } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { SpeciesFindingsSchema } from '@/domain/schema/findings'
const HERE = dirname(fileURLToPath(import.meta.url))
const SRC_PATH = resolve(HERE, '../../src/domain/species/equine/pathologies.json')
const PUBLIC_PATH = resolve(HERE, '../../public/species/equine/pathologies.json')
interface RawNode {
id: string
name_fr?: string
name_en?: string
description_fr?: string
description_en?: string
requires_vet_referral?: boolean
sources?: unknown[]
children?: RawNode[]
}
interface RawZone { id: string; name_fr: string; name_en: string; categories: RawNode[] }
interface RawCatalog {
schema_version: string
scope_disclaimer: string
species: { id: string; name_fr: string; name_en: string }
zones: Record<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])
})
})
@@ -0,0 +1,293 @@
/**
* Characterisation (Step 1): the zone-click chain of EditorRoute
* (onZoneClick → detail / fallback / spine / bilateral / toggle), the
* disclaimer-once-per-session rule, the zone removal and the pickers'
* integration with the store. Exercised through the rendered route on the
* real Horse.svg / Horse_head.svg, with loadSvg mocked to read the files.
*
* Limitation: the chain lives inside the route component (audit 13 §4, no
* unit seam). These tests go through the DOM; plan Step 5 extracts the
* chain into a service and will replace them with unit tests one-to-one.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor, within, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import EditorRoute from '@/app/routes/EditorRoute'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import minimal from '../fixtures/report-v2.minimal.json'
import type { Report } from '@/domain/schema/report'
const HERE = dirname(fileURLToPath(import.meta.url))
const FILES: Record<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()
})
})
@@ -0,0 +1,127 @@
/**
* 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' })
})
@@ -0,0 +1,146 @@
/**
* Characterisation (Step 1): public/pathology-editor.html, the standalone
* findings editor. Its JavaScript is extracted by text and evaluated so that
* the inline matcher, id generator, translations and species config are
* pinned without touching the file (BDR-020/021, LRN-026).
*
* Limitation: the DOM-editing behaviour (tree add/edit/delete, dirty flag,
* download) is not executed here; it is described in
* docs/faunosteo-audit/05-findings-editor.md §3.5 and will be re-specified
* as tests of the merged editor (plan Step 17).
*/
import { describe, it, expect } from 'vitest'
import { existsSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { matchZoneFindings, normalizeLabel, scorePair } from '@/lib/zoneMatch'
import FINDINGS from '@/domain/species/equine/pathologies'
import { fr } from '@/i18n/fr'
const HERE = dirname(fileURLToPath(import.meta.url))
const ROOT = resolve(HERE, '../..')
const HTML = readFileSync(resolve(ROOT, 'public/pathology-editor.html'), 'utf8')
function slice(from: string, to: string): string {
const a = HTML.indexOf(from)
const b = HTML.indexOf(to, a)
if (a < 0 || b < 0) throw new Error(`markers not found: ${from} … ${to}`)
return HTML.slice(a, b)
}
type Zone = { id: string; name_fr: string; name_en: string }
interface InlineApi {
normalizeLabel: (s: string) => string
scorePair: (a: string, b: string) => number
matchZone: (fr: string, en: string, zones: Zone[]) => Zone | null
generateId: (en: string, fr: string, existing: string[]) => string
}
const matcherSrc = slice('function normalizeLabel(s)', '// ── Node stats ──')
const inline = new Function(
`${matcherSrc}; return { normalizeLabel, scorePair, matchZone, generateId };`,
)() as InlineApi
const translationsSrc = slice('var TRANSLATIONS = ', '\n };') + '\n };'
const TRANSLATIONS = new Function(`${translationsSrc} return TRANSLATIONS;`)() as {
fr: Record<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
@@ -0,0 +1,250 @@
/**
* Characterisation (Step 1): the full PDF pipeline on the golden fixture
* (every zone kind, findings with vet flag and side, free text, severity,
* comment, conclusion, next appointment): page count, drawn text, attachment
* roundtrip, import error kinds, and the attachment fallback path.
*
* Text is captured by spying on PDFPage.drawText (pdf-lib has no text
* extraction). Rasterization is replaced by a 1×1 PNG: happy-dom has no
* canvas. SVG fetches are served from the committed files; logo fetches 404
* on purpose to pin the "PDF without logos" degradation.
*/
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest'
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import full from '../fixtures/report-v2.full.json'
import type { Report } from '@/domain/schema/report'
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: vi.fn(async () => ONE_PX_PNG) }))
const HERE = dirname(fileURLToPath(import.meta.url))
const FILES: Record<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')
})
})
@@ -0,0 +1,115 @@
/**
* Characterisation (Step 1): what the Report v2 schema accepts or rejects,
* what the browser persistence keeps, and the storage keys the SaaS
* migration must read (plan Step 14 one-time draft import).
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { ReportSchema } from '@/domain/schema/report'
import { ObservationSchema, VertebraSchema, SeveritySchema } from '@/domain/schema/observation'
import { readPersistedDraft, useReportStore } from '@/state/reportStore'
import { readCachedPractitioner, writeCachedPractitioner } from '@/state/practitionerCache'
import { useLocaleStore } from '@/state/localeStore'
import full from '../fixtures/report-v2.full.json'
import minimal from '../fixtures/report-v2.minimal.json'
import type { Report } from '@/domain/schema/report'
describe('Report v2 schema on the golden fixtures', () => {
it('accepts both fixtures unchanged', () => {
expect(ReportSchema.parse(full)).toEqual(full)
expect(ReportSchema.parse(minimal)).toEqual(minimal)
})
it('strips unknown keys silently (forward-compat fields are lost on reimport)', () => {
const parsed = ReportSchema.parse({ ...minimal, futureField: 1, animal: { ...minimal.animal, chip: 'x' } })
expect(parsed).toEqual(minimal)
})
it('rejects version 1 and 3, accepts only the literal 2', () => {
expect(ReportSchema.safeParse({ ...minimal, version: 1 }).success).toBe(false)
expect(ReportSchema.safeParse({ ...minimal, version: 3 }).success).toBe(false)
})
it('does not bound vertebra indexes by the species formula (C99 accepted)', () => {
expect(VertebraSchema.safeParse({ region: 'C', index: 99 }).success).toBe(true)
expect(VertebraSchema.safeParse({ region: 'X', index: 1 }).success).toBe(false)
expect(VertebraSchema.safeParse({ region: 'C', index: 0 }).success).toBe(false)
})
it('stores severities as French enum values', () => {
expect(SeveritySchema.options).toEqual(['légère', 'modérée', 'sévère'])
})
it('accepts findings whose zoneId matches no zone of the observation (orphans)', () => {
const obs = { ...full.observations[0], zones: [] }
expect(ObservationSchema.safeParse(obs).success).toBe(true)
})
it('accepts a speciesId that no manifest registers (checked only at render time)', () => {
expect(ReportSchema.safeParse({ ...minimal, animal: { speciesId: 'dragon', name: 'X' } }).success).toBe(true)
})
it('accepts two zones with the same boneId and different sides, and the same boneId from main and detail', () => {
const obs = {
...minimal,
observations: [
{
id: 'o',
zones: [
{ boneId: 'a', side: 'left' },
{ boneId: 'a', side: 'right' },
{ boneId: 'a', detailSourceId: 'head' },
],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}
expect(ReportSchema.safeParse(obs).success).toBe(true)
})
})
describe('browser persistence', () => {
beforeEach(() => {
sessionStorage.clear()
localStorage.clear()
useReportStore.setState({ report: null, activeObservationIndex: 0 })
})
it('mirrors the full fixture to sessionStorage["osteo:draft"] and restores it unchanged', () => {
useReportStore.getState().hydrateReport(full as Report)
const raw = sessionStorage.getItem('osteo:draft')
expect(raw).not.toBeNull()
expect(JSON.parse(raw!)).toEqual(full)
expect(readPersistedDraft()).toEqual(full)
})
it('hydrateReport does not revalidate (an invalid report can enter the store, the draft is then unreadable)', () => {
const broken = { ...(minimal as Report), version: 7 } as unknown as Report
useReportStore.getState().hydrateReport(broken)
expect(useReportStore.getState().report?.version).toBe(7)
expect(readPersistedDraft()).toBeNull()
})
it('initReport creates one empty observation, a uuid id and version 2', () => {
const { observations, ...draft } = minimal as Report
void observations
useReportStore.getState().initReport({ ...draft, observations: [] } as never)
const r = useReportStore.getState().report!
expect(r.version).toBe(2)
expect(r.id).toMatch(/^[0-9a-f-]{36}$/)
expect(r.observations).toHaveLength(1)
expect(r.observations[0]).toMatchObject({ zones: [], findings: [], freeTextFindings: [], comment: '' })
})
it('caches the practitioner block under localStorage["osteo:lastPractitioner"]', () => {
writeCachedPractitioner(full.practitioner)
expect(JSON.parse(localStorage.getItem('osteo:lastPractitioner')!)).toEqual(full.practitioner)
expect(readCachedPractitioner()).toEqual(full.practitioner)
})
it('persists the locale under localStorage["osteo:locale"] (shared with pathology-editor.html)', () => {
useLocaleStore.getState().setLocale('en')
expect(localStorage.getItem('osteo:locale')).toBe('en')
})
})
@@ -0,0 +1,222 @@
/**
* Characterisation (Step 1): the real SVG assets, their attributes, the
* SVG ↔ catalog link computed by zoneMatch, the opens-detail ↔ manifest
* contract and the spine helpers on the real Horse.svg.
* Oracle: docs/faunosteo-audit/06-svg-findings-link.md §4 (full table).
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { parseSvgBones } from '@/anatomy/svgConvention'
import { matchZoneFindings, scorePair, levenshtein, normalizeLabel } from '@/lib/zoneMatch'
import {
regionFromLabel,
findSpineZoneId,
collectSpineVertebrae,
syncSpineZones,
} from '@/lib/spineZones'
import { getSpecies } from '@/domain/species/registry'
import FINDINGS from '@/domain/species/equine/pathologies'
import type { Bone } from '@/anatomy/types'
const HERE = dirname(fileURLToPath(import.meta.url))
const HORSE_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8')
const HEAD_TEXT = readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8')
function parse(text: string): Map<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 }] })
})
})
@@ -0,0 +1,39 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import AnatomyCanvas from '@/components/canvas/AnatomyCanvas'
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
}),
}))
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(),
)
})
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 }),
)
await waitFor(() => expect(onZoneClick).toHaveBeenCalledWith('epaule'))
})
})
@@ -0,0 +1,12 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import Brand from '@/components/brand/Brand'
describe('Brand', () => {
it('renders the logo image with alt text', () => {
render(<Brand />)
const img = screen.getByAltText('Faunosteo')
expect(img).toBeInTheDocument()
expect(img).toHaveAttribute('src', '/logo-horizontal.svg')
})
})
@@ -0,0 +1,298 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
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'
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' })
})
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', () => {
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}
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([
{
zoneId: 'sphenoid',
path: ['dysfunctions', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
},
])
})
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>()
const selected: Finding[] = [
{
zoneId: 'sphenoid',
path: ['dysfunctions', 'flexion'],
labelFrSnapshot: 'Flexion',
labelEnSnapshot: 'Flexion',
},
]
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={selected}
onChange={onChange}
/>,
)
await userEvent.click(screen.getByLabelText('Ouvrir Dysfonctions'))
await userEvent.click(screen.getByLabelText('Flexion'))
expect(onChange).toHaveBeenCalledWith([])
})
it('navigates back to parent via the Retour button', async () => {
render(
<FindingsTreePicker
zoneId="sphenoid"
tree={TREE}
selected={[]}
onChange={() => {}}
/>,
)
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'),
).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()
})
})
@@ -0,0 +1,24 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import { useLocaleStore } from '@/state/localeStore'
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
})
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')
})
it('clicking EN updates the store', async () => {
const user = userEvent.setup()
render(<LanguageSwitcher />)
await user.click(screen.getByRole('button', { name: /english/i }))
expect(useLocaleStore.getState().locale).toBe('en')
})
})
@@ -0,0 +1,104 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { 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'
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
})
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()
})
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(
'aria-selected',
'true',
)
})
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',
)
})
})
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()
})
})
+18
View File
@@ -0,0 +1,18 @@
import { describe, it, expect } from 'vitest'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
describe('i18n dicts', () => {
it('fr and en share the exact same key set', () => {
const frKeys = Object.keys(fr).sort()
const enKeys = Object.keys(en).sort()
expect(frKeys).toEqual(enKeys)
})
it('every value is a non-empty string', () => {
for (const k of Object.keys(fr)) {
expect(fr[k].length).toBeGreaterThan(0)
expect(en[k].length).toBeGreaterThan(0)
}
})
})
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
})
describe('useT', () => {
it('returns the FR value for a known key', () => {
const { result } = renderHook(() => useT())
expect(result.current('common.cancel')).toBe('Annuler')
})
it('returns the EN value after switching locale', () => {
const { result } = renderHook(() => useT())
act(() => useLocaleStore.getState().setLocale('en'))
expect(result.current('common.cancel')).toBe('Cancel')
})
it('returns the key literal and warns when key is missing', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { result } = renderHook(() => useT())
expect(result.current('nonexistent.key')).toBe('nonexistent.key')
expect(warn).toHaveBeenCalled()
warn.mockRestore()
})
})
+40
View File
@@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest'
import { formatDate, todayIso, nowIso } from '@/lib/dates'
describe('formatDate fr', () => {
it('formats "2026-05-18" as "18 mai 2026"', () => {
expect(formatDate('2026-05-18', 'fr')).toBe('18 mai 2026')
})
it('drops leading zero on the day', () => {
expect(formatDate('2026-01-03', 'fr')).toBe('3 janvier 2026')
})
})
describe('formatDate en', () => {
it('formats "2026-05-18" as "May 18, 2026"', () => {
expect(formatDate('2026-05-18', 'en')).toBe('May 18, 2026')
})
it('drops leading zero on the day', () => {
expect(formatDate('2026-01-03', 'en')).toBe('January 3, 2026')
})
})
describe('formatDate edge', () => {
it('throws on invalid ISO input', () => {
expect(() => formatDate('not-a-date', 'fr')).toThrow()
})
})
describe('todayIso', () => {
it('returns YYYY-MM-DD', () => {
expect(todayIso()).toMatch(/^\d{4}-\d{2}-\d{2}$/)
})
})
describe('nowIso', () => {
it('returns a full ISO instant', () => {
expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)
})
})
+14
View File
@@ -0,0 +1,14 @@
import { describe, it, expect } from 'vitest'
import { generateId } from '@/lib/id'
describe('generateId', () => {
it('returns a non-empty string', () => {
expect(generateId().length).toBeGreaterThan(0)
})
it('returns distinct ids on consecutive calls', () => {
const a = generateId()
const b = generateId()
expect(a).not.toBe(b)
})
})
+120
View File
@@ -0,0 +1,120 @@
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
@@ -0,0 +1,154 @@
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()
})
})
@@ -0,0 +1,26 @@
import { describe, it, expect } from 'vitest'
import { inflateFlate } from '@/pdf/attachment'
async function deflate(data: Uint8Array): Promise<Uint8Array> {
const stream = new Blob([data as BlobPart])
.stream()
.pipeThrough(new CompressionStream('deflate'))
return new Uint8Array(await new Response(stream).arrayBuffer())
}
describe('inflateFlate decompression cap', () => {
it('inflates a normal-size payload', async () => {
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')
})
it('returns null for a decompression bomb above the cap', async () => {
// 24 MB of zeros deflates to a few KB but inflates past the 16 MB cap
const bomb = await deflate(new Uint8Array(24 * 1024 * 1024))
expect(bomb.byteLength).toBeLessThan(1024 * 1024)
const out = await inflateFlate(bomb)
expect(out).toBeNull()
})
})
@@ -0,0 +1,40 @@
import { describe, it, expect } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { attachReportJson, extractReportJson } from '@/pdf/attachment'
import type { Report } from '@/domain/schema/report'
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',
}
describe('PDF attachment roundtrip', () => {
it('attaches and extracts the report JSON', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await attachReportJson(doc, report)
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)
})
it('throws on PDFs without the attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const bytes = await doc.save()
const reopened = await PDFDocument.load(bytes)
await expect(extractReportJson(reopened)).rejects.toThrow()
})
})
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect, vi } from 'vitest'
import { AFRelationship, PDFDocument } from 'pdf-lib'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { embedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: async () => new Uint8Array([137, 80, 78, 71]) }))
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: '',
}
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,
})
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)
}
})
})
+85
View File
@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { rasterizeSvg } from '@/pdf/render/svgToPng'
const PNG_BYTES = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x00,
])
class MockImage {
decoding: 'sync' | 'async' | 'auto' = 'auto'
crossOrigin: string | null = null
onload: (() => void) | null = null
onerror: ((err?: unknown) => void) | null = null
private _src = ''
get src(): string {
return this._src
}
set src(value: string) {
this._src = value
queueMicrotask(() => this.onload?.())
}
}
describe('rasterizeSvg', () => {
beforeEach(() => {
vi.stubGlobal('Image', MockImage)
vi.stubGlobal('URL', {
createObjectURL: () => 'blob:mock',
revokeObjectURL: () => undefined,
})
})
it('returns PNG bytes for a valid SVG', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
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,
)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
)
expect(out).toBeInstanceOf(Uint8Array)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
expect(out[2]).toBe(0x4e)
expect(out[3]).toBe(0x47)
})
it('falls back to toDataURL when toBlob returns null', async () => {
const canvas = document.createElement('canvas')
canvas.getContext = (() => ({
fillStyle: '',
fillRect: () => undefined,
drawImage: () => undefined,
})) as unknown as HTMLCanvasElement['getContext']
canvas.toBlob = ((cb: BlobCallback) => {
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,
)
const out = await rasterizeSvg(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"/>',
)
expect(out[0]).toBe(0x89)
expect(out[1]).toBe(0x50)
})
})
@@ -0,0 +1,96 @@
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,157 @@
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
@@ -0,0 +1,53 @@
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()
})
})
+55
View File
@@ -0,0 +1,55 @@
import { describe, it, expect } from 'vitest'
import { ReportSchema } from '@/domain/schema/report'
import { generateId } from '@/lib/id'
import { todayIso, nowIso } from '@/lib/dates'
import { assert } from '@/lib/assert'
describe('skeleton smoke test', () => {
it('generates a non-empty id', () => {
const id = generateId()
expect(typeof id).toBe('string')
expect(id.length).toBeGreaterThan(0)
})
it('todayIso returns an ISO date string', () => {
const today = todayIso()
expect(today).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/)
})
it('ReportSchema parses a valid minimal report', () => {
const validReport = {
version: 2 as const,
id: generateId(),
createdAt: nowIso(),
date: todayIso(),
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
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)
})
it('assert passes when condition is truthy', () => {
expect(() => assert(true, 'should not throw')).not.toThrow()
})
it('assert throws when condition is falsy', () => {
expect(() => assert(false, 'boom')).toThrow('Assertion failed: boom')
})
})
@@ -0,0 +1,52 @@
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([])
})
})
@@ -0,0 +1,24 @@
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()
})
})
@@ -0,0 +1,35 @@
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()
})
})
@@ -0,0 +1,23 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useLocaleStore, LOCALE_STORAGE_KEY } from '@/state/localeStore'
beforeEach(() => {
localStorage.removeItem(LOCALE_STORAGE_KEY)
useLocaleStore.setState({ locale: 'fr' })
})
describe('localeStore', () => {
it('defaults to fr when localStorage is empty', () => {
expect(useLocaleStore.getState().locale).toBe('fr')
})
it('setLocale updates state', () => {
useLocaleStore.getState().setLocale('en')
expect(useLocaleStore.getState().locale).toBe('en')
})
it('setLocale writes to localStorage', () => {
useLocaleStore.getState().setLocale('en')
expect(localStorage.getItem(LOCALE_STORAGE_KEY)).toBe('en')
})
})
@@ -0,0 +1,33 @@
import { describe, it, expect, beforeEach } from 'vitest'
import {
readCachedPractitioner,
writeCachedPractitioner,
clearPractitionerCache,
} from '@/state/practitionerCache'
beforeEach(() => localStorage.clear())
describe('practitionerCache', () => {
it('returns undefined when empty', () => {
expect(readCachedPractitioner()).toBeUndefined()
})
it('round-trips a valid practitioner', () => {
writeCachedPractitioner({ name: 'Dr. Dupont', cabinet: 'Clinic A' })
expect(readCachedPractitioner()).toEqual({
name: 'Dr. Dupont',
cabinet: 'Clinic A',
})
})
it('returns undefined on malformed JSON', () => {
localStorage.setItem('osteo:lastPractitioner', 'not-json')
expect(readCachedPractitioner()).toBeUndefined()
})
it('clear removes the entry', () => {
writeCachedPractitioner({ name: 'Dr. Dupont' })
clearPractitionerCache()
expect(readCachedPractitioner()).toBeUndefined()
})
})
@@ -0,0 +1,58 @@
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()
})
})
@@ -0,0 +1,56 @@
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()
})
})
@@ -0,0 +1,120 @@
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.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)
expect(useReportStore.getState().activeObservationIndex).toBe(0)
})
})
describe('reportStore.reset', () => {
it('clears the report', () => {
useReportStore.getState().initReport(draft)
useReportStore.getState().reset()
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('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('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)
})
})
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('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)
})
})
+18
View File
@@ -0,0 +1,18 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Button from '@/components/ui/Button'
describe('Button', () => {
it('renders children and handles clicks', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>Save</Button>)
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
expect(onClick).toHaveBeenCalledOnce()
})
it('respects disabled', () => {
render(<Button disabled>Save</Button>)
expect(screen.getByRole('button')).toBeDisabled()
})
})
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import Dialog from '@/components/ui/Dialog'
describe('Dialog', () => {
it('renders nothing when open=false', () => {
render(
<Dialog open={false} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(screen.queryByText('body')).toBeNull()
})
it('renders content when open=true', () => {
render(
<Dialog open={true} onClose={() => {}} title="X">
body
</Dialog>,
)
expect(screen.getByText('body')).toBeInTheDocument()
})
it('calls onClose on backdrop click', async () => {
const onClose = vi.fn()
render(
<Dialog open onClose={onClose} title="X">
body
</Dialog>,
)
await userEvent.click(screen.getByTestId('dialog-backdrop'))
expect(onClose).toHaveBeenCalled()
})
})