diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 1163b14..353ccd8 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -22,6 +22,8 @@ export interface FigureState { categoryLabels?: readonly CategoryLabel[]; minimumPlotWidth?: number; donutLegend?: readonly DonutLegendEntry[]; + // The figure already lays out its own rings (C1 double donut): show the legend, keep the figure as is. + ownLayout?: boolean; plotWidth?: number; plotHeight?: number; message?: string; @@ -87,7 +89,7 @@ export class IndicadorFigureCard implements OnChanges { ? { ...presentationFigure, layout: { ...presentationFigure.layout, height: this.state.plotHeight } } : presentationFigure; this.chartFigure = source && hierarchy ? donutView(source, hierarchy, this.activeParent, this.state.plotWidth) - : source && this.state.donutLegend ? donutSimpleView(source) : source; + : source && this.state.donutLegend && !this.state.ownLayout ? donutSimpleView(source) : source; } expandParent(parent: string) { if (this.state.status !== 'ready' || !this.state.hierarchy?.parents.includes(parent) diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 3d8d9aa..f68e2e4 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -13,6 +13,7 @@ import { figureIdentity, identityElementId } from './indicadores-identities'; import { DonutHierarchy, DonutSelection, donutHierarchy, donutLegend, donutPeriod } from './indicadores-donut-drilldown'; import { IndicadoresSnapshots } from './indicadores-snapshots'; import { c2Capability, c2Figure } from './indicadores-c2-adapter'; +import { C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; @@ -245,6 +246,17 @@ export class IndicadorFigurePanel implements OnChanges { const state = this.presentStratified(data); this.stratifiedData = data; return state; })); } + if (c1DonutCapability(this.indicador.contrato, selection.figura)) { + if (selection.tipoPeriodo !== 'semestre' || selection.periodos?.length !== 1) + return of({ status: 'incompatible', message: 'Esta figura muestra un solo semestre. Elige el intervalo semestral y un periodo.' } as FigureState); + return this.snapshots.datos(selection.dominio!, selection.indicador, 'semestre', selection.periodos, this.indicador.version, { estrato: C1_DONUT_ESTRATO }).pipe(map(data => { + const adapted = c1DonutFigure(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, + donutLegend: adapted.legend, ownLayout: true, + emptyMessage: adapted.total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual 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-donut.spec.ts b/src/app/features/indicadores/indicadores-c1-donut.spec.ts new file mode 100644 index 0000000..bd9b762 --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-donut.spec.ts @@ -0,0 +1,61 @@ +import { c1DonutCapability, c1DonutFigure, c1DonutLabels } from './indicadores-c1-donut'; +import { FigureSelection, IndicadorDatos } from './indicadores.models'; + +const fila = (estrato: string, numerador: number, denominador: number, extra: object = {}) => ({ + periodo: '2025-S2', grupo: 'TOTAL', estrato, suprimido: 0, numerador, denominador, valor: 0, ic_bajo: null, ic_alto: null, + n_sin_evento: denominador - numerador, n_excluido: 0, ...extra, +}); +const datos = (filas = [fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]): IndicadorDatos => ({ + id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1', unidad: 'paciente', + tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: 'grupo_edad', valores_estrato: ['16-23', '24-29', '30-36'], + etiquetas_estrato: { '16-23': '16 a 23 meses', '24-29': '24 a 29 meses', '30-36': '30 a 36 meses' }, + grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, notas: ['Datos ficticios.'], filas, +}); +const selection: FigureSelection = { dominio: 'tea', indicador: 'M21_diagnosticados_con_eeg', figura: 'fig_c1_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; + +describe('Dona de dos anillos para C1', () => { + it('solo aplica a C1 con fig_c1_donas', () => { + expect(c1DonutCapability('C1', 'fig_c1_donas')).toBe(true); + expect(c1DonutCapability('C2', 'fig_c1_donas')).toBe(false); + expect(c1DonutCapability('C1', 'fig_c1_grupos')).toBe(false); + }); + it('anillo interior con y sin el evento; exterior por grupo de edad, con el total al centro', () => { + const result = c1DonutFigure(datos(), selection); + expect(result.status).toBe('supported'); + if (result.status !== 'supported') return; + const [center, inner, outer] = result.figure.data as { labels: string[]; values: number[]; text: string[] }[]; + expect(center.text[0]).toContain('64'); + expect(inner.labels).toEqual(['Con EEG', 'Sin EEG']); + expect(inner.values).toEqual([46, 18]); + expect(inner.text).toEqual(['Con EEG
71.9 %', 'Sin EEG
28.1 %']); + expect(outer.labels).toEqual(['Con EEG · 16 a 23 meses', 'Con EEG · 24 a 29 meses', 'Con EEG · 30 a 36 meses', + 'Sin EEG · 16 a 23 meses', 'Sin EEG · 24 a 29 meses', 'Sin EEG · 30 a 36 meses']); + expect(outer.values).toEqual([16, 13, 17, 8, 5, 5]); + // Inside the outer ring only the age group; slices under 5 % stay unlabeled. + expect(outer.text[0]).toMatch(/^16 a 23 meses
/); + expect(outer.text[4]).toMatch(/^24 a 29 meses
7.8/); + const small = c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 14), fila('30-36', 17, 40)]), selection); + if (small.status === 'supported') expect((small.figure.data[2] as { text: string[] }).text[4]).toBe(''); + expect(result.total).toBe(64); + expect(result.notes).toEqual(['Datos ficticios.']); + expect(result.legend.map(e => e.label)).toEqual(['Con EEG', 'Sin EEG', '16 a 23 meses', '24 a 29 meses', '30 a 36 meses']); + expect(result.figure.layout['title']).toEqual({ text: 'Porcentaje de pacientes con diagnóstico de TEA con EEG, 2025-S2' }); + }); + 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('M22_diagnosticados_sin_eeg')).toEqual(['Sin EEG', 'Con EEG']); + expect(c1DonutLabels('otro')).toEqual(['Con el evento', 'Sin el evento']); + }); + it('solo un semestre', () => { + expect(c1DonutFigure({ ...datos(), tipo_periodo: 'mes', periodos: ['2025-12'] }, { ...selection, tipoPeriodo: 'mes', periodos: ['2025-12'] })) + .toEqual({ status: 'unsupported', reason: 'Esta figura solo está disponible para un semestre.' }); + expect(c1DonutFigure({ ...datos(), periodos: ['2025-S1', '2025-S2'] }, { ...selection, periodos: ['2025-S1', '2025-S2'] }).status).toBe('unsupported'); + expect(c1DonutFigure(datos(), { ...selection, periodos: ['2025-S1'] }).status).toBe('unsupported'); + }); + it('rechaza estratos incompletos, suprimidos o imposibles', () => { + expect(c1DonutFigure({ ...datos(), estrato: null }, selection).status).toBe('unsupported'); + expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18)]), selection).status).toBe('unsupported'); + expect(c1DonutFigure(datos([fila('16-23', 16, 24), fila('24-29', 13, 18), fila('30-36', null as unknown as number, 22, { suprimido: 1 })]), selection).status).toBe('unsupported'); + expect(c1DonutFigure(datos([fila('16-23', 30, 24), fila('24-29', 13, 18), fila('30-36', 17, 22)]), selection).status).toBe('unsupported'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-c1-donut.ts b/src/app/features/indicadores/indicadores-c1-donut.ts new file mode 100644 index 0000000..0da279c --- /dev/null +++ b/src/app/features/indicadores/indicadores-c1-donut.ts @@ -0,0 +1,87 @@ +import { Categoria, dona, Grupo, Modelo } from './indicadores-eu7-escenario'; +import { percentNumber, shareText } from './indicadores-format'; +import { DonutLegendEntry } from './indicadores-donut-drilldown'; +import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models'; + +// Double donut for a C1 proportion over one semester, drawn like CaCu's «Distribución de resultados +// citológicos»: the inner ring splits the denominator into patients with and without the event, the +// outer ring splits each of them by age group. Built from the age-stratified C1 rows. +export const C1_DONUT = 'fig_c1_donas'; +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'], +}; +// The CaCu ring colours: blue for the event, orange for its complement; age groups get lighter shades. +const RING_COLORS = ['#2F6DB3', '#D9822B'] as const; + +export type C1DonutResult = { status: 'unsupported'; reason: string } + | { status: 'supported'; figure: PlotlyFigure; legend: DonutLegendEntry[]; total: number; notes: string[] }; +export function c1DonutCapability(contract: string, representation: string): boolean { + return contract === 'C1' && representation === C1_DONUT; +} +export function c1DonutLabels(indicador: string): readonly [string, string] { + return EVENT_LABELS[indicador] ?? ['Con el evento', 'Sin el evento']; +} + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0; +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +function shade(hex: string, step: number, steps: number): string { + const t = steps > 1 ? 0.65 * step / (steps - 1) : 0; + const rgb = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)).map(c => Math.round(c + (255 - c) * t)); + return '#' + rgb.map(c => c.toString(16).padStart(2, '0')).join('').toUpperCase(); +} + +export function c1DonutFigure(data: IndicadorDatos, selection: FigureSelection): C1DonutResult { + const unsupported = (reason: string): C1DonutResult => ({ status: 'unsupported', reason }); + if (!c1DonutCapability(data.contrato, selection.figura)) return unsupported('Representación no soportada'); + if (selection.tipoPeriodo !== 'semestre' || data.tipo_periodo !== 'semestre') return unsupported('Esta figura solo está disponible para un semestre.'); + if (data.periodos.length !== 1 || (selection.periodos && (selection.periodos.length !== 1 || selection.periodos[0] !== data.periodos[0]))) + return unsupported('Se requiere un semestre único concordante'); + const values = data['valores_estrato'], names = data['etiquetas_estrato']; + if (data['estrato'] !== C1_DONUT_ESTRATO || !Array.isArray(values) || !values.length || !values.every(v => typeof v === 'string') + || new Set(values).size !== values.length || (names != null && !record(names))) return unsupported('Estratificación por grupo de edad no verificable'); + const period = data.periodos[0]; + const rows = values.map(v => data.filas.filter(r => r['periodo'] === period && r['estrato'] === v)); + if (rows.some(r => r.length !== 1) || data.filas.length !== values.length) return unsupported('Partición por grupo de edad incompleta'); + const strata = rows.map(([r], i) => ({ id: values[i] as string, label: typeof names?.[values[i]] === 'string' ? names[values[i]] as string : values[i] as string, + numerador: r['numerador'], denominador: r['denominador'], suprimido: r['suprimido'], grupo: r['grupo'] })); + if (strata.some(s => s.grupo !== 'TOTAL' || (s.suprimido !== 0 && s.suprimido !== false) + || !count(s.numerador) || !count(s.denominador) || s.numerador > s.denominador)) return unsupported('Conteos por grupo de edad suprimidos o no verificables'); + + const labels = c1DonutLabels(data.id); + const grupos: Grupo[] = labels.map((etiqueta, g) => ({ id: g ? 'SIN' : 'CON', etiqueta, color: RING_COLORS[g] })); + const categorias: Categoria[] = [], celdas: Modelo['celdas'] = {}; + grupos.forEach((g, gi) => strata.forEach((s, i) => { + const id = g.id + ':' + s.id, n = gi ? (s.denominador as number) - (s.numerador as number) : s.numerador as number; + // Unique labels: Plotly merges pie slices that share one. + categorias.push({ id, etiqueta: g.etiqueta + ' · ' + s.label, color: shade(g.color, i, strata.length), grupo: g.id }); + celdas[id] = { n, estado: 'Publicado' }; + })); + const total = strata.reduce((sum, s) => sum + (s.denominador as number), 0); + const notes = Array.isArray(data.notas) ? [...data.notas] : []; + const modelo: Modelo = { periodo: period, categorias, grupos, celdas, total, sinDato: { n: 0, estado: 'Publicado' }, + escenarios: [], vacio: total === 0, notas: notes, sinDatoEtiqueta: '' }; + const figure = dona(modelo, {}, selection.tema); + if (figure.data.length === 3) { + const [, inner, outer] = figure.data as Record[]; + const hover = '%{label}
%{customdata[0]} pacientes, %{customdata[1]} % de ' + total + ''; + inner['hovertemplate'] = outer['hovertemplate'] = hover; + // Inside the outer ring the colour already tells the group: show only the age group and its share. + const outerValues = outer['values'] as number[]; + outer['text'] = categorias.map((c, i) => outerValues[i] / total < .05 ? '' + : escape(strata[i % strata.length].label) + '
' + shareText(outerValues[i], total)); + inner['text'] = grupos.map((g, i) => { + const n = (inner['values'] as number[])[i]; + return n / total < .05 ? '' : escape(g.etiqueta) + '
' + percentNumber(100 * n / total) + ' %'; + }); + } + figure.layout = { ...figure.layout, title: { text: escape(String(data['titulo'] ?? data.id)) + ', ' + period } }; + // Both rings, then the age groups in the shades of the first ring. + const legend = [...grupos.map(g => ({ label: g.etiqueta, color: g.color })), + ...strata.map((s, i) => ({ label: s.label, color: categorias[i].color }))]; + return { status: 'supported', figure, legend, total, notes }; +} diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index 46c48dd..4ac5d04 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_donas: 'Dona de dos anillos', fig_c1_grupos: 'Grupos', fig_c1_puntos: 'Puntos', fig_c2_apiladas: 'Barras apiladas',