Files
faunosteo/src/pdf/export.ts
T
ZenQuality b5b2e163c9 feat: domain core — schemas, store, equine data, PDF roundtrip
Phase A — Domain & schemas (15 tests):
- Zod schemas: ReportSchema, FindingSchema, PractitionerSchema, SeveritySchema
- Types derived via z.infer (single source of truth)
- newId() helper with optional prefix

Phase B — Equine anatomy + pathology DB (7 tests):
- 26 macro zones, axial subzones C1-7/T1-18/L1-6/S1-5
- 31 pathologies, each citing Merck Vet Manual, PubMed, IMAIOS or LCAO
- Placeholder SVGs (lateral L/R + dorsal) with data-zone convention
- Species registry: equine registered, 8 others remain stubs

Phase C — Zustand store (8 tests):
- Single source of truth with persist middleware (localStorage key osteo-report-draft)
- Actions: hydrate, reset, toggleZone, addFinding, updateFinding, removeFinding, setConclusion/Recommendations/NextAppointment

Phase H/I — PDF export + import roundtrip (2 tests):
- A4 portrait, pdf-lib StandardFonts
- Header (practitioner + animal), anatomy pages (per used view), findings
  table, conclusion/recommendations/RDV page, page footer with date+page#
- Attachment: base64 data URI workaround (pdf-lib treats raw string as
  base64 input, and rejects cross-realm Uint8Array in jsdom tests)
- Import: walks Catalog→Names→EmbeddedFiles→Names array→F stream; inflates
  via pako directly (bypasses pdf-lib's reference-equality FlateDecode check
  which fails across module realms in vitest); validates with ReportSchema

Tooling:
- Add pako 2.x + @types/pako (already transitive of pdf-lib)
- Switch vitest 2 → 3 (already done in prior commit)
- Add 8 test files (34 tests total green)
2026-05-17 07:06:59 +02:00

248 lines
8.2 KiB
TypeScript

