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)
This commit is contained in:
1 parent
4c465a5743
commit
b5b2e163c9
20 files changed
+1383
-41
No files matched your search
+241
-3
@@ -1,9 +1,247 @@
|
||||
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 {
|
||||
svg: Record<string, string>;
|
||||
anatomy: SpeciesAnatomy;
|
||||
rasters: Partial<Record<'lateral_left' | 'lateral_right' | 'dorsal', Uint8Array | ArrayBuffer>>;
|
||||
}
|
||||
|
||||
export function exportReport(_report: Report, _assets: AnatomyAssets): Promise<Blob> {
|
||||
return Promise.reject(new Error('exportReport not implemented'));
|
||||
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;
|
||||
}
|
||||
+100
-2
@@ -1,5 +1,11 @@
|
||||
import * as pako from 'pako';
|
||||
import { PDFDocument, PDFName, type PDFRawStream } from 'pdf-lib';
|
||||
|
||||
import { ReportSchema } from '../schema/report';
|
||||
import type { Report } from '../schema/report';
|
||||
|
||||
import { PDF_ATTACHMENT_NAME } from './version';
|
||||
|
||||
export type ImportFailure =
|
||||
| { ok: false; reason: 'NO_ATTACHMENT' }
|
||||
| { ok: false; reason: 'INVALID_JSON'; details?: string }
|
||||
@@ -8,6 +14,98 @@ export type ImportFailure =
|
||||
|
||||
export type ImportResult = { ok: true; report: Report } | ImportFailure;
|
||||
|
||||
export function importReport(_file: File): Promise<ImportResult> {
|
||||
return Promise.reject(new Error('importReport not implemented'));
|
||||
export async function importReport(file: File | Blob | ArrayBuffer | Uint8Array): Promise<ImportResult> {
|
||||
let pdf: PDFDocument;
|
||||
try {
|
||||
const buf = await toBytes(file);
|
||||
pdf = await PDFDocument.load(buf, { ignoreEncryption: true });
|
||||
} catch (e) {
|
||||
return { ok: false, reason: 'UNREADABLE_PDF', details: (e as Error).message };
|
||||
}
|
||||
|
||||
const json = extractAttachment(pdf, PDF_ATTACHMENT_NAME);
|
||||
if (!json) return { ok: false, reason: 'NO_ATTACHMENT' };
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
const decoded = new TextDecoder().decode(json);
|
||||
parsed = JSON.parse(decoded);
|
||||
} catch (e) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'INVALID_JSON',
|
||||
details: `${(e as Error).message} | first 80 bytes: ${Array.from(json.slice(0, 80))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join(' ')}`,
|
||||
};
|
||||
}
|
||||
|
||||
const result = ReportSchema.safeParse(parsed);
|
||||
if (!result.success) {
|
||||
return { ok: false, reason: 'SCHEMA_MISMATCH', details: result.error.message };
|
||||
}
|
||||
return { ok: true, report: result.data };
|
||||
}
|
||||
|
||||
async function toBytes(input: File | Blob | ArrayBuffer | Uint8Array): Promise<Uint8Array> {
|
||||
if (input instanceof Uint8Array) return input;
|
||||
if (input instanceof ArrayBuffer) return new Uint8Array(input);
|
||||
return new Uint8Array(await input.arrayBuffer());
|
||||
}
|
||||
|
||||
function extractAttachment(pdf: PDFDocument, name: string): Uint8Array | null {
|
||||
// Walk catalog → Names → EmbeddedFiles → Names array → filespec → EF → F
|
||||
// pdf-lib has no public attachment-extract API, so we navigate the tree.
|
||||
const catalog = pdf.catalog;
|
||||
const names = catalog.lookup(PDFName.of('Names')) as
|
||||
| { lookup?: (n: PDFName) => unknown }
|
||||
| undefined;
|
||||
if (!names?.lookup) return null;
|
||||
const embeddedFiles = names.lookup(PDFName.of('EmbeddedFiles')) as
|
||||
| { lookup?: (n: PDFName) => unknown }
|
||||
| undefined;
|
||||
if (!embeddedFiles?.lookup) return null;
|
||||
const namesArr = embeddedFiles.lookup(PDFName.of('Names')) as
|
||||
| { size?: () => number; lookup?: (i: number) => unknown }
|
||||
| undefined;
|
||||
if (!namesArr?.lookup || typeof namesArr.size !== 'function') return null;
|
||||
const size = namesArr.size();
|
||||
for (let i = 0; i < size; i += 2) {
|
||||
const k = namesArr.lookup(i) as { decodeText?: () => string } | undefined;
|
||||
const fname = k?.decodeText?.();
|
||||
if (fname !== name) continue;
|
||||
const fileSpec = namesArr.lookup(i + 1) as
|
||||
| { lookup?: (n: PDFName) => unknown }
|
||||
| undefined;
|
||||
if (!fileSpec?.lookup) continue;
|
||||
const ef = fileSpec.lookup(PDFName.of('EF')) as
|
||||
| { lookup?: (n: PDFName) => unknown }
|
||||
| undefined;
|
||||
if (!ef?.lookup) continue;
|
||||
const stream = (ef.lookup(PDFName.of('F')) ?? ef.lookup(PDFName.of('UF'))) as
|
||||
| { dict?: unknown; contents?: Uint8Array }
|
||||
| undefined;
|
||||
if (!stream) continue;
|
||||
// Duck-type instead of `instanceof PDFRawStream` (instanceof fails when
|
||||
// multiple pdf-lib realms coexist, e.g. during tests).
|
||||
if (stream.dict !== undefined && stream.contents !== undefined) {
|
||||
const s = stream as PDFRawStream;
|
||||
const filter = (s.dict as { lookup?: (n: PDFName) => unknown }).lookup?.(
|
||||
PDFName.of('Filter'),
|
||||
);
|
||||
const filterName = (filter as { encodedName?: string } | undefined)?.encodedName;
|
||||
// We bypass pdf-lib's `decodePDFRawStream` because its reference-equality
|
||||
// check on `PDFName.of('FlateDecode')` is unreliable across module realms
|
||||
// (e.g. when vitest dual-loads pdf-lib). Use pako directly on raw bytes.
|
||||
if (filterName === '/FlateDecode') {
|
||||
return pako.inflate(s.contents);
|
||||
}
|
||||
if (filterName === undefined || filter === null) {
|
||||
return s.contents;
|
||||
}
|
||||
// Other filters (ASCII85, LZW, etc.) not expected for embedded files we wrote.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user