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

+3 -3
View File
@@ -126,7 +126,7 @@ pnpm test # vitest watch — dev loop
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Characterisation suite: files prefixed `char.`.
@testing-library/jest-dom. Suites run on the bundled reference sheet (`tests/helpers/sheet.ts`); frozen v2 fixtures under `tests/fixtures/`.
SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts`
on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack.
@@ -171,10 +171,10 @@ faunosteo/
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,FindingsTreePicker,
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ ├─ pdf/
+2 -2
View File
@@ -145,13 +145,13 @@ v0.1.0 MVP — implementation complete.
- `pnpm typecheck` ✅
- `pnpm lint` ✅
- `pnpm test:run` ✅ — 310 tests across the workspace (domain, anatomy, supabase, app)
- `pnpm test:run` ✅ — 367 tests across the workspace (domain, anatomy, supabase, app)
- `pnpm build` ✅
The first species ships as the equine anatomical sheet: the historical
`Horse.svg`, `Horse_head.svg` and findings catalog (26 zones, 792 nodes)
imported, then audited and curated (`supabase/seed/anatomical-sheets/equine/`,
44 traced changes, 48 references). The application bundles that curated
45 traced changes, 48 references). The application bundles that curated
draft in development (`SHEET_BUNDLE=draft`); it is not medically validated and
a production build carries no sheet unless asked. Another species is another
sheet document produced the same way.
+2
View File
@@ -76,6 +76,8 @@ function parseAttachment(
typeof (data as { version?: unknown }).version === 'number'
? (data as { version: number }).version
: null
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (version === null) throw new Error('attachment carries no report version')
try {
return {
...readReportDocument(data, map),
@@ -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()
})
})
+1 -1
View File
@@ -102,7 +102,7 @@ Package-scoped: `pnpm --filter @faunosteo/app <script>`.
1. From a clean clone, Node 24 active: `pnpm install` completes with no
"Ignored build scripts" warning.
2. `pnpm typecheck`, `pnpm test:run` (310 tests), `pnpm lint`, `pnpm build`
2. `pnpm typecheck`, `pnpm test:run` (367 tests), `pnpm lint`, `pnpm build`
all exit 0; `apps/app/dist/` contains `index.html`, `env.js`,
`favicon`, logos (anatomy assets are bundled from the sheet seed, Step 5).
3. `pnpm dev`, then in the browser: `/` (home), `/new` (form, species defaults
+27 -3
View File
@@ -69,9 +69,9 @@ describe('report v3 leaf schemas', () => {
it('ObservationSchema rejects an empty id', () => {
expect(ObservationSchema.safeParse(observation).success).toBe(true)
expect(ObservationSchema.safeParse({ ...observation, id: '' }).success).toBe(
false,
)
expect(
ObservationSchema.safeParse({ ...observation, id: '' }).success,
).toBe(false)
})
it('SeveritySchema accepts the three codes only', () => {
@@ -116,3 +116,27 @@ describe('report v3 document and identity', () => {
)
})
})
describe('report v3 permissive boundaries', () => {
it('strips unknown keys silently', () => {
const out = ReportSchema.parse({ ...report, foo: 1 })
expect('foo' in out).toBe(false)
})
it('accepts a vertebra index above any region count (bounds are a sheet concern)', () => {
expect(VertebraSchema.safeParse({ region: 'C', index: 99 }).success).toBe(
true,
)
})
it('accepts an unregistered speciesId', () => {
const animal = { speciesId: 'dragon', name: 'A' }
expect(ReportSchema.safeParse({ ...report, animal }).success).toBe(true)
})
it('accepts orphan findings citing a zone absent from zones (D5)', () => {
const orphan = { ...observation, findings: [finding] }
const out = ReportSchema.safeParse({ ...report, observations: [orphan] })
expect(out.success).toBe(true)
})
})