Files
faunosteo/apps/app/tests/unit/char.pdfFull.test.ts
T
bchanot 8673475293 chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates
dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and
pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager,
root devDependency, engine-strict). Dockerfile builds @faunosteo/app on
node:24-alpine and copies apps/app/dist; nginx and runtime config
unchanged. CI workflow for Gitea Actions. packages/ reserved (README only).
Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan.
271/271 tests, typecheck, lint, build green from the root.
2026-10-08 21:51:13 +02:00

251 lines
11 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.
/**
* Characterisation (Step 1): the full PDF pipeline on the golden fixture
* (every zone kind, findings with vet flag and side, free text, severity,
* comment, conclusion, next appointment): page count, drawn text, attachment
* roundtrip, import error kinds, and the attachment fallback path.
*
* Text is captured by spying on PDFPage.drawText (pdf-lib has no text
* extraction). Rasterization is replaced by a 1×1 PNG: happy-dom has no
* canvas. SVG fetches are served from the committed files; logo fetches 404
* on purpose to pin the "PDF without logos" degradation.
*/
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } 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 { exportReportToPdf } from '@/pdf/export'
import { importReportFromPdf, ImportError } from '@/pdf/import'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
import full from '../fixtures/report-v2.full.json'
import type { Report } from '@/domain/schema/report'
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 FILES: Record<string, string> = {
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
}
const fetched: string[] = []
const realFetch = globalThis.fetch
beforeAll(() => {
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = String(input)
fetched.push(url)
const text = FILES[url]
if (text) return new Response(text, { status: 200, headers: { 'content-type': 'image/svg+xml' } })
return new Response('not found', { status: 404 })
}) as typeof fetch
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
})
afterAll(() => {
globalThis.fetch = realFetch
})
const report = full as Report
let drawn: string[] = []
beforeEach(() => {
drawn = []
fetched.length = 0
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (this: PDFPage, text: string) {
drawn.push(text)
} as never)
})
/** Rebuilds wrapped values: lines are drawn one by one, joined by a space. */
const joined = () => drawn.join(' ').replace(/\s+/g, ' ')
describe('export on the full fixture (FR)', () => {
it('produces one page per observation plus a conclusion page', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
expect(doc.getPageCount()).toBe(report.observations.length + 1)
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
expect(doc.getAuthor()).toBe('Dr. Claire Dupont')
})
it('re-fetches the SVGs from public/ and the logos at export time (external dependencies)', async () => {
await exportReportToPdf(report, { locale: 'fr' })
const svgFetches = fetched.filter((u) => u.endsWith('.svg') && u.includes('/species/'))
// buildZoneLabels (2) + one colorized view per rendered image (general ×2, head ×1)
expect(svgFetches.filter((u) => u.endsWith('Horse.svg')).length).toBeGreaterThanOrEqual(3)
expect(svgFetches.filter((u) => u.endsWith('Horse_head.svg')).length).toBeGreaterThanOrEqual(2)
expect(fetched.some((u) => u.includes('/assets/') && u.endsWith('.png'))).toBe(true)
})
it('draws the ZONES section as bullet rows with vertebrae and side suffixes', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.zones'])
const zonesIdx = drawn.indexOf(fr['pdf.section.zones'])
// The ' · ' joined value is split back into one row per zone with a bullet glyph.
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)')
})
it('draws one CONSTATS section per (catalog zone, side) with snapshot labels and the (!) vet marker', async () => {
await exportReportToPdf(report, { locale: 'fr' })
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(`${prefix}VERTÈBRES CERVICALES`)
expect(drawn).toContain(`${prefix}ARTICULATION TEMPORO-MANDIBULAIRE (ATM)`)
expect(drawn).toContain('Fixation de la charnière')
expect(drawn).toContain('Restriction en flexion')
expect(drawn.some((l) => l.startsWith('(!) Trébuchements'))).toBe(true)
expect(drawn).toContain('(!) Headshaking (secouement de tête)')
})
it('draws free findings, severity, comment, and the view captions', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.free_findings'])
expect(drawn).toContain('Sensibilité au garrot')
expect(drawn).toContain(fr['pdf.section.severity'])
expect(drawn).toContain(fr['severity.modérée'])
expect(drawn).toContain(fr['severity.sévère'])
expect(drawn).toContain(fr['pdf.section.comment'])
expect(drawn).toContain('Réagit à la palpation du garrot.')
expect(drawn.filter((l) => l === fr['pdf.view.general'])).toHaveLength(2)
expect(drawn).toContain(`${fr['pdf.view.detail_prefix']}HEAD`)
})
it('draws the conclusion page and the header identity on every page', async () => {
await exportReportToPdf(report, { locale: 'fr' })
expect(drawn).toContain(fr['pdf.section.conclusion'])
expect(drawn).toContain(fr['pdf.section.recommendations'])
expect(drawn).toContain(fr['pdf.section.next_appointment'])
expect(joined()).toContain('Dysfonction cervico-thoracique avec compensation du bassin.')
expect(drawn.filter((l) => l === 'Dr. Claire Dupont').length).toBe(4)
expect(drawn.filter((l) => l.includes('12345678901234')).length).toBe(4)
})
it('uses the EN snapshots and dictionary when locale=en, same attachment bytes', async () => {
const frBytes = await exportReportToPdf(report, { locale: 'fr' })
const frDrawn = [...drawn]
drawn = []
const enBytes = await exportReportToPdf(report, { locale: 'en' })
expect(drawn).toContain(en['pdf.section.zones'])
expect(drawn).toContain(`${en['pdf.section.findings_prefix']}HIP JOINT (LEFT)`)
expect(drawn).toContain('Junction fixation')
expect(drawn).toContain('(!) Headshaking')
expect(frDrawn).not.toContain('Junction fixation')
const a = await importReportFromPdf(frBytes)
const b = await importReportFromPdf(enBytes)
expect(a).toEqual(b)
})
})
describe('roundtrip and import', () => {
it('re-imports the full fixture unchanged (deep equality)', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const imported = await importReportFromPdf(bytes)
expect(imported).toEqual(report)
})
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, description "Faunosteo state v2"', async () => {
const bytes = await exportReportToPdf(report, { locale: 'fr' })
const doc = await PDFDocument.load(bytes)
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) => String(o))
const filespec = objects.find((s) => s.includes('/Type /Filespec'))!
expect(filespec).toContain('/F (osteo-report.json)')
expect(filespec).toContain('/AFRelationship /Data')
// /Desc is a UTF-16BE hex string: "Faunosteo state v2"
expect(filespec).toContain('/Desc <FEFF004600610075006E006F007300740065006F002000730074006100740065002000760032>')
const embedded = objects.find((s) => s.includes('/Type /EmbeddedFile'))!
expect(embedded).toContain('/Subtype /application#2Fjson')
expect(embedded).toContain('/Filter /FlateDecode')
expect(objects.some((s) => s.includes('/EmbeddedFiles'))).toBe(true)
})
it('pdf-lib 1.17.1 has no getAttachments: the object-traversal fallback IS the import path', async () => {
expect(typeof (PDFDocument.prototype as unknown as { getAttachments?: unknown }).getAttachments).toBe('undefined')
})
it('reports incompatible_version with the found version for a v3 attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode(JSON.stringify({ ...report, version: 3 })), 'osteo-report.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect(err).toBeInstanceOf(ImportError)
expect((err as ImportError).kind).toBe('incompatible_version')
expect((err as ImportError).foundVersion).toBe(3)
})
it('KNOWN: a foreign JSON attachment is picked up by the traversal and fails as no_attachment', async () => {
const doc = await PDFDocument.create()
doc.addPage()
await doc.attach(new TextEncoder().encode('{"hello":1}'), 'other.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect(err).toBeInstanceOf(ImportError)
expect((err as ImportError).kind).toBe('no_attachment')
})
it('KNOWN: a Zod-invalid report attachment is also reported as no_attachment (cause lost)', async () => {
const doc = await PDFDocument.create()
doc.addPage()
const broken = { ...report, practitioner: { name: '' } }
await doc.attach(new TextEncoder().encode(JSON.stringify(broken)), 'osteo-report.json', {
mimeType: 'application/json',
afRelationship: AFRelationship.Data,
})
const err = await importReportFromPdf(await doc.save()).catch((e) => e)
expect((err as ImportError).kind).toBe('no_attachment')
})
it('an orphan finding (zone removed) is still printed under its catalog zone', async () => {
const orphaned: Report = {
...report,
observations: [{ ...report.observations[0], zones: [] }],
}
await exportReportToPdf(orphaned, { locale: 'fr' })
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}CHARNIÈRE C7-T1 (CERVICO-THORACIQUE)`)
expect(drawn).toContain(fr['pdf.empty'])
})
it('an unknown boneId is printed raw and an unknown zoneId is printed raw', async () => {
const stale: Report = {
...report,
observations: [
{
...report.observations[0],
zones: [{ boneId: 'point-gone' }],
findings: [
{
zoneId: 'zone-gone',
path: ['x'],
labelFrSnapshot: 'Snapshot FR',
labelEnSnapshot: 'Snapshot EN',
},
],
},
],
}
await exportReportToPdf(stale, { locale: 'fr' })
expect(drawn).toContain('point-gone')
expect(drawn).toContain(`${fr['pdf.section.findings_prefix']}ZONE-GONE`)
expect(drawn).toContain('Snapshot FR')
})
})