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

522 lines
19 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Replaces char.pdfFull / pdf.roundtrip / pdf.zoneLabels: the application
* export path on the core's session with the bundled sheet (drawn strings
* from the document, read back from the file's content streams since R4.6,
* envelope attachment, roundtrip FR/EN) and the import of the frozen v2
* archive PDFs, migrated without silent loss.
*/
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import type { Observation, Report } from '@faunosteo/core-wasm/types'
import { exportReportToPdf } from '@/pdf/export'
import { browserRasterizer } from '@/pdf/browserRasterizer'
import { defaultPdfLabels } from '@/pdf/labels'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { importReportFromPdf, ImportError } from '../helpers/pdfImport'
import {
PdfFile,
buildPdfWithAttachment,
nameOf,
textOf,
} from '../helpers/pdfFile'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
import { bytesOf, readDrawing } from '../helpers/pdfRead'
// The fixed 1×1 PNG for every raster; the view SVGs the session asks for are kept.
const raster = vi.hoisted(() => ({ svgs: [] as string[] }))
vi.mock('@/pdf/browserRasterizer', async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return {
browserRasterizer: vi.fn(async (svg: string) => {
raster.svgs.push(svg)
return ONE_PX_PNG
}),
}
})
/** The layered reading the application does on import (the core's reader). */
async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes)).read
}
const pageCount = (bytes: Uint8Array) => PdfFile.parse(bytes).pages().length
/** The static PDF strings belong to the app's label set. */
const { fr, en } = defaultPdfLabels
/**
* The bytes of an app export (its warnings are not under test here); `drawn` holds the
* texts of its content streams, in draw order.
*/
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
raster.svgs = []
const bytes = await bytesOf(
(await exportReportToPdf(report, sheet, { locale })).pdf,
)
drawn = (await readDrawing(bytes)).texts.map((t) => t.text)
return bytes
}
const HERE = dirname(fileURLToPath(import.meta.url))
const fixture = (name: string) =>
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
let sheet: SheetIndex
let drawn: string[] = []
beforeAll(async () => {
sheet = await loadTestSheet()
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => vi.restoreAllMocks())
/** 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 exportPdf(report, 'fr')
expect(pageCount(bytes)).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 the envelope and roundtrips in both locales', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
for (const locale of ['fr', 'en'] as const) {
const bytes = await exportPdf(report, locale)
const out = await readBack(bytes)
expect(out.migrated).toBe(false)
expect(out.origin).toBe('envelope_v1')
expect(out.report).toEqual(report)
expect(out.archive?.locale).toBe(locale)
expect(out.archive?.sheetSnapshot.ref.documentSha256).toBe(
sheet.sheet.ref.documentSha256,
)
}
})
// The core composes only the observation's markers (the browser pipeline
// hid the others with display="none"); the view facts are frozen in
// pdf.goldens.test.ts "highlighted views". The SVGs are the ones the
// session asked the rasteriser for: the bundled partner logo (the one SVG
// logo) first, then the main view, then the head.
it('highlights the observation zones of a view and omits the other markers', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
await exportPdf(report, 'fr')
expect(raster.svgs).toHaveLength(3)
const [svg, head] = raster.svgs.slice(1)
expect(svg).toContain('viewBox="0 0 2073.4 1629.4"')
expect(svg).toContain('fill="#b85a3f"')
expect(svg).toContain('url(#osteo-halo)')
expect(svg).not.toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
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 exportPdf(fullReport(), '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 exportPdf(report, '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 exportPdf(fullReport(), '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 exportPdf(report, 'fr')
const pages = pageCount(bytes)
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 and the archive keyword', async () => {
const bytes = await exportPdf(fullReport(), 'fr')
const info = PdfFile.parse(bytes).info().dict
expect(textOf(info, 'Title')).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(textOf(info, 'Author')).toBe('Dr. Dupont')
expect(textOf(info, 'Subject')).toBe(fr['pdf.subject'])
expect(textOf(info, 'Keywords')).toContain('faunosteo-archive/1')
})
it('embeds the four bundled logos without any network request', async () => {
const fetchSpy = vi.fn()
vi.stubGlobal('fetch', fetchSpy)
try {
const { pdf, warnings } = await exportReportToPdf(fullReport(), sheet, {
locale: 'fr',
})
expect(fetchSpy).not.toHaveBeenCalled()
expect(warnings).toEqual([])
const out = await readBack(await bytesOf(pdf))
const branding = out.archive!.branding
expect(branding.headerLogo?.kind).toBe('png')
expect(branding.footerLogo?.kind).toBe('png')
expect(branding.poweredBy?.logo?.kind).toBe('png')
expect(branding.partner?.logo?.kind).toBe('svg')
} finally {
vi.unstubAllGlobals()
}
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
const bytes = await exportPdf(fullReport(), 'fr')
const objects = PdfFile.parse(bytes).all()
const filespec = objects.find((o) => nameOf(o.dict, 'Type') === 'Filespec')!
expect(textOf(filespec.dict, 'F')).toBe('osteo-report.json')
expect(textOf(filespec.dict, 'UF')).toBe('osteo-report.json')
expect(nameOf(filespec.dict, 'AFRelationship')).toBe('Data')
expect(textOf(filespec.dict, 'Desc')).toBe('Faunosteo report archive v1')
const embedded = objects.find(
(o) => nameOf(o.dict, 'Type') === 'EmbeddedFile',
)!
expect(nameOf(embedded.dict, 'Filter')).toBe('FlateDecode')
expect(embedded.stream).not.toBeNull()
})
})
describe('a raster the browser cannot draw', () => {
it('is a view_raster_failed warning; the export continues without that image', async () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const whole = await readDrawing(await exportPdf(report, 'fr'))
const failing = vi.mocked(browserRasterizer)
failing.mockImplementation(async (svg) => {
// The head view's picture is framed on the head's own viewBox.
if (svg.includes('viewBox="60 100 500 380"')) {
throw new Error('canvas lost')
}
const { ONE_PX_PNG } = await import('../helpers/goldens')
return ONE_PX_PNG
})
try {
const { pdf, warnings } = await exportReportToPdf(report, sheet, {
locale: 'fr',
})
expect(warnings).toEqual([
{
kind: 'view_raster_failed',
observationId: 'obs-full',
viewId: 'head',
},
])
const bytes = await bytesOf(pdf)
const { images, texts } = await readDrawing(bytes)
// One image fewer on the observation page (the head view), the logos and
// the main view drawn; the page keeps its texts and the file still
// carries the whole report.
expect(images.filter((i) => i.page === 0)).toHaveLength(
whole.images.filter((i) => i.page === 0).length - 1,
)
expect(texts.map((t) => t.text)).toContain(fr['pdf.view.general']!)
expect(texts.map((t) => t.text)).not.toContain(
`${fr['pdf.view.detail_prefix']}TÊTE (VUE LATÉRALE GAUCHE)`,
)
expect((await readBack(bytes)).report).toEqual(report)
} finally {
failing.mockImplementation(async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return ONE_PX_PNG
})
}
})
})
describe('attachment rejection', () => {
const pdfWith = (name: string, payload: unknown): Uint8Array =>
buildPdfWithAttachment(
name,
new TextEncoder().encode(JSON.stringify(payload)),
)
it('reports no_attachment for a foreign JSON attachment (no version)', async () => {
const bytes = pdfWith('other.json', { hello: 'world' })
await expect(importReportFromPdf(bytes)).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 = pdfWith('osteo-report.json', broken)
await expect(importReportFromPdf(bytes)).rejects.toMatchObject({
kind: 'no_attachment',
})
})
it('reads the same attachment through the core when the report is sound', async () => {
const report = minimalReport(sheet)
const out = await readBack(pdfWith('osteo-report.json', report))
expect(out.origin).toBe('bare_v3')
expect(out.report).toEqual(report)
})
})
describe('import of the frozen v2 archive PDFs', () => {
it('migrates the full v2 report: ids, views, paths, severities, unresolved findings', async () => {
const out = await readBack(fixture('report-v2.full.pdf'))
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 readBack(await exportPdf(report, 'fr'))
expect(again.report).toEqual(report)
expect(again.migrated).toBe(false)
expect(again.origin).toBe('envelope_v1')
})
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 out = await readBack(
buildPdfWithAttachment(
'osteo-report.json',
new TextEncoder().encode(JSON.stringify(v2)),
),
)
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 readBack(await exportPdf(out.report, 'en'))
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
})
it('migrates the minimal v2 report', async () => {
const out = await readBack(fixture('report-v2.minimal.pdf'))
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 v7 = buildPdfWithAttachment(
'osteo-report.json',
new TextEncoder().encode(JSON.stringify({ version: 7 })),
)
await expect(importReportFromPdf(v7)).rejects.toMatchObject({
kind: 'incompatible_version',
foundVersion: 7,
})
const fake = new Uint8Array([37, 80, 68, 70, 45, 49, 46, 52, 10])
await expect(importReportFromPdf(fake)).rejects.toThrow(ImportError)
})
})