TEA patient pages: the record and the risk analysis page

Keep the TEA record branch inside Paciente and lazy-load the risk route.
Separate FHIR adaptation, figures, shared section rendering, and PDF
content under paciente. Use the existing section cards, tables, and
buttons, with flexible summary fields and scrollable detail tables.

Read the Patient by _id with Observation, DiagnosticReport, and
RiskAssessment reverse includes. Group neurology observations by
encounter, use aggregate ADOS-2 evaluations, and use the lab-record
observation for EEG dates without reports. Order the timeline and exams
newest first and use the RiskAssessment headline flag for pair order.
Render absent fields and empty tables with an em dash.

Use a normalized 10–20 layout and a 41-by-41 inverse-distance weighted
contour clipped to the head outline, with symmetric z colors and
electrode labels. Keep the head outline and markers when no site has a
score. Request each aggregate champion's version once per record load,
draw the median and p5–p95 band with banded(), and place the observed
value at the EEG's age. Omit unavailable bands and count-rate bands.

Use the RiskAssessment's EEG for z and pair status, falling back to the
newest EEG with z scores for the bars when needed. Use site outside flags
for the forest filter, aggregate scores for global and posterior-rhythm
pairs, and show the unit-OR line and available CI bounds. Select the
headline pair by default. The current RiskAssessment carries no logistic
coefficients, so the view shows patient and reference points at the
served z and at zero. Keep the optional logistic figure input independent
of the FHIR mapping. Link to Seguimiento with the agreed query parameter.

Share section data with the PDF and include snapshots of the rendered
figures. Use the existing safe seguimiento and riesgos filename tokens
with the UTC date. Format values for es-MX and size categorical charts
to their row count.

Add Vitest coverage for the head map, norm and point, forest filtering,
z band, probability fallback, ADOS-2 rows, PDF content, included data,
and the domain branch. Static TypeScript and Angular template checks
passed with a temporary PDF type shim. The Angular build, Vitest runtime
and Playwright run on the test machines.
This commit is contained in:
2026-11-30 13:51:25 -06:00
parent 56d1ef2e8a
commit 3f6fa28590
13 changed files with 1567 additions and 144 deletions
+179
View File
@@ -0,0 +1,179 @@
import type { PdfContent } from '../export/pdf';
import { downloadPdf } from '../export/pdf';
import { safeName } from '../export/safe-name';
import type { Figure } from '../plot';
import plotly from '../plotly-bundle';
import {
adosItems,
adosSummary,
alteration,
identity,
Pair,
percent,
shown,
TeaPatient,
} from './tea-data';
import { headMap } from './tea-figures';
type Table = { headers: string[]; rows: string[][] };
type Chart = { title: string; figure: Figure; height?: number };
export 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';
export 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.';
export 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: 'Datos', blocks: [{ fields: identity(patient.patient) }] },
{
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: ['Ítem', 'Dominio', '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 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));
}