diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index e960920..3d8c515 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -59,16 +59,16 @@ @if (d.eeg; as e) { -
+

Alteraciones del EEG Datos de ejemplo

-

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.

+

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.

@if (!alteradas(e).length) {

Sin alteraciones en las métricas evaluadas.

}
    @for (m of e.alteraciones; track m.codigo) {
  • - {{ estado[m.estado] }}
    @@ -88,8 +88,24 @@
- @if (mapaActual(e); as mapa) { -
+ @if (abierto(e)) { +
+ @if (mapaActual(e) && normaActual(e)) { +
+ + +
+ } + @if (vista === 'norma' && normaActual(e); as m) { +

Norma por edad

+

{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}

+ @if (figuraNorma) { + + } +

La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura). + El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).

+ } @else if (mapaActual(e); as mapa) {

Zonas más afectadas

{{ mapa.metrica }} · mapa ilustrativo

Azul: menos actividad Rojo: más actividad

@@ -102,6 +118,7 @@
  • {{ r.etiqueta }}z = {{ r.valor_z }}
  • } + }
    }
    diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 5c88782..c75b477 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -88,3 +88,9 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border .barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } .barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } .nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } +// The switch between the head map and the age norm, when the metric has both. +.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; } +.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; } +.vistas button + button { border-inline-start: 1px solid var(--issste-border); } +.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; } +.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index c3c960a..2f073cd 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -51,6 +51,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl }; } +// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point. +const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E'; +export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure { + const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse(); + const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({ + type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color, + line: { width: 0 }, name: nombre, hoverinfo: 'skip', + }); + const unidad = m.unidad ? ` ${m.unidad}` : ''; + const alterado = m.estado === 'aumentado' || m.estado === 'disminuido'; + return { + data: [ + banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'), + banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'), + { type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 }, + hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}` }, + { type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente', + marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } }, + hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})` }, + ], + layout: { + margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', + showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK }, + xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true }, + yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true }, + }, + config: { displayModeBar: false }, + }; +} + @Component({ selector: 'app-tea-paciente-resumen', imports: [PlotlyChart], @@ -64,7 +94,7 @@ export class TeaPacienteResumen implements OnInit { readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly detalle = signal(undefined); figura?: PlotlyFigure; - private mapaElegido?: string; + mapaElegido?: string; private readonly elemento = inject>(ElementRef); // The first solid background around this component: the map has no box of its own. private fondo() { @@ -74,13 +104,29 @@ export class TeaPacienteResumen implements OnInit { } return '#FFFFFF'; } + // The side panel shows the chosen metric's head map, its age norm, or both with a switch between them. + vista: 'zonas' | 'norma' = 'zonas'; + figuraNorma?: PlotlyFigure; mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } - elegirMapa(eeg: TeaEeg, codigo: string) { - // The chosen card closes the map again, and the cards take the whole space back. - const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo); - this.mapaElegido = mapa?.codigo; - this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + // The age norm can only be drawn with the curve, the patient's value and their age. + private conNorma(eeg: TeaEeg, codigo?: string) { + const m = eeg.alteraciones.find(a => a.codigo === codigo); + return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined; } + normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); } + abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); } + private mostrar(eeg: TeaEeg, codigo: string | undefined) { + const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo); + this.mapaElegido = mapa || norma ? codigo : undefined; + this.vista = mapa ? 'zonas' : 'norma'; + this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number); + } + elegirMapa(eeg: TeaEeg, codigo: string) { + // The chosen card closes the panel again, and the cards take the whole space back. + this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo); + } + verVista(vista: 'zonas' | 'norma') { this.vista = vista; } readonly clasificacion = CLASIFICACIONES_ADOS2; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -90,10 +136,12 @@ export class TeaPacienteResumen implements OnInit { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ next: d => { - // Opens on the first altered metric, or on the first one if none is altered. - const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0]; - this.mapaElegido = inicial?.codigo; - this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined; + // Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered. + const e = d.eeg; + if (e) { + const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo)); + this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo); + } else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; } this.detalle.set(d); this.status.set('ready'); }, error: () => this.status.set('error'), diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 83ad8fd..74ed6f4 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -56,10 +56,17 @@ export interface TeaEegAlteracion { valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; // Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age. sin_evaluar: 'sin_valor' | 'sin_referencia' | null; + // The age norm the reference comes from (percentiles by month), when the analysis sends it. + curva_referencia?: TeaCurvaReferencia | null; +} +export interface TeaCurvaReferencia { + fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[]; } export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] } export interface TeaEeg { fecha: string; duracion_min: number | null; canales: number | null; + // Age at the EEG, to place the patient on the age norms. + edad_meses?: number | null; // The overall rating is the EEG analysis's verdict; its checks say why. calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[]; alteraciones: TeaEegAlteracion[]; @@ -154,13 +161,24 @@ function validAdos(a: unknown): boolean { return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0) && a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0); } +// An age norm: ages in increasing order and, at each one, percentiles that never cross. +const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const; +function validCurva(c: unknown): boolean { + if (c === undefined || c === null) return true; + if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false; + const edades = c['edad_meses'] as unknown[], n = edades.length; + if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false; + const series = PERCENTILES.map(k => c[k]); + return series.every(s => Array.isArray(s) && s.length === n && s.every(finite)) + && edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i])); +} // A metric that can't be evaluated says why and has no z; one that can has its value, z and reference. function validAlteracion(a: unknown): boolean { const ref = a !== null && record(a) ? a['referencia'] : undefined; if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number) && (ref['mediana'] === null || finite(ref['mediana']))) - || !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false; + || !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false; const estado = a['estado']; if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string) && (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null); @@ -170,7 +188,9 @@ function validAlteracion(a: unknown): boolean { function validEeg(e: unknown): boolean { if (e === null) return true; const optional = (v: unknown) => v === null || integer(v); + const edad = record(e) ? e['edad_meses'] : undefined; if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales']) + || !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0) || !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string) || !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean' diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index a58e589..9e91ad6 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -172,6 +172,41 @@ describe('Seguimiento TEA', () => { expect(root.querySelector('section.mapa')).not.toBeNull(); http.verify(); }); + it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => { + const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48], + p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] }; + const conCurva = detalle.eeg.alteraciones.map(m => + m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m); + const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } }; + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges(); + const panel = () => root.querySelector('section.mapa')!; + const vistas = () => panel().querySelectorAll('.vistas button'); + // Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age. + expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']); + expect(panel().textContent).toContain('Zonas más afectadas'); + vistas()[1].click(); fixture.detectChanges(); + expect(vistas()[1].getAttribute('aria-pressed')).toBe('true'); + expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad'); + expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)'); + expect(panel().querySelector('.regiones')).toBeNull(); + // Gradiente has no map: its card opens the norm alone, without the switch. + const tarjetas = root.querySelectorAll('button.nombre'); + tarjetas[4].click(); fixture.detectChanges(); + expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true'); + expect(vistas().length).toBe(0); + expect(panel().textContent).toContain('Gradiente anteroposterior'); + const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance; + const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[]; + expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']); + expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]); + const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m); + expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow(); + http.verify(); + }); it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo); const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor;