diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index eb30893..062b9b9 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -3,7 +3,6 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; -import { MatSelect } from '@angular/material/select'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -28,7 +27,6 @@ describe('UX-06E.D.2.1 selector de representación', () => { fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] }); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); } - function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } @@ -47,13 +45,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { expect(fixture.componentInstance.indicador.contrato).toBe(contrato); http.expectNone(() => true); }); - it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para selector, consulta y memoria', () => { + it('UX-07A/07D.1 presenta nombres amigables y conserva IDs para consulta y memoria', () => { fixture.destroy(); create(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c2_barras', 'fig_c2_donas', 'fig_c9_futura']); fixture.componentRef.setInput('indicador', { ...fixture.componentInstance.indicador, contrato: 'C1' }); fixture.detectChanges(); - expect(select().options.map(option => [option.value, option.viewValue])).toEqual([ - ['fig_c1_grupos', 'Grupos'], ['fig_c2_apiladas', 'Barras apiladas'], - ['fig_c2_barras', 'Barras'], ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], - ]); http.expectNone(() => true); open(); request('fig_c1_grupos').flush({ data: [], layout: {} }); for (const [id, label] of [ @@ -62,7 +56,7 @@ describe('UX-06E.D.2.1 selector de representación', () => { ['fig_c2_donas', 'Donas'], ['fig_c9_futura', 'Representación 5'], ]) { - select().selectionChange.emit({ source: select(), value: id }); fixture.detectChanges(); + fixture.componentInstance.selectFigure(id); fixture.detectChanges(); const pending = request(id); expect(pending.request.url).toBe('/cacu/indicadores/i/figuras/' + id); expect(pending.request.params.get('tema')).toBe('claro'); @@ -74,9 +68,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { } http.expectNone(() => true); }); - it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { - fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); - expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); + it('no ofrece selector de representación y sólo consulta la figura mostrada', () => { + fixture.destroy(); create(['f', 'g']); open(); expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); + request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); }); it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => { fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2', @@ -98,9 +92,8 @@ describe('UX-06E.D.2.1 selector de representación', () => { expect(cards.every(card => card.interpretation.every(line => line !== 'No debe asignarse.'))).toBe(true); }); it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => { - open(); const first = request('f'); expect(select().disabled).toBe(false); - expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1); - select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges(); + open(); const first = request('f'); expect(panels()).toHaveLength(1); + fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1); expect(next.request.params.get('periodos')).toBe('2025-S1'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 25e56cd..29fa3db 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -2,8 +2,6 @@ import { ChangeDetectorRef, Component, effect, ElementRef, inject, Input, OnChan import { catchError, of, Subscription } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; -import { MatFormFieldModule } from '@angular/material/form-field'; -import { MatSelectModule } from '@angular/material/select'; import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; @@ -25,7 +23,7 @@ import { parTiempos } from './indicadores-tiempos-pareados'; @Component({ selector: 'app-indicador-catalog-card', host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], + imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], template: `
@@ -53,16 +51,6 @@ import { parTiempos } from './indicadores-tiempos-pareados'; } @else if (selectedFigure) { - @if (!pair.length || otherFigures.length) { - - Representación gráfica - - @if (pair.length) { Dona y barras } - @for (figure of (pair.length ? otherFigures : indicador.figuras); track figure) { {{ figureDisplayName(figure, indicador.figuras) }} } - - - }
@for (figure of displayFigures; track panelIdentity(figure)) {
@@ -136,7 +124,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } // Connected time pairs replace the diagnosis card with one coordinated box plot. get tiempos() { return parTiempos(this.dominio, this.indicador.id); } - get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } private updateNumeric() { diff --git a/src/app/features/indicadores/indicadores-c1-donut.spec.ts b/src/app/features/indicadores/indicadores-c1-donut.spec.ts index 49cb7a7..699d293 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.spec.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.spec.ts @@ -59,13 +59,16 @@ describe('Dona de dos anillos para C1', () => { expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); expect(result.highlight.items[0].center).toBe('34.8 %
16 a 23 meses'); }); - it('«Sin EEG» conserva su color rojo en M21 y en M22', () => { - const anillos = c1DonutFigure(datos(), selection); - if (anillos.status !== 'supported') throw new Error('sin figura'); - expect((anillos.figure.data[1] as { marker: { colors: string[] } }).marker.colors).toEqual(['rgba(168,194,67,1)', 'rgba(184,67,58,1)']); + it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => { + const colores = ['#2F6DB3', '#E0A526', '#A23E8C']; + const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' }); + if (dona.status !== 'supported') throw new Error('sin figura'); + expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores); + expect(dona.highlight.items.map(i => i.color)).toEqual(colores); const barras = c1DonutFigure({ ...datos(), id: 'M22_diagnosticados_sin_eeg' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' }); if (barras.status !== 'supported') throw new Error('sin figura'); - expect((barras.figure.data[0] as { marker: { color: string } }).marker.color).toBe('#B8433A'); + expect((barras.figure.data[0] as { marker: { color: string[] } }).marker.color).toEqual(colores); + expect(barras.highlight.items.map(i => i.color)).toEqual(colores); }); it('barras por grupo de edad: una barra por grupo con su porcentaje', () => { const result = c1DonutFigure({ ...datos([fila('16-23', 8, 24), fila('24-29', 5, 18), fila('30-36', 5, 22)]), id: 'M22_diagnosticados_sin_eeg' }, diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts index d713b1f..410ba9a 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -22,8 +22,8 @@ const EVENT_LABELS: Readonly> = { }; // Green for the event, red for its complement; age groups get lighter shades. const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const; -// M22's event is M21's complement: «Sin EEG» keeps its colour across both indicators. -const ringColors = (indicador: string): readonly [string, string] => indicador === 'M22_diagnosticados_sin_eeg' ? [RING_COLORS[1], RING_COLORS[0]] : RING_COLORS; +// One colour per age group, the same in the donut (M21) and the bars (M22). +const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length]; export type C1DonutResult = { status: 'unsupported'; reason: string } | { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] }; @@ -65,15 +65,14 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): const title = { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period }; const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0); if (selection.figura === C1_AGE_BARS) { - const colors = ringColors(data.id); - const figure = ageBars(strata, labels[0], colors[0], selection); + const figure = ageBars(strata, labels[0], selection); figure.layout = { ...figure.layout, title }; const highlight: FigureHighlight = { groups: [], traces: [0], allLabel: 'Todos los grupos de edad', - items: strata.map((s, i) => ({ id: s.id, label: s.label, color: colors[0], points: [{ trace: 0, index: i }] })) }; + items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }] })) }; return { status: 'supported', figure, highlight, total, notes }; } - const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: ringColors(data.id)[g] })); + const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] })); const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {}; grupos.forEach((g, gi) => strata.forEach((s, i) => { const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number; @@ -102,14 +101,14 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): const numerador = strata.reduce((sum, s) => sum + (s.numerador as number), 0); const values = strata.map(s => s.numerador as number); figure.data = [{ ...outer, hole: .6, values, labels: strata.map(s => escape(s.label)), - marker: { ...(outer['marker'] as object), colors: categorias.slice(0, strata.length).map(c => c.color) }, + marker: { ...(outer['marker'] as object), colors: strata.map((_, i) => ageColor(i)) }, text: values.map((n, i) => !numerador || n / numerador < .05 ? '' : escape(strata[i].label) + '
' + shareText(n, numerador)), customdata: values.map(n => [n, numerador ? percentNumber(100 * n / numerador) : '0']), hovertemplate: '%{label}
%{customdata[0]} pacientes, %{customdata[1]} % de los ' + numerador + ' ' + escape(what(labels[0])) + '' }]; figure.layout = { ...figure.layout, title, annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, text: '' + percentNumber(100 * numerador / total) + ' %', font: { size: 26, color: c2Theme(selection.tema).text } }] }; const highlight: FigureHighlight = { groups: [], traces: [0], center: { annotation: 0 }, allLabel: labels[0], - items: strata.map((s, i) => ({ id: s.id, label: s.label, color: categorias[i].color, points: [{ trace: 0, index: i }], + items: strata.map((s, i) => ({ id: s.id, label: s.label, color: ageColor(i), points: [{ trace: 0, index: i }], center: '' + (numerador ? percentNumber(100 * values[i] / numerador) : '0') + ' %
' + escape(s.label) })) }; return { status: 'supported', figure, highlight, total, notes }; } @@ -123,11 +122,11 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): // "Con EEG" -> "con EEG", to follow «pacientes». const what = (label: string) => label.charAt(0).toLowerCase() + label.slice(1); // One bar per age group: the share of its patients with the event. -function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, color: string, selection: FigureSelection): PlotlyFigure { +function ageBars(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], event: string, selection: FigureSelection): PlotlyFigure { const theme = c2Theme(selection.tema); const x = strata.map(s => escape(s.label)); const y = strata.map(s => (s.denominador as number) ? 100 * (s.numerador as number) / (s.denominador as number) : null); - return { data: [{ type: 'bar', x, y, marker: { color, line: { color: theme.background, width: 1 } }, + return { data: [{ type: 'bar', x, y, marker: { color: strata.map((_, i) => ageColor(i)), line: { color: theme.background, width: 1 } }, text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false, customdata: strata.map(s => [s.numerador, s.denominador]), hovertemplate: '%{x}
%{y:.1f} % (%{customdata[0]} de %{customdata[1]} pacientes)' }], diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts index 6c9d577..f3c310e 100644 --- a/src/app/features/indicadores/indicadores-c2-palette.ts +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -5,6 +5,8 @@ import { Tema } from './indicadores.models'; export const C2_PALETTE = Object.freeze({ // ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness. series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']), + // Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest. + edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']), states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }), // line: the green for thin marks; the brand green itself is too light to read as a line on white. claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }), diff --git a/src/app/features/indicadores/indicadores-evolucion-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts similarity index 90% rename from src/app/features/indicadores/indicadores-evolucion-figures.ts rename to src/app/features/indicadores/indicadores-historico-figures.ts index ab0ef6b..6677ded 100644 --- a/src/app/features/indicadores/indicadores-evolucion-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -2,7 +2,7 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette'; import { sortedPeriods } from './indicadores-periodos'; -export interface EvolucionFigura { +export interface HistoricoFigura { figure: PlotlyFigure; comoLeer: string; suprimidos: string[]; @@ -10,13 +10,15 @@ export interface EvolucionFigura { } const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The EEG indicators avoid green; their colours are shared with their age groups' palette. +const LINEAS: Readonly> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] }; const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); // sortedPeriods lists the newest first, for selectors; time here runs left to right. export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); function validar(data: IndicadorDatos) { for (const row of data.filas) { - if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de evolución inválida'); + if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida'); } return cronologico(data.periodos); } @@ -65,14 +67,14 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); -function porcentaje(data: IndicadorDatos, tema: Tema): EvolucionFigura { +function porcentaje(data: IndicadorDatos, tema: Tema): HistoricoFigura { const periodos = validar(data); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor'])); - const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'); + const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line; return { figure: { data: [ - banda(periodos, campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', c2Theme(tema).line), - { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos, y: campo(validas, 'valor'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, + banda(periodos, campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea), + { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos, y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 }, text: validas.map(row => row ? `${row['valor']} %
${row['numerador']} de ${row['denominador']}
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), hovertemplate: '%{x}
%{text}' }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, @@ -80,7 +82,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): EvolucionFigura { suprimidos, sinDato, }; } -function mediana(data: IndicadorDatos, tema: Tema): EvolucionFigura { +function mediana(data: IndicadorDatos, tema: Tema): HistoricoFigura { const periodos = validar(data); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana'])); return { @@ -94,12 +96,12 @@ function mediana(data: IndicadorDatos, tema: Tema): EvolucionFigura { suprimidos, sinDato, }; } -function conteo(data: IndicadorDatos, tema: Tema): EvolucionFigura { +function conteo(data: IndicadorDatos, tema: Tema): HistoricoFigura { const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}; const celdas = new Map>(), categorias = new Map(); for (const row of data.filas) { const id = row['categoria'], key = JSON.stringify([id, row['periodo']]); - if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de evolución inválida'); + if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida'); celdas.set(key, row); categorias.set(id, row['orden']); } @@ -121,7 +123,7 @@ function conteo(data: IndicadorDatos, tema: Tema): EvolucionFigura { } // The plot follows from what the contract's numbers mean: counts add up to a total, percentages // and medians do not, so those two are never stacked. -export function evolucionFigura(data: IndicadorDatos, tema: Tema): EvolucionFigura { +export function historicoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura { if (data.contrato === 'C2') return conteo(data, tema); if (data.contrato === 'C1') return porcentaje(data, tema); if (data.contrato === 'C3r') return mediana(data, tema); diff --git a/src/app/features/indicadores/indicadores-evolucion.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts similarity index 73% rename from src/app/features/indicadores/indicadores-evolucion.spec.ts rename to src/app/features/indicadores/indicadores-historico.spec.ts index e42a6de..4e4a39b 100644 --- a/src/app/features/indicadores/indicadores-evolucion.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -3,22 +3,22 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { IndicadoresEvolucion } from './indicadores-evolucion'; -import { evolucionFigura } from './indicadores-evolucion-figures'; +import { IndicadoresHistorico } from './indicadores-historico'; +import { historicoFigura } from './indicadores-historico-figures'; import { Indicador, IndicadorDatos } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) class ChartStub {} -const traza = (d: IndicadorDatos, i: number) => evolucionFigura(d, 'claro').figure.data[i] as Record & { x: unknown[]; y: unknown[] }; +const traza = (d: IndicadorDatos, i: number) => historicoFigura(d, 'claro').figure.data[i] as Record & { x: unknown[]; y: unknown[] }; const base = { id: 'i', tipo_periodo: 'mes' as const, periodos: ['2024-03', '2024-01', '2024-02'] }; const c1 = (periodo: string, valor: number | null, suprimido = 0) => ({ periodo, suprimido, valor, numerador: valor, denominador: valor === null ? null : 100, ic_bajo: valor === null ? null : valor - 5, ic_alto: valor === null ? null : valor + 5 }); const c2 = (periodo: string, categoria: string, n: number | null, orden: number, suprimido = 0) => ({ periodo, categoria, n, orden, suprimido }); -describe('Figuras de evolución', () => { +describe('Figuras de histórico', () => { it('C2 apila conteos en orden cronológico, por categoría y con el color publicado', () => { const data: IndicadorDatos = { ...base, contrato: 'C2', categorias: { B: { etiqueta: 'Bé ', color: '#112233' } }, filas: base.periodos.flatMap(p => [c2(p, 'B', 2, 1), c2(p, 'A', 1, 0)]) }; - const { figure, suprimidos, sinDato } = evolucionFigura(data, 'claro'); + const { figure, suprimidos, sinDato } = historicoFigura(data, 'claro'); expect(figure.layout['barmode']).toBe('stack'); expect(figure.data.map(t => t['name'])).toEqual(['A', 'Bé <b>']); expect(figure.data[0]['x']).toEqual(['2024-01', '2024-02', '2024-03']); @@ -27,14 +27,14 @@ describe('Figuras de evolución', () => { }); it('C2 no dibuja como cero una celda suprimida y sombrea su periodo', () => { const data: IndicadorDatos = { ...base, contrato: 'C2', filas: [c2('2024-01', 'A', 5, 0), c2('2024-02', 'A', null, 0, 1), c2('2024-03', 'A', 0, 0)] }; - const { figure, suprimidos } = evolucionFigura(data, 'claro'); + const { figure, suprimidos } = historicoFigura(data, 'claro'); expect(figure.data[0]['y']).toEqual([5, null, 0]); expect(suprimidos).toEqual(['2024-02']); expect(figure.layout['shapes']).toEqual([expect.objectContaining({ x0: .5, x1: 1.5 })]); }); it('C1 es una línea que no cruza huecos y su banda tampoco', () => { const data: IndicadorDatos = { ...base, contrato: 'C1', filas: [c1('2024-01', 40), c1('2024-02', null, 1), c1('2024-03', 60)] }; - const { suprimidos, figure } = evolucionFigura(data, 'claro'); + const { suprimidos, figure } = historicoFigura(data, 'claro'); expect(traza(data, 1).y).toEqual([40, null, 60]); expect(traza(data, 0).x).toEqual(['2024-01', '2024-01', null, '2024-03', '2024-03']); expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]); @@ -44,25 +44,29 @@ describe('Figuras de evolución', () => { }); it('C3r muestra la mediana con la banda entre cuartiles y distingue sin dato de suprimido', () => { const data: IndicadorDatos = { ...base, periodos: ['2024-01', '2024-02'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }; - const { sinDato, suprimidos } = evolucionFigura(data, 'claro'); + const { sinDato, suprimidos } = historicoFigura(data, 'claro'); expect(traza(data, 1).y).toEqual([20, null]); expect(traza(data, 0).y).toEqual([30, 10]); expect(sinDato).toEqual(['2024-02']); expect(suprimidos).toEqual([]); }); it('las líneas usan el verde legible en cada tema', () => { const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }; - const color = (tema: 'claro' | 'oscuro') => (evolucionFigura(data, tema).figure.data[1]['line'] as { color: string }).color; + const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color; expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243'); }); + it('M21 y M22 no usan verde en sus líneas', () => { + const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color; + expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C'); + }); it('rechaza contratos sin representación y filas ambiguas', () => { - expect(() => evolucionFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada'); - expect(() => evolucionFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas'); + expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada'); + expect(() => historicoFigura({ ...base, contrato: 'C1', filas: [c1('2024-01', 1), c1('2024-01', 2)] }, 'claro')).toThrow('ambiguas'); }); }); -describe('Pestaña Evolución', () => { +describe('Pestaña Histórico', () => { let http: HttpTestingController; - let fixture: ComponentFixture; + let fixture: ComponentFixture; const catalog: Indicador[] = [{ id: 'm1', titulo: 'Uno', contrato: 'C1', figuras: [], tipos_periodo: ['semestre', 'mes'] }]; const periodos = { id: 'm1', version: '1', periodos: [ { periodo: '2024-01', tipo: 'mes', report_id: 1, periodo_inicio: '2024-01-01', periodo_fin: '2024-02-01', fecha_corte: '2024-03-01', generado_en: '2024-03-01T00:00:00+00:00' }, @@ -74,9 +78,9 @@ describe('Pestaña Evolución', () => { const render = () => { TestBed.tick(); fixture.detectChanges(); }; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); - TestBed.overrideComponent(IndicadoresEvolucion, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); - fixture = TestBed.createComponent(IndicadoresEvolucion); + fixture = TestBed.createComponent(IndicadoresHistorico); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('catalog', catalog); fixture.componentRef.setInput('tema', 'claro'); @@ -95,7 +99,6 @@ describe('Pestaña Evolución', () => { expect(request.request.params.get('periodos')!.split(',').sort()).toEqual(['2024-01', '2024-02']); request.flush(datos('mes', ['2024-01', '2024-02'])); render(); expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-01 a 2024-02 (2 meses)'); - expect(fixture.nativeElement.querySelector('mat-select')).toBeNull(); }); it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => { abrir(); @@ -109,6 +112,26 @@ describe('Pestaña Evolución', () => { fixture.componentRef.setInput('tema', 'oscuro'); render(); http.expectNone(() => true); }); + it('el selector ofrece pasos de cinco en la unidad elegida y recorta a los periodos más recientes sin consultar', () => { + const c = fixture.componentInstance; + const meses = Array.from({ length: 12 }, (_, i) => '2024-' + String(i + 1).padStart(2, '0')); + const semestres = ['2020-S1', '2020-S2', '2021-S1', '2021-S2', '2022-S1', '2022-S2']; + fixture.componentRef.setInput('active', true); render(); + http.expectOne('/tea/indicadores/m1/periodos').flush({ id: 'm1', periodos: [...meses.map(periodo => ({ periodo, tipo: 'mes' })), ...semestres.map(periodo => ({ periodo, tipo: 'semestre' }))] }); + http.expectOne(r => r.url === datosUrl).flush(datos('mes', meses)); render(); + expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 meses', 'Últimos 10 meses', 'Todos (12 meses)']); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-01 a 2024-12 (12 meses)'); + c.elegirVentana(5); render(); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-08 a 2024-12 (5 meses)'); + http.expectNone(() => true); + c.tipo.set('semestre'); render(); + expect(c.ventana()).toBe(0); + http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render(); + expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)']); + c.tipo.set('mes'); render(); + expect(c.ventana()).toBe(5); + http.expectNone(() => true); + }); it('avisa del error sin perder la pestaña y reintenta', () => { abrir(); http.expectOne(r => r.url === datosUrl).flush({}, { status: 500, statusText: 'Error' }); render(); diff --git a/src/app/features/indicadores/indicadores-evolucion.ts b/src/app/features/indicadores/indicadores-historico.ts similarity index 72% rename from src/app/features/indicadores/indicadores-evolucion.ts rename to src/app/features/indicadores/indicadores-historico.ts index fffc2b8..4e98627 100644 --- a/src/app/features/indicadores/indicadores-evolucion.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -2,31 +2,40 @@ import { Component, computed, DestroyRef, effect, inject, input, signal, untrack import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { cronologico, evolucionFigura, EvolucionFigura } from './indicadores-evolucion-figures'; +import { cronologico, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; +const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; type Panel = { item: Indicador; rango?: string } & ( - { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: EvolucionFigura }); + { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura }); -// Evolution of each indicator over every published period; only the granularity is chosen. +// Evolution of each indicator: the granularity and how many of the latest periods to show. // Nothing is requested until the tab is first opened, and each granularity is requested once. @Component({ - selector: 'app-indicadores-evolucion', - imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart], + selector: 'app-indicadores-historico', + imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], template: `
- Intervalo de análisis - + Intervalo de análisis + Mensual Semestral + + Periodos a mostrar + + @for (opcion of opciones(); track opcion.valor) { {{ opcion.etiqueta }} } + +
@for (panel of paneles(); track panel.item.id) { @@ -42,7 +51,7 @@ type Panel = { item: Indicador; rango?: string } & ( } @case ('listo') { + [label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />

{{ panel.figura.comoLeer }}

@if (panel.figura.suprimidos.length) {

Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}

@@ -66,14 +75,18 @@ type Panel = { item: Indicador; rango?: string } & ( p { margin: var(--issste-space-3) 0 0; } .rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } app-plotly-chart { margin-top: var(--issste-space-3); } + mat-form-field { min-width: 14rem; } `, }) -export class IndicadoresEvolucion { +export class IndicadoresHistorico { readonly dominio = input.required(); readonly catalog = input.required(); readonly tema = input.required(); readonly active = input(false); readonly tipo = signal('mes'); + // How many of the latest periods to show, per granularity; 0 shows them all. + private readonly ventanas = signal>>({}); + readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); private readonly service = inject(IndicadoresService); private readonly periodos = inject(IndicadoresPeriodos); private readonly cargas = signal>>>({}); @@ -81,19 +94,27 @@ export class IndicadoresEvolucion { private solicitada?: string; private catalogoCargado?: readonly Indicador[]; + // Steps of five, up to what the indicator with the most periods has published. + readonly opciones = computed(() => { + const tipo = this.tipo(); + const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); + const opciones = []; + for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); + return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }]; + }); readonly paneles = computed(() => { - const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(); + const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(), ventana = this.ventana(); return this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => { const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; if (carga.estado !== 'listo') return { item, ...carga }; - const periodos = cronologico(carga.datos.periodos); - const unidad = tipo === 'mes' ? (periodos.length === 1 ? 'mes' : 'meses') : (periodos.length === 1 ? 'semestre' : 'semestres'); - const rango = `${periodos[0]} a ${periodos[periodos.length - 1]} (${periodos.length} ${unidad})`; + const periodos = cronologico(carga.datos.periodos).slice(-ventana); + const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; + const rango = `${periodos[0]} a ${periodos[periodos.length - 1]} (${periodos.length} ${unidad(tipo, periodos.length)})`; try { - return { item, rango, estado: 'listo', figura: evolucionFigura(carga.datos, tema) }; + return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema) }; } catch (error) { - return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de evolución inválidos' }; + return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } }); }); @@ -123,6 +144,7 @@ export class IndicadoresEvolucion { : of({ estado: 'vacio' })), catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); } + elegirVentana(valor: number) { this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); } reintentar() { const tipo = this.tipo(); this.solicitada = tipo; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index bace965..a9bd616 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -122,8 +122,8 @@
@if (dominio === 'tea') { -
- +
+
} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index ae25aac..d543cf3 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -101,11 +101,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true); http.expectNone(() => true); }); - it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => { + it('D.3.A muestra identidad y skeleton sin control de expansión ni HTTP', () => { load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); expect(host.querySelector('h2').textContent).toBe('Uno'); expect(host.querySelector('header button')).toBeNull(); - expect(host.querySelector('mat-select')).toBeTruthy(); + expect(host.querySelector('mat-select')).toBeNull(); expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); expect(host.textContent).not.toContain('Contrato C1'); expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); @@ -341,9 +341,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); - const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf; expect(panels()[0].titleId).not.toBe(panels()[1].titleId); - expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); }); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 6481f10..598173d 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -27,20 +27,20 @@ import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; -import { IndicadoresEvolucion } from './indicadores-evolucion'; +import { IndicadoresHistorico } from './indicadores-historico'; -type DashboardSection = 'resumen' | 'evolucion' | 'seguimiento' | 'datos'; +type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos'; const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ { id: 'resumen', label: 'Resumen' }, { id: 'seguimiento', label: 'Seguimiento' }, { id: 'datos', label: 'Datos y definiciones' }, ]; -// Only TEA has enough periods for an evolution to say anything. -const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'evolucion', label: 'Evolución' }, SECTIONS[1], SECTIONS[2]]; +// Only TEA has enough periods for its history to say anything. +const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]]; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresEvolucion, TeaResumenPeriodo], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index c44a708..fae604f 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -38,7 +38,7 @@ describe('Secciones compartidas por dominio', () => { const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' - ? ['Resumen', 'Evolución', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']); + ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index bcf7343..4bf94a3 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -3,25 +3,7 @@ [registrosTemporales]="pacienteDetalle.registrosTemporales()" (registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" /> } -@if (teaFicha; as p) { -
- -
-

Paciente {{ p.id_seudonimo }}

- @if (teaData; as d) {

Fecha de corte: {{ d.corte }}.

} -
-
Identificador seudónimo
{{ p.id_seudonimo }}
-
Grupo de edad
{{ p.grupo_edad }}
-
Último EEG
{{ p.ultimo_eeg ?? 'No disponible' }}
-
Puntaje M-CHAT
{{ p.mchat ?? 'No disponible' }}
-
CSS ADOS-2
{{ p.css_ados2 ?? 'No disponible' }}
-
Alteraciones EEG
{{ p.alteraciones_eeg === 'anormal' ? 'Anormal' : p.alteraciones_eeg === 'normal' ? 'Normal' : 'No disponible' }}
-
-
- -
-} -
+

Seguimiento de {{ domainLabel }}

@if (dominio !== 'cacu' && dominio !== 'tea') {

El seguimiento aún no está disponible.

@@ -61,15 +43,10 @@ Identificador seudónimoGrupo de edadÚltimo EEGPuntaje M-CHATCSS ADOS-2Alteraciones EEG @for (item of response.items; track item.id_seudonimo) { - - @if (teaVentana(item)) { - - } @else { - - } + + {{ item.grupo_edad }}{{ item.ultimo_eeg ?? 'No disponible' }} {{ item.mchat ?? 'No disponible' }}{{ item.css_ados2 ?? 'No disponible' }} @if (item.alteraciones_eeg; as eeg) { {{ eeg === 'anormal' ? 'Anormal' : 'Normal' }} } @else { No disponible } diff --git a/src/app/features/indicadores/indicadores-tracking.scss b/src/app/features/indicadores/indicadores-tracking.scss index a5734ba..8a5a852 100644 --- a/src/app/features/indicadores/indicadores-tracking.scss +++ b/src/app/features/indicadores/indicadores-tracking.scss @@ -32,11 +32,3 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i @media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } } tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); } // TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page. -.window-icon { width: 1.1rem; height: 1.1rem; font-size: 1.1rem; color: var(--issste-accent); } -.tea-ficha header { margin-block: 1.5rem; } -.tea-ficha h2 { margin-block: .5rem 1rem; font-size: 1.65rem; } -.tea-ficha .back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; } -.tea-ficha .back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; } -.tea-ficha .summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; margin: 0; } -.tea-ficha dt { color: var(--issste-text-secondary); font-size: .9rem; } -.tea-ficha dd { margin: .4rem 0 0; font-weight: 600; } diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index e9dd7a1..dbad6aa 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -6,7 +6,6 @@ import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; import { MatButtonModule } from '@angular/material/button'; -import { MatIconModule } from '@angular/material/icon'; import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; @@ -16,7 +15,7 @@ import { TeaPacienteResumen } from './tea-paciente-resumen'; @Component({ selector: 'app-indicadores-tracking', - imports: [FormsModule, MatButtonModule, MatIconModule, PacienteDetalleComponent, TeaPacienteResumen], + imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen], providers: [PacienteDetalleState], templateUrl: './indicadores-tracking.html', styleUrl: './indicadores-tracking.scss', @@ -44,8 +43,6 @@ export class IndicadoresTracking implements OnChanges { teaData?: TeaSeguimientoResponse; // One open summary at a time, like an accordion. teaAbierto?: string; - // Patient shown in its own window, like CaCu's patient page. - teaFicha?: TeaSeguimientoPaciente; statuses: SeguimientoStatus[] = []; private metadataLoaded = false; categories: Record = {}; @@ -92,8 +89,7 @@ export class IndicadoresTracking implements OnChanges { ngOnChanges() { if (this.previousDomain !== this.dominio) { if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false); - if (this.teaFicha) this.fichaPacienteAbierta.emit(false); - this.pacienteDetalle.cerrar(); this.controlPaciente = undefined; this.teaFicha = undefined; + this.pacienteDetalle.cerrar(); this.controlPaciente = undefined; this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined; this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft }; } @@ -131,25 +127,6 @@ export class IndicadoresTracking implements OnChanges { if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return; this.teaAbierto = this.teaAbierto === id ? undefined : id; } - // Mock: to show both ideas side by side, odd-numbered patients open their own window and - // even-numbered ones expand in place. - teaVentana(item: TeaSeguimientoPaciente) { return Number(item.id_seudonimo.replace(/\D/g, '')) % 2 === 1; } - abrirTea(item: TeaSeguimientoPaciente, evento: Event) { - evento.stopPropagation(); - if (!this.teaVentana(item)) { this.alternarTea(item.id_seudonimo, evento); return; } - if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement - && evento.target.closest('button, a, input, select, textarea')) return; - this.controlPaciente = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined; - this.teaAbierto = undefined; this.teaFicha = item; - this.fichaPacienteAbierta.emit(true); - afterNextRender(() => document.getElementById('tea-ficha-titulo')?.focus(), { injector: this.injector }); - } - cerrarTea() { - this.teaFicha = undefined; - this.fichaPacienteAbierta.emit(false); - const control = this.controlPaciente; - afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector }); - } volverASeguimiento() { this.pacienteDetalle.cerrar(); this.fichaPacienteAbierta.emit(false); diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index 1d4696b..feb6c09 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -4,7 +4,7 @@ } @if (status() === 'ready' && detalle(); as d) { -
+

ADOS-2

@if (d.ados2; as a) { @@ -19,8 +19,7 @@
} - -
+
Puntajes por reactivo @@ -87,7 +86,7 @@

Zonas más afectadas

{{ e.mapa.metrica }} · mapa ilustrativo

@if (figura) { - }
    diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 6b64fa3..589ae88 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -45,29 +45,3 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font .efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; } .efectos { padding-inline-start: 1.1rem; list-style: disc; font-size: .8rem; } button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; } - -// Own window: three columns. ADOS-2 with its item scores on the left, EEG quality over its alterations -// in the middle, the map with its regions on the right. Narrower windows fall back to two, then one. -.resumen.amplio { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-areas: "ados calidad mapa" "ados alteraciones mapa"; - grid-template-rows: auto 1fr; gap: 1rem; align-items: start; } -.resumen.amplio.sin-eeg { grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "ados calidad"; grid-template-rows: auto; } -.resumen.amplio > .ados { grid-area: ados; } -.resumen.amplio > .calidad { grid-area: calidad; } -.resumen.amplio > .alteraciones { grid-area: alteraciones; } -.resumen.amplio > .mapa { grid-area: mapa; } -.resumen.amplio > .panel { padding: 1rem; } -.resumen.amplio h3 { font-size: 1.1rem; } -@container (max-width: 68rem) { - // The tall ADOS-2 panel spans both rows: the second one takes the leftover height, so no gap opens. - .resumen.amplio { grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-areas: "ados calidad" "ados alteraciones" "mapa mapa"; grid-template-rows: auto 1fr auto; } - // The map spans the width: put its region list beside it. - .resumen.amplio > .mapa { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); grid-template-areas: "titulo titulo" "meta meta" "grafico lista"; column-gap: 1.5rem; align-items: center; } - .resumen.amplio > .mapa > h3 { grid-area: titulo; } - .resumen.amplio > .mapa > .meta { grid-area: meta; } - .resumen.amplio > .mapa > app-plotly-chart { grid-area: grafico; } - .resumen.amplio > .mapa > .regiones { grid-area: lista; } -} -@container (max-width: 42rem) { - .resumen.amplio, .resumen.amplio.sin-eeg { grid-template-columns: minmax(0, 1fr); grid-template-areas: "ados" "calidad" "alteraciones" "mapa"; grid-template-rows: auto; } - .resumen.amplio > .mapa { display: block; } -} diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 455c9de..d6e693c 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -52,7 +52,6 @@ export function mapaFigure(eeg: TeaEeg): PlotlyFigure { export class TeaPacienteResumen implements OnInit { @Input({ required: true }) id = ''; // In its own window there is room for two wide columns instead of four narrow ones. - @Input() amplio = false; private readonly service = inject(TeaSeguimientoService); private readonly destroy = inject(DestroyRef); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 7a78941..74fb5e0 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -97,13 +97,13 @@ describe('Seguimiento TEA', () => { // Mock: odd-numbered patients open their own window; even-numbered ones expand in place. const tres = { ...data, paginacion: { ...data.paginacion, total_items: 3 }, items: [item, { ...item, id_seudonimo: 'T-0002' }, { ...item, id_seudonimo: 'T-0004' }] }; - it('los pacientes pares despliegan su resumen en la fila, uno a la vez, y lo piden al abrirlo', () => { + it('el resumen se despliega en la fila, uno a la vez, y se pide al abrirlo', () => { const fixture = open(); request().flush(tres); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; const toggles = root.querySelectorAll('button.row-toggle'); expect(toggles).toHaveLength(3); - expect(toggles[0].hasAttribute('aria-expanded')).toBe(false); + expect(toggles[0].getAttribute('aria-expanded')).toBe('false'); expect(toggles[1].getAttribute('aria-expanded')).toBe('false'); toggles[1].click(); fixture.detectChanges(); expect(toggles[1].getAttribute('aria-expanded')).toBe('true'); @@ -130,29 +130,24 @@ describe('Seguimiento TEA', () => { expect(root.querySelector('tr.tea-detalle')).toBeNull(); http.verify(); }); - it('los pacientes impares abren su propia ventana y Regresar vuelve a la lista', async () => { + it('todas las filas son un acordeón: se despliegan en su lugar y una a la vez', () => { const fixture = open(); const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha); request().flush(tres); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; - const toggle = root.querySelector('button.row-toggle')!; - expect(toggle.getAttribute('aria-label')).toBe('Abrir ficha del paciente T-0001'); - toggle.click(); fixture.detectChanges(); await fixture.whenStable(); - expect(ficha).toHaveBeenLastCalledWith(true); - expect(root.querySelector('tr.tea-detalle')).toBeNull(); - const ventana = root.querySelector('section.tea-ficha')!; - expect(ventana.querySelector('h2')!.textContent).toBe('Paciente T-0001'); - expect(document.activeElement).toBe(ventana.querySelector('h2')); - expect(ventana.textContent).toContain('Fecha de corte: 2026-09-30.'); - expect(ventana.querySelector('.summary')!.textContent).toContain('18-23 meses'); - expect((root.querySelector('.tracking-table')!.closest('[hidden]'))).not.toBeNull(); + const toggles = root.querySelectorAll('button.row-toggle'); + expect(toggles).toHaveLength(tres.items.length); + toggles.forEach(toggle => expect(toggle.getAttribute('aria-expanded')).toBe('false')); + toggles[0].click(); fixture.detectChanges(); + expect(toggles[0].getAttribute('aria-expanded')).toBe('true'); http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); - expect(ventana.querySelector('app-tea-paciente-resumen .resumen.amplio')!.textContent).toContain('CSS 3'); - ventana.querySelector('.back-button')!.click(); fixture.detectChanges(); await fixture.whenStable(); - expect(ficha).toHaveBeenLastCalledWith(false); + expect(root.querySelector('#tea-detalle-T-0001')?.textContent).toContain('CSS 3'); + (root.querySelectorAll('tbody tr.tea-row')[1] as HTMLElement).click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges(); + expect(root.querySelector('#tea-detalle-T-0001')).toBeNull(); + expect(root.querySelector('#tea-detalle-T-0002')).not.toBeNull(); expect(root.querySelector('section.tea-ficha')).toBeNull(); - expect(root.querySelector('.tracking-table')!.closest('[hidden]')).toBeNull(); - expect(document.activeElement).toBe(root.querySelector('button.row-toggle')); + expect(ficha).not.toHaveBeenCalled(); http.verify(); }); it('muestra un error recuperable si el resumen no es válido', () => {
ReactivoPuntajeAlgoritmo