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
+323
View File
@@ -0,0 +1,323 @@
import type {
DiagnosticReport,
Observation,
ObservationComponent,
Patient,
RiskAssessment,
} from 'fhir/r4';
import { code, ext, Fhir, label, resources } from '../fhir';
const steps: Record<string, string> = {
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología',
neurology: 'Neurología',
eeg: 'EEG',
};
const metrics: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior',
spindles_n2: 'Husos N2',
spindles_n3: 'Husos N3',
paroxysmal_spikes: 'Puntas paroxísticas',
anteroposterior_gradient: 'Gradiente anteroposterior',
};
const regions: Record<string, string> = {
frontal_left: 'Frontal izquierda',
frontal_right: 'Frontal derecha',
frontal_midline: 'Frontal medial',
central: 'Central',
parietal: 'Parietal',
temporal_left: 'Temporal izquierda',
temporal_right: 'Temporal derecha',
occipital: 'Occipital',
posterior: 'Posterior',
global: 'Global',
};
const biomarkers: Record<string, string> = {
spikes: 'paroxysmal_spikes',
spindles: 'spindles_n2',
posterior_rhythm: 'posterior_rhythm',
gradient: 'anteroposterior_gradient',
};
const repetitive = new Set([
'ados2.intonation',
'ados2.stereotyped_language',
'ados2.unusual_sensory_interest',
'ados2.hand_finger_mannerisms',
'ados2.repetitive_interests',
]);
const classifications: Record<string, string> = {
non_spectrum: 'Fuera del espectro',
autism_spectrum: 'Espectro autista',
autism: 'Autismo',
mild_to_moderate_concern: 'Preocupación leve a moderada',
severe_concern: 'Preocupación grave',
};
const quality: Record<string, string> = {
good: 'Buena',
bad: 'Mala',
not_analyzed: 'Sin analizar',
valid: 'Válido',
not_valid: 'No válido',
};
const number = new Intl.NumberFormat('es-MX', { maximumFractionDigits: 3 });
const percentage = new Intl.NumberFormat('es-MX', { style: 'percent', maximumFractionDigits: 1 });
export function shown(value: string | number | undefined): string {
return typeof value === 'number' ? number.format(value) : value || '—';
}
export function percent(value: number | undefined): string {
return value == null ? '—' : percentage.format(value);
}
function answer(value: boolean | undefined): string {
return value === undefined ? '—' : value ? 'Sí' : 'No';
}
function observationValue(o: Observation | ObservationComponent): string {
if (o.valueQuantity?.value != null) {
return [shown(o.valueQuantity.value), o.valueQuantity.unit].filter(Boolean).join(' ');
}
return shown(label(o.valueCodeableConcept) || o.valueString || o.valueInteger);
}
export function identity(patient: Patient): string[][] {
const group = ext(patient, 'tea-age-group')?.valueCode;
const step = ext(patient, 'tea-step')?.valueCode;
const sex = { female: 'Femenino', male: 'Masculino', other: 'Otro', unknown: '—' };
return [
['Nombre', shown(patient.name?.[0]?.text)],
...(patient.identifier ?? []).map((id) => [id.type?.text || 'Identificador', shown(id.value)]),
['Sexo', patient.gender ? sex[patient.gender] : '—'],
['Fecha de nacimiento', shown(patient.birthDate)],
['Grupo de edad', group && group !== 'no_data' ? `${group} meses` : '—'],
['Paso', shown(steps[step ?? ''] ?? step)],
];
}
export function adosItems(observation: Observation): string[][] {
return (observation.component ?? [])
.filter((item) => code(item.code) !== 'ados2.module')
.map((item) => [
shown(label(item.code)),
repetitive.has(code(item.code) ?? '') ? 'RRB' : 'SA',
observationValue(item),
]);
}
export function adosSummary(observation: Observation): string[][] {
const module = observation.component?.find((item) => code(item.code) === 'ados2.module');
return [
['Módulo', module ? observationValue(module) : '—'],
['CSS', shown(observation.valueInteger)],
[
'Clasificación',
shown(
classifications[code(observation.interpretation?.[0]) ?? ''] ??
label(observation.interpretation?.[0]),
),
],
];
}
function timeline(observations: Observation[], ados: Observation[], reports: DiagnosticReport[]) {
const events = [
...ados.map((o) => [o.effectiveDateTime ?? '', 'ADOS-2', adosSummary(o)[2][1]]),
...reports.map((r) => [
r.effectiveDateTime ?? '',
'EEG',
shown(quality[code(r.conclusionCode?.[0]) ?? '']),
]),
];
const notes = new Map<string, Observation[]>();
for (const o of observations) {
const field = code(o.code);
const date = o.effectiveDateTime ?? '';
if (field === 'mchat.score') {
events.push([date, 'M-CHAT', observationValue(o)]);
}
if (field === 'eeg.lab_record_id' && !reports.some((r) => r.effectiveDateTime === date)) {
events.push([date, 'EEG', observationValue(o)]);
}
if (field?.startsWith('clinical_note.') && o.encounter?.reference) {
const group = notes.get(o.encounter.reference) ?? [];
group.push(o);
notes.set(o.encounter.reference, group);
}
}
for (const group of notes.values()) {
const specialty = group.find((o) => code(o.code) === 'clinical_note.specialty');
if (code(specialty?.valueCodeableConcept) === 'pediatric_neurology') {
const detail = group
.filter((o) => o !== specialty)
.map(observationValue)
.join(' · ');
events.push([specialty?.effectiveDateTime ?? '', 'Nota de neurología', shown(detail)]);
}
}
return events
.sort((a, b) => b[0].localeCompare(a[0]))
.map(([date, kind, detail]) => [shown(date), kind, detail]);
}
function checkRow(o: Observation): string[] {
const range = o.referenceRange?.[0];
const abnormal = code(o.interpretation?.[0]);
return [
[label(o.code), label(o.component?.[0]?.code)].filter(Boolean).join(' · '),
observationValue(o),
range ? `${shown(range.low?.value)} a ${shown(range.high?.value)}` : '—',
answer(abnormal ? abnormal === 'A' : undefined),
answer(ext(o, 'eeg-check-decisive')?.valueBoolean),
];
}
export type Site = {
name: string;
kind: 'zone' | 'electrode';
z?: number;
outside?: number;
};
function metric(o: Observation) {
const key = code(o.code) ?? '';
return {
key,
title: metrics[key] ?? shown(label(o.code)),
value: o.valueQuantity?.value,
unit: o.valueQuantity?.unit,
z: ext(o, 'eeg-z')?.valueDecimal,
outside: ext(o, 'eeg-outside')?.valueInteger,
model: ext(o, 'eeg-model')?.valueString,
sites: (o.component ?? []).map((site): Site => ({
name: code(site.code) ?? '',
kind: site.code.coding?.[0]?.system?.endsWith('eeg-electrode-10-20') ? 'electrode' : 'zone',
z: ext(site, 'eeg-z')?.valueDecimal,
outside: ext(site, 'eeg-outside')?.valueInteger,
})),
};
}
export type Metric = ReturnType<typeof metric>;
function study(report: DiagnosticReport, observations: Map<string | undefined, Observation>) {
const results = (report.result ?? [])
.map((r) => observations.get(r.reference?.split('/').pop()))
.filter((o): o is Observation => !!o);
return {
id: report.id,
date: shown(report.effectiveDateTime),
age: ext(report, 'eeg-age-months')?.valueDecimal,
summary: [
['Calidad', shown(quality[code(report.conclusionCode?.[0]) ?? ''])],
['Validez', shown(quality[code(report.conclusionCode?.[1]) ?? ''])],
['Duración (min)', shown(ext(report, 'eeg-duration-min')?.valueDecimal)],
['Canales', shown(ext(report, 'eeg-channels')?.valueInteger)],
],
checks: results
.filter((o) => o.code.coding?.[0]?.system?.endsWith('tea-eeg-check'))
.map(checkRow),
metrics: results
.filter((o) => o.code.coding?.[0]?.system?.endsWith('tea-eeg-metric'))
.map(metric),
};
}
export type Pair = {
key: string;
title: string;
headline: boolean;
altered: boolean;
z?: number;
odds?: number;
low?: number;
high?: number;
probability?: number;
reference?: number;
};
export type Study = ReturnType<typeof study>;
export function zoneLabel(zone: string): string {
return regions[zone] ?? zone;
}
export function alteration(outside: number | undefined): string {
return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango';
}
function associations(
risk: RiskAssessment | undefined,
eeg: Study | undefined,
ados: Observation[],
) {
const items = ados[0] ? adosItems(ados[0]) : [];
return (risk?.prediction ?? [])
.map((p): Pair => {
const key = code(p.outcome) ?? '';
const [biomarker, zone = '', outcome = ''] = key.split('|');
const metric = eeg?.metrics.find((m) => m.key === biomarkers[biomarker]);
const site =
zone === 'global' || biomarker === 'posterior_rhythm'
? metric
: metric?.sites.find((s) => s.kind === 'zone' && s.name === zone);
const item = /^ados2_item_(\d+)$/.exec(outcome);
return {
key,
title: [
metric?.title ?? metrics[biomarkers[biomarker]] ?? biomarker,
zoneLabel(zone),
item ? (items[Number(item[1]) - 1]?.[0] ?? outcome) : outcome,
].join(' · '),
headline: ext(p, 'association-headline')?.valueBoolean === true,
altered: site?.outside != null && site.outside !== 0,
z: site?.z,
odds: ext(p, 'association-odds-ratio')?.valueDecimal,
low: ext(p, 'association-ci-low')?.valueDecimal,
high: ext(p, 'association-ci-high')?.valueDecimal,
probability: p.probabilityDecimal,
reference: ext(p, 'association-reference-probability')?.valueDecimal,
};
})
.sort((a, b) => Number(b.headline) - Number(a.headline));
}
export async function loadTeaPatient(fhir: Fhir, id: string) {
const bundle = await fhir.search('tea', 'Patient', {
_id: id,
_revinclude: ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'],
});
const patient = resources<Patient>(bundle, 'Patient', 'match').find((p) => p.id === id);
if (!patient) throw new Error('No se encontró el paciente.');
const observations = resources<Observation>(bundle, 'Observation', 'include');
const ados = observations
.filter((o) => code(o.code) === 'ados2')
.sort((a, b) => (b.effectiveDateTime ?? '').localeCompare(a.effectiveDateTime ?? ''));
const reports = resources<DiagnosticReport>(bundle, 'DiagnosticReport', 'include')
.filter((r) => code(r.code) === 'eeg')
.reverse();
const byId = new Map(observations.map((o) => [o.id, o]));
const studies = reports.map((r) => study(r, byId));
const risk = resources<RiskAssessment>(bundle, 'RiskAssessment', 'include')[0];
const basis = risk?.basis?.find((r) => r.reference?.startsWith('DiagnosticReport/'));
const riskStudy = studies.find(
(eeg) => eeg.id && basis?.reference === `DiagnosticReport/${eeg.id}`,
);
return {
patient,
ados,
studies,
timeline: timeline(observations, ados, reports),
riskStudy,
pairs: associations(risk, riskStudy, ados),
};
}
export type TeaPatient = Awaited<ReturnType<typeof loadTeaPatient>>;