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

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

No files matched your search

+302 -102
View File
@@ -1,112 +1,312 @@
import { describe, it, expect, vi } from 'vitest'
import { AFRelationship, PDFDocument } from 'pdf-lib'
/**
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the v3 pipeline on
* the bundled sheet (drawn strings from the document, attachment v3,
* roundtrip FR/EN) and the import of the frozen v2 archive PDFs, migrated
* without silent loss.
*/
import {
describe,
it,
expect,
vi,
beforeAll,
beforeEach,
afterAll,
} from 'vitest'
import { PDFDocument, PDFPage } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation } from '@faunosteo/domain'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { embedFonts } from '@/pdf/fonts'
import type { Report } from '@/domain/schema/report'
import { highlightedViewSvg } from '@/pdf/render/observationPage'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/render/svgToPng', () => ({ rasterizeSvg: async () => new Uint8Array([137, 80, 78, 71]) }))
const ONE_PX_PNG = Uint8Array.from(
Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64',
),
)
vi.mock('@/pdf/render/svgToPng', () => ({
rasterizeSvg: vi.fn(async () => ONE_PX_PNG),
}))
const report: Report = {
version: 2,
id: 'r1',
createdAt: '2026-05-18T10:00:00Z',
date: '2026-05-18',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: 'ok',
recommendations: '',
const HERE = dirname(fileURLToPath(import.meta.url))
const fixture = (name: string) =>
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
let sheet: SheetIndex
let drawn: string[] = []
const realFetch = globalThis.fetch
beforeAll(async () => {
sheet = await loadTestSheet()
globalThis.fetch = (async () =>
new Response('not found', { status: 404 })) as typeof fetch
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => {
globalThis.fetch = realFetch
})
beforeEach(() => {
drawn = []
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
this: PDFPage,
text: string,
) {
drawn.push(text)
} as never)
})
/** A full v3 observation: plain zone, bilateral both sides, spine with vertebrae, head zone, findings. */
function fullObservation(): Observation {
return {
id: 'obs-full',
zones: [
{ annotationId: 'c7-t1', viewId: 'main' },
{ annotationId: 'hip', viewId: 'main', side: 'left' },
{ annotationId: 'hip', viewId: 'main', side: 'right' },
{
annotationId: 'cervical',
viewId: 'main',
vertebrae: [
{ region: 'C', index: 3 },
{ region: 'C', index: 4 },
],
},
{ annotationId: 'atm', viewId: 'head' },
],
findings: [
{
findingZoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'Fixation de la charnière',
labelEnSnapshot: 'Junction fixation',
},
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
side: 'left',
},
{
findingZoneId: 'atm',
path: ['atm-consultation-reasons', 'headshaking'],
labelFrSnapshot: 'Headshaking (secouement de tête)',
labelEnSnapshot: 'Headshaking',
requiresVetReferral: true,
unresolved: true,
},
],
freeTextFindings: ['Sensibilité au garrot'],
severity: 'moderate',
comment: 'note',
}
}
describe('PDF roundtrip', () => {
it('rejects unrelated PDF bytes with ImportError', async () => {
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10, 37, 226, 227, 207, 211, 10])
await expect(importReportFromPdf(fake)).rejects.toThrow(ImportError)
})
it('roundtrips a minimal report (no observations)', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('roundtrips a report exported with locale=fr', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('roundtrips a report exported with locale=en', async () => {
const bytes = await exportReportToPdf(report, { locale: 'en' })
const imported = await importReportFromPdf(bytes)
expect(imported.animal.name).toBe('Mistral')
expect(imported.version).toBe(2)
})
it('FR and EN exports both produce non-empty byte streams', async () => {
// pdf-lib subsets fonts (LRN-016), so plain-text grep over the bytes
// is unreliable. The imported JSON is the strongest invariant — the
// locale lives outside the Report, so both imports return the same
// payload while the static label snapshots differ inside the PDF.
const fr = await exportReportToPdf(report, { locale: 'fr' })
const en = await exportReportToPdf(report, { locale: 'en' })
expect(fr.byteLength).toBeGreaterThan(0)
expect(en.byteLength).toBeGreaterThan(0)
const frImported = await importReportFromPdf(fr)
const enImported = await importReportFromPdf(en)
expect(frImported.animal.name).toBe(enImported.animal.name)
expect(frImported.version).toBe(enImported.version)
})
it('vet-referral marker is encodable by the body font (regression: WinAnsi cannot encode U+26A0)', async () => {
// observationPage prefixes vet-referral leaves with a marker that
// is rendered using the WinAnsi-encoded StandardFonts.Helvetica.
// The previous "⚠ " marker (U+26A0) threw `WinAnsi cannot encode "⚠"`
// the moment the text-height estimator measured the leaf label.
// Guard against re-introducing a non-WinAnsi marker by exercising
// the same path: load the body font and measure a label that
// carries the prefix.
const doc = await PDFDocument.create()
const fonts = await embedFonts(doc)
expect(() =>
fonts.bodyRegular.widthOfTextAtSize('(!) Difficulté de déglutition', 10),
).not.toThrow()
})
it('rejects a legacy v1 PDF with a version-specific message', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const legacyPayload = {
version: 1,
id: 'legacy',
createdAt: '2025-12-01T00:00:00Z',
date: '2025-12-01',
practitioner: { name: 'Dr. Dupont' },
animal: { speciesId: 'equine', name: 'Mistral' },
owner: { name: 'Jean Martin' },
observations: [],
conclusion: '',
recommendations: '',
}
const bytes = new TextEncoder().encode(JSON.stringify(legacyPayload))
await doc.attach(bytes, 'osteo-report.json', {
mimeType: 'application/json',
description: 'Osteo Report state v1',
afRelationship: AFRelationship.Data,
describe('export on a full v3 report (FR)', () => {
it('produces one page per observation plus the conclusion, labels from the sheet', async () => {
const report = minimalReport(sheet, {
observations: [fullObservation()],
conclusion: 'ok',
})
const pdfBytes = await doc.save()
try {
await importReportFromPdf(pdfBytes)
throw new Error('expected rejection')
} catch (err) {
expect(err).toBeInstanceOf(ImportError)
const e = err as ImportError
expect(e.kind).toBe('incompatible_version')
expect(e.foundVersion).toBe(1)
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getPageCount()).toBe(2)
const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!)
expect(drawn.slice(zonesIdx + 1, zonesIdx + 6)).toEqual([
'Charnière C7-T1 (cervico-thoracique)',
'•',
'Hanche (coxo-fémorale) (Gauche)',
'•',
'Hanche (coxo-fémorale) (Droite)',
])
expect(drawn).toContain('Vertèbres cervicales (C3, C4)')
expect(drawn).toContain('Articulation temporo-mandibulaire (ATM)')
const prefix = fr['pdf.section.findings_prefix']!
expect(drawn).toContain(`${prefix}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
expect(drawn).toContain(`${prefix}HANCHE (COXO-FÉMORALE) (GAUCHE)`)
expect(drawn).toContain('(!) Headshaking (secouement de tête)')
expect(drawn).toContain(fr['severity.moderate']!)
expect(drawn).toContain(fr['pdf.view.general']!)
expect(drawn).toContain(
`${fr['pdf.view.detail_prefix']}TÊTE (VUE LATÉRALE GAUCHE)`,
)
})
it('attaches v3 and roundtrips in both locales', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportReportToPdf(report, sheet, { locale })
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
expect(out.migrated).toBe(false)
expect(out.report).toEqual(report)
}
})
it('highlights the observation zones of a view and hides the other markers', () => {
const svg = highlightedViewSvg(sheet, 'main', fullObservation())
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
expect(svg).toContain('url(#osteo-halo)')
expect(svg).toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
const head = highlightedViewSvg(sheet, 'head', fullObservation())
expect(head).toContain('viewBox="60 100 500 380"')
expect(head).not.toContain('osteo-halo')
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await importReportFromPdf(
fixture('report-v2.full.pdf'),
sheet.sheet.migrationMap,
)
expect(out.migrated).toBe(true)
const { report } = out
expect(report.version).toBe(3)
expect(report.sheet).toEqual(sheet.sheet.ref)
expect(report.animal.name).toBe('Mistral')
const zones = report.observations.flatMap((o) => o.zones)
expect(
zones.map(
(z) => `${z.annotationId}@${z.viewId}${z.side ? ':' + z.side : ''}`,
),
).toEqual(
expect.arrayContaining([
'c7-t1@main',
'hip@main:left',
'hip@main:right',
'cervical@main',
'atm@head',
]),
)
expect(zones.every((z) => !z.unresolved)).toBe(true)
const findings = report.observations.flatMap((o) => o.findings)
const moved = findings.find((f) =>
f.path.includes('stumbling-proprioceptive'),
)!
expect(moved.path[0]).toBe('cervical-consultation-reasons')
expect(moved.unresolved).toBeUndefined()
const headshaking = findings.find((f) => f.path.includes('headshaking'))!
expect(headshaking.path).toEqual([
'atm-consultation-reasons',
'headshaking',
])
expect(findings.some((f) => f.unresolved)).toBe(false)
expect(out.unresolvedFindings).toBe(0)
expect(report.observations.map((o) => o.severity)).toEqual(
expect.arrayContaining(['moderate', 'severe']),
)
// Re-export and re-import: stable.
const again = await importReportFromPdf(
await exportReportToPdf(report, sheet, { locale: 'fr' }),
sheet.sheet.migrationMap,
)
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
})
it('keeps a v2 finding whose node was removed and a zone whose id is unknown, both flagged', async () => {
const v2 = {
...JSON.parse(
readFileSync(
resolve(HERE, '../fixtures/report-v2.minimal.json'),
'utf8',
),
),
observations: [
{
id: 'o-legacy',
zones: [
{ boneId: 'point-mpbyphay', detailSourceId: 'head' },
{ boneId: 'point-gone' },
],
findings: [
{
zoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
labelFrSnapshot: 'Suture sphéno-zygomatique',
labelEnSnapshot: 'Sphenozygomatic suture',
},
],
freeTextFindings: [],
comment: '',
severity: 'légère',
},
],
}
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify(v2)),
'osteo-report.json',
{ mimeType: 'application/json' },
)
const out = await importReportFromPdf(
await doc.save(),
sheet.sheet.migrationMap,
)
const [obs] = out.report.observations
expect(obs!.zones).toEqual([
expect.objectContaining({
annotationId: 'ssb',
viewId: 'head',
labelFrSnapshot: 'Synchondrose Sphéno-Basilaire (SSB)',
}),
expect.objectContaining({
annotationId: 'point-gone',
viewId: 'main',
unresolved: true,
}),
])
expect(obs!.findings[0]).toMatchObject({
findingZoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
unresolved: true,
labelFrSnapshot: 'Suture sphéno-zygomatique',
})
expect(obs!.severity).toBe('mild')
expect(out.unresolvedFindings).toBe(1)
expect(out.unresolvedZones).toBe(1)
// The migrated document is a valid v3 document: exporting it again keeps the flags.
const again = await importReportFromPdf(
await exportReportToPdf(out.report, sheet, { locale: 'en' }),
sheet.sheet.migrationMap,
)
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
})
it('migrates the minimal v2 report', async () => {
const out = await importReportFromPdf(
fixture('report-v2.minimal.pdf'),
sheet.sheet.migrationMap,
)
expect(out.report.version).toBe(3)
expect(out.report.observations).toEqual([])
expect(out.unresolvedFindings + out.unresolvedZones).toBe(0)
})
it('refuses unknown versions and unrelated PDFs with typed errors', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify({ version: 7 })),
'osteo-report.json',
{ mimeType: 'application/json' },
)
await expect(
importReportFromPdf(await doc.save(), sheet.sheet.migrationMap),
).rejects.toMatchObject({ kind: 'incompatible_version', foundVersion: 7 })
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(
importReportFromPdf(fake, sheet.sheet.migrationMap),
).rejects.toThrow(ImportError)
})
})