Files
faunosteo/apps/app/tests/unit/pdf.roundtrip.test.ts
T

467 lines
16 KiB
TypeScript

/**
* 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 { AFRelationship, 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 { 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'
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 fixture = (name: string) =>
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
let sheet: SheetIndex
let drawn: string[] = []
const fetched: string[] = []
const realFetch = globalThis.fetch
beforeAll(async () => {
sheet = await loadTestSheet()
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(() => {
globalThis.fetch = realFetch
})
beforeEach(() => {
drawn = []
fetched.length = 0
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('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 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')
})
})
/** 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(
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)
})
})