313 lines
10 KiB
TypeScript
313 lines
10 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 { 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 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 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('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')
|
|
})
|
|
})
|
|
|
|
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)
|
|
})
|
|
})
|