import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
import { FR } from '../i18n/fr';
import { formatDateFr } from '../lib/date';
import type { Report } from '../schema/report';
import type { SpeciesAnatomy } from '../species/types';
import { PDF_ATTACHMENT_NAME } from './version';
const A4 = { width: 595.28, height: 841.89 } as const;
const MARGIN = 48;
const FOOT = 32;
export interface AnatomyAssets {
anatomy: SpeciesAnatomy;
rasters: Partial<Record<'lateral_left' | 'lateral_right' | 'dorsal', Uint8Array | ArrayBuffer>>;
}
function zoneLabel(anatomy: SpeciesAnatomy, id: string): string {
return anatomy.zones.find((z) => z.id === id)?.label ?? id;
}
export async function exportReportBytes(report: Report, assets: AnatomyAssets): Promise<Uint8Array> {
const pdf = await PDFDocument.create();
pdf.setTitle(`Bilan ostéopathique — ${report.animal.name}`);
pdf.setAuthor(report.practitioner.fullName);
pdf.setSubject(FR.app.tagline);
pdf.setCreator(FR.app.name);
pdf.setProducer('pdf-lib');
pdf.setCreationDate(new Date(report.createdAt));
const font = await pdf.embedFont(StandardFonts.Helvetica);
const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);
let page = pdf.addPage([A4.width, A4.height]);
let y = A4.height - MARGIN;
// ───────── Header
page.drawText(FR.app.name, {
x: MARGIN,
y,
size: 18,
font: fontBold,
color: rgb(0.29, 0.49, 0.35),
});
page.drawText(FR.app.tagline, { x: MARGIN, y: y - 16, size: 9, font, color: rgb(0.4, 0.4, 0.4) });
y -= 36;
page.drawText(`Animal : ${report.animal.name}`, { x: MARGIN, y, size: 11, font: fontBold });
page.drawText(`Propriétaire : ${report.animal.owner}`, { x: MARGIN, y: y - 14, size: 11, font });
page.drawText(`Séance : ${formatDateFr(report.sessionDate)}`, { x: MARGIN, y: y - 28, size: 11, font });
const practX = A4.width / 2 + 20;
page.drawText(report.practitioner.fullName, { x: practX, y, size: 11, font: fontBold });
let practY = y - 14;
for (const line of [
report.practitioner.title,
report.practitioner.phone,
report.practitioner.email,
report.practitioner.address,
report.practitioner.siret ? `SIRET ${report.practitioner.siret}` : undefined,
]) {
if (!line) continue;
page.drawText(line, { x: practX, y: practY, size: 10, font });
practY -= 12;
}
y = Math.min(y - 60, practY - 24);
page.drawLine({
start: { x: MARGIN, y },
end: { x: A4.width - MARGIN, y },
thickness: 0.6,
color: rgb(0.29, 0.49, 0.35),
});
y -= 20;
// ───────── Anatomy pages (one per view with selected zones)
const viewLabels: Record<keyof AnatomyAssets['rasters'], string> = {
lateral_left: 'Vue latérale gauche',
lateral_right: 'Vue latérale droite',
dorsal: 'Vue dorsale',
};
const viewsInUse = new Set<keyof AnatomyAssets['rasters']>();
for (const f of report.findings) {
for (const zId of [...f.zones, ...f.linkedZones]) {
const z = assets.anatomy.zones.find((zz) => zz.id === zId);
if (!z) continue;
for (const v of z.views) viewsInUse.add(v);
}
}
for (const view of viewsInUse) {
const raster = assets.rasters[view];
if (!raster) continue;
page = pdf.addPage([A4.width, A4.height]);
page.drawText(viewLabels[view], {
x: MARGIN,
y: A4.height - MARGIN,
size: 14,
font: fontBold,
});
const png = await pdf.embedPng(raster);
const maxW = A4.width - MARGIN * 2;
const maxH = A4.height - MARGIN * 2 - 50;
const ratio = Math.min(maxW / png.width, maxH / png.height);
const w = png.width * ratio;
const h = png.height * ratio;
page.drawImage(png, { x: MARGIN, y: A4.height - MARGIN - 30 - h, width: w, height: h });
}
// ───────── Findings table
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
page.drawText('Observations cliniques', { x: MARGIN, y, size: 14, font: fontBold });
y -= 22;
if (report.findings.length === 0) {
page.drawText('Aucune observation enregistrée.', { x: MARGIN, y, size: 10, font });
}
for (let i = 0; i < report.findings.length; i++) {
const f = report.findings[i];
if (!f) continue;
if (y < MARGIN + 120) {
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
}
const zones = f.zones.map((id) => zoneLabel(assets.anatomy, id)).join(', ');
const linked = f.linkedZones.length
? ` (liées : ${f.linkedZones.map((id) => zoneLabel(assets.anatomy, id)).join(', ')})`
: '';
const pathos = f.pathologies.map((p) => p.label).join(', ') || '—';
const sev = FR.severity[f.severity] ?? f.severity;
page.drawText(`#${(i + 1).toString()} ${zones}${linked}`, {
x: MARGIN,
y,
size: 11,
font: fontBold,
});
page.drawText(`Pathologies : ${pathos}`, { x: MARGIN, y: y - 14, size: 10, font });
page.drawText(`Sévérité : ${sev}`, { x: MARGIN, y: y - 28, size: 10, font });
if (f.comment) {
const wrapped = wrap(f.comment, 90);
let yy = y - 44;
page.drawText('Commentaire :', { x: MARGIN, y: yy, size: 10, font: fontBold });
yy -= 14;
for (const line of wrapped) {
page.drawText(line, { x: MARGIN + 8, y: yy, size: 10, font });
yy -= 12;
}
y = yy - 8;
} else {
y -= 50;
}
}
// ───────── Conclusion + recommandations + RDV
if (report.conclusion || report.recommendations || report.nextAppointment) {
page = pdf.addPage([A4.width, A4.height]);
y = A4.height - MARGIN;
if (report.conclusion) {
page.drawText('Conclusion', { x: MARGIN, y, size: 14, font: fontBold });
y -= 20;
for (const line of wrap(report.conclusion, 90)) {
page.drawText(line, { x: MARGIN, y, size: 11, font });
y -= 14;
}
y -= 12;
}
if (report.recommendations) {
page.drawText('Recommandations', { x: MARGIN, y, size: 14, font: fontBold });
y -= 20;
for (const line of wrap(report.recommendations, 90)) {
page.drawText(line, { x: MARGIN, y, size: 11, font });
y -= 14;
}
y -= 12;
}
if (report.nextAppointment) {
page.drawText(`Prochain rendez-vous : ${formatDateFr(report.nextAppointment)}`, {
x: MARGIN,
y,
size: 12,
font: fontBold,
});
}
}
// ───────── Footer on each page
const pages = pdf.getPages();
const exported = new Date().toISOString().slice(0, 10);
for (let i = 0; i < pages.length; i++) {
const p = pages[i];
if (!p) continue;
p.drawText(`${FR.app.name} · exporté le ${formatDateFr(exported)} · page ${(i + 1).toString()}/${pages.length.toString()}`, {
x: MARGIN,
y: FOOT,
size: 8,
font,
color: rgb(0.45, 0.45, 0.45),
});
}
// ───────── Attach report.json
// pdf-lib's `attach` treats a raw string as base64-data-URI input (not as
// UTF-8 text), and rejects cross-realm Uint8Array/ArrayBuffer in tests.
// Wrap the JSON in a base64 data-URI string so it's portable everywhere.
const json = JSON.stringify(report);
const jsonBytes = new TextEncoder().encode(json);
let base64 = '';
const chunk = 8192;
for (let i = 0; i < jsonBytes.length; i += chunk) {
base64 += String.fromCharCode(
...jsonBytes.subarray(i, Math.min(i + chunk, jsonBytes.length)),
);
}
const dataUri = `data:application/json;base64,${btoa(base64)}`;
await pdf.attach(dataUri, PDF_ATTACHMENT_NAME, {
mimeType: 'application/json',
description: 'Données sources du bilan (réimport possible).',
creationDate: new Date(report.createdAt),
modificationDate: new Date(),
});
return pdf.save();
}
export async function exportReport(report: Report, assets: AnatomyAssets): Promise<Blob> {
const bytes = await exportReportBytes(report, assets);
return new Blob([bytes], { type: 'application/pdf' });
}
function wrap(text: string, max: number): string[] {
const words = text.split(/\s+/);
const lines: string[] = [];
let buf = '';
for (const w of words) {
if ((buf + ' ' + w).trim().length > max) {
lines.push(buf);
buf = w;
} else {
buf = (buf + ' ' + w).trim();
}
}
if (buf) lines.push(buf);
return lines;
}