diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 90ab335..a6bb41f 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -15,6 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2'; import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; +import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; @@ -258,6 +259,15 @@ export class IndicadorFigurePanel implements OnChanges { emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined }; })); } + if (c1AlterationCapability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { + return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(map(data => { + const adapted = c1AlterationFigure(data, selection); + if (adapted.status !== 'supported') return { status: 'incompatible', message: adapted.reason } as FigureState; + return { ...this.present(adapted.figure, selection), source: 'datos' as const, footnotes: adapted.notes, + highlight: adapted.highlight, ownLayout: true, plotHeight: 400, + emptyMessage: adapted.total === 0 ? 'Ningún niño tiene su primer EEG de buena calidad en la selección; no hay un porcentaje que representar.' : undefined }; + })); + } if (c2Capability(this.indicador.contrato, selection.figura) && selection.tipoPeriodo) { // Both panels, KPI and numeric table share the exact same transport key. // Do not catch /datos errors here: a backend failure is a real error state. diff --git a/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts b/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts new file mode 100644 index 0000000..3c4e2fd --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-alteraciones.spec.ts @@ -0,0 +1,63 @@ +import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; +import { FigureSelection, IndicadorDatos } from './indicadores.models'; + +const fila = (grupo: string, numerador: number, denominador: number, extra: object = {}) => ({ + periodo: '2025-S2', grupo, estrato: null, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null, + n_sin_evento: denominador - numerador, n_excluido: 0, ...extra, +}); +const datos = (filas: Record[] = [fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20), fila('picos_paroxisticos', 0, 20)]): IndicadorDatos => ({ + id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1', unidad: 'paciente', + tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, valores_estrato: [], + grupos: { TOTAL: 'Total', ritmo_posterior: 'Ritmo posterior', picos_paroxisticos: 'Picos paroxísticos' }, + grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas, +}); +const selection: FigureSelection = { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; + +describe('Barras por alteración para C1', () => { + it('solo aplica a C1 con la figura por alteración', () => { + expect(c1AlterationCapability('C1', 'fig_c1_barras_alteracion')).toBe(true); + expect(c1AlterationCapability('C2', 'fig_c1_barras_alteracion')).toBe(false); + expect(c1AlterationCapability('C1', 'fig_c1_barras_edad')).toBe(false); + }); + it('una barra por alteración tras la de alguna alteración, con su porcentaje y sus conteos', () => { + const result = c1AlterationFigure(datos(), selection); + if (result.status !== 'supported') throw new Error(result.reason); + const [trace] = result.figure.data as Record[]; + expect(result.figure.data.length).toBe(1); + expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Picos paroxísticos']); + expect(trace['y']).toEqual([55, 25, 0]); + expect(trace['text']).toEqual(['55.0 %', '25.0 %', '0.0 %']); + expect(trace['customdata']).toEqual([[11, 20], [5, 20], [0, 20]]); + expect(result.total).toBe(20); + expect(result.notes).toEqual(['Datos ficticios.']); + expect(result.highlight.items.map(i => i.id)).toEqual(['TOTAL', 'ritmo_posterior', 'picos_paroxisticos']); + expect((result.figure.layout['title'] as { text: string }).text).toBe('Porcentaje de EEG normal y anormal, 2025-S2'); + }); + it('varios periodos se dibujan lado a lado, uno por serie', () => { + const otro = (grupo: string, n: number, d: number) => fila(grupo, n, d, { periodo: '2025-S1' }); + const data = { ...datos([otro('TOTAL', 2, 8), otro('ritmo_posterior', 1, 8), otro('picos_paroxisticos', 1, 8), ...datos().filas]), periodos: ['2025-S1', '2025-S2'] }; + const result = c1AlterationFigure(data, { ...selection, periodos: ['2025-S1', '2025-S2'] }); + if (result.status !== 'supported') throw new Error(result.reason); + const traces = result.figure.data as Record[]; + expect(traces.map(t => t['name'])).toEqual(['2025-S1', '2025-S2']); + expect(traces[0]['y']).toEqual([25, 12.5, 12.5]); + expect(result.figure.layout['showlegend']).toBe(true); + expect(result.total).toBe(28); + expect(result.highlight.items[1].points).toEqual([{ trace: 0, index: 1 }, { trace: 1, index: 1 }]); + }); + it('un periodo sin niños con EEG bueno no dibuja ceros', () => { + const result = c1AlterationFigure(datos([fila('TOTAL', 0, 0), fila('ritmo_posterior', 0, 0), fila('picos_paroxisticos', 0, 0)]), selection); + if (result.status !== 'supported') throw new Error(result.reason); + expect((result.figure.data[0] as Record)['y']).toEqual([null, null, null]); + expect(result.total).toBe(0); + }); + it('rechaza datos que no son los grupos por alteración de la selección', () => { + expect(c1AlterationFigure({ ...datos(), grupos: { TOTAL: 'Total' } }, selection).status).toBe('unsupported'); + expect(c1AlterationFigure({ ...datos(), estrato: 'grupo_edad' }, selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 25, 20), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos([fila('TOTAL', 11, 20), fila('ritmo_posterior', 5, 20, { suprimido: 1 }), fila('picos_paroxisticos', 0, 20)]), selection).status).toBe('unsupported'); + expect(c1AlterationFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported'); + expect(c1AlterationFigure(datos(), { ...selection, figura: 'fig_c1_barras_edad' }).status).toBe('unsupported'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c1-alteraciones.ts b/src/app/features/indicadores/indicadores-c1-alteraciones.ts new file mode 100644 index 0000000..8f95020 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-alteraciones.ts @@ -0,0 +1,71 @@ +import { percentNumber } from './indicadores-format'; +import { FigureHighlight } from './indicadores-highlight'; +import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; +import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +// fig_c1_barras_alteracion: a C1 proportion whose groups are the alterations of the EEG. One bar per alteration with +// the share of the period's children that have it, after a first bar for the children with any of them (the TOTAL +// group). A child counts in every alteration it has, so the bars don't add up. Several periods draw side by side. +export const C1_ALTERATION_BARS = 'fig_c1_barras_alteracion'; +const TOTAL = 'TOTAL'; +const ANY_LABEL = 'Alguna alteración'; + +export type C1AlterationResult = { status: 'unsupported'; reason: string } + | { status: 'supported'; figure: PlotlyFigure; highlight: FigureHighlight; total: number; notes: string[] }; +export function c1AlterationCapability(contract: string, representation: string): boolean { + return contract === 'C1' && representation === C1_ALTERATION_BARS; +} + +const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0; +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The any-alteration bar keeps the red of the event; each alteration takes its own colour. +const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]]; +const color = (i: number) => COLORS[i % COLORS.length]; + +export function c1AlterationFigure(data: IndicadorDatos, selection: FigureSelection): C1AlterationResult { + const unsupported = (reason: string): C1AlterationResult => ({ status: 'unsupported', reason }); + if (!c1AlterationCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada'); + if (data['estrato'] != null) return unsupported('Esta figura no admite una dimensión'); + const periods = selection.periodos ? data.periodos.filter(p => selection.periodos!.includes(p)) : data.periodos; + if (!periods.length) return unsupported('No hay periodos publicados para esta selección'); + const published = data['grupos']; + const groups = Object.entries(published && typeof published === 'object' ? published : {}).filter(([id]) => id !== TOTAL); + if (!groups.length) return unsupported('El indicador no publica grupos por alteración'); + const bars = [{ id: TOTAL, label: ANY_LABEL }, ...groups.map(([id, label]) => ({ id, label: String(label) }))]; + + const cells = periods.map(period => bars.map(bar => + data.filas.filter(r => r['periodo'] === period && r['grupo'] === bar.id && r['estrato'] == null))); + if (cells.some(row => row.some(found => found.length !== 1))) return unsupported('Grupos por alteración incompletos'); + const rows = cells.map(row => row.map(([r]) => r)); + if (rows.some(row => row.some(r => (r['suprimido'] !== 0 && r['suprimido'] !== false) + || !count(r['numerador']) || !count(r['denominador']) || r['numerador'] > r['denominador']))) + return unsupported('Conteos por alteración suprimidos o no verificables'); + + const theme = c2Theme(selection.tema); + const x = bars.map(b => escape(b.label)); + const single = periods.length === 1; + const traces = rows.map((row, p) => { + const y = row.map(r => (r['denominador'] as number) ? 100 * (r['numerador'] as number) / (r['denominador'] as number) : null); + return { type: 'bar', name: periods[p], x, y, + marker: { color: single ? bars.map((_, i) => color(i)) : color(p), line: { color: theme.background, width: 1 } }, + text: y.map(v => v === null ? '' : percentNumber(v) + ' %'), textposition: 'outside', cliponaxis: false, + customdata: row.map(r => [r['numerador'], r['denominador']]), + hovertemplate: '%{x}' + (single ? '' : ', %{fullData.name}') + '
%{y:.1f} % (%{customdata[0]} de %{customdata[1]} niños)' }; + }); + const figure: PlotlyFigure = { + data: traces, + layout: { autosize: true, height: 400, barmode: 'group', margin: { t: 56, l: 72, r: 24, b: single ? 64 : 96 }, showlegend: !single, + legend: { orientation: 'h', y: -0.3, itemclick: false, itemdoubleclick: false }, + title: { text: escape(String(data['titulo'] ?? data.id)) + (single ? ', ' + periods[0] : '') }, + paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + xaxis: { type: 'category', title: { text: 'Alteración del EEG' }, automargin: true }, + yaxis: { title: { text: '% de niños con EEG de buena calidad' }, range: [0, 100], ticksuffix: ' %', gridcolor: theme.grid, zeroline: false } }, + config: { displayModeBar: false }, + }; + const highlight: FigureHighlight = { groups: [], traces: traces.map((_, t) => t), allLabel: 'Todas las alteraciones', + items: bars.map((b, i) => ({ id: b.id, label: b.label, color: single ? color(i) : theme.line, + points: traces.map((_, t) => ({ trace: t, index: i })) })) }; + // Children with a first good EEG over the periods drawn: zero means there is nothing to draw a share of. + const total = rows.reduce((sum, row) => sum + (row[0]['denominador'] as number), 0); + return { status: 'supported', figure, highlight, total, notes: Array.isArray(data.notas) ? [...data.notas] : [] }; +} diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index 00e471a..5d3c484 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -13,6 +13,7 @@ import { periodosDesde, Report, } from './indicadores-fhir'; import * as fx from './indicadores-fhir.fixtures'; +import { c1AlterationFigure } from './indicadores-c1-alteraciones'; import { c2Figure } from './indicadores-c2-adapter'; import { datosValidos } from './indicadores.service'; import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir'; @@ -32,6 +33,29 @@ describe('Indicadores sobre FHIR', () => { expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' }); }); + it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => { + // Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and + // that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures + // hold none for M30). Fails if the groups are dropped or renamed on the way, or the figure stops reading them. + const m30 = measure('M30-resultado-eeg'); + const pop = (code: string, count: number) => ({ code: { coding: [{ code }] }, count }); + const group = (code: string, n: number) => ({ code: { coding: [{ code }] }, population: [pop('denominator', 8), pop('numerator', n)], + measureScore: { value: n / 8 } }); + const codes = (m30.group ?? []).map(g => g.code?.coding?.[0]?.code as string); + const report = { resourceType: 'MeasureReport', id: 'M30-resultado-eeg-1', period: { start: '2025-07-01', end: '2025-12-31' }, + group: codes.map((c, i) => group(c, c === 'TOTAL' ? 4 : i % 3)) } as unknown as Report; + const datos = datosValidos(datosDeReportes(m30, [report], 'semestre'), 'M30_resultado_eeg', 'semestre', ['2025-S2']); + expect(datos.filas.map(f => f['grupo'])).toEqual(codes); + expect(codes).toContain('ritmo_posterior'); + const result = c1AlterationFigure(datos, { dominio: 'tea', indicador: 'M30_resultado_eeg', figura: 'fig_c1_barras_alteracion', + tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }); + if (result.status !== 'supported') throw new Error(result.reason); + const [trace] = result.figure.data as Record[]; + expect(trace['x']).toEqual(['Alguna alteración', 'Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', + 'Gradiente anteroposterior']); + expect((trace['y'] as number[])[0]).toBe(50); + }); + it('una proporción da numerador, denominador y porcentaje, y por grupo de edad los códigos de la página', () => { // Pins down: the score becomes a percentage, the age groups `16-23`..., and an empty «Sin dato» stratum is left // out. Fails if the fraction isn't multiplied, the codes keep FHIR's underscore or the empty stratum becomes a bar. diff --git a/src/app/features/indicadores/indicadores-figure-labels.spec.ts b/src/app/features/indicadores/indicadores-figure-labels.spec.ts index 1e6db48..c2c0f16 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.spec.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.spec.ts @@ -2,6 +2,7 @@ import { figureDisplayName } from './indicadores-figure-labels'; describe('UX-07A nombres de representaciones', () => { it.each([ + ['fig_c1_barras_alteracion', 'Barras por alteración'], ['fig_c1_grupos', 'Grupos'], ['fig_c1_puntos', 'Puntos'], ['fig_c2_apiladas', 'Barras apiladas'], diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index 6c77c01..7b19694 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_alteracion: 'Barras por alteración', 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',