T8/T9: TEA Seguimiento and Análisis de riesgo as two components in rebuild's list style

tea-list is replaced by tab-seguimiento-tea and tab-riesgos-tea over one
tea-rows module (params, rows, workbook, export), with Material filters,
cards and pager. The risk list defaults to every child and keeps the
association pairs per row; the focused patient is fetched with the list's
own search. Specs and page cases follow.
This commit is contained in:
2026-12-01 03:55:35 -06:00
parent 48e6c9f390
commit fcb3634fa9
17 changed files with 1219 additions and 990 deletions
+356
View File
@@ -0,0 +1,356 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { ados2Component } from '../ados2';
import { safeName } from '../export/safe-name';
import { downloadXlsx, type Sheet } from '../export/xlsx';
import { code, ext, resources, type Fhir, type Params } from '../fhir';
import { name } from './measures';
import { matchesSearch } from './patient-search';
const TEA_STEPS = [
{ code: 'mchat_only', label: 'M-CHAT' },
{ code: 'psychology', label: 'Psicología' },
{ code: 'neurology', label: 'Neuropediatría' },
{ code: 'eeg', label: 'EEG' },
] as const;
type Prediction = NonNullable<RiskAssessment['prediction']>[number];
function associationPair(p: Prediction) {
const stat = (name: string) => ext(p, `association-${name}`)?.valueDecimal;
return {
pair: code(p.outcome),
or: stat('odds-ratio'),
low: stat('ci-low'),
high: stat('ci-high'),
q: stat('q'),
probability: p.probabilityDecimal,
reference: stat('reference-probability'),
sameDirection: ext(p, 'association-same-direction')?.valueBoolean,
headline: ext(p, 'association-headline')?.valueBoolean === true,
};
}
function concordance(headline?: ReturnType<typeof associationPair>, ados?: Observation): string {
if (!headline || !ados || headline.probability == null || headline.reference == null) return '—';
const outcome = headline.pair?.split('|')[2];
const item = Number(outcome?.match(/^ados2_item_(\d{2})$/)?.[1]);
const score =
outcome === 'CSS' ? ados.valueInteger : ados2Component(ados, item)?.valueQuantity?.value;
if (score == null) return '—';
const event = score >= (outcome === 'CSS' ? 8 : 1);
const predicted = headline.probability >= headline.reference;
return event === predicted ? 'Concordante' : 'No concordante';
}
function byPatient<T extends DiagnosticReport | Observation | RiskAssessment>(
records: T[],
): Map<string | undefined, T[]> {
const grouped = new Map<string | undefined, T[]>();
for (const record of records) {
const subject = record.subject?.reference;
const group = grouped.get(subject);
if (group) group.push(record);
else grouped.set(subject, [record]);
}
return grouped;
}
export function teaRows(page: Bundle) {
const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport'));
const observations = byPatient(resources<Observation>(page, 'Observation'));
const risks = byPatient(resources<RiskAssessment>(page, 'RiskAssessment'));
const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) =>
(a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '');
return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const subject = `Patient/${patient.id}`;
const obs = observations.get(subject) ?? [];
const eegs = (reports.get(subject) ?? []).filter((r) => code(r.code) === 'eeg').sort(dateOrder);
const ados = obs.filter((o) => code(o.code) === 'ados2').sort(dateOrder);
const mchat = obs.filter((o) => code(o.code) === 'mchat.score').sort(dateOrder)[0];
const neurology = obs
.filter(
(o) =>
code(o.code) === 'clinical_note.specialty' &&
code(o.valueCodeableConcept) === 'pediatric_neurology',
)
.sort(dateOrder)[0];
const risk = risks.get(subject)?.[0];
const pairs = (risk?.prediction ?? []).map(associationPair);
const headline = pairs.find((p) => p.headline);
const basisAdos = risk?.basis?.find((ref) =>
ref.reference?.startsWith('Observation/'),
)?.reference;
const evaluation = basisAdos
? ados.find((o) => `Observation/${o.id}` === basisAdos)
: ados.at(-1);
const dates = [
mchat?.effectiveDateTime,
ados[0]?.effectiveDateTime,
neurology?.effectiveDateTime,
[
...eegs.map((e) => e.effectiveDateTime),
...obs.filter((o) => code(o.code) === 'eeg.lab_record_id').map((o) => o.effectiveDateTime),
]
.filter((day) => !!day)
.sort()[0],
];
const step = ext(patient, 'tea-step')?.valueCode;
return {
patient,
name: patient.name?.[0]?.text,
recordNumbers: [
...new Set(
(patient.identifier ?? [])
.filter((i) => i.system?.startsWith('urn:isssteleon:') && !!i.value)
.map((i) => i.value!),
),
],
step: TEA_STEPS.find(({ code }) => code === step)?.label,
case: ext(patient, 'tea-case')?.valueCode,
eegResult: ext(patient, 'tea-eeg-result')?.valueCode,
steps: TEA_STEPS.map((step, i) => ({ ...step, date: dates[i] })),
mchatScore: mchat?.valueQuantity?.value,
css: ados.at(-1)?.valueInteger,
headline,
concordance: concordance(headline, evaluation),
pairs,
};
});
}
export type TeaRow = ReturnType<typeof teaRows>[number];
export type TeaFilters = {
step?: string;
case?: string;
eeg?: string;
model?: string;
age?: string;
sex?: string;
alteration?: string;
mchatMin?: number | null;
mchatMax?: number | null;
cssMin?: number | null;
cssMax?: number | null;
window?: number;
start?: string;
cutoff?: string;
status?: string;
};
export function teaParams(f: TeaFilters): Params {
const range = (min?: number | null, max?: number | null) => {
const values = [min == null ? '' : `ge${min}`, max == null ? '' : `le${max}`].filter(Boolean);
return values.length ? values : undefined;
};
return {
'tea-step': f.step || undefined,
'tea-case': f.case || undefined,
'tea-eeg-result': f.eeg || undefined,
'tea-model': f.model || undefined,
'tea-age-group': f.age || undefined,
'tea-sex': f.sex || undefined,
'tea-alteration': f.alteration || undefined,
'tea-mchat': range(f.mchatMin, f.mchatMax),
'tea-css': range(f.cssMin, f.cssMax),
'follow-up-window': f.window,
'follow-up-start': f.start || undefined,
'follow-up-cutoff': f.cutoff || undefined,
'follow-up-status': f.status || undefined,
};
}
export type AssociationFilter = 'with' | 'without' | 'all';
export const DEFAULT_ASSOCIATION_FILTER: AssociationFilter = 'all';
export const ASSOCIATION_LABELS = {
with: 'Con resultados',
without: 'Sin resultados',
all: 'Todos',
};
export function associationRows(
rows: TeaRow[],
filter: AssociationFilter = DEFAULT_ASSOCIATION_FILTER,
) {
return rows.filter((row) => filter === 'all' || !!row.pairs.length === (filter === 'with'));
}
const INCLUDES = ['Observation:subject', 'DiagnosticReport:subject', 'RiskAssessment:subject'];
export const SCORE_FILTERS = [
{ label: 'M-CHAT', min: 'mchatMin', max: 'mchatMax' },
{ label: 'CSS', min: 'cssMin', max: 'cssMax' },
] as const;
export const TOKEN_FILTERS = [
{ key: 'step', label: 'Etapa', options: TEA_STEPS },
{
key: 'case',
label: 'Estado del caso',
options: choices('confirmed', 'in_process', 'not_confirmed'),
},
{
key: 'eeg',
label: 'Resultado del EEG',
options: [
...choices('normal', 'abnormal', 'no_valid_eeg'),
{ code: 'not_scored', label: 'Sin analizar' },
],
},
{
key: 'model',
label: 'Con modelo',
options: [
{ code: 'yes', label: 'Sí' },
{ code: 'no', label: 'No' },
],
},
{
key: 'age',
label: 'Grupo de edad (meses)',
options: [...choices('16-23', '24-29', '30-36'), { code: 'no_data', label: 'Sin dato' }],
},
{ key: 'sex', label: 'Sexo', options: choices('female', 'male') },
{
key: 'alteration',
label: 'Alteración',
options: choices(
'posterior_rhythm',
'spindles_n2',
'spindles_n3',
'paroxysmal_spikes',
'anteroposterior_gradient',
),
},
{
key: 'status',
label: 'Estatus',
options: [
{ code: 'active', label: 'Activo' },
{ code: 'finished', label: 'Finalizado' },
],
},
] as const;
function choices(...codes: string[]) {
return codes.map((code) => ({ code, label: name(code) }));
}
export function matchesTeaSearch(row: TeaRow, query: string): boolean {
return matchesSearch(query, [
...(row.patient.name ?? []).map(({ text }) => text),
...row.recordNumbers,
]);
}
export function parameters(page?: Bundle): Record<string, string> {
const self = page?.link?.find((l) => l.relation === 'self')?.url;
const result: Record<string, string> = {};
if (!self) return result;
new URL(self).searchParams.forEach((value, key) => {
if (key === '_id' || !key.startsWith('_')) {
result[key] = result[key] ? `${result[key]}, ${value}` : value;
}
});
return result;
}
const columns = (entries: [string, string][]): Sheet['columns'] =>
entries.map(([key, header]) => ({ key, header }));
export function teaWorkbook(
rows: TeaRow[],
risk: boolean,
day = new Date(),
): { name: string; sheets: Sheet[] } {
const identity: [string, string][] = [
['id', 'Paciente'],
['record', 'Expediente'],
['name', 'Nombre'],
];
const headline: [string, string][] = [
['pair', 'Par principal'],
['or', 'OR'],
['q', 'q'],
['concordance', 'Concordancia con el ADOS-2'],
];
const steps: [string, string][] = TEA_STEPS.map(({ code, label }) => [code, label]);
const sheets: Sheet[] = [
{
name: risk ? 'Niños' : 'Seguimiento',
columns: columns([
...identity,
['sex', 'Sexo'],
['birth', 'Nacimiento'],
...(risk ? [] : steps),
...headline,
]),
rows: rows.map((row) => ({
id: row.patient.id,
record: row.recordNumbers.join(', '),
name: row.name,
sex: row.patient.gender ? name(row.patient.gender) : undefined,
birth: row.patient.birthDate,
...Object.fromEntries(row.steps.map(({ code, date }) => [code, date])),
pair: row.headline?.pair,
or: row.headline?.or,
q: row.headline?.q,
concordance: row.concordance,
})),
},
];
if (risk) {
sheets.push({
name: 'Pares',
columns: columns([
['id', 'Paciente'],
['pair', 'Par'],
['or', 'OR'],
['low', 'IC inferior'],
['high', 'IC superior'],
['q', 'q'],
['probability', 'Probabilidad'],
['reference', 'Referencia'],
['sameDirection', 'Mismo sentido'],
]),
rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))),
});
}
const page = risk ? 'riesgos' : 'seguimiento';
return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets };
}
export function exportTea(
rows: TeaRow[],
params: Record<string, string>,
risk: boolean,
): Promise<void> {
const { name, sheets } = teaWorkbook(rows, risk);
return downloadXlsx(name, sheets, params);
}
export function ageMonths(birth: string | undefined, cutoff: string): number | undefined {
if (!birth || !cutoff || birth.length !== 10) return undefined;
const [by, bm, bd] = birth.split('-').map(Number);
const [y, m, d] = cutoff.split('-').map(Number);
return Math.max(0, (y - by) * 12 + m - bm - Number(d < bd));
}
export function teaPatientPage(fhir: Fhir, params: Params): Promise<Bundle> {
return fhir.search('tea', 'Patient', { ...params, _revinclude: INCLUDES });
}
export async function fetchTeaRows(
fhir: Fhir,
params: Params,
abort?: AbortSignal,
): Promise<{ first: Bundle; rows: TeaRow[] }> {
const first = await teaPatientPage(fhir, { ...params, _count: 200 });
const rows: TeaRow[] = [];
let page = first;
for (;;) {
abort?.throwIfAborted();
rows.push(...teaRows(page));
const next = fhir.follow('tea', page, 'next');
if (!next) return { first, rows };
page = await next;
}
}