diff --git a/e2e/pages.spec.ts b/e2e/pages.spec.ts index b2b67dc..ad7b770 100644 --- a/e2e/pages.spec.ts +++ b/e2e/pages.spec.ts @@ -34,6 +34,18 @@ test('tea indicators: every tab loads, and the follow-up list exports to Excel', await page.getByRole('tab', { name: 'Seguimiento' }).click(); 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('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( page, page.getByRole('button', { name: 'Exportar a Excel' }), @@ -49,6 +61,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( /^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 page.getByRole('option', { name: 'Con resultados' }).click(); await expect(risk.getByText('No hay registros para los filtros aplicados.')).toBeVisible(); @@ -74,7 +98,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.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'); expect(record).toMatch(/^tea-seguimiento-/); @@ -83,12 +110,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(); const focusedRows = focused.locator('table tbody tr'); await expect(focusedRows).toHaveCount(1); - await expect(focusedRows.first().locator('td').nth(4)).toHaveText( - /M-CHAT|Psicología|Neuropediatría|EEG/, - ); - await expect(focusedRows.first().locator('td').nth(5)).toHaveText( - /Diagnóstico confirmado|En proceso|Sin TEA/, - ); + await expect(focusedRows.first().locator('td')).toHaveCount(9); + await expect(focusedRows.first().locator('app-tea-stepper')).toBeVisible(); await focusedRows.first().getByRole('link').click(); await page.getByRole('link', { name: 'Análisis de riesgo' }).click(); diff --git a/src/app/indicadores/tab-riesgos-tea.html b/src/app/indicadores/tab-riesgos-tea.html index 02664fc..2446657 100644 --- a/src/app/indicadores/tab-riesgos-tea.html +++ b/src/app/indicadores/tab-riesgos-tea.html @@ -145,8 +145,14 @@ Expediente Nombre - Pares - Acciones + Sexo + Edad (meses) + Asociación principal + Razón de momios + IC 95 % + q + Probabilidad + Probabilidad de referencia @@ -158,9 +164,6 @@ {{ row.name || '—' }} - - {{ row.pairs.length || '—' }} -
@if (row.pairs.length) {
+ {{ row.patient.gender ? name(row.patient.gender) : '—' }} + {{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }} + {{ row.headline?.title ?? '—' }} + {{ formatOr(row.headline?.or) }} + {{ formatIc(row.headline?.low, row.headline?.high) }} + {{ formatQ(row.headline?.q) }} + {{ formatProbability(row.headline?.probability) }} + {{ formatProbability(row.headline?.reference) }} @if (expanded()[id] && row.pairs.length) { - + - + + - + @for (pair of row.pairs; track pair.pair) { - - - - - + + + + + + @@ -214,7 +223,7 @@ } } @empty { - + } diff --git a/src/app/indicadores/tab-riesgos-tea.ts b/src/app/indicadores/tab-riesgos-tea.ts index cde8a40..0d11fe0 100644 --- a/src/app/indicadores/tab-riesgos-tea.ts +++ b/src/app/indicadores/tab-riesgos-tea.ts @@ -1,5 +1,4 @@ import { HttpClient } from '@angular/common/http'; -import { DecimalPipe } from '@angular/common'; import { Component, computed, inject, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; @@ -17,11 +16,16 @@ import { name } from './measures'; import { Pager } from './pager'; import { PatientSearch } from './patient-search'; import { + ageMonths, ASSOCIATION_LABELS, associationRows, DEFAULT_ASSOCIATION_FILTER, exportTea, fetchTeaRows, + formatIc, + formatOr, + formatProbability, + formatQ, matchesTeaSearch, parameters, SCORE_FILTERS, @@ -34,7 +38,6 @@ import { @Component({ selector: 'app-tab-riesgos-tea', imports: [ - DecimalPipe, FormsModule, Loading, MatButtonModule, @@ -57,6 +60,11 @@ export class TabRiesgosTea { protected readonly tokenFilters = TOKEN_FILTERS; protected readonly scoreFilters = SCORE_FILTERS; 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 association = signal(DEFAULT_ASSOCIATION_FILTER); protected readonly associationLabels = ASSOCIATION_LABELS; diff --git a/src/app/indicadores/tab-seguimiento-tea.html b/src/app/indicadores/tab-seguimiento-tea.html index 24baec1..06263c8 100644 --- a/src/app/indicadores/tab-seguimiento-tea.html +++ b/src/app/indicadores/tab-seguimiento-tea.html @@ -103,18 +103,16 @@ - - - - - - - + + + + + + @for (row of rows(); track row.patient.id) { - @let age = ageMonths(row.patient.birthDate, cutoff()); - - - + + - - + + } @empty { -
ParOR (IC)Razón de momiosIC 95 % q ProbabilidadReferenciaProbabilidad de referencia Mismo sentido
{{ pair.pair || '—' }} - {{ (pair.or | number: '1.0-3') ?? '—' }} ({{ - (pair.low | number: '1.0-3') ?? '—' - }}–{{ (pair.high | number: '1.0-3') ?? '—' }}) - {{ (pair.q | number: '1.0-4') ?? '—' }}{{ (pair.probability | number: '1.0-4') ?? '—' }}{{ (pair.reference | number: '1.0-4') ?? '—' }}{{ pair.title }}{{ formatOr(pair.or) }}{{ formatIc(pair.low, pair.high) }}{{ formatQ(pair.q) }}{{ formatProbability(pair.probability) }}{{ formatProbability(pair.reference) }} {{ pair.sameDirection == null ? '—' : pair.sameDirection ? 'Sí' : 'No' }}
No hay registros para los filtros aplicados.No hay registros para los filtros aplicados.
Expediente Nombre SexoEdadEtapasEstado del casoM-CHATCSSEEGConcordanciaEdad (meses)EtapaPuntaje M-CHATCSS ADOS-2Estatus de EEGAlteraciones encontradas
{{ row.recordNumbers.join(', ') || '—' }} @@ -123,17 +121,16 @@ {{ row.patient.gender ? name(row.patient.gender) : '—' }}{{ age == null ? '—' : age + ' meses' }}{{ row.step ?? '—' }}{{ row.case ? name(row.case) : '—' }}{{ ageMonths(row.patient.birthDate, cutoff()) ?? '—' }} {{ row.mchatScore ?? '—' }} {{ row.css ?? '—' }}{{ eegDisplay(row.eegResult) }}{{ row.concordance }}{{ eegResultLabel(row.eegResult) }}{{ row.alterations ?? '—' }}
+ @if (focused()) { Este paciente no está en la lista de seguimiento } @else { diff --git a/src/app/indicadores/tab-seguimiento-tea.ts b/src/app/indicadores/tab-seguimiento-tea.ts index 2b640a2..aaedae9 100644 --- a/src/app/indicadores/tab-seguimiento-tea.ts +++ b/src/app/indicadores/tab-seguimiento-tea.ts @@ -8,12 +8,14 @@ import { RouterLink } from '@angular/router'; import type { Bundle } from 'fhir/r4'; import { Fhir } from '../fhir'; import { Loading } from '../loading'; +import type { TeaStep } from '../paciente/tea-data'; import { windowStart } from './follow-up'; import { name } from './measures'; import { Pager } from './pager'; import { PatientSearch, patientSearch } from './patient-search'; import { ageMonths, + eegResultLabel, exportTea, fetchTeaRows, parameters, @@ -25,6 +27,77 @@ import { type TeaFilters, } from './tea-rows'; +@Component({ + selector: 'app-tea-stepper', + template: ` +
    + @for (step of steps(); track step.code; let i = $index) { +
  1. + +
  2. + } +
+ `, + 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(); + 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({ selector: 'app-tab-seguimiento-tea', imports: [ @@ -37,6 +110,7 @@ import { PatientSearch, Pager, RouterLink, + TeaStepper, ], templateUrl: './tab-seguimiento-tea.html', styleUrl: './tab-seguimiento-tea.scss', @@ -54,11 +128,11 @@ export class TabSeguimientoTea { ({ key }) => key !== 'sex' && key !== 'alteration' && key !== 'status', ); protected readonly scoreFilters = SCORE_FILTERS; - private readonly eegOptions = TOKEN_FILTERS.find(({ key }) => key === 'eeg')!.options; protected readonly size = signal(20); protected readonly search = signal(''); protected readonly name = name; protected readonly ageMonths = ageMonths; + protected readonly eegResultLabel = eegResultLabel; private readonly request = computed(() => { const id = this.focused(); @@ -99,10 +173,6 @@ export class TabSeguimientoTea { protected readonly exporting = signal(false); protected readonly actionError = signal(''); - protected eegDisplay(code: string | undefined): string { - return this.eegOptions.find((option) => option.code === code)?.label ?? '—'; - } - protected clearFocus(id: string): void { this.cleared.set(id); } diff --git a/src/app/indicadores/tea-indicators.spec.ts b/src/app/indicadores/tea-indicators.spec.ts index f8b9d1a..710e486 100644 --- a/src/app/indicadores/tea-indicators.spec.ts +++ b/src/app/indicadores/tea-indicators.spec.ts @@ -1,5 +1,6 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; import { EXT } from '../fhir'; +import { teaSteps } from '../paciente/tea-data'; import { ageStack, nestedDonut, @@ -9,10 +10,15 @@ import { teaSankey, teaSexDonut, } from './figures'; +import { teaSteps } from '../paciente/tea-data'; import type { Catalog } from './pages'; import { ageMonths, associationRows, + formatIc, + formatOr, + formatProbability, + formatQ, matchesTeaSearch, teaParams, teaRows, @@ -34,6 +40,9 @@ function fixture(): Bundle { { url: EXT + 'tea-step', valueCode: 'eeg' }, { url: EXT + 'tea-case', valueCode: 'confirmed' }, { 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 = { @@ -71,6 +80,8 @@ function fixture(): Bundle { { url: EXT + 'association-headline', valueBoolean: true }, { url: EXT + 'association-reference-probability', valueDecimal: 0.35 }, { 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 }, ], }, @@ -82,9 +93,17 @@ function fixture(): Bundle { code: { coding: [{ code: 'eeg' }] }, subject, effectiveDateTime: '2026-03-04', - conclusionCode: [{ text: 'Bueno' }], + conclusionCode: [{ coding: [{ code: 'good' }], text: 'Bueno' }], 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 { resourceType: 'Bundle', type: 'searchset', @@ -93,6 +112,7 @@ function fixture(): Bundle { { resource: { resourceType: 'Patient', id: 'other' }, search: { mode: 'match' } }, { resource: ados, search: { mode: 'include' } }, { resource: risk, search: { mode: 'include' } }, + { resource: neurology, search: { mode: 'include' } }, { resource: eeg, search: { mode: 'include' } }, ...['2026-03-01', '2026-02-27'].map((date) => ({ search: { mode: 'include' as const }, @@ -101,7 +121,7 @@ function fixture(): Bundle { status: 'final' as const, subject, code: { coding: [{ code: 'mchat.score' }] }, - valueQuantity: { value: 9 }, + valueQuantity: { value: 7 }, effectiveDateTime: date, }, })), @@ -177,36 +197,54 @@ describe('TEA indicators', () => { 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()); expect(row.steps.map(({ date }) => date)).toEqual([ '2026-02-27', '2026-03-02', - undefined, + '2026-03-03', '2026-03-04', ]); + expect(row.steps.map(({ completed }) => completed)).toEqual([true, true, true, true]); expect(row).toMatchObject({ name: 'Ana López', - step: 'EEG', - case: 'confirmed', eegResult: 'normal', recordNumbers: ['123'], mchatScore: 9, css: 8, - headline: { pair: cssPair, or: 2, q: 0.01 }, - concordance: 'Concordante', + alterations: 2, + 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 risk = page.entry!.find((e) => e.resource?.resourceType === 'RiskAssessment')! .resource as RiskAssessment; - const prediction = risk.prediction![0]; - prediction.outcome = { coding: [{ code: 'rhythm|central|ados2_item_01' }] }; - prediction.probabilityDecimal = 0.1; - expect(teaRows(page)[0].concordance).toBe('No concordante'); + risk.prediction![0].outcome = { coding: [{ code: 'posterior_rhythm|central|ados2_item_01' }] }; + expect(teaRows(page)[0].headline?.title).toBe( + 'Ritmo posterior · Central · Frecuencia de la vocalización espontánea dirigida a otros', + ); + }); + + 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', () => { @@ -230,13 +268,20 @@ describe('TEA indicators', () => { }); 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', sheets: [ expect.objectContaining({ name: 'Seguimiento', 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, + }), ]), }), ], @@ -244,10 +289,23 @@ describe('TEA indicators', () => { }); 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', 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({ name: 'Pares', rows: [ @@ -361,3 +419,96 @@ describe('TEA clinical figures', () => { }); }); }); + +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 }); + }); +}); diff --git a/src/app/indicadores/tea-rows.ts b/src/app/indicadores/tea-rows.ts index 2444fbb..dd13610 100644 --- a/src/app/indicadores/tea-rows.ts +++ b/src/app/indicadores/tea-rows.ts @@ -1,17 +1,10 @@ import type { Bundle, DiagnosticReport, Observation, Patient, RiskAssessment } from 'fhir/r4'; -import { ados2Component } from '../ados2'; import { downloadXlsx, safeName, type Sheet } from '../export'; 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 { 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[number]; function associationPair(p: Prediction) { @@ -29,18 +22,6 @@ function associationPair(p: Prediction) { }; } -function concordance(headline?: ReturnType, 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( records: T[], ): Map { @@ -58,42 +39,23 @@ export function teaRows(page: Bundle) { const reports = byPatient(resources(page, 'DiagnosticReport')); const observations = byPatient(resources(page, 'Observation')); const risks = byPatient(resources(page, 'RiskAssessment')); - const dateOrder = (a: Observation | DiagnosticReport, b: Observation | DiagnosticReport) => - (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? ''); return resources(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 ados = obs + .filter((o) => code(o.code) === 'ados2') + .sort((a, b) => (a.effectiveDateTime ?? '').localeCompare(b.effectiveDateTime ?? '')); 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; + const pairs = (risk?.prediction ?? []).map((p) => { + const pair = associationPair(p); + return { ...pair, title: pairTitle(pair.pair ?? '', evaluation) }; + }); return { patient, name: patientName(patient), @@ -104,14 +66,12 @@ export function teaRows(page: Bundle) { .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), + steps: teaSteps(obs, reports.get(subject) ?? [], ext(patient, 'tea-step')?.valueCode), + mchatScore: ext(patient, 'tea-mchat')?.valueDecimal, + css: ext(patient, 'tea-css')?.valueInteger, + alterations: ext(patient, 'tea-alterations')?.valueInteger, + headline: pairs.find((p) => p.headline), pairs, }; }); @@ -233,6 +193,22 @@ function choices(...codes: string[]) { 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 { return matchesSearch(query, [ ...(row.patient.name ?? []).map(({ text }) => text), @@ -258,61 +234,87 @@ const columns = (entries: [string, string][]): Sheet['columns'] => export function teaWorkbook( rows: TeaRow[], risk: boolean, + cutoff = '', day = new Date(), ): { name: string; sheets: Sheet[] } { const identity: [string, string][] = [ ['id', 'Paciente'], ['record', 'Expediente'], ['name', 'Nombre'], + ['sex', 'Sexo'], + ['birth', 'Nacimiento'], + ['age', 'Edad (meses)'], ]; - 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 people = 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, + age: ageMonths(row.patient.birthDate, cutoff), + })); + const sheets: Sheet[] = risk + ? [ + { + name: 'Niños', + columns: columns([ + ...identity, + ['pair', 'Asociación principal'], + ['or', 'Razón de momios'], + ['low', 'IC 95 % inferior'], + ['high', 'IC 95 % superior'], + ['q', 'q'], + ['probability', 'Probabilidad'], + ['reference', 'Probabilidad de referencia'], + ]), + rows: rows.map((row, i) => ({ + ...people[i], + pair: row.headline?.title, + or: row.headline?.or, + low: row.headline?.low, + high: row.headline?.high, + q: row.headline?.q, + probability: row.headline?.probability, + reference: row.headline?.reference, + })), + }, + { + 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 }))), + }, + ] + : [ + { + 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'; return { name: safeName(['tea', page, day.toISOString().slice(0, 10)]), sheets }; } @@ -322,7 +324,7 @@ export function exportTea( params: Record, risk: boolean, ): Promise { - const { name, sheets } = teaWorkbook(rows, risk); + const { name, sheets } = teaWorkbook(rows, risk, params['follow-up-cutoff']); return downloadXlsx(name, sheets, params); } diff --git a/src/app/paciente/tea-data.ts b/src/app/paciente/tea-data.ts index a153950..b532715 100644 --- a/src/app/paciente/tea-data.ts +++ b/src/app/paciente/tea-data.ts @@ -10,16 +10,51 @@ import { ados2Component, ados2Groups } from '../ados2'; import { ZONE_NAMES } from '../eeg-labels'; 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 = { - mchat_only: 'Solo M-CHAT', - psychology: 'Psicología', - neurology: 'Neurología', - eeg: 'EEG', -}; +export type TeaStep = { code: string; label: string; date?: string; completed: boolean }; -const metrics: Record = { +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 = { posterior_rhythm: 'Ritmo posterior', spindles_n2: 'Husos N2', spindles_n3: 'Husos N3', @@ -27,13 +62,36 @@ const metrics: Record = { anteroposterior_gradient: 'Gradiente anteroposterior', }; -const biomarkers: Record = { +const BIOMARKER_METRICS: Record = { spikes: 'paroxysmal_spikes', spindles: 'spindles_n2', posterior_rhythm: 'posterior_rhythm', 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 = { + mchat_only: 'Solo M-CHAT', + psychology: 'Psicología', + neurology: 'Neurología', + eeg: 'EEG', +}; + const classifications: Record = { non_spectrum: 'Fuera del espectro', 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(); - 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]); @@ -193,7 +211,7 @@ function metric(o: Observation) { const key = code(o.code) ?? ''; return { key, - title: metrics[key] ?? shown(label(o.code)), + title: METRIC_TITLES[key] ?? shown(label(o.code)), value: o.valueQuantity?.value, unit: o.valueQuantity?.unit, z: ext(o, 'eeg-z')?.valueDecimal, @@ -248,10 +266,6 @@ export type Pair = { export type Study = ReturnType; -export function zoneLabel(zone: string): string { - return zone === 'frontal_midline' ? 'Frontal medial' : (ZONE_NAMES[zone] ?? zone); -} - export function alteration(outside: number | undefined): string { return outside == null ? '—' : outside < 0 ? 'Bajo' : outside > 0 ? 'Alto' : 'En rango'; } @@ -264,20 +278,15 @@ function associations( 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 [biomarker, zone = ''] = key.split('|'); + const metric = eeg?.metrics.find((m) => m.key === BIOMARKER_METRICS[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(' · '), + title: pairTitle(key, ados[0]), headline: ext(p, 'association-headline')?.valueBoolean === true, altered: site?.outside != null && site.outside !== 0, z: site?.z, @@ -316,7 +325,7 @@ export async function loadTeaPatient(fhir: Fhir, id: string) { patient, ados, studies, - timeline: timeline(observations, ados, reports), + steps: teaSteps(observations, reports), riskStudy, pairs: associations(risk, riskStudy, ados), }; diff --git a/src/app/paciente/tea-figures.ts b/src/app/paciente/tea-figures.ts index dab7964..cfb672f 100644 --- a/src/app/paciente/tea-figures.ts +++ b/src/app/paciente/tea-figures.ts @@ -1,6 +1,98 @@ import { banded } from '../gobernanza/figures'; 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}', + 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 = { Fp1: [-0.3, 0.87], diff --git a/src/app/paciente/tea-patient.spec.ts b/src/app/paciente/tea-patient.spec.ts index 7a97a81..9677359 100644 --- a/src/app/paciente/tea-patient.spec.ts +++ b/src/app/paciente/tea-patient.spec.ts @@ -1,8 +1,8 @@ import type { Observation, Patient } from 'fhir/r4'; import { describe, expect, it } from 'vitest'; import { EXT } from '../fhir'; -import { identityRows, Metric, Pair } from './tea-data'; -import { ageNorm, forest, headMap, probabilityCurve, zBars } from './tea-figures'; +import { identityRows, Metric, Pair, pairTitle, TeaStep, zoneLabel } from './tea-data'; +import { ageNorm, forest, headMap, probabilityCurve, timeline, zBars } from './tea-figures'; import { forestTitle, 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 = { patient: { resourceType: 'Patient' as const, id: 'child', name: [{ text: 'Paciente de prueba' }], }, - timeline: [['2025-11-22', 'ADOS-2', '—']], + steps, ados: [ados], studies: [], riskStudy: undefined, @@ -150,6 +157,47 @@ describe('Figuras del paciente TEA', () => { { 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', () => { @@ -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', () => { const section = recordSections(record, new Map()).find((s) => s.title === 'ADOS-2'); expect(section?.blocks).toHaveLength(1); @@ -278,3 +343,26 @@ describe('Análisis de riesgo TEA', () => { 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'); + }); +}); diff --git a/src/app/paciente/tea-sections.ts b/src/app/paciente/tea-sections.ts index 4d52a6f..aeea330 100644 --- a/src/app/paciente/tea-sections.ts +++ b/src/app/paciente/tea-sections.ts @@ -2,7 +2,7 @@ import { downloadPdf, safeName, type PdfContent } from '../export'; import type { Figure } from '../plot'; import plotly from '../plotly-bundle'; 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 Chart = { title: string; figure: Figure; height?: number }; @@ -34,17 +34,13 @@ function associationRows(pairs: Pair[]): string[][] { } export function recordSections(patient: TeaPatient, norms: ReadonlyMap): Section[] { + const gantt = timeline(patient.steps); return [ { title: 'Línea del tiempo', - blocks: [ - { - table: { - headers: ['Fecha', 'Evento', 'Detalle'], - rows: patient.timeline, - }, - }, - ], + blocks: gantt + ? [{ chart: { title: 'Etapas del tamizaje', figure: gantt, height: 260 } }] + : [], }, { title: 'ADOS-2',