diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 9fd05cf..7197e8c 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,4 +1,4 @@ -export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; page: number; page_size: number; } +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } export interface SeguimientoPaciente { id_seudonimo: string; diff --git a/src/app/features/indicadores/indicadores-c1-donut.spec.ts b/src/app/features/indicadores/indicadores-c1-donut.spec.ts index 699d293..4a0bd44 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.spec.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.spec.ts @@ -70,6 +70,14 @@ describe('Dona de dos anillos para C1', () => { 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 apiladas por grupo de edad: confirmados y en proceso, con un botón por estado', () => { + const result = c1DonutFigure({ ...datos(), id: 'M24_confirmacion_diagnostico' }, { ...selection, indicador: 'M24_confirmacion_diagnostico', figura: 'fig_c1_barras_apiladas_edad' }); + if (result.status !== 'supported') throw new Error('sin figura'); + expect(result.figure.layout['barmode']).toBe('stack'); + expect(result.figure.data.map(t => [t['name'], t['y']])).toEqual([['Diagnóstico confirmado', [16, 13, 17]], ['En proceso', [8, 5, 5]]]); + expect(result.figure.data[1]['text']).toEqual(['8 (33.3 %)', '5 (27.8 %)', '5 (22.7 %)']); + expect(result.highlight.items.map(i => i.label)).toEqual(['Diagnóstico confirmado', 'En proceso']); + }); 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' }, { ...selection, indicador: 'M22_diagnosticados_sin_eeg', figura: 'fig_c1_barras_edad' }); @@ -82,7 +90,7 @@ describe('Dona de dos anillos para C1', () => { expect(result.highlight.items.map(i => i.points)).toEqual([[{ trace: 0, index: 0 }], [{ trace: 0, index: 1 }], [{ trace: 0, index: 2 }]]); }); it('usa etiquetas propias por indicador y neutrales para otros', () => { - expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Con diagnóstico positivo de TEA', 'Sin diagnóstico de TEA']); + expect(c1DonutLabels('M24_confirmacion_diagnostico')).toEqual(['Diagnóstico confirmado', 'En proceso']); expect(c1DonutLabels('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']); expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']); }); diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts index 410ba9a..db83d2a 100644 --- a/src/app/features/indicadores/indicadores-c1-donut.ts +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -12,13 +12,14 @@ import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.mod export const C1_DONUT = 'fig_c1_donas'; export const C1_RING = 'fig_c1_dona_edad'; export const C1_AGE_BARS = 'fig_c1_barras_edad'; -const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS]; +export const C1_AGE_STACK = 'fig_c1_barras_apiladas_edad'; +const C1_AGE_FIGURES = [C1_DONUT, C1_RING, C1_AGE_BARS, C1_AGE_STACK]; export const C1_DONUT_ESTRATO = 'grupo_edad'; // Mock (TEA): ring labels per indicator; any other C1 indicator falls back to a neutral wording. const EVENT_LABELS: Readonly> = { M21_diagnosticados_con_eeg: ['Con EEG', 'Sin EEG'], M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'], - M24_confirmacion_diagnostico: ['Con diagnóstico positivo de TEA', 'Sin diagnóstico de TEA'], + M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'], }; // 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; @@ -64,6 +65,13 @@ export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): const notes = Array.isArray(data.notas) ? [...data.notas] : []; 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_STACK) { + const figure = ageStack(strata, labels, selection); + figure.layout = { ...figure.layout, title }; + const highlight: FigureHighlight = { groups: [], traces: [0, 1], allLabel: 'Todos los pacientes', + items: labels.map((label, g) => ({ id: g ? 'SIN' : 'CON', label, color: RING_COLORS[g], points: strata.map((_, i) => ({ trace: g, index: i })) })) }; + return { status: 'supported', figure, highlight, total, notes }; + } if (selection.figura === C1_AGE_BARS) { const figure = ageBars(strata, labels[0], selection); figure.layout = { ...figure.layout, title }; @@ -121,6 +129,21 @@ 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 stacked bar per age group: how many of its patients have the event and how many don't. +function ageStack(strata: readonly { label: string; numerador: unknown; denominador: unknown }[], labels: readonly [string, string], selection: FigureSelection): PlotlyFigure { + const theme = c2Theme(selection.tema); + const x = strata.map(s => escape(s.label)); + const conEvento = strata.map(s => s.numerador as number), sinEvento = strata.map(s => (s.denominador as number) - (s.numerador as number)); + return { data: [conEvento, sinEvento].map((y, g) => ({ type: 'bar', name: escape(labels[g]), x, y, marker: { color: RING_COLORS[g], line: { color: theme.background, width: 1 } }, + text: y.map((n, i) => (strata[i].denominador as number) ? n + ' (' + percentNumber(100 * n / (strata[i].denominador as number)) + ' %)' : ''), + textposition: 'inside', insidetextanchor: 'middle', hovertemplate: '%{x}
%{fullData.name}: %{y} pacientes' })), + layout: { autosize: true, height: 400, barmode: 'stack', margin: { t: 24, l: 72, r: 24, b: 80 }, showlegend: true, + legend: { orientation: 'h', y: -0.28, itemclick: false, itemdoubleclick: false }, + paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + xaxis: { type: 'category', title: { text: 'Grupo de edad' }, automargin: true }, + yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero', gridcolor: theme.grid, zeroline: false } }, + config: { displayModeBar: false } }; +} // 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, selection: FigureSelection): PlotlyFigure { const theme = c2Theme(selection.tema); diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index c7ec47f..6c77c01 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -2,6 +2,7 @@ // Exact IDs remain the option values and HTTP identities; never infer a type // from a prefix. Unknown options keep a neutral label in publication order. const FIGURE_LABELS: Readonly> = { + fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad', fig_c1_barras_edad: 'Barras por grupo de edad', fig_c1_dona_edad: 'Dona por grupo de edad', fig_c1_donas: 'Dona de dos anillos', diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 6677ded..90cb05f 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -16,20 +16,32 @@ const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFi // sortedPeriods lists the newest first, for selectors; time here runs left to right. export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); +const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']; +// «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years. +export function etiquetaPeriodo(periodo: string): string { + const [anio, resto] = periodo.split('-'); + return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`; +} +export interface HistoricoOpciones { + // Same vertical scale across small charts, so their heights compare. + yMax?: number; + pequena?: boolean; +} function validar(data: IndicadorDatos) { for (const row of data.filas) { if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida'); } return cronologico(data.periodos); } -function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string) { - const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes'; +function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string, pequena = false) { + const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo); + const cada = pequena && periodos.length > 12 ? 6 : 3; return { - autosize: true, height: 380, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, - margin: { l: 64, r: 16, t: 16, b: mensual ? 96 : 64 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.3 : -0.12, itemclick: false, itemdoubleclick: false }, + autosize: true, height: pequena ? 340 : 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false }, // A label for every month does not fit: one per quarter is still readable with the full period on hover. - xaxis: { type: 'category', categoryorder: 'array', categoryarray: periodos, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0, - tickmode: 'array', tickvals: periodos.filter((_, i) => periodos.length <= 12 || i % 3 === 0) }, + xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0, + title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % cada === 0) }, yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false }, // Shaded, because an empty space alone reads as zero. Text below the figure says the same. shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 }, @@ -73,8 +85,8 @@ function porcentaje(data: IndicadorDatos, tema: Tema): HistoricoFigura { 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', linea), - { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos, y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 }, + banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea), + { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), 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: ' %' } } }, @@ -82,20 +94,28 @@ function porcentaje(data: IndicadorDatos, tema: Tema): HistoricoFigura { suprimidos, sinDato, }; } -function mediana(data: IndicadorDatos, tema: Tema): HistoricoFigura { +function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): HistoricoFigura { const periodos = validar(data); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana'])); return { figure: { data: [ - banda(periodos, campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line), - { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos, y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, + banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line), + { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, text: validas.map(row => row ? `Mediana: ${row['mediana']} días
Q1 a Q3: ${row['q1']} a ${row['q3']} días
${row['n']} pacientes` : ''), hovertemplate: '%{x}
%{text}' }, - ], layout: ejes(data, periodos, suprimidos, tema, 'Días') }, + ], layout: (() => { + const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena); + return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout; + })() }, comoLeer: 'La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de los pacientes.', suprimidos, sinDato, }; } +// What each count means, for the indicators that don't count patients in the period. +const CONTEOS: Readonly> = { + M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' }, + M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' }, +}; function conteo(data: IndicadorDatos, tema: Tema): HistoricoFigura { const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}; const celdas = new Map>(), categorias = new Map(); @@ -114,18 +134,39 @@ function conteo(data: IndicadorDatos, tema: Tema): HistoricoFigura { const meta = record(catalogo[id]) ? catalogo[id] : {}; const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined; const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; }); - return { type: 'bar', name: escape(typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id), x: periodos, y: valores, + return { type: 'bar', name: escape(typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : id), x: periodos.map(etiquetaPeriodo), y: valores, marker: { color: c2Color(color, i) }, hovertemplate: '%{y}%{fullData.name}' }; - }), layout: { ...ejes(data, periodos, suprimidos, tema, 'Pacientes'), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, - comoLeer: 'Cada barra es el total de pacientes del periodo, y sus partes muestran cuántos hay en cada categoría.', + }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? 'Pacientes'), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, + comoLeer: CONTEOS[data.id]?.comoLeer ?? 'Cada barra es el total de pacientes del periodo, y sus partes muestran cuántos hay en cada categoría.', suprimidos, sinDato, }; } // 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 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); - throw new Error('Representación no soportada'); +export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura { + const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema) + : data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined; + if (!figura) throw new Error('Representación no soportada'); + return { ...figura, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; +} +// The share of cases still in process, from the case-status counts. Cases out of the protocol aren't in the base. +export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura { + const periodos = validar(data); + const n = (periodo: string, categoria: string) => { + const valor = data.filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria)?.['n']; + return numero(valor) ? valor : null; + }; + const puntos = periodos.map(periodo => { + const proceso = n(periodo, 'EN_PROCESO'), completo = n(periodo, 'COMPLETO'); + return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo }; + }); + const layout = ejes(data, periodos, [], tema, 'Porcentaje'); + return { + figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 }, + y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} casos` : ''), + hovertemplate: '%{x}
%{y} % en proceso
%{text}' }], + layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, + comoLeer: 'De los casos completos o en proceso al cierre de cada periodo, el porcentaje que seguía en proceso. Los que quedaron fuera del protocolo no cuentan.', + suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo), + }; } diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts index 4e4a39b..7c3fb81 100644 --- a/src/app/features/indicadores/indicadores-historico.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -4,7 +4,7 @@ import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistorico } from './indicadores-historico'; -import { historicoFigura } from './indicadores-historico-figures'; +import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures'; import { Indicador, IndicadorDatos } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @@ -21,7 +21,8 @@ describe('Figuras de histórico', () => { 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']); + expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024', 'mar 2024']); + expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Mes y año'); expect((figure.data[1]['marker'] as { color: string }).color).toBe('#112233'); expect(suprimidos).toEqual([]); expect(sinDato).toEqual([]); }); @@ -29,16 +30,16 @@ describe('Figuras de histórico', () => { 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 } = historicoFigura(data, 'claro'); expect(figure.data[0]['y']).toEqual([5, null, 0]); - expect(suprimidos).toEqual(['2024-02']); + expect(suprimidos).toEqual(['feb 2024']); 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 } = 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).x).toEqual(['ene 2024', 'ene 2024', null, 'mar 2024', 'mar 2024']); expect(traza(data, 0).y).toEqual([45, 35, null, 65, 55]); - expect(suprimidos).toEqual(['2024-02']); + expect(suprimidos).toEqual(['feb 2024']); expect(figure.layout['barmode']).toBeUndefined(); expect((figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 100]); }); @@ -47,13 +48,30 @@ describe('Figuras de histórico', () => { 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([]); + expect(sinDato).toEqual(['feb 2024']); 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') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color; expect(color('claro')).toBe('#6A8000'); expect(color('oscuro')).toBe('#A8C243'); }); + it('escribe los periodos con mes y año', () => { + expect(etiquetaPeriodo('2024-03')).toBe('mar 2024'); + expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2'); + }); + it('el porcentaje en proceso se calcula sobre completos y en proceso, sin los que quedaron fuera', () => { + const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 }); + const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [ + fila('2024-01', 'COMPLETO', 10), fila('2024-01', 'EN_PROCESO', 30), fila('2024-01', 'FUERA_PROTOCOLO', 99), + fila('2024-02', 'COMPLETO', 30), fila('2024-02', 'EN_PROCESO', 10), fila('2024-02', 'FUERA_PROTOCOLO', 99)] }, 'claro'); + expect(figure.data[0]['y']).toEqual([75, 25]); + expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']); + }); + it('una escala compartida fija el máximo de las medianas', () => { + const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }; + expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]); + expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined(); + }); 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'); @@ -98,7 +116,7 @@ describe('Pestaña Histórico', () => { const request = http.expectOne(r => r.url === datosUrl); 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('.rango').textContent).toBe('ene 2024 a feb 2024 (2 meses)'); }); it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => { abrir(); @@ -107,7 +125,7 @@ describe('Pestaña Histórico', () => { const semestre = http.expectOne(r => r.url === datosUrl); expect(semestre.request.params.get('periodos')).toBe('2024-S1'); semestre.flush(datos('semestre', ['2024-S1'])); render(); - expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-S1 a 2024-S1 (1 semestre)'); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 a 2024 S1 (1 semestre)'); fixture.componentInstance.tipo.set('mes'); render(); fixture.componentRef.setInput('tema', 'oscuro'); render(); http.expectNone(() => true); @@ -120,9 +138,9 @@ describe('Pestaña Histórico', () => { 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)'); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ene 2024 a dic 2024 (12 meses)'); c.elegirVentana(5); render(); - expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024-08 a 2024-12 (5 meses)'); + expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)'); http.expectNone(() => true); c.tipo.set('semestre'); render(); expect(c.ventana()).toBe(0); @@ -132,6 +150,24 @@ describe('Pestaña Histórico', () => { expect(c.ventana()).toBe(5); http.expectNone(() => true); }); + it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => { + const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'] + .map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] })); + fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render(); + for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] }); + for (const { id } of items) { + const c2 = id.startsWith('M28'); + http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'], + filas: c2 ? [{ periodo: '2024-01', categoria: 'COMPLETO', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'EN_PROCESO', n: 1, orden: 1, suprimido: 0 }] + : [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] }); + } + render(); + const paneles = fixture.componentInstance.paneles(); + expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']); + const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>; + expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]); + expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3); + }); 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-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 4e98627..b982981 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -7,7 +7,7 @@ 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, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; +import { cronologico, enProcesoFigura, etiquetaPeriodo, 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'; @@ -15,8 +15,30 @@ 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: HistoricoFigura }); +type Panel = { item: Pick; rango?: string } & ( + { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); +const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; +const CASOS = 'M28_casos_por_estado'; + +// The screening steps go together as small charts, and the case counts are followed by their in-process share. +function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] { + const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id)); + const listos = pasos.every(p => p?.estado === 'listo'); + return paneles.flatMap((panel): Panel[] => { + if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') { + const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract).figura })); + const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))]; + return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras, + figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.', + suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }]; + } + if (listos && TIEMPOS.includes(panel.item.id)) return []; + if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) { + return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de casos en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }]; + } + return [panel]; + }); +} // 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. @@ -39,7 +61,7 @@ type Panel = { item: Indicador; rango?: string } & (
@for (panel of paneles(); track panel.item.id) { -
+

{{ panel.item.titulo }}

@if (panel.rango) {

{{ panel.rango }}

} @switch (panel.estado) { @@ -50,8 +72,18 @@ type Panel = { item: Indicador; rango?: string } & (
} @case ('listo') { - + @if (panel.pasos; as pasos) { +
+ @for (paso of pasos; track paso.titulo) { +

{{ paso.titulo }}

+ +
+ } +
+ } @else { + + }

{{ 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.}

@@ -75,6 +107,10 @@ 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); } + .panel.ancho { grid-column: 1 / -1; } + .pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); } + @container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } } + h3 { margin: 0; font: var(--mat-sys-title-small); } mat-form-field { min-width: 14rem; } `, }) @@ -104,19 +140,27 @@ export class IndicadoresHistorico { }); readonly paneles = computed(() => { 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 => { + // Top of the shared scale: the highest third quartile of the steps, in the periods on screen. + const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => { + const carga = cargas?.[id]; + if (carga?.estado !== 'listo') return []; + const visibles = cronologico(carga.datos.periodos).slice(-ventana); + return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0); + })) * 1.05; + const base: (Panel & { datos?: IndicadorDatos })[] = 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).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)})`; + const rango = `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])} (${periodos.length} ${unidad(tipo, periodos.length)})`; try { - return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema) }; + return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos }; } catch (error) { return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } }); + return agrupar(base, tema); }); constructor() { diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 33aed03..042758e 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -15,6 +15,12 @@ export const CACU_RESULTADO_KPI: KpiDefinition = { // in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories // (patients), not the distribution. If a TOML title changes, change it here too, until the // cards read the `titulo` that the API already sends. +// What only TEA's summary paragraph needs: case status and the time of each screening step. +export const KPI_RESUMEN_TEA: KpiDefinition[] = [ + { id: 'M28_casos_por_estado', title: 'Casos iniciados', contrato: 'C2', unit: 'casos' }, + { id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' }, + { id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, +]; export const KPI_BY_DOMAIN: Record = { tea: [ { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, @@ -47,7 +53,7 @@ const C3R_INFO: Record string> = cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`, cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`, }; -export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; } +export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record; } const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0; const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' }; @@ -82,7 +88,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai if (!rows.every(row => count(row['n']))) return empty; const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0); if (!count(value)) return empty; - return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' }; + return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' }; } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a9bd616..a4e7d5e 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -1,4 +1,4 @@ -
+
@if (fichaPacienteAbierta()) {

Ficha del paciente

@@ -76,7 +76,7 @@

{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}

@if (!catalogLoading() && !catalogError() && catalog().length) { -

{{ catalog().length }} indicadores publicados

+

{{ catalogOrder().length }} indicadores publicados

}
@if (catalogLoading()) { @@ -105,12 +105,18 @@

- Mostrando {{ searchResults().items.length }} de {{ catalog().length }} indicadores. + Mostrando {{ searchResults().items.length }} de {{ catalogOrder().length }} indicadores.

} @if (!searchResults().items.length) {

No hay indicadores seleccionados. Elige al menos uno en «Buscar indicadores».

} + @if (dominio === 'tea') { +
+ + Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión. +
+ }
@for (item of searchResults().items; track cardIdentity(item)) { app-indicador-catalog-card { min-width: 0; margin: 0; } .catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } .catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; } diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index d543cf3..926afc5 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -111,6 +111,13 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas'); http.expectNone(() => true); }); + it('Resumen omite los indicadores publicados solo para otra pestaña', () => { + load([item, { ...second, vistas: ['historico'] }]); + expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]); + expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicadores'); + expect(page.catalog()).toHaveLength(2); + http.expectNone(r => r.url.endsWith('/figuras/f1')); + }); it('D.3.A conserva encabezado y contenido al salir del viewport', () => { load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); const header = host.querySelector('header'); toggle(); flushAll(); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 598173d..4c7b242 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -16,7 +16,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KPI_RESUMEN_TEA } from './indicadores-kpi'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; @@ -160,7 +160,26 @@ export class IndicadoresPage { this.visibilityObserver = observer; for (const region of this.observedRegions.keys()) observer.observe(region); } + // Report: every selected chart has to be drawn, narrow enough for a page, before opening the print dialog. + readonly preparandoReporte = signal(false); + async descargarReporte() { + const browser = this.document.defaultView; + if (!browser || this.preparandoReporte()) return; + this.preparandoReporte.set(true); + for (const card of this.graphicCards()) card.setVisible(true); + this.changeDetector.markForCheck(); + const espera = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + const pendiente = () => this.element.nativeElement.querySelector('#panel-resumen mat-progress-bar, #panel-resumen .figure-skeleton'); + await espera(100); + for (let i = 0; pendiente() && i < 150; i++) await espera(100); + // Charts resize to the page width on their next frames. + await espera(500); + const terminar = () => { this.preparandoReporte.set(false); this.changeDetector.markForCheck(); this.visibilityChanged(); }; + browser.addEventListener('afterprint', terminar, { once: true }); + browser.print(); + } private evaluateVisibility() { + if (this.preparandoReporte()) return; const browser = this.document.defaultView; if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; if (this.activeSection() !== 'resumen') return; @@ -180,9 +199,9 @@ export class IndicadoresPage { changeIndicatorSelection(ids: string[]) { this.preserveCardFocus(); // Every indicator checked is the same as no filter, so later catalog additions also show. - this.indicatorSelection.set(ids.length === this.catalog().length ? null : ids); + this.indicatorSelection.set(ids.length === this.catalogOrder().length ? null : ids); } - showAllIndicators() { this.changeIndicatorSelection(this.catalog().map(item => item.id)); } + showAllIndicators() { this.changeIndicatorSelection(this.catalogOrder().map(item => item.id)); } isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); } togglePinned(item: Indicador) { this.preserveCardFocus(); @@ -254,7 +273,7 @@ export class IndicadoresPage { // Short form for the domain-switcher buttons (our shell's own nav, see the // template comment above it) -- `domainLabels`/`domainTitles` are prose-length. readonly domainNavLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; - readonly kpisByDomain = KPI_BY_DOMAIN; + readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] }; figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } kpiIndicator(id: string) { @@ -287,13 +306,13 @@ export class IndicadoresPage { readonly catalog = signal([]); // Ids of the indicators to render; null shows the whole catalog. readonly indicatorSelection = signal(null); - readonly searchVisible = computed(() => this.catalog().length >= 2); + readonly searchVisible = computed(() => this.catalogOrder().length >= 2); // Stable presentation priority; pins still take precedence in the grid. readonly catalogOrder = computed(() => { const catalog = this.catalog(); return this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] - : catalog; + : catalog.filter(item => !item.vistas || item.vistas.includes('resumen')); }); readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id)); readonly selectionSummary = computed(() => { diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index d1350f8..8c6b005 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -36,6 +36,14 @@ @for (r of rangosCss; track r.codigo) { } + + } @@ -48,23 +56,39 @@

Ventana consultada: {{ response.ventana.desde }} al {{ response.ventana.hasta }}.

} @if (teaData; as response) { +
+

EEG de los pacientes filtrados

+
+
Normales
{{ response.resumen_eeg.normales }}
+
Anormales
{{ response.resumen_eeg.anormales }}
+
Sin EEG
{{ response.resumen_eeg.sin_eeg }}
+ @for (a of response.resumen_eeg.por_alteracion; track a.codigo) { +
{{ a.etiqueta }}
{{ a.n }}
+ } +
+

Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.

+
- + @for (item of response.items; track item.id_seudonimo) { - - + + + + + @if (teaAbierto === item.id_seudonimo) { - + } - } @empty { } + } @empty { }
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadÚltimo EEGPuntaje M-CHATCSS ADOS-2Alteraciones EEG
Identificador seudónimoGrupo de edadEstado del casoÚltimo EEGPuntaje M-CHATCSS ADOS-2Alteraciones EEG
{{ item.grupo_edad }}{{ item.ultimo_eeg ?? 'No disponible' }}{{ item.mchat ?? 'No disponible' }}{{ item.css_ados2 ?? 'No disponible' }}{{ item.grupo_edad }}{{ etiquetaEstado[item.estado_caso] }} + @if (item.pendientes.length) { Falta: {{ item.pendientes.join(', ') }} }{{ item.ultimo_eeg ?? 'No disponible' }}{{ item.mchat ?? 'No disponible' }}{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { Módulo {{ item.modulo_ados2 }} } @if (item.alteraciones_eeg; as eeg) { {{ eeg === 'anormal' ? 'Anormal' : 'Normal' }} } @else { No disponible }
No hay registros para los filtros aplicados.
No hay registros para los filtros aplicados.
diff --git a/src/app/features/indicadores/indicadores-tracking.scss b/src/app/features/indicadores/indicadores-tracking.scss index 8a5a852..f3b1cf3 100644 --- a/src/app/features/indicadores/indicadores-tracking.scss +++ b/src/app/features/indicadores/indicadores-tracking.scss @@ -15,6 +15,16 @@ caption { text-align: start; padding: 1rem; } th, td { text-align: start; vertical-align: top; padding: 1rem; border-top: 1px solid var(--issste-border); } th { background: var(--issste-background); font-weight: 600; } small { display: block; margin-top: .35rem; } +.resumen-eeg { margin-bottom: 1rem; padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +.resumen-eeg h3 { margin: 0 0 .75rem; font-size: 1.1rem; } +.resumen-eeg dl { display: flex; flex-wrap: wrap; gap: 1rem 2rem; margin: 0; } +.resumen-eeg dt { color: var(--issste-text-secondary); font-size: .9rem; } +.resumen-eeg dd { margin: .2rem 0 0; font-size: 1.5rem; font-weight: 700; } +.resumen-eeg .tipo dd { font-size: 1.15rem; font-weight: 600; } +.resumen-eeg p { margin: .75rem 0 0; font-size: .85rem; } +.estado-caso { font-weight: 600; } +.estado-caso[data-estado=en_proceso] { color: #B26A00; } +.estado-caso[data-estado=fuera_protocolo] { color: var(--issste-text-secondary); } nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; } tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; } tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); } diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 5fd9165..268f295 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -10,7 +10,7 @@ import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { ALTERACIONES_EEG, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service'; +import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service'; import { TeaPacienteResumen } from './tea-paciente-resumen'; @Component({ @@ -52,6 +52,10 @@ export class IndicadoresTracking implements OnChanges { readonly gruposEdad = GRUPOS_EDAD_TEA; readonly rangosMchat = RANGOS_MCHAT; readonly rangosCss = RANGOS_CSS; + readonly etiquetaEstado = ESTADOS_CASO; + readonly estadosCaso = Object.entries(ESTADOS_CASO).map(([codigo, etiqueta]) => ({ codigo, etiqueta })); + // Kept from the last answer, so the filter doesn't empty while a query is running. + tiposAlteracion: { codigo: string; etiqueta: string }[] = []; get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); } get response() { return this.dominio === 'tea' ? this.teaData : this.data; } constructor() { @@ -84,6 +88,7 @@ export class IndicadoresTracking implements OnChanges { this.status = result.status; this.teaData = result.data; this.message = result.message; this.teaAbierto = undefined; if (result.data) { const data = result.data; + this.tiposAlteracion = data.tipos_alteracion; this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; this.draft = { ...this.applied }; } diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index f40a8d4..b8980a0 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -16,6 +16,8 @@ export interface Indicador { figuras: string[]; tipos_periodo: TipoPeriodo[]; filtros?: IndicadorFiltro[]; + // Tabs that show it; without this field, all of them. + vistas?: string[]; } export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado'; export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index 72a3f4e..3a8f43a 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -53,15 +53,17 @@
@if (d.eeg; as e) { +

Alteraciones del EEG Datos de ejemplo

-

Rangos de referencia y efectos asociados de ejemplo, pendientes de validación médica.

+

Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.

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

Sin alteraciones en las métricas evaluadas.

}
    @for (m of e.alteraciones; track m.codigo) {
  • - {{ m.etiqueta }} + {{ estado[m.estado] }}
    @if (m.valor !== null) { @@ -80,19 +82,23 @@
-
-

Zonas más afectadas

-

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

- @if (figura) { - - } -
    - @for (r of e.regiones; track r.codigo) { -
  1. {{ r.etiqueta }}z = {{ r.valor_z }}
  2. + @if (mapaActual(e); as mapa) { +
    +

    Zonas más afectadas

    +

    {{ mapa.metrica }} · mapa ilustrativo

    +

    Azul: menos actividad Rojo: más actividad

    + @if (figura) { + } -
-
+
    + @for (r of mapa.regiones; track r.codigo) { +
  1. {{ r.etiqueta }}z = {{ r.valor_z }}
  2. + } +
+
+ } + } } diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 9e0a85a..6826e0b 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -13,6 +13,16 @@ h3 { margin: 0 0 .15rem; font-size: 1rem; } .css[data-nivel=bajo], .css[data-nivel=minimo], .css[data-calidad=bueno] { border-color: var(--issste-accent); } .css[data-calidad] { flex: none; white-space: nowrap; } dd[data-calidad=malo] { color: #B3261E; } +// The button's area covers its whole card, so the card is clickable without nesting the effects list in a button. +button.nombre { margin: 0; min-height: 0; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; } +button.nombre::after { content: ''; position: absolute; inset: 0; border-radius: inherit; } +button.nombre:disabled { cursor: default; } +button.nombre:focus-visible { outline: none; } +button.nombre:focus-visible::after { outline: 2px solid var(--issste-text); outline-offset: 2px; } +.leyenda-mapa { display: flex; flex-wrap: wrap; align-items: center; gap: .35rem; margin: .25rem 0; font-size: .8rem; } +.leyenda-mapa span { width: .8rem; height: .8rem; border-radius: 2px; } +.leyenda-mapa .azul { background: #2166AC; } +.leyenda-mapa .rojo { margin-inline-start: .5rem; background: #B2182B; } dd[data-calidad=aceptable] { color: #B26A00; } .dominio { display: grid; grid-template-columns: 1fr auto; gap: .15rem 1rem; margin-bottom: .4rem; font-size: .85rem; } .bar { grid-column: 1 / -1; height: .375rem; border-radius: 999px; background: var(--issste-border); overflow: hidden; } @@ -38,7 +48,21 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; } .sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; } .metricas, .efectos { margin: 0; padding: 0; list-style: none; } -.metricas > li { padding: .4rem 0 .4rem .6rem; border-top: 1px solid var(--issste-border); border-inline-start: 4px solid transparent; } +// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it. +.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; } +.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; } +.marco-mapa { min-width: 0; overflow: hidden; } +.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; } +.mapa h3 { margin-top: 0; } +@keyframes aparecer { from { opacity: 0; } } +@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } } +@container zona (max-width: 42rem) { .mapa { width: 100cqw; } } +@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } } +@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } } +.metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; } +.metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; } +.metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); } +.metricas > li:has(button[aria-expanded=true]) { border-color: var(--issste-accent); background: color-mix(in srgb, var(--issste-accent) 12%, transparent); } .metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; } .metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; } li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 50d25d7..1170859 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -1,8 +1,8 @@ -import { Component, DestroyRef, inject, Input, OnInit, signal } from '@angular/core'; +import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; -import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service'; +import { TeaAdos2, TeaAlteracionEstado, TeaEeg, TeaEegMapa, TeaPacienteDetalle, TeaSeguimientoService } from './tea-seguimiento.service'; const CLASIFICACION: Record = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro' }; // ADOS-2 calibrated severity score ranges. @@ -14,17 +14,17 @@ const INK = '#081839'; // Shape paths have no arcs: the hole is a polygon, wound against the frame so it stays empty under either fill rule. const HOLE = Array.from({ length: 96 }, (_, i) => -2 * Math.PI * i / 96) .map((a, i) => `${i ? 'L' : 'M'} ${Math.cos(a).toFixed(4)} ${Math.sin(a).toFixed(4)}`).join(' '); -// A white frame with a round hole hides the map outside the head; then the head outline, nose and ears. -const HEAD_SHAPES = [ - { type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: '#FFFFFF', line: { width: 0 } }, +// A frame with a round hole hides the map outside the head, in the colour behind the map; then the head outline, nose and ears. +const headShapes = (fondo: string) => [ + { type: 'path', path: `M -2 -2 L 2 -2 L 2 2 L -2 2 Z ${HOLE} Z`, fillrule: 'evenodd', fillcolor: fondo, line: { width: 0 } }, { type: 'circle', xref: 'x', yref: 'y', x0: -1, y0: -1, x1: 1, y1: 1, line: { color: INK, width: 2 } }, { type: 'path', path: 'M -0.13 0.99 L 0 1.13 L 0.13 0.99', line: { color: INK, width: 2 } }, { type: 'path', path: 'M -0.99 0.14 Q -1.1 0.12 -1.08 0 Q -1.1 -0.12 -0.99 -0.14', line: { color: INK, width: 2 } }, { type: 'path', path: 'M 0.99 0.14 Q 1.1 0.12 1.08 0 Q 1.1 -0.12 0.99 -0.14', line: { color: INK, width: 2 } }, ]; -export function mapaFigure(eeg: TeaEeg): PlotlyFigure { - const m = eeg.mapa; +export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): PlotlyFigure { + const m = { ...eeg.ejes_mapa, z: mapa.z }; return { data: [ { type: 'contour', x: m.x, y: m.y, z: m.z, zmin: -3, zmax: 3, zmid: 0, colorscale: 'RdBu', connectgaps: false, @@ -34,7 +34,7 @@ export function mapaFigure(eeg: TeaEeg): PlotlyFigure { textposition: 'top center', textfont: { size: 9, color: INK }, marker: { size: 5, color: INK }, hoverinfo: 'text', showlegend: false }, ], layout: { - margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: HEAD_SHAPES, + margin: { l: 8, r: 8, t: 8, b: 8 }, showlegend: false, shapes: headShapes(fondo), paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', xaxis: { visible: false, range: [-1.2, 1.2], fixedrange: true }, yaxis: { visible: false, range: [-1.15, 1.2], scaleanchor: 'x', fixedrange: true }, @@ -51,12 +51,28 @@ 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. private readonly service = inject(TeaSeguimientoService); private readonly destroy = inject(DestroyRef); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly detalle = signal(undefined); figura?: PlotlyFigure; + private mapaElegido?: string; + private readonly elemento = inject>(ElementRef); + // The first solid background around this component: the map has no box of its own. + private fondo() { + for (let e: HTMLElement | null = this.elemento.nativeElement; e; e = e.parentElement) { + const color = getComputedStyle(e).backgroundColor; + if (/^rgb\(/.test(color)) return color; + } + return '#FFFFFF'; + } + 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()); + } readonly clasificacion = CLASIFICACION; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -65,7 +81,7 @@ export class TeaPacienteResumen implements OnInit { load() { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: d => { this.figura = d.eeg ? mapaFigure(d.eeg) : undefined; this.detalle.set(d); this.status.set('ready'); }, + next: d => { this.mapaElegido = undefined; this.figura = undefined; this.detalle.set(d); this.status.set('ready'); }, error: () => this.status.set('error'), }); } diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index 7e4ae2a..b0dd516 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -3,7 +3,7 @@ import { TestBed } from '@angular/core/testing'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; -type Result = { state: string; value?: string | number; loading?: boolean; period?: string }; +type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record }; function panel(id: string, result: Result) { return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType>; retry: ReturnType }; } @@ -16,18 +16,19 @@ describe('Resumen TEA por periodo', () => { fixture.detectChanges(); return fixture; } - const completos = () => [panel('M23_pacientes_evaluados', listo(409)), panel('M24_confirmacion_diagnostico', listo('86.5')), - panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1'))]; + const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { COMPLETO: 60, EN_PROCESO: 25, FUERA_PROTOCOLO: 15 } }), panel('M24_confirmacion_diagnostico', listo('86.5')), + panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')), + panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))]; it('redacta el párrafo con cada población y resalta los valores', () => { const root: HTMLElement = render(completos()).nativeElement; const text = root.textContent!.replace(/\s+/g, ' '); - expect(text).toContain('En el periodo 2025-S2, 409 pacientes evaluados por psicología tuvieron un diagnóstico confirmado o en proceso.'); + expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 casos iniciados hasta entonces, 60 están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), 25 siguen en proceso y 15 quedaron fuera del protocolo.'); expect(text).toContain('De los pacientes con nota médica, 86.5 % tuvo diagnóstico positivo de TEA (CIE-10 F84.0).'); - expect(text).toContain('hasta el diagnóstico positivo de TEA fue de 22 días.'); + expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.'); expect(text).toContain('De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), 71.9 % tenían EEG y 28.1 % no lo tenían.'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '409', '86.5 %', '22 días', '71.9 %', '28.1 %']); + .toEqual(['2025-S2', '100', '60', '25', '15', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']); expect(root.querySelector('button')).toBeNull(); }); diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index b87c093..4f6e0c7 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -7,16 +7,19 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta // TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the // requests, contract checks and suppression rules stay those of the cards. Each sentence names -// its own population: M23, M24, M25 and M21/M22 do not count the same patients. +// its own population: M28, M24, M25 and M21/M22 do not count the same patients. @Component({ selector: 'app-tea-resumen-periodo', imports: [MatButtonModule, NgTemplateOutlet], template: `

- En el periodo {{ periodo }}, - pacientes evaluados por psicología tuvieron un diagnóstico confirmado o en proceso. De los pacientes con nota médica, - tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana del tiempo desde la aplicación del M-CHAT por psicología hasta el diagnóstico positivo de TEA fue de + Al cierre del periodo {{ periodo }}, de los casos iniciados hasta entonces, + están completos (con M-CHAT, ADOS-2, nota de neuropediatría y EEG), + siguen en proceso y quedaron fuera del protocolo. + De los pacientes con nota médica, + tuvo diagnóstico positivo de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de , de ADOS-2 a diagnóstico, de + , y en total, de M-CHAT a diagnóstico, de . De los pacientes con TEA positivo por ADOS-2 (16 a 36 meses), tenían EEG y no lo tenían. @@ -56,6 +59,13 @@ export class TeaResumenPeriodo { return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state }; return { texto: result.value + sufijo, estado: 'listo' }; } + // One status of M28, under the same rules as valor(). + caso(categoria: string): Valor { + const base = this.valor('M28_casos_por_estado', ''); + if (base.estado !== 'listo') return base; + const n = this.panel('M28_casos_por_estado')?.result().categorias?.[categoria]; + return n === undefined ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Estado no publicado' } : { texto: String(n), estado: 'listo' }; + } get cargando() { return this.paneles.some(p => p.result().loading); } get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); } reintentar() { this.conError.forEach(p => p.retry()); } diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 619df74..dedc1fc 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -5,6 +5,7 @@ import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } fro import { validSeguimientoQuery } from './cacu-seguimiento.service'; export type AlteracionesEeg = 'normal' | 'anormal'; +export type EstadoCaso = 'completo' | 'en_proceso' | 'fuera_protocolo'; export interface TeaSeguimientoPaciente { id_seudonimo: string; grupo_edad: string; @@ -12,10 +13,23 @@ export interface TeaSeguimientoPaciente { mchat: number | null; css_ados2: number | null; alteraciones_eeg: AlteracionesEeg | null; + modulo_ados2: string | null; + estado_caso: EstadoCaso; + // What a case in process still lacks. + pendientes: string[]; + // Codes of the alterations found. + alteraciones: string[]; +} +export interface TeaResumenEeg { + normales: number; anormales: number; sin_eeg: number; + por_alteracion: { codigo: string; etiqueta: string; n: number }[]; } export interface TeaSeguimientoResponse extends Pick { filtros: { alteraciones_eeg: AlteracionesEeg | null }; items: TeaSeguimientoPaciente[]; + tipos_alteracion: { codigo: string; etiqueta: string }[]; + // Of every patient that matches the filters, not only this page's. + resumen_eeg: TeaResumenEeg; } export interface TeaAdosReactivo { codigo: string; etiqueta: string; puntaje: number; puntaje_algoritmo: number } export interface TeaAdosDominio { codigo: string; etiqueta: string; puntaje: number; maximo: number; reactivos: TeaAdosReactivo[] } @@ -31,16 +45,19 @@ export interface TeaEegAlteracion { codigo: string; etiqueta: string; unidad: string; referencia: { min: number; max: number }; valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; } +export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] } export interface TeaEeg { fecha: string; duracion_min: number; canales: number; // The overall rating is in words, like Automagic, and is the worst of its criteria, which report numbers. calidad: TeaNivelCalidad; criterios_calidad: { codigo: string; etiqueta: string; valor: number; unidad: string; nivel: TeaNivelCalidad }[]; - regiones: TeaEegRegion[]; alteraciones: TeaEegAlteracion[]; - mapa: { metrica: string; x: number[]; y: number[]; z: (number | null)[][]; electrodos: { nombre: string; x: number; y: number }[] }; + // One map per alteration that could be evaluated, on shared axes. + mapas: TeaEegMapa[]; + ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] }; } export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null } // TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape. +export const ESTADOS_CASO: Record = { completo: 'Completo', en_proceso: 'En proceso', fuera_protocolo: 'Fuera del protocolo' }; export const GRUPOS_EDAD_TEA = ['16-23 meses', '24-29 meses', '30-36 meses']; // M-CHAT-R/F risk bands, and the ADOS-2 calibrated severity levels used in the patient summary. export const RANGOS_MCHAT = [ @@ -60,6 +77,11 @@ const record = (v: unknown): v is Record => !!v && typeof v === const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; const eeg = (v: unknown) => v === null || v === 'normal' || v === 'anormal'; const score = (v: unknown, min: number, max: number) => v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max; +const textos = (v: unknown) => Array.isArray(v) && v.every(t => typeof t === 'string'); +function validResumenEeg(r: unknown): boolean { + return record(r) && integer(r['normales']) && integer(r['anormales']) && integer(r['sin_eeg']) && Array.isArray(r['por_alteracion']) + && r['por_alteracion'].every(a => record(a) && typeof a['codigo'] === 'string' && typeof a['etiqueta'] === 'string' && integer(a['n'])); +} export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse { // Same rule as CaCu: demonstration records only. if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); @@ -72,7 +94,10 @@ export function teaSeguimientoResponse(v: unknown): TeaSeguimientoResponse { && typeof item['id_seudonimo'] === 'string' && typeof item['grupo_edad'] === 'string' && (item['ultimo_eeg'] === null || isoDate(item['ultimo_eeg'])) && score(item['mchat'], 0, 20) && score(item['css_ados2'], 1, 10) - && eeg(item['alteraciones_eeg']))) + && eeg(item['alteraciones_eeg']) && (item['modulo_ados2'] === null || typeof item['modulo_ados2'] === 'string') + && Object.hasOwn(ESTADOS_CASO, item['estado_caso'] as string) && textos(item['pendientes']) && textos(item['alteraciones'])) + || !Array.isArray(v['tipos_alteracion']) || !v['tipos_alteracion'].every(t => record(t) && typeof t['codigo'] === 'string' && typeof t['etiqueta'] === 'string') + || !validResumenEeg(v['resumen_eeg'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as TeaSeguimientoResponse; } @@ -108,14 +133,15 @@ function validEeg(e: unknown): boolean { if (!record(e) || !isoDate(e['fecha']) || !integer(e['duracion_min'], 1) || !integer(e['canales'], 1) || !nivel(e['calidad']) || !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && nivel(c['nivel']) && text(c['unidad']) && integer(c['valor']) && (c['unidad'] !== 'canales' || (c['valor'] as number) <= (e['canales'] as number)))) return false; - const mapa = e['mapa']; - if (!Array.isArray(e['regiones']) || !e['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))) return false; if (!Array.isArray(e['alteraciones']) || !e['alteraciones'].every(validAlteracion)) return false; - if (!record(mapa) || !text(mapa['metrica']) || !Array.isArray(mapa['x']) || !Array.isArray(mapa['y']) || !Array.isArray(mapa['z'])) return false; - const x = mapa['x'], y = mapa['y'], z = mapa['z']; - return x.every(finite) && y.every(finite) && z.length === y.length - && z.every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) - && Array.isArray(mapa['electrodos']) && mapa['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y'])); + const ejes = e['ejes_mapa']; + if (!record(ejes) || !Array.isArray(ejes['x']) || !Array.isArray(ejes['y']) || !Array.isArray(e['mapas'])) return false; + const x = ejes['x'], y = ejes['y']; + return x.every(finite) && y.every(finite) + && Array.isArray(ejes['electrodos']) && ejes['electrodos'].every(p => record(p) && text(p['nombre']) && finite(p['x']) && finite(p['y'])) + && e['mapas'].every(m => record(m) && text(m['codigo']) && text(m['metrica']) && Array.isArray(m['z']) && m['z'].length === y.length + && m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) + && Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))); } export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle { if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); @@ -137,6 +163,8 @@ export class TeaSeguimientoService { const mchat = RANGOS_MCHAT.find(r => r.codigo === query.mchat), css = RANGOS_CSS.find(r => r.codigo === query.css); if (mchat) params = params.set('mchat_min', mchat.min).set('mchat_max', mchat.max); if (css) params = params.set('css_min', css.min).set('css_max', css.max); + if (query.estado_caso) params = params.set('estado_caso', query.estado_caso); + if (query.alteracion) params = params.set('alteracion', query.alteracion); return this.http.get('/tea/seguimiento', { params }).pipe(map(teaSeguimientoResponse)); } detalle(id: string) { diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index b4f8cb5..68f907f 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -1,15 +1,19 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { teaPacienteDetalle, teaSeguimientoResponse } from './tea-seguimiento.service'; +import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service'; +import { mapaFigure } from './tea-paciente-resumen'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; import { IndicadoresTracking } from './indicadores-tracking'; -const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal' }; +const item = { id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ultimo_eeg: '2026-09-12', mchat: 14, css_ados2: 8, alteraciones_eeg: 'anormal', + modulo_ados2: '2', estado_caso: 'en_proceso', pendientes: ['Neuropediatría'], alteraciones: ['ritmo_posterior'] }; const data = { simulado: true, corte: '2026-09-30', ventana: { meses: 3, desde: '2026-07-01', hasta: '2026-09-30' }, filtros: { alteraciones_eeg: null }, paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 }, - items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null }], + items: [item, { ...item, id_seudonimo: 'T-0002', ultimo_eeg: null, mchat: null, css_ados2: null, alteraciones_eeg: null, modulo_ados2: null, estado_caso: 'fuera_protocolo', pendientes: [], alteraciones: [] }], + tipos_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior' }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos' }], + resumen_eeg: { normales: 3, anormales: 1, sin_eeg: 1, por_alteracion: [{ codigo: 'ritmo_posterior', etiqueta: 'Ritmo posterior', n: 1 }, { codigo: 'picos_paroxisticos', etiqueta: 'Picos paroxísticos', n: 0 }] }, }; const reactivo = (codigo: string, puntaje: number) => ({ codigo, etiqueta: 'Reactivo ' + codigo, puntaje, puntaje_algoritmo: Math.min(puntaje, 2) }); const metrica = (codigo: string, etiqueta: string, extra: object) => ({ codigo, etiqueta, unidad: '', referencia: { min: 1, max: 2 }, efectos: [], ...extra }); @@ -20,6 +24,7 @@ const alteraciones = [ metrica('picos_paroxisticos', 'Picos paroxísticos', { valor: 1.5, valor_z: 0.3, estado: 'normal' }), metrica('gradiente_anteroposterior', 'Gradiente anteroposterior', { valor: 1.2, valor_z: -0.4, estado: 'normal' }), ]; +const mapa = (codigo: string, metrica: string, region: string) => ({ codigo, metrica, z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], regiones: [{ codigo: 'r', etiqueta: region, valor_z: 2.1 }] }); const detalle = { simulado: true, id_seudonimo: 'T-0001', grupo_edad: '16-23 meses', ados2: { fecha: '2026-08-23', modulo: '1', algoritmo: 'Pocas o ninguna palabra', total: 5, total_maximo: 8, clasificacion: 'no_espectro', css: 3, nivel_css: 'bajo', @@ -27,8 +32,9 @@ const detalle = { { codigo: 'CRR', etiqueta: 'Comportamiento restringido y repetitivo', puntaje: 1, maximo: 4, reactivos: [reactivo('D1', 1), reactivo('D2', 0)] }] }, eeg: { fecha: '2026-09-12', duracion_min: 20, canales: 19, calidad: 'aceptable', criterios_calidad: [{ codigo: 'amplitud', etiqueta: 'Canales con amplitud extrema', valor: 1, unidad: 'canales', nivel: 'bueno' }, { codigo: 'linea', etiqueta: 'Ruido de la línea eléctrica', valor: 8, unidad: 'dB', nivel: 'aceptable' }], - regiones: [{ codigo: 'central', etiqueta: 'Central', valor_z: 2.1 }], alteraciones, - mapa: { metrica: 'Potencia theta relativa (puntuación z)', x: [-1, 0, 1], y: [-1, 0, 1], z: [[null, 1, null], [0, 2.1, 0], [null, 1, null]], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } }, + alteraciones, + mapas: [mapa('ritmo_posterior', 'Ritmo posterior (puntuación z)', 'Central'), mapa('picos_paroxisticos', 'Picos paroxísticos (puntuación z)', 'Occipital')], + ejes_mapa: { x: [-1, 0, 1], y: [-1, 0, 1], electrodos: [{ nombre: 'Cz', x: 0, y: 0 }] } }, }; const anormal = { ...data, filtros: { alteraciones_eeg: 'anormal' }, paginacion: { ...data.paginacion, total_items: 1 }, items: [item] }; @@ -46,16 +52,16 @@ describe('Seguimiento TEA', () => { return fixture; } const request = () => http.expectOne(r => r.url === '/tea/seguimiento'); - it('muestra las seis columnas y los valores ausentes como No disponible', () => { + it('muestra las siete columnas y los valores ausentes como No disponible', () => { const fixture = open(); request().flush(data); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual( - ['Identificador seudónimo', 'Grupo de edad', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']); + ['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']); const rows = root.querySelectorAll('tbody tr'); expect(rows).toHaveLength(2); expect(rows[0].textContent).toContain('Anormal'); - expect(rows[1].querySelectorAll('td')[2].textContent).toContain('No disponible'); + expect(rows[1].querySelectorAll('td')[3].textContent).toContain('No disponible'); expect(root.textContent).toContain('Página 1 de 1, 2 registros'); http.verify(); }); @@ -106,6 +112,68 @@ describe('Seguimiento TEA', () => { expect(parametros(request())).toEqual(esperados); http.verify(); }); + it('muestra el estado del caso, lo que falta y el módulo junto al puntaje', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const celdas = fixture.nativeElement.querySelector('tbody tr').querySelectorAll('td'); + expect(celdas[2].textContent).toContain('En proceso'); + expect(celdas[2].textContent).toContain('Falta: Neuropediatría'); + expect(celdas[5].textContent).toContain('8'); + expect(celdas[5].textContent).toContain('Módulo 2'); + http.verify(); + }); + it('resume los EEG arriba de la tabla y filtra por estado y tipo de alteración', () => { + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect(Array.from(root.querySelectorAll('.resumen-eeg dd')).map(d => d.textContent)).toEqual(['3', '1', '1', '1', '0']); + expect(root.querySelector('.resumen-eeg')!.textContent).toContain('Picos paroxísticos'); + expect(Array.from(root.querySelector('select[name=alteracion]')!.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Ritmo posterior', 'Picos paroxísticos']); + const c = fixture.componentInstance; + c.draft = { ...c.draft, estado_caso: 'completo', alteracion: 'picos_paroxisticos' }; + c.apply(); + const filtrada = request(); + expect(filtrada.request.params.get('estado_caso')).toBe('completo'); + expect(filtrada.request.params.get('alteracion')).toBe('picos_paroxisticos'); + filtrada.flush(data); fixture.detectChanges(); + expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' }); + http.verify(); + }); + it('al elegir una alteración aparecen sus zonas, con la leyenda, y al repetirla se cierran', () => { + 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(detalle); fixture.detectChanges(); + const tarjetas = root.querySelectorAll('button.nombre'); + expect(root.querySelector('section.mapa')).toBeNull(); + expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); + tarjetas[0].click(); fixture.detectChanges(); + expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true'); + const panel = () => root.querySelector('section.mapa')!; + expect(panel().classList.contains('panel')).toBe(false); + expect(panel().textContent).toContain('Azul: menos actividad'); + expect(panel().textContent).toContain('Rojo: más actividad'); + expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior'); + expect(panel().querySelector('.regiones')!.textContent).toContain('Central'); + tarjetas[3].click(); fixture.detectChanges(); + expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos'); + expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital'); + expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); + expect(tarjetas[1].disabled).toBe(true); + expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false); + tarjetas[3].click(); fixture.detectChanges(); + expect(root.querySelector('section.mapa')).toBeNull(); + 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; + expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)'); + expect(marco()).toBe('#FFFFFF'); + }); it('sin filtros no envía sus parámetros', () => { open(); expect(request().request.params.keys().sort()).toEqual(['meses', 'page', 'page_size']); @@ -142,7 +210,8 @@ describe('Seguimiento TEA', () => { expect(panel.textContent).toContain('CSS 3'); expect(panel.textContent).toContain('Afecto social (AS)'); expect(panel.textContent).toContain('Aceptable'); - expect(panel.querySelector('app-plotly-chart')).not.toBeNull(); + // The map stays closed until an alteration is chosen. + expect(panel.querySelector('app-plotly-chart')).toBeNull(); // Item scores start collapsed. expect(panel.querySelector('details')!.open).toBe(false); const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!; @@ -198,7 +267,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, css: 11 } }, 'T-0001')).toThrow(); const [as, crr] = detalle.ados2.dominios; expect(() => teaPacienteDetalle({ ...detalle, ados2: { ...detalle.ados2, dominios: [{ ...as, reactivos: [reactivo('A2', 4), as.reactivos[1]] }, crr] } }, 'T-0001')).toThrow(); - expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapa: { ...detalle.eeg.mapa, z: [[0, 0]] } } }, 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, mapas: [{ ...detalle.eeg.mapas[0], z: [[0, 0]] }] } }, 'T-0001')).toThrow(); expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow(); }); it('la calidad general es una palabra, sus criterios son números y se validan', () => { diff --git a/src/styles.scss b/src/styles.scss index 69fa857..8dfa4e9 100644 --- a/src/styles.scss +++ b/src/styles.scss @@ -126,3 +126,15 @@ body { color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; } .indicator-select-panel .option-go:hover { background: var(--issste-accent); } .indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + +// The TEA report: while it's being prepared, charts draw at a width that fits a page. +.dashboard.reporte-impresion .catalog-grid { grid-template-columns: minmax(0, 1fr) !important; max-width: 680px; } +@media print { + .site-header, .site-footer, .institutional-header, .domain-nav, .section-tabs, .global-filters, .catalog-search, .search-result, .reporte-acciones, + .dashboard > header > p, .kpi-grid-oculto, app-indicador-catalog-card button, .catalog-metadata, .selection-status { display: none !important; } + .dashboard app-indicador-catalog-card, .dashboard .resumen { break-inside: avoid; } + .dashboard .plot-viewport { overflow: visible; } + // The app scrolls inside its shell; on paper everything has to flow across pages. + html, body, .app-shell, .app-shell--workspace, .app-main { display: block !important; height: auto !important; min-height: 0 !important; overflow: visible !important; } + body { background: #fff; } +}