Files
WebApp/src/app/paciente/tea-data.ts
T
alberto b847e04697 ADOS-2 items shown by the child's module, grouped by domain and subdomain
The patient record ADOS-2 table and the Seguimiento ADOS-2 card list only
the module's items, in the order of core.tea.ados2_items as the FHIR
aggregate Observation carries them: each module item component has the
module's item code and exact title as a second coding (and code.text), and
ados2-domain / ados2-subdomain extensions. Components without those
(items outside the module) are not listed. Association titles and the
concordance look the item up by catalog field instead of by row index, so
they do not depend on which items the module has. ADOS2_ITEMS moves to a
shared src/app/ados2.ts.
2026-11-30 16:56:26 -06:00

320 lines
11 KiB
TypeScript

import type {
DiagnosticReport,
Observation,
ObservationComponent,
Patient,
RiskAssessment,
} from 'fhir/r4';
import { ados2Component, ados2Groups } from '../ados2';
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 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 ados2Groups(observation).flatMap((group) =>
group.subdomains.flatMap((sub) =>
sub.items.map((item) => [
group.domain,
sub.subdomain,
item.code,
item.title,
shown(item.score),
]),
),
);
}
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[],
) {
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 ? label(ados2Component(ados[0], Number(item[1]))?.code) || 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>>;