clean all

This commit is contained in:
Bastien Chanot committed 2026-05-18 19:40:08 +02:00
1 parent f57d6ec3d3
commit 27afb719f5
101 files changed
+45 -14426

No files matched your search

-250
View File
@@ -1,250 +0,0 @@
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);
// BlobPart requires ArrayBuffer (not ArrayBufferLike). Copy into a fresh buffer.
const ab = new ArrayBuffer(bytes.byteLength);
new Uint8Array(ab).set(bytes);
return new Blob([ab], { 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;
}