7c98566579
Removed the legacy indicator layout, unused chart helpers, styles and exports, the card-actions component, fetch-all and explanatory comments; one pager shared by the four worklists, shared filter-row styles, one FHIR name and CURP reader, downloads through export/, the concept-map editor on Material controls.
223 lines
7.1 KiB
TypeScript
223 lines
7.1 KiB
TypeScript
import { downloadPdf, safeName, type PdfContent } from '../export';
|
|
import type { Figure } from '../plot';
|
|
import plotly from '../plotly-bundle';
|
|
import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data';
|
|
import { forest, headMap, probabilityCurve, zBars } from './tea-figures';
|
|
|
|
type Table = { headers: string[]; rows: string[][] };
|
|
type Chart = { title: string; figure: Figure; height?: number };
|
|
type Block = {
|
|
title?: string;
|
|
fields?: string[][];
|
|
table?: Table;
|
|
chart?: Chart;
|
|
text?: string;
|
|
};
|
|
export type Section = { title: string; blocks: Block[] };
|
|
|
|
export const forestTitle = 'Razones de momios por par';
|
|
export const probabilityTitle = 'Probabilidad según z';
|
|
|
|
const calculation =
|
|
'El modelo estima, para cada par de métrica o zona del EEG y resultado del ADOS-2, la probabilidad de un puntaje elevado de severidad calibrada (CSS) o de un ítem alterado. La razón de momios corresponde al cambio asociado con una unidad de z. La probabilidad de referencia corresponde a z = 0, la edad media y el módulo más frecuente de la cohorte.';
|
|
const limitations =
|
|
'Las estimaciones dependen de la cohorte de referencia, de la calidad del EEG y de la disponibilidad de mediciones y pares. Las asociaciones no establecen causalidad. Las probabilidades no sustituyen la evaluación clínica ni establecen un diagnóstico.';
|
|
|
|
function associationRows(pairs: Pair[]): string[][] {
|
|
return pairs.map((p) => [
|
|
p.headline ? `${p.title} (principal)` : p.title,
|
|
shown(p.odds),
|
|
p.low == null && p.high == null ? '—' : `${shown(p.low)} a ${shown(p.high)}`,
|
|
percent(p.probability),
|
|
percent(p.reference),
|
|
]);
|
|
}
|
|
|
|
export function recordSections(patient: TeaPatient, norms: ReadonlyMap<string, Chart>): Section[] {
|
|
return [
|
|
{
|
|
title: 'Línea del tiempo',
|
|
blocks: [
|
|
{
|
|
table: {
|
|
headers: ['Fecha', 'Evento', 'Detalle'],
|
|
rows: patient.timeline,
|
|
},
|
|
},
|
|
],
|
|
},
|
|
{
|
|
title: 'ADOS-2',
|
|
blocks: patient.ados.map((o) => ({
|
|
title: shown(o.effectiveDateTime),
|
|
fields: adosSummary(o),
|
|
table: {
|
|
headers: ['Dominio', 'Subdominio', 'Código', 'Ítem', 'Puntaje'],
|
|
rows: adosItems(o),
|
|
},
|
|
})),
|
|
},
|
|
{
|
|
title: 'Calidad del EEG',
|
|
blocks: patient.studies.map((eeg) => ({
|
|
title: eeg.date,
|
|
fields: eeg.summary,
|
|
table: { headers: ['Control', 'Valor', 'Rango', 'Anormal', 'Decisivo'], rows: eeg.checks },
|
|
})),
|
|
},
|
|
{
|
|
title: 'Alteraciones',
|
|
blocks: patient.studies.flatMap((eeg) =>
|
|
eeg.metrics.flatMap((m) => {
|
|
const norm = norms.get(`${eeg.id}|${m.key}`);
|
|
return [
|
|
{
|
|
title: `${eeg.date} · ${m.title}`,
|
|
fields: [
|
|
['z', shown(m.z)],
|
|
['Resultado', alteration(m.outside)],
|
|
],
|
|
chart: m.sites.length
|
|
? { title: 'Mapa de la cabeza', figure: headMap(m.sites) }
|
|
: undefined,
|
|
},
|
|
...(norm ? [{ chart: norm }] : []),
|
|
];
|
|
}),
|
|
),
|
|
},
|
|
{
|
|
title: 'Relación con el ADOS-2',
|
|
blocks: [
|
|
{
|
|
table: {
|
|
headers: ['Par', 'OR', 'IC 95 %', 'Probabilidad', 'Referencia'],
|
|
rows: associationRows(patient.pairs),
|
|
},
|
|
},
|
|
],
|
|
},
|
|
];
|
|
}
|
|
|
|
export function riskSections(patient: TeaPatient, alteredOnly: boolean, pair?: Pair): Section[] {
|
|
const studies = patient.riskStudy ? [patient.riskStudy] : patient.studies;
|
|
const scores = studies
|
|
.map((eeg) => ({ date: eeg.date, figure: zBars(eeg) }))
|
|
.find(({ figure }) => figure.data[0].x?.length);
|
|
const effects = forest(patient.pairs, alteredOnly);
|
|
return [
|
|
{ title: 'Qué calcula', blocks: [{ text: calculation }] },
|
|
{
|
|
title: 'Puntuaciones z por métrica y zona',
|
|
blocks: scores
|
|
? [
|
|
{
|
|
chart: {
|
|
title: scores.date,
|
|
figure: scores.figure,
|
|
height: Math.max(340, 24 * (scores.figure.data[0].x?.length ?? 0) + 80),
|
|
},
|
|
},
|
|
]
|
|
: [],
|
|
},
|
|
{
|
|
title: forestTitle,
|
|
blocks: [
|
|
effects.data[0].x?.length
|
|
? {
|
|
chart: {
|
|
title: 'OR e IC 95 %',
|
|
figure: effects,
|
|
height: Math.max(340, 26 * effects.data[0].x.length + 80),
|
|
},
|
|
}
|
|
: { text: '—' },
|
|
],
|
|
},
|
|
{
|
|
title: 'Probabilidad frente a la referencia',
|
|
blocks: [{ table: probabilityRows(patient.pairs) }],
|
|
},
|
|
{
|
|
title: probabilityTitle,
|
|
blocks: pair ? [{ chart: { title: pair.title, figure: probabilityCurve(pair) } }] : [],
|
|
},
|
|
{ title: 'Limitaciones', blocks: [{ text: limitations }] },
|
|
];
|
|
}
|
|
|
|
function probabilityRows(pairs: Pair[]): Table {
|
|
return {
|
|
headers: ['Par', 'Probabilidad', 'Referencia'],
|
|
rows: pairs.map((p) => [
|
|
p.headline ? `${p.title} (principal)` : p.title,
|
|
percent(p.probability),
|
|
percent(p.reference),
|
|
]),
|
|
};
|
|
}
|
|
|
|
export function teaPdfName(page: 'seguimiento' | 'riesgos', day = new Date()): string {
|
|
return safeName(['tea', page, day.toISOString().slice(0, 10)]);
|
|
}
|
|
|
|
export function teaPdfContent(
|
|
title: string,
|
|
sections: Section[],
|
|
images: (string | undefined)[],
|
|
): PdfContent[] {
|
|
const charts = images[Symbol.iterator]();
|
|
const content: PdfContent[] = [{ text: title, fontSize: 18, bold: true }];
|
|
for (const section of sections) {
|
|
content.push({ text: section.title, bold: true, fontSize: 14, margin: [0, 12, 0, 5] });
|
|
if (!section.blocks.length) content.push('—');
|
|
for (const block of section.blocks) {
|
|
if (block.title) content.push({ text: block.title, bold: true, margin: [0, 8, 0, 3] });
|
|
if (block.text) content.push(block.text);
|
|
if (block.fields) content.push(...block.fields.map(([key, value]) => `${key} · ${value}`));
|
|
if (block.table) {
|
|
const { headers, rows } = block.table;
|
|
content.push(
|
|
rows.length
|
|
? {
|
|
layout: 'lightHorizontalLines',
|
|
table: {
|
|
headerRows: 1,
|
|
widths: ['*', ...headers.slice(1).map(() => 'auto' as const)],
|
|
body: [headers, ...rows],
|
|
},
|
|
}
|
|
: '—',
|
|
);
|
|
}
|
|
if (block.chart) {
|
|
const image = charts.next().value;
|
|
content.push({ text: block.chart.title, bold: true });
|
|
if (image) content.push({ image, fit: [510, 620] });
|
|
}
|
|
}
|
|
}
|
|
return content;
|
|
}
|
|
|
|
export async function exportTeaPdf(
|
|
page: 'seguimiento' | 'riesgos',
|
|
title: string,
|
|
sections: Section[],
|
|
plots: Iterable<HTMLDivElement>,
|
|
): Promise<void> {
|
|
const images: string[] = [];
|
|
for (const plot of plots) {
|
|
images.push(
|
|
await plotly.toImage(plot, {
|
|
format: 'png',
|
|
width: Math.max(780, plot.clientWidth),
|
|
height: plot.clientHeight,
|
|
}),
|
|
);
|
|
}
|
|
await downloadPdf(teaPdfName(page), teaPdfContent(title, sections, images));
|
|
}
|