test(app): former PDF, observation card, route and schema assertions restored on v3; foreign JSON attachment reported as no_attachment; doc counts

This commit is contained in:
bchanot committed 2026-10-10 12:21:19 +02:00
1 parent 06a2e86f3c
commit 17a6d9b323
9 files changed
+406 -27

No files matched your search

@@ -0,0 +1,161 @@
/**
* ObservationCard on the bundled sheet: one findings picker per (finding
* zone, side), unresolved findings and zones, zone removal and the vertebra
* picker entry point.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterEach,
} from 'vitest'
import { render, screen, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Observation } from '@faunosteo/domain'
import ObservationCard from '@/components/observation/ObservationCard'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { emptyObservation, loadTestSheet } from '../helpers/sheet'
let sheet: SheetIndex
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
function mount(observation: Observation) {
const handlers = {
onChange: vi.fn(),
onRemoveZone: vi.fn(),
onOpenVertebraPicker: vi.fn(),
}
render(
<ObservationCard
observation={observation}
index={0}
expanded
onToggle={vi.fn()}
onDelete={vi.fn()}
onMoveUp={vi.fn()}
onMoveDown={vi.fn()}
canMoveUp={false}
canMoveDown={false}
sheet={sheet}
{...handlers}
/>,
)
return handlers
}
const HIP = 'Hanche (coxo-fémorale)'
describe('ObservationCard', () => {
it('renders one findings picker per (finding zone, side), none for the head trigger', () => {
mount({
...emptyObservation(),
zones: [
{ annotationId: 'hip', viewId: 'main', side: 'left' },
{ annotationId: 'hip', viewId: 'main', side: 'right' },
{ annotationId: 'c7-t1', viewId: 'main' },
{ annotationId: 'head-trigger', viewId: 'main' },
],
})
const headers = screen
.getAllByRole('button', { expanded: false })
.filter((b) =>
b.getAttribute('aria-controls')?.startsWith('findings-zone-'),
)
.map((b) => b.textContent?.replace('▼', ''))
expect(headers).toEqual([
`${HIP} (Gauche)`,
`${HIP} (Droite)`,
'Charnière C7-T1 (cervico-thoracique)',
])
})
it('lists unresolved findings and removes one without touching the zones', async () => {
const user = userEvent.setup()
const zones = [{ annotationId: 'c7-t1', viewId: 'main' }]
const observation: Observation = {
...emptyObservation(),
zones,
findings: [
{
findingZoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
labelFrSnapshot: 'Suture sphéno-zygomatique',
labelEnSnapshot: 'Sphenozygomatic suture',
unresolved: true,
},
],
}
const { onChange } = mount(observation)
expect(
screen.getByText(fr['observation.findings_unresolved_label']!),
).toBeInTheDocument()
expect(screen.getByText('Suture sphéno-zygomatique')).toBeInTheDocument()
await user.click(
screen.getByRole('button', {
name: `${fr['common.delete']} Suture sphéno-zygomatique`,
}),
)
expect(onChange).toHaveBeenCalledWith({ ...observation, findings: [] })
expect(onChange.mock.calls[0]![0].zones).toBe(zones)
})
it('removes a zone by index', async () => {
const user = userEvent.setup()
const { onRemoveZone } = mount({
...emptyObservation(),
zones: [
{ annotationId: 'c7-t1', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
],
})
await user.click(
screen.getByRole('button', {
name: `${fr['observation.remove_zone']} ${HIP}`,
}),
)
expect(onRemoveZone).toHaveBeenCalledWith(1)
})
it('offers the vertebrae button on spine zones only', async () => {
const user = userEvent.setup()
const { onOpenVertebraPicker } = mount({
...emptyObservation(),
zones: [
{ annotationId: 'c7-t1', viewId: 'main' },
{ annotationId: 'cervical', viewId: 'main' },
],
})
const buttons = screen.getAllByText(fr['observation.vertebrae_button']!)
expect(buttons).toHaveLength(1)
await user.click(buttons[0]!)
expect(onOpenVertebraPicker).toHaveBeenCalledWith(1)
})
it('shows the snapshot and the unresolved marker for a zone unknown to the sheet', () => {
mount({
...emptyObservation(),
zones: [
{
annotationId: 'point-gone',
viewId: 'main',
unresolved: true,
labelFrSnapshot: 'Point disparu',
labelEnSnapshot: 'Gone point',
},
],
})
expect(screen.getByText(/Point disparu/)).toBeInTheDocument()
expect(
screen.getByText(fr['observation.unresolved_short']!),
).toBeInTheDocument()
})
})
+157 -3
View File
@@ -13,7 +13,7 @@ import {
beforeEach,
afterAll,
} from 'vitest'
import { PDFDocument, PDFPage } from 'pdf-lib'
import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
@@ -22,6 +22,8 @@ import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import { formatDate } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
@@ -41,12 +43,15 @@ const fixture = (name: string) =>
let sheet: SheetIndex
let drawn: string[] = []
const fetched: string[] = []
const realFetch = globalThis.fetch
beforeAll(async () => {
sheet = await loadTestSheet()
globalThis.fetch = (async () =>
new Response('not found', { status: 404 })) as typeof fetch
globalThis.fetch = (async (input: RequestInfo | URL) => {
fetched.push(String(input))
return new Response('not found', { status: 404 })
}) as typeof fetch
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => {
@@ -54,6 +59,7 @@ afterAll(() => {
})
beforeEach(() => {
drawn = []
fetched.length = 0
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
this: PDFPage,
text: string,
@@ -162,6 +168,154 @@ describe('export on a full v3 report (FR)', () => {
})
})
/** Rebuilds wrapped values: lines are drawn one by one. */
const joined = () => drawn.join(' ').replace(/\s+/g, ' ')
function fullReport() {
const second: Observation = {
id: 'obs-2',
zones: [],
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'Fixation de la charnière',
labelEnSnapshot: 'Junction fixation',
},
],
freeTextFindings: ['Raideur au garrot'],
comment: 'Réagit à la palpation.',
}
return minimalReport(sheet, {
observations: [fullObservation(), second],
conclusion: 'Dysfonction cervico-thoracique.',
recommendations: 'Repos au pré.',
nextAppointment: { kind: 'date', date: '2026-11-20' },
})
}
describe('PDF content on a two-observation report', () => {
it('prints the empty marker for a zoneless observation and keeps its findings', async () => {
await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.empty'])
const prefix = fr['pdf.section.findings_prefix']!
const occurrences = drawn.filter(
(l) => l === `${prefix}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`,
)
expect(occurrences).toHaveLength(2)
})
it('prints an unknown annotation id and an unknown finding zone raw', async () => {
const stale: Observation = {
...fullObservation(),
zones: [{ annotationId: 'point-gone', viewId: 'main' }],
findings: [
{
findingZoneId: 'zone-gone',
path: ['x'],
labelFrSnapshot: 'Snapshot FR',
labelEnSnapshot: 'Snapshot EN',
},
],
}
const report = minimalReport(sheet, { observations: [stale] })
await exportReportToPdf(report, sheet, { locale: 'fr' })
expect(drawn).toContain('point-gone')
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
expect(drawn).toContain('Snapshot FR')
})
it('draws the EN dictionary, annotation names and finding snapshots', async () => {
await exportReportToPdf(fullReport(), sheet, { locale: 'en' })
expect(drawn).toContain(en['pdf.section.zones'])
expect(drawn.some((l) => l.includes('Hip joint'))).toBe(true)
expect(drawn).toContain('Junction fixation')
expect(drawn).not.toContain('Fixation de la charnière')
})
it('draws free findings, comments, the conclusion page and the header on every page', async () => {
const report = fullReport()
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
const pages = (await PDFDocument.load(bytes)).getPageCount()
expect(drawn).toContain(fr['pdf.section.free_findings'])
expect(joined()).toContain('Sensibilité au garrot')
expect(joined()).toContain('Raideur au garrot')
expect(drawn).toContain(fr['pdf.section.comment'])
expect(joined()).toContain('Réagit à la palpation.')
expect(drawn).toContain(fr['pdf.section.conclusion'])
expect(joined()).toContain('Dysfonction cervico-thoracique.')
expect(drawn).toContain(fr['pdf.section.recommendations'])
expect(joined()).toContain('Repos au pré.')
expect(drawn).toContain(fr['pdf.section.next_appointment'])
expect(drawn).toContain(formatDate('2026-11-20', 'fr'))
const header = drawn.filter((l) => l === 'Dr. Dupont').length
expect(header).toBeGreaterThanOrEqual(pages)
})
it('sets the PDF metadata', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(doc.getAuthor()).toBe('Dr. Dupont')
expect(doc.getSubject()).toBe(fr['pdf.subject'])
})
it('fetches the logos at export time', async () => {
await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
expect(
fetched.some(
(u) => u.endsWith('.png') || u.endsWith('Paws_in_harmony.svg'),
),
).toBe(true)
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo state v3"', async () => {
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
String(o),
)
const filespec = objects.find((o) => o.includes('/Type /Filespec'))!
expect(filespec).toContain('osteo-report.json')
expect(filespec).toContain('/AFRelationship /Data')
const utf16 = (text: string) =>
[...text]
.map((c) => c.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0'))
.join('')
expect(filespec).toContain(utf16('Faunosteo state v3'))
const embedded = objects.find((o) => o.includes('/Type /EmbeddedFile'))!
expect(embedded).toContain('/Filter /FlateDecode')
})
})
describe('attachment rejection', () => {
async function pdfWith(name: string, payload: unknown): Promise<Uint8Array> {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode(JSON.stringify(payload)), name, {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
return doc.save()
}
it('reports no_attachment for a foreign JSON attachment (no version)', async () => {
const bytes = await pdfWith('other.json', { hello: 'world' })
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
})
it('reports no_attachment for a v3 report failing validation', async () => {
const broken: Record<string, unknown> = { ...minimalReport(sheet) }
delete broken.sheet
const bytes = await pdfWith('osteo-report.json', broken)
await expect(
importReportFromPdf(bytes, sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'no_attachment' })
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await importReportFromPdf(
+29 -15
View File
@@ -41,21 +41,19 @@ beforeEach(() => {
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore
.getState()
.hydrateReport(
minimalReport(sheet, {
observations: [
{
id: 'o1',
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
useReportStore.getState().hydrateReport(
minimalReport(sheet, {
observations: [
{
id: 'o1',
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
},
],
}),
)
})
afterEach(() => {
cleanup()
@@ -150,6 +148,22 @@ describe('EditorRoute on the canonical sheet', () => {
])
})
it('cancelling the vertebra picker keeps the spine zone without vertebrae', async () => {
const user = userEvent.setup()
await mount()
clickZone('cervical')
const dialog = await screen.findByRole('dialog', {
name: /Vertèbres cervicales/,
})
await user.click(within(dialog).getByText('C3'))
await user.click(
within(dialog).getByRole('button', { name: fr['common.cancel'] }),
)
expect(zonesOf().map((z) => [z.annotationId, z.vertebrae])).toEqual([
['cervical', undefined],
])
})
it('the head trigger opens the detail view by its name and its zones carry the head view id', async () => {
await mount()
clickZone('head-trigger')
@@ -153,3 +153,27 @@ describe('sessionStorage mirror and restore', () => {
expect(saved.at(-1)).toMatchObject({ version: 3 })
})
})
describe('store edge cases', () => {
it('hydrateReport stores the given object as is, without revalidating', () => {
const odd = { ...minimalReport(sheet), extra: 1 }
useReportStore.getState().hydrateReport(odd)
expect(useReportStore.getState().report).toBe(odd)
expect(
(useReportStore.getState().report as unknown as { extra: number }).extra,
).toBe(1)
})
it('identity setters are no-ops without a report', () => {
const s = useReportStore.getState()
s.setPractitioner({ name: 'X' })
s.setAnimal({ speciesId: 'equine', name: 'X' })
s.setOwner({ name: 'X' })
expect(useReportStore.getState().report).toBeNull()
})
it('restoreDraft with no draft leaves the store empty', () => {
useReportStore.getState().restoreDraft(sheet.sheet.migrationMap)
expect(useReportStore.getState().report).toBeNull()
})
})