import { downloadPdf, type PdfContent } from '../../export/pdf'; import { safeName } from '../../export/safe-name'; import type { PreviewResult } from '../../api/models/preview-result'; import type { Score } from '../../api/models/score'; function shown(value: unknown): string { return value == null || value === '' ? '—' : String(value); } function yesNo(value: unknown): string { return value === true ? 'Sí' : value === false ? 'No' : '—'; } function verdict(valid: boolean | null): string { return valid === true ? 'Válido' : valid === false ? 'No válido' : '—'; } function scoreCells(score: Score | null): string[] { return [ shown(score?.z), `${shown(score?.p5)} / ${shown(score?.median)} / ${shown(score?.p95)}`, shown(score?.outside), ]; } function table(headers: string[], rows: string[][]): PdfContent { if (!rows.length) return '—'; return { layout: 'lightHorizontalLines', table: { headerRows: 1, widths: ['*', ...headers.slice(1).map(() => 'auto' as const)], body: [headers, ...rows], }, }; } function heading(text: string): PdfContent { return { text, bold: true, fontSize: 14, margin: [0, 12, 0, 5] }; } export function previewPdfName(day = new Date()): string { return safeName(['tea', 'gobernanza', day.toISOString().slice(0, 10)]); } export function previewPdfContent(result: PreviewResult): PdfContent[] { const { eeg, ados2, warnings } = result; const content: PdfContent[] = [ { text: 'Vista previa del estudio EEG', fontSize: 18, bold: true }, `${eeg.level} · ${verdict(eeg.valid)}`, ]; if (eeg.error) content.push(eeg.error); content.push( heading('Comprobaciones'), table( ['Comprobación', 'Electrodo', 'Resultado', 'Rango', 'Anormal'], eeg.checks.map((check) => [ shown(check['code']), shown(check['electrode']), `${shown(check['value'] ?? check['text'])}${check['unit'] ? ' ' + check['unit'] : ''}`, `${shown(check['low'])} / ${shown(check['high'])}`, yesNo(check['abnormal']), ]), ), ); content.push( heading('Métricas'), table( ['Métrica', 'Valor', 'z', 'p5 / mediana / p95', 'Fuera de rango'], eeg.metrics.flatMap((metric) => [ [metric.code, shown(metric.value), ...scoreCells(metric.score)], ...[...Object.entries(metric.electrodes), ...Object.entries(metric.zones)].map( ([site, value]) => [ `${metric.code} · ${site}`, shown(value.value), ...scoreCells(value.score), ], ), ]), ), ); if (ados2) { content.push( heading('ADOS-2'), `${shown(ados2.classification)} · CSS ${shown(ados2.css)}`, table( ['Ítem', 'Puntuación'], Object.entries(ados2.items) .filter(([field, value]) => field in ados2.titles || value != null) .map(([field, value]) => [ados2.titles[field] ?? field, shown(value)]), ), ); } if (warnings.length) content.push(heading('Advertencias'), { ul: [...warnings] }); return content; } export function downloadPreviewPdf(result: PreviewResult): Promise { return downloadPdf(previewPdfName(), previewPdfContent(result)); }