F1c: user fixes

Render the worklist stepper from the Patient stage and read M-CHAT, CSS
and alteration count from its FHIR extensions. Keep the compact stepper
private to Seguimiento and share the dated screening logic with the
patient record. Use the first dated event for each step, require prior
steps, and use the later date when an event predates its prerequisite.
Only a good-quality EEG completes that stage.

Use horizontal Plotly bars on the destination rows for elapsed spans,
diamonds for completed steps, and labels for pending steps. Keep the
screening order on the axis and show 30 days on either side when all
completed steps share one date. Reuse the registered bar and scatter
traces and the rebuild palette.

Use completed months at the applied cutoff and show the marked headline
association with the reference formatting. Resolve item labels from
the model's ADOS-2 observation and fall back to the item code. Move the
existing detail and risk actions into the patient-name cell to keep the
requested ten columns. Keep raw association numbers and separate CI
bounds in Excel and keep the screening dates in the follow-up export.

Update the two logic specs and the follow-up, risk and record page
assertions. All 34 targeted Vitest cases passed with Plotly rendering
stubbed. The local TypeScript check reached the existing PDF export
code and reported missing pdfmake typings. Angular and page runs are
reserved for the test machines.
This commit is contained in:
2026-12-01 11:32:17 -06:00
parent 7c98566579
commit a2bf98e9da
11 changed files with 686 additions and 242 deletions
+30 -7
View File
@@ -20,6 +20,18 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel',
await page.getByRole('tab', { name: 'Seguimiento' }).click(); await page.getByRole('tab', { name: 'Seguimiento' }).click();
const rows = page.locator('app-tab-seguimiento-tea table tbody tr'); const rows = page.locator('app-tab-seguimiento-tea table tbody tr');
await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/); await expect(rows.first().locator('td').first()).toHaveText(/^N-?\d{4}$/);
await expect(rows.first().locator('app-tea-stepper li')).toHaveCount(4);
await expect(page.locator('app-tab-seguimiento-tea').getByRole('columnheader')).toHaveText([
'Expediente',
'Nombre',
'Sexo',
'Edad (meses)',
'Etapa',
'Puntaje M-CHAT',
'CSS ADOS-2',
'Estatus de EEG',
'Alteraciones encontradas',
]);
const name = await downloaded( const name = await downloaded(
page, page,
page.getByRole('button', { name: 'Exportar a Excel' }), page.getByRole('button', { name: 'Exportar a Excel' }),
@@ -35,6 +47,18 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel',
await expect(risk.locator('table.worklist tbody tr').first().locator('td').first()).toHaveText( await expect(risk.locator('table.worklist tbody tr').first().locator('td').first()).toHaveText(
/^N-?\d{4}$/, /^N-?\d{4}$/,
); );
await expect(risk.locator('table.worklist > thead').getByRole('columnheader')).toHaveText([
'Expediente',
'Nombre',
'Sexo',
'Edad (meses)',
'Asociación principal',
'Razón de momios',
'IC 95 %',
'q',
'Probabilidad',
'Probabilidad de referencia',
]);
await risk.getByRole('combobox', { name: 'Modelo de asociación' }).click(); await risk.getByRole('combobox', { name: 'Modelo de asociación' }).click();
await page.getByRole('option', { name: 'Con resultados' }).click(); await page.getByRole('option', { name: 'Con resultados' }).click();
await expect(risk.getByText('No hay registros para los filtros aplicados.')).toBeVisible(); await expect(risk.getByText('No hay registros para los filtros aplicados.')).toBeVisible();
@@ -54,7 +78,10 @@ test('tea patient: the record and the risk page load and export to PDF', async (
await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/); await expect(page).toHaveURL(/\/indicadores\/tea\/pacientes\/[^/]+$/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible(); await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
await expect(page.locator('app-tea-section').first()).toBeVisible(); const timeline = page.locator('app-tea-section').first();
await expect(timeline.getByText('Línea del tiempo', { exact: true })).toBeVisible();
await expect(timeline.locator('app-plot .scatterlayer .point').first()).toBeVisible();
await expect(timeline.getByRole('table')).toHaveCount(0);
const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf'); const record = await downloaded(page, page.getByRole('button', { name: 'Exportar PDF' }), 'pdf');
expect(record).toMatch(/^tea-seguimiento-/); expect(record).toMatch(/^tea-seguimiento-/);
@@ -63,12 +90,8 @@ test('tea patient: the record and the risk page load and export to PDF', async (
await expect(focused.getByRole('button', { name: 'Ver todos los pacientes' })).toBeVisible(); await expect(focused.getByRole('button', { name: 'Ver todos los pacientes' })).toBeVisible();
const focusedRows = focused.locator('table tbody tr'); const focusedRows = focused.locator('table tbody tr');
await expect(focusedRows).toHaveCount(1); await expect(focusedRows).toHaveCount(1);
await expect(focusedRows.first().locator('td').nth(4)).toHaveText( await expect(focusedRows.first().locator('td')).toHaveCount(9);
/M-CHAT|Psicología|Neuropediatría|EEG/, await expect(focusedRows.first().locator('app-tea-stepper')).toBeVisible();
);
await expect(focusedRows.first().locator('td').nth(5)).toHaveText(
/Diagnóstico confirmado|En proceso|Sin TEA/,
);
await focusedRows.first().getByRole('link').click(); await focusedRows.first().getByRole('link').click();
await page.getByRole('link', { name: 'Análisis de riesgo' }).click(); await page.getByRole('link', { name: 'Análisis de riesgo' }).click();
+27 -18
View File
@@ -145,8 +145,14 @@
<tr> <tr>
<th scope="col">Expediente</th> <th scope="col">Expediente</th>
<th scope="col">Nombre</th> <th scope="col">Nombre</th>
<th scope="col">Pares</th> <th scope="col">Sexo</th>
<th scope="col">Acciones</th> <th scope="col">Edad (meses)</th>
<th scope="col">Asociación principal</th>
<th scope="col">Razón de momios</th>
<th scope="col">IC 95 %</th>
<th scope="col">q</th>
<th scope="col">Probabilidad</th>
<th scope="col">Probabilidad de referencia</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -158,9 +164,6 @@
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id]"> <a [routerLink]="['/indicadores', 'tea', 'pacientes', id]">
{{ row.name || '—' }} {{ row.name || '—' }}
</a> </a>
</td>
<td>{{ row.pairs.length || '—' }}</td>
<td>
<div class="row-actions"> <div class="row-actions">
@if (row.pairs.length) { @if (row.pairs.length) {
<button <button
@@ -175,33 +178,39 @@
<a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">Riesgo</a> <a [routerLink]="['/indicadores', 'tea', 'pacientes', id, 'riesgo']">Riesgo</a>
</div> </div>
</td> </td>
<td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
<td>{{ row.headline?.title ?? '—' }}</td>
<td>{{ formatOr(row.headline?.or) }}</td>
<td>{{ formatIc(row.headline?.low, row.headline?.high) }}</td>
<td>{{ formatQ(row.headline?.q) }}</td>
<td>{{ formatProbability(row.headline?.probability) }}</td>
<td>{{ formatProbability(row.headline?.reference) }}</td>
</tr> </tr>
@if (expanded()[id] && row.pairs.length) { @if (expanded()[id] && row.pairs.length) {
<tr> <tr>
<td colspan="4"> <td colspan="10">
<table class="plain pairs"> <table class="plain pairs">
<thead> <thead>
<tr> <tr>
<th>Par</th> <th>Par</th>
<th>OR (IC)</th> <th>Razón de momios</th>
<th>IC 95 %</th>
<th>q</th> <th>q</th>
<th>Probabilidad</th> <th>Probabilidad</th>
<th>Referencia</th> <th>Probabilidad de referencia</th>
<th>Mismo sentido</th> <th>Mismo sentido</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (pair of row.pairs; track pair.pair) { @for (pair of row.pairs; track pair.pair) {
<tr> <tr>
<td>{{ pair.pair || '—' }}</td> <td>{{ pair.title }}</td>
<td> <td>{{ formatOr(pair.or) }}</td>
{{ (pair.or | number: '1.0-3') ?? '—' }} ({{ <td>{{ formatIc(pair.low, pair.high) }}</td>
(pair.low | number: '1.0-3') ?? '—' <td>{{ formatQ(pair.q) }}</td>
}}–{{ (pair.high | number: '1.0-3') ?? '—' }}) <td>{{ formatProbability(pair.probability) }}</td>
</td> <td>{{ formatProbability(pair.reference) }}</td>
<td>{{ (pair.q | number: '1.0-4') ?? '—' }}</td>
<td>{{ (pair.probability | number: '1.0-4') ?? '—' }}</td>
<td>{{ (pair.reference | number: '1.0-4') ?? '—' }}</td>
<td> <td>
{{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }} {{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }}
</td> </td>
@@ -214,7 +223,7 @@
} }
} @empty { } @empty {
<tr> <tr>
<td colspan="4" class="muted">No hay registros para los filtros aplicados.</td> <td colspan="10" class="muted">No hay registros para los filtros aplicados.</td>
</tr> </tr>
} }
</tbody> </tbody>
+10 -2
View File
@@ -1,5 +1,4 @@
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import { DecimalPipe } from '@angular/common';
import { Component, computed, inject, resource, signal } from '@angular/core'; import { Component, computed, inject, resource, signal } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
@@ -17,11 +16,16 @@ import { name } from './measures';
import { Pager } from './pager'; import { Pager } from './pager';
import { PatientSearch } from './patient-search'; import { PatientSearch } from './patient-search';
import { import {
ageMonths,
ASSOCIATION_LABELS, ASSOCIATION_LABELS,
associationRows, associationRows,
DEFAULT_ASSOCIATION_FILTER, DEFAULT_ASSOCIATION_FILTER,
exportTea, exportTea,
fetchTeaRows, fetchTeaRows,
formatIc,
formatOr,
formatProbability,
formatQ,
matchesTeaSearch, matchesTeaSearch,
parameters, parameters,
SCORE_FILTERS, SCORE_FILTERS,
@@ -34,7 +38,6 @@ import {
@Component({ @Component({
selector: 'app-tab-riesgos-tea', selector: 'app-tab-riesgos-tea',
imports: [ imports: [
DecimalPipe,
FormsModule, FormsModule,
Loading, Loading,
MatButtonModule, MatButtonModule,
@@ -57,6 +60,11 @@ export class TabRiesgosTea {
protected readonly tokenFilters = TOKEN_FILTERS; protected readonly tokenFilters = TOKEN_FILTERS;
protected readonly scoreFilters = SCORE_FILTERS; protected readonly scoreFilters = SCORE_FILTERS;
protected readonly name = name; protected readonly name = name;
protected readonly ageMonths = ageMonths;
protected readonly formatOr = formatOr;
protected readonly formatIc = formatIc;
protected readonly formatQ = formatQ;
protected readonly formatProbability = formatProbability;
protected readonly search = signal(''); protected readonly search = signal('');
protected readonly association = signal<AssociationFilter>(DEFAULT_ASSOCIATION_FILTER); protected readonly association = signal<AssociationFilter>(DEFAULT_ASSOCIATION_FILTER);
protected readonly associationLabels = ASSOCIATION_LABELS; protected readonly associationLabels = ASSOCIATION_LABELS;
+11 -14
View File
@@ -103,18 +103,16 @@
<th scope="col">Expediente</th> <th scope="col">Expediente</th>
<th scope="col">Nombre</th> <th scope="col">Nombre</th>
<th scope="col">Sexo</th> <th scope="col">Sexo</th>
<th scope="col">Edad</th> <th scope="col">Edad (meses)</th>
<th scope="col">Etapas</th> <th scope="col">Etapa</th>
<th scope="col">Estado del caso</th> <th scope="col">Puntaje M-CHAT</th>
<th scope="col">M-CHAT</th> <th scope="col">CSS ADOS-2</th>
<th scope="col">CSS</th> <th scope="col">Estatus de EEG</th>
<th scope="col">EEG</th> <th scope="col">Alteraciones encontradas</th>
<th scope="col">Concordancia</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@for (row of rows(); track row.patient.id) { @for (row of rows(); track row.patient.id) {
@let age = ageMonths(row.patient.birthDate, cutoff());
<tr> <tr>
<td>{{ row.recordNumbers.join(', ') || '—' }}</td> <td>{{ row.recordNumbers.join(', ') || '—' }}</td>
<td> <td>
@@ -123,17 +121,16 @@
</a> </a>
</td> </td>
<td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td> <td>{{ row.patient.gender ? name(row.patient.gender) : '—' }}</td>
<td>{{ age == null ? '—' : age + ' meses' }}</td> <td>{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }}</td>
<td>{{ row.step ?? '—' }}</td> <td><app-tea-stepper [steps]="row.steps" /></td>
<td>{{ row.case ? name(row.case) : '—' }}</td>
<td>{{ row.mchatScore ?? '—' }}</td> <td>{{ row.mchatScore ?? '—' }}</td>
<td>{{ row.css ?? '—' }}</td> <td>{{ row.css ?? '—' }}</td>
<td>{{ eegDisplay(row.eegResult) }}</td> <td>{{ eegResultLabel(row.eegResult) }}</td>
<td>{{ row.concordance }}</td> <td>{{ row.alterations ?? '—' }}</td>
</tr> </tr>
} @empty { } @empty {
<tr> <tr>
<td colspan="10" class="muted"> <td colspan="9" class="muted">
@if (focused()) { @if (focused()) {
Este paciente no está en la lista de seguimiento Este paciente no está en la lista de seguimiento
} @else { } @else {
+75 -5
View File
@@ -8,12 +8,14 @@ import { RouterLink } from '@angular/router';
import type { Bundle } from 'fhir/r4'; import type { Bundle } from 'fhir/r4';
import { Fhir } from '../fhir'; import { Fhir } from '../fhir';
import { Loading } from '../loading'; import { Loading } from '../loading';
import type { TeaStep } from '../paciente/tea-data';
import { windowStart } from './follow-up'; import { windowStart } from './follow-up';
import { name } from './measures'; import { name } from './measures';
import { Pager } from './pager'; import { Pager } from './pager';
import { PatientSearch, patientSearch } from './patient-search'; import { PatientSearch, patientSearch } from './patient-search';
import { import {
ageMonths, ageMonths,
eegResultLabel,
exportTea, exportTea,
fetchTeaRows, fetchTeaRows,
parameters, parameters,
@@ -25,6 +27,77 @@ import {
type TeaFilters, type TeaFilters,
} from './tea-rows'; } from './tea-rows';
@Component({
selector: 'app-tea-stepper',
template: `
<ol role="list" aria-label="Etapas del tamizaje">
@for (step of steps(); track step.code; let i = $index) {
<li
[class.completed]="step.completed"
[class.connected]="step.completed && steps()[i + 1]?.completed"
[attr.aria-current]="i === lastCompleted() ? 'step' : null"
[attr.aria-label]="status(step)"
[attr.title]="status(step)"
>
<span class="circle" aria-hidden="true"></span>
</li>
}
</ol>
`,
styles: `
ol {
--circle-size: 12px;
display: flex;
width: max-content;
padding: 0;
margin: 0;
list-style: none;
}
li {
position: relative;
display: flex;
flex: 1 1 0;
min-width: 24px;
}
li:not(:last-child)::after {
content: '';
position: absolute;
top: calc(var(--circle-size) / 2 - 1px);
left: calc(50% + var(--circle-size) / 2);
width: max(0px, calc(100% - var(--circle-size)));
height: 2px;
background: var(--color-text-secondary);
}
li.connected::after {
background: var(--color-primary);
}
.circle {
box-sizing: border-box;
width: var(--circle-size);
height: var(--circle-size);
margin: 0 auto;
border: 1px solid var(--color-text-secondary);
border-radius: 50%;
}
li.completed .circle {
background: var(--color-primary);
border-color: var(--color-primary);
}
`,
})
class TeaStepper {
readonly steps = input.required<TeaStep[]>();
protected readonly lastCompleted = computed(() =>
this.steps()
.map((step) => step.completed)
.lastIndexOf(true),
);
protected status(step: TeaStep): string {
return `${step.label}: ${step.completed ? 'completado' : 'pendiente'}`;
}
}
@Component({ @Component({
selector: 'app-tab-seguimiento-tea', selector: 'app-tab-seguimiento-tea',
imports: [ imports: [
@@ -37,6 +110,7 @@ import {
PatientSearch, PatientSearch,
Pager, Pager,
RouterLink, RouterLink,
TeaStepper,
], ],
templateUrl: './tab-seguimiento-tea.html', templateUrl: './tab-seguimiento-tea.html',
styleUrl: './tab-seguimiento-tea.scss', styleUrl: './tab-seguimiento-tea.scss',
@@ -54,11 +128,11 @@ export class TabSeguimientoTea {
({ key }) => key !== 'sex' && key !== 'alteration' && key !== 'status', ({ key }) => key !== 'sex' && key !== 'alteration' && key !== 'status',
); );
protected readonly scoreFilters = SCORE_FILTERS; protected readonly scoreFilters = SCORE_FILTERS;
private readonly eegOptions = TOKEN_FILTERS.find(({ key }) => key === 'eeg')!.options;
protected readonly size = signal(20); protected readonly size = signal(20);
protected readonly search = signal(''); protected readonly search = signal('');
protected readonly name = name; protected readonly name = name;
protected readonly ageMonths = ageMonths; protected readonly ageMonths = ageMonths;
protected readonly eegResultLabel = eegResultLabel;
private readonly request = computed(() => { private readonly request = computed(() => {
const id = this.focused(); const id = this.focused();
@@ -99,10 +173,6 @@ export class TabSeguimientoTea {
protected readonly exporting = signal(false); protected readonly exporting = signal(false);
protected readonly actionError = signal(''); protected readonly actionError = signal('');
protected eegDisplay(code: string | undefined): string {
return this.eegOptions.find((option) => option.code === code)?.label ?? '—';
}
protected clearFocus(id: string): void { protected clearFocus(id: string): void {
this.cleared.set(id); this.cleared.set(id);
} }
+168 -18
View File
@@ -1,10 +1,15 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { EXT } from '../fhir'; import { EXT } from '../fhir';
import { teaSteps } from '../paciente/tea-data';
import { nestedDonut, shareDonut } from './figures'; import { nestedDonut, shareDonut } from './figures';
import type { Catalog } from './pages'; import type { Catalog } from './pages';
import { import {
ageMonths, ageMonths,
associationRows, associationRows,
formatIc,
formatOr,
formatProbability,
formatQ,
matchesTeaSearch, matchesTeaSearch,
teaParams, teaParams,
teaRows, teaRows,
@@ -26,6 +31,9 @@ function fixture(): Bundle {
{ url: EXT + 'tea-step', valueCode: 'eeg' }, { url: EXT + 'tea-step', valueCode: 'eeg' },
{ url: EXT + 'tea-case', valueCode: 'confirmed' }, { url: EXT + 'tea-case', valueCode: 'confirmed' },
{ url: EXT + 'tea-eeg-result', valueCode: 'normal' }, { url: EXT + 'tea-eeg-result', valueCode: 'normal' },
{ url: EXT + 'tea-mchat', valueDecimal: 9 },
{ url: EXT + 'tea-css', valueInteger: 8 },
{ url: EXT + 'tea-alterations', valueInteger: 2 },
], ],
}; };
const ados: Observation = { const ados: Observation = {
@@ -63,6 +71,8 @@ function fixture(): Bundle {
{ url: EXT + 'association-headline', valueBoolean: true }, { url: EXT + 'association-headline', valueBoolean: true },
{ url: EXT + 'association-reference-probability', valueDecimal: 0.35 }, { url: EXT + 'association-reference-probability', valueDecimal: 0.35 },
{ url: EXT + 'association-odds-ratio', valueDecimal: 2 }, { url: EXT + 'association-odds-ratio', valueDecimal: 2 },
{ url: EXT + 'association-ci-low', valueDecimal: 1.2 },
{ url: EXT + 'association-ci-high', valueDecimal: 4.5 },
{ url: EXT + 'association-q', valueDecimal: 0.01 }, { url: EXT + 'association-q', valueDecimal: 0.01 },
], ],
}, },
@@ -74,9 +84,17 @@ function fixture(): Bundle {
code: { coding: [{ code: 'eeg' }] }, code: { coding: [{ code: 'eeg' }] },
subject, subject,
effectiveDateTime: '2026-03-04', effectiveDateTime: '2026-03-04',
conclusionCode: [{ text: 'Bueno' }], conclusionCode: [{ coding: [{ code: 'good' }], text: 'Bueno' }],
extension: [{ url: EXT + 'eeg-channels', valueInteger: 19 }], extension: [{ url: EXT + 'eeg-channels', valueInteger: 19 }],
}; };
const neurology: Observation = {
resourceType: 'Observation',
status: 'final',
subject,
code: { coding: [{ code: 'clinical_note.specialty' }] },
valueCodeableConcept: { coding: [{ code: 'pediatric_neurology' }] },
effectiveDateTime: '2026-03-03',
};
return { return {
resourceType: 'Bundle', resourceType: 'Bundle',
type: 'searchset', type: 'searchset',
@@ -85,6 +103,7 @@ function fixture(): Bundle {
{ resource: { resourceType: 'Patient', id: 'other' }, search: { mode: 'match' } }, { resource: { resourceType: 'Patient', id: 'other' }, search: { mode: 'match' } },
{ resource: ados, search: { mode: 'include' } }, { resource: ados, search: { mode: 'include' } },
{ resource: risk, search: { mode: 'include' } }, { resource: risk, search: { mode: 'include' } },
{ resource: neurology, search: { mode: 'include' } },
{ resource: eeg, search: { mode: 'include' } }, { resource: eeg, search: { mode: 'include' } },
...['2026-03-01', '2026-02-27'].map((date) => ({ ...['2026-03-01', '2026-02-27'].map((date) => ({
search: { mode: 'include' as const }, search: { mode: 'include' as const },
@@ -93,7 +112,7 @@ function fixture(): Bundle {
status: 'final' as const, status: 'final' as const,
subject, subject,
code: { coding: [{ code: 'mchat.score' }] }, code: { coding: [{ code: 'mchat.score' }] },
valueQuantity: { value: 9 }, valueQuantity: { value: 7 },
effectiveDateTime: date, effectiveDateTime: date,
}, },
})), })),
@@ -169,36 +188,54 @@ describe('TEA indicators', () => {
expect(teaParams({ cssMax: 0 })['tea-css']).toEqual(['le0']); expect(teaParams({ cssMax: 0 })['tea-css']).toEqual(['le0']);
}); });
it('uses follow-up codes and assembles the included dates and association headline', () => { it('reads the follow-up extensions and assembles the stepper and association headline', () => {
const [row, other] = teaRows(fixture()); const [row, other] = teaRows(fixture());
expect(row.steps.map(({ date }) => date)).toEqual([ expect(row.steps.map(({ date }) => date)).toEqual([
'2026-02-27', '2026-02-27',
'2026-03-02', '2026-03-02',
undefined, '2026-03-03',
'2026-03-04', '2026-03-04',
]); ]);
expect(row.steps.map(({ completed }) => completed)).toEqual([true, true, true, true]);
expect(row).toMatchObject({ expect(row).toMatchObject({
name: 'Ana López', name: 'Ana López',
step: 'EEG',
case: 'confirmed',
eegResult: 'normal', eegResult: 'normal',
recordNumbers: ['123'], recordNumbers: ['123'],
mchatScore: 9, mchatScore: 9,
css: 8, css: 8,
headline: { pair: cssPair, or: 2, q: 0.01 }, alterations: 2,
concordance: 'Concordante', headline: {
pair: cssPair,
title: 'Husos N2 · Central · CSS',
or: 2,
low: 1.2,
high: 4.5,
q: 0.01,
},
}); });
expect(other.concordance).toBe('—'); expect(other.headline).toBeUndefined();
}); });
it('compares the headline item score with the prediction and reference', () => { it('titles an item association with the patient’s ADOS-2 item', () => {
const page = fixture(); const page = fixture();
const risk = page.entry!.find((e) => e.resource?.resourceType === 'RiskAssessment')! const risk = page.entry!.find((e) => e.resource?.resourceType === 'RiskAssessment')!
.resource as RiskAssessment; .resource as RiskAssessment;
const prediction = risk.prediction![0]; risk.prediction![0].outcome = { coding: [{ code: 'posterior_rhythm|central|ados2_item_01' }] };
prediction.outcome = { coding: [{ code: 'rhythm|central|ados2_item_01' }] }; expect(teaRows(page)[0].headline?.title).toBe(
prediction.probabilityDecimal = 0.1; 'Ritmo posterior · Central · Frecuencia de la vocalización espontánea dirigida a otros',
expect(teaRows(page)[0].concordance).toBe('No concordante'); );
});
it('formats the association values like the reference list', () => {
expect(formatOr(2)).toBe('2.00');
expect(formatOr(undefined)).toBe('—');
expect(formatIc(1.2, 4.5)).toBe('1.20–4.50');
expect(formatIc(undefined, 4.5)).toBe('—');
expect(formatQ(0.0004)).toBe('< 0.001');
expect(formatQ(0.0123)).toBe('0.012');
expect(formatQ(undefined)).toBe('—');
expect(formatProbability(0.35)).toBe('35 %');
expect(formatProbability(undefined)).toBe('—');
}); });
it('defaults to all children and filters by association results', () => { it('defaults to all children and filters by association results', () => {
@@ -222,13 +259,20 @@ describe('TEA indicators', () => {
}); });
it('builds the follow-up workbook', () => { it('builds the follow-up workbook', () => {
expect(teaWorkbook(teaRows(fixture()), false, DAY)).toEqual({ expect(teaWorkbook(teaRows(fixture()), false, '2026-03-31', DAY)).toEqual({
name: 'tea-seguimiento-2026-11-30', name: 'tea-seguimiento-2026-11-30',
sheets: [ sheets: [
expect.objectContaining({ expect.objectContaining({
name: 'Seguimiento', name: 'Seguimiento',
rows: expect.arrayContaining([ rows: expect.arrayContaining([
expect.objectContaining({ id: 'child', pair: cssPair, eeg: '2026-03-04' }), expect.objectContaining({
id: 'child',
eeg: '2026-03-04',
mchat: 9,
css: 8,
eegResult: 'Normal',
alterations: 2,
}),
]), ]),
}), }),
], ],
@@ -236,10 +280,23 @@ describe('TEA indicators', () => {
}); });
it('builds the risk workbook with children and pair details', () => { it('builds the risk workbook with children and pair details', () => {
expect(teaWorkbook(associationRows(teaRows(fixture())), true, DAY)).toEqual({ expect(teaWorkbook(associationRows(teaRows(fixture())), true, '2026-03-31', DAY)).toEqual({
name: 'tea-riesgos-2026-11-30', name: 'tea-riesgos-2026-11-30',
sheets: [ sheets: [
expect.objectContaining({ name: 'Niños' }), expect.objectContaining({
name: 'Niños',
rows: expect.arrayContaining([
expect.objectContaining({
id: 'child',
pair: 'Husos N2 · Central · CSS',
or: 2,
low: 1.2,
high: 4.5,
probability: 0.35,
reference: 0.35,
}),
]),
}),
expect.objectContaining({ expect.objectContaining({
name: 'Pares', name: 'Pares',
rows: [ rows: [
@@ -255,3 +312,96 @@ describe('TEA indicators', () => {
}); });
}); });
}); });
const observation = (field: string, day: string, value?: string): Observation => ({
resourceType: 'Observation',
status: 'final',
code: { coding: [{ code: field }] },
effectiveDateTime: day,
...(value ? { valueCodeableConcept: { coding: [{ code: value }] } } : {}),
});
const eeg = (day: string, quality: string): DiagnosticReport => ({
resourceType: 'DiagnosticReport',
status: 'final',
code: { coding: [{ code: 'eeg' }] },
effectiveDateTime: day,
conclusionCode: [{ coding: [{ code: quality }] }],
});
describe('Etapas del tamizaje TEA', () => {
it('toma la primera fecha de cada etapa en el orden del proceso', () => {
const steps = teaSteps(
[
observation('mchat.score', '2026-03-01'),
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatric_neurology'),
],
[eeg('2026-03-10', 'good')],
);
expect(steps.map(({ code, label }) => ({ code, label }))).toEqual([
{ code: 'mchat_only', label: 'M-CHAT' },
{ code: 'psychology', label: 'Psicología' },
{ code: 'neurology', label: 'Neuropediatría' },
{ code: 'eeg', label: 'EEG' },
]);
expect(steps.map((step) => step.date)).toEqual([
'2026-02-27',
'2026-03-04',
'2026-03-06',
'2026-03-10',
]);
expect(steps.every((step) => step.completed)).toBe(true);
});
it('completa el EEG solo con un estudio de buena calidad', () => {
const observations = [
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatric_neurology'),
observation('eeg.lab_record_id', '2026-03-08'),
];
const steps = teaSteps(observations, [eeg('2026-03-10', 'bad'), eeg('2026-03-12', 'good')]);
expect(steps[3]).toMatchObject({ date: '2026-03-12', completed: true });
expect(teaSteps(observations, [eeg('2026-03-10', 'bad')])[3]).toMatchObject({
date: undefined,
completed: false,
});
expect(teaSteps(observations, [])[3]).toMatchObject({ date: undefined, completed: false });
});
it('ignora las notas de otras especialidades', () => {
const steps = teaSteps(
[
observation('mchat.score', '2026-02-27'),
observation('ados2', '2026-03-04'),
observation('clinical_note.specialty', '2026-03-06', 'pediatrics'),
],
[],
);
expect(steps[2]).toMatchObject({ date: undefined, completed: false });
});
it('deja pendientes las etapas tras un hueco', () => {
const steps = teaSteps(
[observation('mchat.score', '2026-02-27'), observation('ados2', '2026-03-04')],
[eeg('2026-03-10', 'good')],
);
expect(steps.map((step) => step.completed)).toEqual([true, true, false, false]);
expect(steps[3].date).toBeUndefined();
});
it('usa la etapa registrada para mostrar el avance del seguimiento', () => {
const steps = teaSteps([], [], 'neurology');
expect(steps.map((step) => step.completed)).toEqual([true, true, true, false]);
});
it('fecha cada etapa a partir de la anterior cuando el estudio ocurrió antes', () => {
const steps = teaSteps(
[observation('mchat.score', '2026-02-27'), observation('ados2', '2026-02-26')],
[],
);
expect(steps[1]).toMatchObject({ date: '2026-02-27', completed: true });
});
});
+104 -102
View File
@@ -1,17 +1,10 @@
import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4';
import { ados2Component } from '../ados2';
import { downloadXlsx, safeName, type Sheet } from '../export'; import { downloadXlsx, safeName, type Sheet } from '../export';
import { code, ext, patientName, resources, type Fhir, type Params } from '../fhir'; import { code, ext, patientName, resources, type Fhir, type Params } from '../fhir';
import { pairTitle, TEA_STEPS, teaSteps } from '../paciente/tea-data';
import { name } from './measures'; import { name } from './measures';
import { matchesSearch } from './patient-search'; 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]; type Prediction = NonNullable<RiskAssessment['prediction']>[number];
function associationPair(p: Prediction) { function associationPair(p: Prediction) {
@@ -29,18 +22,6 @@ function associationPair(p: Prediction) {
}; };
} }
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>( function byPatient<T extends DiagnosticReport | Observation | RiskAssessment>(
records: T[], records: T[],
): Map<string | undefined, T[]> { ): Map<string | undefined, T[]> {
@@ -58,42 +39,23 @@ export function teaRows(page: Bundle) {
const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport')); const reports = byPatient(resources<DiagnosticReport>(page, 'DiagnosticReport'));
const observations = byPatient(resources<Observation>(page, 'Observation')); const observations = byPatient(resources<Observation>(page, 'Observation'));
const risks = byPatient(resources<RiskAssessment>(page, 'RiskAssessment')); 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) => { return resources<Patient>(page, 'Patient', 'match').map((patient) => {
const subject = `Patient/${patient.id}`; const subject = `Patient/${patient.id}`;
const obs = observations.get(subject) ?? []; const obs = observations.get(subject) ?? [];
const eegs = (reports.get(subject) ?? []).filter((r) => code(r.code) === 'eeg').sort(dateOrder); const ados = obs
const ados = obs.filter((o) => code(o.code) === 'ados2').sort(dateOrder); .filter((o) => code(o.code) === 'ados2')
const mchat = obs.filter((o) => code(o.code) === 'mchat.score').sort(dateOrder)[0]; .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''));
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 risk = risks.get(subject)?.[0];
const pairs = (risk?.prediction ?? []).map(associationPair);
const headline = pairs.find((p) => p.headline);
const basisAdos = risk?.basis?.find((ref) => const basisAdos = risk?.basis?.find((ref) =>
ref.reference?.startsWith('Observation/'), ref.reference?.startsWith('Observation/'),
)?.reference; )?.reference;
const evaluation = basisAdos const evaluation = basisAdos
? ados.find((o) => `Observation/${o.id}` === basisAdos) ? ados.find((o) => `Observation/${o.id}` === basisAdos)
: ados.at(-1); : ados.at(-1);
const dates = [ const pairs = (risk?.prediction ?? []).map((p) => {
mchat?.effectiveDateTime, const pair = associationPair(p);
ados[0]?.effectiveDateTime, return { ...pair, title: pairTitle(pair.pair ?? '', evaluation) };
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 { return {
patient, patient,
name: patientName(patient), name: patientName(patient),
@@ -104,14 +66,12 @@ export function teaRows(page: Bundle) {
.map((i) => 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, eegResult: ext(patient, 'tea-eeg-result')?.valueCode,
steps: TEA_STEPS.map((step, i) => ({ ...step, date: dates[i] })), steps: teaSteps(obs, reports.get(subject) ?? [], ext(patient, 'tea-step')?.valueCode),
mchatScore: mchat?.valueQuantity?.value, mchatScore: ext(patient, 'tea-mchat')?.valueDecimal,
css: ados.at(-1)?.valueInteger, css: ext(patient, 'tea-css')?.valueInteger,
headline, alterations: ext(patient, 'tea-alterations')?.valueInteger,
concordance: concordance(headline, evaluation), headline: pairs.find((p) => p.headline),
pairs, pairs,
}; };
}); });
@@ -233,6 +193,22 @@ function choices(...codes: string[]) {
return codes.map((code) => ({ code, label: name(code) })); return codes.map((code) => ({ code, label: name(code) }));
} }
export function eegResultLabel(result: string | undefined): string {
const filter = TOKEN_FILTERS.find(({ key }) => key === 'eeg')!;
return filter.options.find((option) => option.code === result)?.label ?? '—';
}
export const formatOr = (value?: number): string => (value == null ? '—' : value.toFixed(2));
export const formatIc = (low?: number, high?: number): string =>
low == null || high == null ? '—' : `${low.toFixed(2)}–${high.toFixed(2)}`;
export const formatQ = (q?: number): string =>
q == null ? '—' : q < 0.001 ? '< 0.001' : q.toFixed(3);
export const formatProbability = (probability?: number): string =>
probability == null ? '—' : `${Math.round(probability * 100)} %`;
export function matchesTeaSearch(row: TeaRow, query: string): boolean { export function matchesTeaSearch(row: TeaRow, query: string): boolean {
return matchesSearch(query, [ return matchesSearch(query, [
...(row.patient.name ?? []).map(({ text }) => text), ...(row.patient.name ?? []).map(({ text }) => text),
@@ -258,61 +234,87 @@ const columns = (entries: [string, string][]): Sheet['columns'] =>
export function teaWorkbook( export function teaWorkbook(
rows: TeaRow[], rows: TeaRow[],
risk: boolean, risk: boolean,
cutoff = '',
day = new Date(), day = new Date(),
): { name: string; sheets: Sheet[] } { ): { name: string; sheets: Sheet[] } {
const identity: [string, string][] = [ const identity: [string, string][] = [
['id', 'Paciente'], ['id', 'Paciente'],
['record', 'Expediente'], ['record', 'Expediente'],
['name', 'Nombre'], ['name', 'Nombre'],
['sex', 'Sexo'],
['birth', 'Nacimiento'],
['age', 'Edad (meses)'],
]; ];
const headline: [string, string][] = [ const people = rows.map((row) => ({
['pair', 'Par principal'], id: row.patient.id,
['or', 'OR'], record: row.recordNumbers.join(', '),
['q', 'q'], name: row.name,
['concordance', 'Concordancia con el ADOS-2'], sex: row.patient.gender ? name(row.patient.gender) : undefined,
]; birth: row.patient.birthDate,
const steps: [string, string][] = TEA_STEPS.map(({ code, label }) => [code, label]); age: ageMonths(row.patient.birthDate, cutoff),
const sheets: Sheet[] = [ }));
{ const sheets: Sheet[] = risk
name: risk ? 'Niños' : 'Seguimiento', ? [
columns: columns([ {
...identity, name: 'Niños',
['sex', 'Sexo'], columns: columns([
['birth', 'Nacimiento'], ...identity,
...(risk ? [] : steps), ['pair', 'Asociación principal'],
...headline, ['or', 'Razón de momios'],
]), ['low', 'IC 95 % inferior'],
rows: rows.map((row) => ({ ['high', 'IC 95 % superior'],
id: row.patient.id, ['q', 'q'],
record: row.recordNumbers.join(', '), ['probability', 'Probabilidad'],
name: row.name, ['reference', 'Probabilidad de referencia'],
sex: row.patient.gender ? name(row.patient.gender) : undefined, ]),
birth: row.patient.birthDate, rows: rows.map((row, i) => ({
...Object.fromEntries(row.steps.map(({ code, date }) => [code, date])), ...people[i],
pair: row.headline?.pair, pair: row.headline?.title,
or: row.headline?.or, or: row.headline?.or,
q: row.headline?.q, low: row.headline?.low,
concordance: row.concordance, high: row.headline?.high,
})), q: row.headline?.q,
}, probability: row.headline?.probability,
]; reference: row.headline?.reference,
if (risk) { })),
sheets.push({ },
name: 'Pares', {
columns: columns([ name: 'Pares',
['id', 'Paciente'], columns: columns([
['pair', 'Par'], ['id', 'Paciente'],
['or', 'OR'], ['pair', 'Par'],
['low', 'IC inferior'], ['or', 'OR'],
['high', 'IC superior'], ['low', 'IC inferior'],
['q', 'q'], ['high', 'IC superior'],
['probability', 'Probabilidad'], ['q', 'q'],
['reference', 'Referencia'], ['probability', 'Probabilidad'],
['sameDirection', 'Mismo sentido'], ['reference', 'Referencia'],
]), ['sameDirection', 'Mismo sentido'],
rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))), ]),
}); rows: rows.flatMap((row) => row.pairs.map((pair) => ({ id: row.patient.id, ...pair }))),
} },
]
: [
{
name: 'Seguimiento',
columns: columns([
...identity,
...TEA_STEPS.map(({ code, label }): [string, string] => [code, label]),
['mchat', 'Puntaje M-CHAT'],
['css', 'CSS ADOS-2'],
['eegResult', 'Estatus de EEG'],
['alterations', 'Alteraciones encontradas'],
]),
rows: rows.map((row, i) => ({
...people[i],
...Object.fromEntries(row.steps.map(({ code, date }) => [code, date])),
mchat: row.mchatScore,
css: row.css,
eegResult: eegResultLabel(row.eegResult),
alterations: row.alterations,
})),
},
];
const page = risk ? 'riesgos' : 'seguimiento'; const page = risk ? 'riesgos' : 'seguimiento';
return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets }; return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets };
} }
@@ -322,7 +324,7 @@ export function exportTea(
params: Record<string, string>, params: Record<string, string>,
risk: boolean, risk: boolean,
): Promise<void> { ): Promise<void> {
const { name, sheets } = teaWorkbook(rows, risk); const { name, sheets } = teaWorkbook(rows, risk, params['follow-up-cutoff']);
return downloadXlsx(name, sheets, params); return downloadXlsx(name, sheets, params);
} }
+72 -63
View File
@@ -10,16 +10,51 @@ import { ados2Component, ados2Groups } from '../ados2';
import { ZONE_NAMES } from '../eeg-labels'; import { ZONE_NAMES } from '../eeg-labels';
import { code, CURP, ext, Fhir, label, resources } from '../fhir'; import { code, CURP, ext, Fhir, label, resources } from '../fhir';
const NSS = 'https://isssteleon.org/fhir/sid/nss'; export 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;
const steps: Record<string, string> = { export type TeaStep = { code: string; label: string; date?: string; completed: boolean };
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología',
neurology: 'Neurología',
eeg: 'EEG',
};
const metrics: Record<string, string> = { const firstDate = (items: { effectiveDateTime?: string }[]): string | undefined =>
items
.map((item) => item.effectiveDateTime)
.filter((day): day is string => !!day)
.sort()[0];
export function teaSteps(
observations: Observation[],
reports: DiagnosticReport[],
stage?: string,
): TeaStep[] {
const dates = [
firstDate(observations.filter((o) => code(o.code) === 'mchat.score')),
firstDate(observations.filter((o) => code(o.code) === 'ados2')),
firstDate(
observations.filter(
(o) =>
code(o.code) === 'clinical_note.specialty' &&
code(o.valueCodeableConcept) === 'pediatric_neurology',
),
),
firstDate(
reports.filter((r) => code(r.code) === 'eeg' && code(r.conclusionCode?.[0]) === 'good'),
),
];
const current = TEA_STEPS.findIndex(({ code }) => code === stage);
let previous: string | undefined;
return TEA_STEPS.map((step, i) => {
const date = dates[i];
const reached = i === 0 ? date : previous && date && (date < previous ? previous : date);
previous = reached;
return { ...step, date: reached, completed: current < 0 ? reached != null : i <= current };
});
}
const METRIC_TITLES: Record<string, string> = {
posterior_rhythm: 'Ritmo posterior', posterior_rhythm: 'Ritmo posterior',
spindles_n2: 'Husos N2', spindles_n2: 'Husos N2',
spindles_n3: 'Husos N3', spindles_n3: 'Husos N3',
@@ -27,13 +62,36 @@ const metrics: Record<string, string> = {
anteroposterior_gradient: 'Gradiente anteroposterior', anteroposterior_gradient: 'Gradiente anteroposterior',
}; };
const biomarkers: Record<string, string> = { const BIOMARKER_METRICS: Record<string, string> = {
spikes: 'paroxysmal_spikes', spikes: 'paroxysmal_spikes',
spindles: 'spindles_n2', spindles: 'spindles_n2',
posterior_rhythm: 'posterior_rhythm', posterior_rhythm: 'posterior_rhythm',
gradient: 'anteroposterior_gradient', gradient: 'anteroposterior_gradient',
}; };
export function zoneLabel(zone: string): string {
return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone);
}
export function pairTitle(key: string, ados?: Observation): string {
const [biomarker, zone = '', outcome = ''] = key.split('|');
const item = /^ados2_item_(\d+)$/.exec(outcome);
return [
METRIC_TITLES[BIOMARKER_METRICS[biomarker]] ?? biomarker,
zoneLabel(zone),
item ? label(ados2Component(ados, Number(item[1]))?.code) || outcome : outcome,
].join(' · ');
}
const NSS = 'https://isssteleon.org/fhir/sid/nss';
const steps: Record<string, string> = {
mchat_only: 'Solo M-CHAT',
psychology: 'Psicología',
neurology: 'Neurología',
eeg: 'EEG',
};
const classifications: Record<string, string> = { const classifications: Record<string, string> = {
non_spectrum: 'Fuera del espectro', non_spectrum: 'Fuera del espectro',
autism_spectrum: 'Espectro autista', autism_spectrum: 'Espectro autista',
@@ -130,46 +188,6 @@ export function adosSummary(observation: Observation): string[][] {
]; ];
} }
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[] { function checkRow(o: Observation): string[] {
const range = o.referenceRange?.[0]; const range = o.referenceRange?.[0];
const abnormal = code(o.interpretation?.[0]); const abnormal = code(o.interpretation?.[0]);
@@ -193,7 +211,7 @@ function metric(o: Observation) {
const key = code(o.code) ?? ''; const key = code(o.code) ?? '';
return { return {
key, key,
title: metrics[key] ?? shown(label(o.code)), title: METRIC_TITLES[key] ?? shown(label(o.code)),
value: o.valueQuantity?.value, value: o.valueQuantity?.value,
unit: o.valueQuantity?.unit, unit: o.valueQuantity?.unit,
z: ext(o, 'eeg-z')?.valueDecimal, z: ext(o, 'eeg-z')?.valueDecimal,
@@ -248,10 +266,6 @@ export type Pair = {
export type Study = ReturnType<typeof study>; export type Study = ReturnType<typeof study>;
export function zoneLabel(zone: string): string {
return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone);
}
export function alteration(outside: number | undefined): string { export function alteration(outside: number | undefined): string {
return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango'; return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango';
} }
@@ -264,20 +278,15 @@ function associations(
return (risk?.prediction ?? []) return (risk?.prediction ?? [])
.map((p): Pair => { .map((p): Pair => {
const key = code(p.outcome) ?? ''; const key = code(p.outcome) ?? '';
const [biomarker, zone = '', outcome = ''] = key.split('|'); const [biomarker, zone = ''] = key.split('|');
const metric = eeg?.metrics.find((m) => m.key === biomarkers[biomarker]); const metric = eeg?.metrics.find((m) => m.key === BIOMARKER_METRICS[biomarker]);
const site = const site =
zone === 'global' || biomarker === 'posterior_rhythm' zone === 'global' || biomarker === 'posterior_rhythm'
? metric ? metric
: metric?.sites.find((s) => s.kind === 'zone' && s.name === zone); : metric?.sites.find((s) => s.kind === 'zone' && s.name === zone);
const item = /^ados2_item_(\d+)$/.exec(outcome);
return { return {
key, key,
title: [ title: pairTitle(key, ados[0]),
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, headline: ext(p, 'association-headline')?.valueBoolean === true,
altered: site?.outside != null && site.outside !== 0, altered: site?.outside != null && site.outside !== 0,
z: site?.z, z: site?.z,
@@ -316,7 +325,7 @@ export async function loadTeaPatient(fhir: Fhir, id: string) {
patient, patient,
ados, ados,
studies, studies,
timeline: timeline(observations, ados, reports), steps: teaSteps(observations, reports),
riskStudy, riskStudy,
pairs: associations(risk, riskStudy, ados), pairs: associations(risk, riskStudy, ados),
}; };
+93 -1
View File
@@ -1,6 +1,98 @@
import { banded } from '../gobernanza/figures'; import { banded } from '../gobernanza/figures';
import { Figure, PALETTE } from '../plot'; import { Figure, PALETTE } from '../plot';
import { Metric, Pair, Site, Study, zoneLabel } from './tea-data'; import { Metric, Pair, Site, Study, TeaStep, zoneLabel } from './tea-data';
const DAY = 24 * 60 * 60 * 1000;
const day = (iso: string): string => {
const [y, m, d] = iso.slice(0, 10).split('-');
return `${d}/${m}/${y}`;
};
export function timeline(steps: TeaStep[]): Figure | null {
const done = steps.filter((step): step is TeaStep & { date: string } =>
Boolean(step.completed && step.date),
);
if (!done.length) return null;
const spans = done.slice(1).map((step, i) => ({ from: done[i], to: step }));
const last = done.at(-1)!.date;
const bars = {
type: 'bar',
orientation: 'h',
base: spans.map(({ from }) => from.date),
x: spans.map(({ from, to }) => Date.parse(to.date) - Date.parse(from.date)),
y: spans.map(({ to }) => to.label),
width: 0.24,
marker: { color: PALETTE[6] },
hoverinfo: 'skip',
showlegend: false,
} satisfies Figure['data'][number] & { base: string[] };
return {
data: [
bars,
{
type: 'scatter',
mode: 'markers',
x: done.map((step) => step.date),
y: done.map((step) => step.label),
marker: {
symbol: 'diamond',
size: 16,
color: PALETTE[0],
line: { color: '#17324d', width: 1 },
},
customdata: done.map((step) => day(step.date)),
hovertemplate: '%{y} · %{customdata}<extra></extra>',
showlegend: false,
},
],
layout: {
showlegend: false,
margin: { l: 140, r: 90, t: 16, b: 40 },
xaxis: {
type: 'date',
tickformat: '%d/%m/%Y',
...(done.every((step) => step.date === last)
? {
range: [
new Date(Date.parse(last) - 30 * DAY).toISOString().slice(0, 10),
new Date(Date.parse(last) + 30 * DAY).toISOString().slice(0, 10),
],
}
: {}),
},
yaxis: {
type: 'category',
categoryorder: 'array',
categoryarray: steps.map((step) => step.label).reverse(),
range: [-0.5, steps.length - 0.5],
fixedrange: true,
},
annotations: [
...spans.map((span) => ({
x: new Date((Date.parse(span.from.date) + Date.parse(span.to.date)) / 2)
.toISOString()
.slice(0, 10),
y: span.to.label,
yshift: 14,
showarrow: false,
text: `${Math.round((Date.parse(span.to.date) - Date.parse(span.from.date)) / DAY)} días`,
})),
...steps
.filter((step) => !step.completed)
.map((step) => ({
x: 1,
xref: 'paper' as const,
xanchor: 'right' as const,
y: step.label,
showarrow: false,
font: { color: PALETTE[6] },
text: 'Pendiente',
})),
],
},
};
}
const electrodes: Record<string, [number, number]> = { const electrodes: Record<string, [number, number]> = {
Fp1: [-0.3, 0.87], Fp1: [-0.3, 0.87],
+91 -3
View File
@@ -1,8 +1,8 @@
import type { Observation, Patient } from 'fhir/r4'; import type { Observation, Patient } from 'fhir/r4';
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { EXT } from '../fhir'; import { EXT } from '../fhir';
import { identityRows, Metric, Pair } from './tea-data'; import { identityRows, Metric, Pair, pairTitle, TeaStep, zoneLabel } from './tea-data';
import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures'; import { ageNorm, forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures';
import { import {
forestTitle, forestTitle,
probabilityTitle, probabilityTitle,
@@ -91,13 +91,20 @@ const ados: Observation = {
], ],
}; };
const steps: TeaStep[] = [
{ code: 'mchat_only', label: 'M-CHAT', date: '2025-11-01', completed: true },
{ code: 'psychology', label: 'Psicología', date: '2025-11-22', completed: true },
{ code: 'neurology', label: 'Neuropediatría', completed: false },
{ code: 'eeg', label: 'EEG', completed: false },
];
const record = { const record = {
patient: { patient: {
resourceType: 'Patient' as const, resourceType: 'Patient' as const,
id: 'child', id: 'child',
name: [{ text: 'Paciente de prueba' }], name: [{ text: 'Paciente de prueba' }],
}, },
timeline: [['2025-11-22', 'ADOS-2', '—']], steps,
ados: [ados], ados: [ados],
studies: [], studies: [],
riskStudy: undefined, riskStudy: undefined,
@@ -150,6 +157,47 @@ describe('Figuras del paciente TEA', () => {
{ mode: 'markers', x: [0], y: [20] }, { mode: 'markers', x: [0], y: [20] },
]); ]);
}); });
it('marca con un rombo cada etapa completada en su fecha', () => {
const figure = timeline(steps)!;
const markers = figure.data.find((trace) => trace.type === 'scatter')!;
expect(markers).toMatchObject({
marker: expect.objectContaining({ symbol: 'diamond' }),
x: ['2025-11-01', '2025-11-22'],
y: ['M-CHAT', 'Psicología'],
});
expect(figure.data[0]).toMatchObject({
type: 'bar',
orientation: 'h',
base: ['2025-11-01'],
x: [21 * 24 * 60 * 60 * 1000],
y: ['Psicología'],
});
});
it('anota los días entre etapas y deja pendientes las que faltan', () => {
const figure = timeline(steps)!;
const notes = figure.layout?.annotations ?? [];
expect(notes.map((note) => note.text)).toEqual(['21 días', 'Pendiente', 'Pendiente']);
expect(notes.slice(1).map((note) => note.y)).toEqual(['Neuropediatría', 'EEG']);
expect(figure.layout?.yaxis?.categoryarray).toEqual([
'EEG',
'Neuropediatría',
'Psicología',
'M-CHAT',
]);
});
it('amplía el eje de una sola fecha y no dibuja nada sin etapas completadas', () => {
const single = timeline([
steps[0],
...steps.slice(1).map((s) => ({ ...s, completed: false })),
])!;
expect(single.layout?.xaxis?.range).toEqual(['2025-10-02', '2025-12-01']);
expect(
timeline(steps.map((step) => ({ ...step, completed: false, date: undefined }))),
).toBeNull();
});
}); });
describe('Expediente TEA', () => { describe('Expediente TEA', () => {
@@ -192,6 +240,23 @@ describe('Expediente TEA', () => {
]); ]);
}); });
it('dibuja la línea del tiempo como un Gantt con rombos, no como tabla', () => {
const [section] = recordSections(record, new Map());
expect(section.title).toBe('Línea del tiempo');
expect(section.blocks).toHaveLength(1);
expect(section.blocks[0].table).toBeUndefined();
expect(section.blocks[0].chart?.title).toBe('Etapas del tamizaje');
expect(section.blocks[0].chart?.figure.data.at(-1)).toMatchObject({
mode: 'markers',
x: ['2025-11-01', '2025-11-22'],
});
const pending = recordSections(
{ ...record, steps: steps.map((step) => ({ ...step, completed: false, date: undefined })) },
new Map(),
)[0];
expect(pending.blocks).toEqual([]);
});
it('agrupa los ítems del módulo con dominio, subdominio, código y título', () => { it('agrupa los ítems del módulo con dominio, subdominio, código y título', () => {
const section = recordSections(record, new Map()).find((s) => s.title === 'ADOS-2'); const section = recordSections(record, new Map()).find((s) => s.title === 'ADOS-2');
expect(section?.blocks).toHaveLength(1); expect(section?.blocks).toHaveLength(1);
@@ -278,3 +343,26 @@ describe('Análisis de riesgo TEA', () => {
expect(chosen?.blocks[0].chart?.title).toBe(pair.title); expect(chosen?.blocks[0].chart?.title).toBe(pair.title);
}); });
}); });
describe('Títulos de las asociaciones TEA', () => {
it('nombra la métrica, la zona y el resultado del par', () => {
expect(pairTitle('spindles|central|CSS')).toBe('Husos N2 · Central · CSS');
expect(pairTitle('posterior_rhythm|posterior|CSS')).toBe('Ritmo posterior · Posterior · CSS');
});
it('resuelve el ítem del ADOS-2 con la evaluación del paciente', () => {
expect(pairTitle('spikes|frontal_midline|ados2_item_02', ados)).toBe(
'Puntas paroxísticas · Frontal medial · Señalar',
);
expect(pairTitle('spikes|frontal_midline|ados2_item_02')).toBe(
'Puntas paroxísticas · Frontal medial · ados2_item_02',
);
});
it('conserva los códigos que no conoce', () => {
expect(zoneLabel('frontal_midline')).toBe('Frontal medial');
expect(zoneLabel('central')).toBe('Central');
expect(zoneLabel('unknown')).toBe('unknown');
expect(pairTitle('unknown|unknown|CSS')).toBe('unknown · unknown · CSS');
});
});
+5 -9
View File
@@ -2,7 +2,7 @@ import { downloadPdf, safeName, type PdfContent } from '../export';
import type { Figure } from '../plot'; import type { Figure } from '../plot';
import plotly from '../plotly-bundle'; import plotly from '../plotly-bundle';
import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data'; import { adosItems, adosSummary, alteration, Pair, percent, shown, TeaPatient } from './tea-data';
import { forest, headMap, probabilityCurve, zBars } from './tea-figures'; import { forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures';
type Table = { headers: string[]; rows: string[][] }; type Table = { headers: string[]; rows: string[][] };
type Chart = { title: string; figure: Figure; height?: number }; type Chart = { title: string; figure: Figure; height?: number };
@@ -34,17 +34,13 @@ function associationRows(pairs: Pair[]): string[][] {
} }
export function recordSections(patient: TeaPatient, norms: ReadonlyMap<string, Chart>): Section[] { export function recordSections(patient: TeaPatient, norms: ReadonlyMap<string, Chart>): Section[] {
const gantt = timeline(patient.steps);
return [ return [
{ {
title: 'Línea del tiempo', title: 'Línea del tiempo',
blocks: [ blocks: gantt
{ ? [{ chart: { title: 'Etapas del tamizaje', figure: gantt, height: 260 } }]
table: { : [],
headers: ['Fecha', 'Evento', 'Detalle'],
rows: patient.timeline,
},
},
],
}, },
{ {
title: 'ADOS-2', title: 'ADOS-2',