Files
faunosteo/apps/app/tests/unit/pdf.roundtrip.test.ts
T
bchanot 74fcb37564 feat(app): R2 switch — the application runs its domain rules in the Rust core
Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
  (SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
  (v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
  (zone.add_sides, vertebra.initial / sync / select), the findings picker
  (finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
  layered reading and rebase in one call; the export: the core builds the
  sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
2026-10-14 00:41:34 +02:00

475 lines
17 KiB
TypeScript
Raw 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 engine with the bundled sheet (drawn strings from the
* document, envelope attachment, 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, Report } from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
import { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { formatDate } from '@/lib/dates'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet, minimalReport, sheetSnapshot } from '../helpers/sheet'
// The factory runs when the engine first loads the adapter: fixed 1×1 PNG.
vi.mock('@/pdf/browserRasterizer', async () => {
const { ONE_PX_PNG } = await import('../helpers/goldens')
return { browserRasterizer: vi.fn(async () => ONE_PX_PNG) }
})
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
/** The layered reading the application does on import (the core's read part). */
async function readBack(bytes: Uint8Array) {
return (await importReportFromPdf(bytes, sheet)).read
}
/** The static PDF strings now belong to the engine's label set. */
const { fr, en } = defaultPdfLabels
/** The bytes of an app export (its warnings are not under test here). */
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
return (await exportReportToPdf(report, sheet, { locale })).pdf
}
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())
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('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')
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 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 engine draws 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".
it('highlights the observation zones of a view and omits the other markers', () => {
const report = minimalReport(sheet, { observations: [fullObservation()] })
const snapshot = sheetSnapshot(sheet, report) as EngineView[0]
const svg = composeHighlightedViewSvg(snapshot, '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).not.toContain('display="none"')
expect(svg).not.toContain('data-anno-id')
const head = composeHighlightedViewSvg(snapshot, '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 exportPdf(report, '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 and the archive keyword', async () => {
const bytes = await exportPdf(fullReport(), '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'])
expect(doc.getKeywords()).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(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 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 report archive v1'))
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)).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)).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 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 doc = await PDFDocument.create()
doc.addPage()
await doc.attach(
new TextEncoder().encode(JSON.stringify(v2)),
'osteo-report.json',
{ mimeType: 'application/json' },
)
const out = await readBack(await doc.save())
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 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),
).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)).rejects.toThrow(ImportError)
})
})