From 5c8e2866ef92fe866569691737c6d4461f10d484 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Mon, 23 Nov 2026 17:42:21 -0600 Subject: [PATCH] =?UTF-8?q?Mejora=20las=20gr=C3=A1ficas=20de=20CaCu=20y=20?= =?UTF-8?q?la=20navegaci=C3=B3n=20de=20EU7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicador-eu7-escenario.spec.ts | 15 +++++++ .../indicadores/indicador-figure-panel.ts | 2 +- .../indicadores-c2-adapter.spec.ts | 32 ++++++++++++++- .../indicadores/indicadores-c2-adapter.ts | 14 +++++-- .../indicadores/indicadores-cacu-palette.ts | 40 +++++++++++++++++++ ...indicadores-confirmacion-citologia.spec.ts | 12 +++++- .../indicadores-confirmacion-citologia.ts | 24 ++++------- .../indicadores-eu7-escenario.spec.ts | 27 ++++++++++++- .../indicadores/indicadores-eu7-escenario.ts | 27 ++++++------- .../indicadores-historico-figures.ts | 5 ++- .../indicadores/indicadores-stratified.ts | 11 +++-- .../shared/plotly/plotly-controller.spec.ts | 18 +++++++++ src/app/shared/plotly/plotly-controller.ts | 29 ++++++++++++-- 13 files changed, 207 insertions(+), 49 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cacu-palette.ts diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index a0e8c86..15387fb 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -63,6 +63,21 @@ describe('EU7 integración Angular y caché compartida', () => { expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839'); expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe(); }); + it('desde TOTAL, elegir un hijo activa y abre su grupo sin volver a pedir datos', () => { + f.detectChanges(); flush(); + const button = (name: string) => Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf) + .find(item => item.textContent?.trim() === name)!; + const child = button('LIEAG'), parent = button('Anormal'), back = button('Volver'); + expect(parent.getAttribute('aria-pressed')).toBe('false'); + child.click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' }); + expect(parent.getAttribute('aria-pressed')).toBe('true'); + expect(child.getAttribute('aria-pressed')).toBe('true'); + expect((f.componentInstance.donutFigure!.data[2]['values'] as number[])[0]).toBe(0); + back.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' }); + back.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); + http.expectNone(() => true); + }); it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => { const periods: [string, string] = ['2025-S1', '2025-S2']; for (const d of [data.general, data.estatus_seguimiento]) { diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 711c4c4..f9aa158 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -297,7 +297,7 @@ export class IndicadorFigurePanel implements OnChanges { this.estratos = stratumOptions(data); const publicados = new Set(this.estratos.map(e => e.valor)); if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v))); - const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos); + const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos, this.dominio); this.cells = adapted.cells; return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), diff --git a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts index 4a314e1..5302e73 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.spec.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.spec.ts @@ -1,10 +1,12 @@ import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter'; -import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette'; +import { c2Color, C2_PALETTE, recolorFigure, seriesColors } from './indicadores-c2-palette'; import { c2Fixture } from './indicadores-c2-adapter.testing'; -import { FigureSelection } from './indicadores.models'; +import { FigureSelection, IndicadorDatos } from './indicadores.models'; import { donutFixture } from './indicadores-donut-drilldown.testing'; import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { figurePresentation } from './indicadores.presentation'; +import { historicoFigura } from './indicadores-historico-figures'; +import { stratifiedBars } from './indicadores-stratified'; const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] }; function supported(data = c2Fixture(), s = selection) { @@ -13,6 +15,32 @@ function supported(data = c2Fixture(), s = selection) { return result; } describe('C2: datos publicados a Plotly', () => { + it('comparte el color de LIEBG entre dona, barras, estratos e histórico solo para CaCu', () => { + const data: IndicadorDatos = { ...c2Fixture(), id: 'cacu_eu7' }; + const original = data['categorias'] as Record; + data['categorias'] = { LIEBG: { ...original['A'], color: '#E8C28E' }, B: original['B'], C: original['C'] }; + data.filas[0]['categoria'] = 'LIEBG'; + const cacu = { ...selection, dominio: 'cacu' as const, indicador: data.id }; + const pie = supported(data, cacu).figure; + const bars = supported(data, { ...cacu, figura: 'fig_c2_barras' }).figure; + const history = historicoFigura(data, 'claro').figure; + const stratum = { ...data, estrato: 'grupo_edad', valores_estrato: ['estrato'], etiquetas_estrato: { estrato: 'Estrato' }, + filas: data.filas.map(row => ({ ...row, estrato: 'estrato' as const })) }; + const chart = (domain: 'cacu' | 'tea' | 'cama') => stratifiedBars(stratum, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(), domain); + expect(pie.data[0]['marker']).toMatchObject({ colors: expect.arrayContaining(['#AD8F20']) }); + expect(bars.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) }); + expect(history.data[0]['marker']).toMatchObject({ color: '#AD8F20' }); + expect(chart('cacu').figure.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) }); + expect(chart('cacu').figure.data[0]['marker']).not.toHaveProperty('pattern'); + expect(chart('cacu').cells).toEqual(chart('tea').cells); + for (const domain of ['tea', 'cama'] as const) { + expect(chart(domain).figure.data[0]['marker']).toHaveProperty('pattern.shape', ''); + expect(chart(domain).figure.data[0]['marker']).toMatchObject({ color: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] }); + expect(supported(data, { ...selection, indicador: data.id, dominio: domain }).figure.data[0]['marker']).toMatchObject({ colors: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] }); + } + expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bars)).toBe(bars); + expect(recolorFigure(history)).toBe(history); + }); it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => { const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure; expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']])); diff --git a/src/app/features/indicadores/indicadores-c2-adapter.ts b/src/app/features/indicadores/indicadores-c2-adapter.ts index 7303666..4a1baa0 100644 --- a/src/app/features/indicadores/indicadores-c2-adapter.ts +++ b/src/app/features/indicadores/indicadores-c2-adapter.ts @@ -1,6 +1,7 @@ import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models'; import { DonutHierarchy } from './indicadores-donut-drilldown'; import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette'; +import { cacuCategoryColor, cacuGroupColor } from './indicadores-cacu-palette'; export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; } // Normalized presentation nodes and a selection path are independent of Plotly. @@ -81,8 +82,13 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))]; const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] }; const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label); - const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id)); + const isCaCu = selection.dominio === 'cacu'; + const defaults = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id)); + const cacuColors = isCaCu ? categories.map(c => cacuCategoryColor(c.id)) : []; + const colors = defaults.map((color, i) => cacuColors[i] ?? color); const bases = basesPorGrupo(parentIds); + const groupColors = parentIds.map(id => (isCaCu ? cacuGroupColor(id) : undefined) ?? bases.get(id) ?? C2_PALETTE.series[0]); + const edge = cacuColors.some(Boolean) ? { color: theme.background, width: 1.5 } : { color: theme.outline, width: 0.7 }; const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined; const layout: Record = { title: { text: model.title + ', ' + period }, autosize: true, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 }, @@ -94,7 +100,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re const figure: PlotlyFigure = { data: [], layout }; if (selection.figura === 'fig_c2_barras') { if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels, - marker: { color: colors, line: { color: theme.outline, width: 0.7 } }, + marker: { color: colors, line: edge }, hovertemplate: '%{y}
%{x} ' + model.unit + '' }]; layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true, gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1, @@ -105,12 +111,12 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re } else if (total > 0) { layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false, text: '' + total + '', font: { color: theme.text, size: 18 } }]; - figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } }, + figure.data = [{ type: 'pie', labels, values, marker: { colors, line: edge }, hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] }, hovertemplate: '%{label}
%{value} ' + model.unit + '
%{percent} de los ' + total + ' ' + model.unit + ' publicados' }]; if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label), values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)), - marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } }, + marker: { colors: groupColors, line: edge }, hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } }); } const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0 diff --git a/src/app/features/indicadores/indicadores-cacu-palette.ts b/src/app/features/indicadores/indicadores-cacu-palette.ts new file mode 100644 index 0000000..c835ed7 --- /dev/null +++ b/src/app/features/indicadores/indicadores-cacu-palette.ts @@ -0,0 +1,40 @@ +import { isCoffeeColor } from './indicadores-c2-palette'; + +// Exact codes from the CaCu catalog. Cytology and biopsy keep their own groups. +// The ochre sits outside the coffee range that the shared Plotly renderer recolors. +const CATEGORY_COLORS: Readonly> = Object.freeze({ + NORMAL: '#438B53', + 'ASC-US': '#2879BD', + LIEBG: '#AD8F20', + 'ASC-H': '#7959B8', + LIEAG: '#D14D78', + CIS: '#AE4050', + CARCINOMA: '#925078', + SIN_DATO: '#C9CDD2', + SIN_BIOPSIA: '#C9CDD2', +}); + +const GROUP_COLORS: Readonly> = Object.freeze({ + NO_ANORMAL: '#247A71', + ANORMAL: '#656677', + SIN_DATO: '#C9CDD2', +}); + +export function cacuCategoryColor(id: string): string | undefined { + return Object.hasOwn(CATEGORY_COLORS, id) ? CATEGORY_COLORS[id] : undefined; +} + +export function cacuGroupColor(id: string): string | undefined { + return Object.hasOwn(GROUP_COLORS, id) ? GROUP_COLORS[id] : undefined; +} + +export function cacuClinicalColor(id: string, published: string | null): string { + // A new catalog code can keep a valid published color when the renderer can keep it too. + return cacuCategoryColor(id) ?? (published && !isCoffeeColor(published) ? published : '#8A9199'); +} + + +export function cacuRgba(hex: string, alpha: number): string { + const v = parseInt(hex.slice(1), 16); + return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`; +} diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts index 53da8d4..80b43a7 100644 --- a/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts @@ -9,6 +9,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { GlobalApplied } from './indicadores-memory'; import { Indicador, IndicadorDatos } from './indicadores.models'; +import { recolorFigure } from './indicadores-c2-palette'; import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion, periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia'; @@ -128,7 +129,16 @@ describe('Confirmación histopatológica: modelo', () => { const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro'); expect(otra.data[2]['values']).toEqual(d.data[2]['values']); expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/); - expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/); + expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0\.45\)$/); + }); + it('el carcinoma conserva el color del marcador, intervalo y dona al seleccionar', () => { + const m = modeloConfirmacion(respuesta(), '2026-S2'); + const sel = { grupo: 'ANORMAL', categoria: 'CARCINOMA' }; + const tasa = figuraTasas(m, sel, 'oscuro'), pie = donaConfirmacion(m, sel, 'oscuro'); + expect(tasa.data[0]).toMatchObject({ marker: { color: '#925078' }, error_x: { color: '#925078' } }); + const i = m.grados.findIndex(g => g.id === 'CARCINOMA'); + expect((pie.data[2]['marker'] as { colors: string[] }).colors[i]).toBe('rgba(146,80,120,1)'); + expect(recolorFigure(tasa)).toBe(tasa); expect(recolorFigure(pie)).toBe(pie); }); it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => { expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible); diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts index 2d4f425..8d93106 100644 --- a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts @@ -1,5 +1,6 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; -import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette'; +import { c2Theme } from './indicadores-c2-palette'; +import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette'; import { percentNumber, shareText } from './indicadores-format'; // Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia): @@ -69,10 +70,6 @@ function suma(celdas: Celda[]): number | null { function estado(celdas: Celda[]): Celda['estado'] { return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; } -function rgba(hex: string, alfa: number): string { - const v = parseInt(hex.slice(1), 16); - return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; -} // grupos_de_categoria publishes a label, or an object with `etiqueta`. const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined; @@ -97,20 +94,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode const c = cats[a.id]; return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta }; }); - const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => { + const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => { if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.'); - return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] }; + return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, c['color'] as string | null), grupo: c['grupo'] }; }); - const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO); - const colores = paintByGroup(conColor.map(g => g.grupo)); - const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]])); - const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color })); - const bases = basesPorGrupo(conColor.map(g => g.grupo)); const grupos = [...new Set(grados.map(g => g.grupo))].map(id => { // Off-catalogue grades keep the neutral fallback and do not take the group hue. const propios = grados.filter(g => g.grupo === id); - return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO, + return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: cacuGroupColor(id) ?? COLOR_RESPALDO, grados: propios.map(g => g.id) }; }); // The base view is the group of LIEAG ("LIEAG o más"): the true positives. @@ -204,7 +196,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t const y = valores.map(t => t.fila.etiqueta); return { data: [{ type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), - marker: { size: 12, color }, cliponaxis: false, + marker: { size: 12, color, line: { color: p.text, width: 1 } }, cliponaxis: false, error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6, array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) }, customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), @@ -237,10 +229,10 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior), - marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + marker: { colors: m.grupos.map(g => cacuRgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .45)), line: { color: p.background, width: 2 } } }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior), - marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + marker: { colors: m.grados.map(g => cacuRgba(g.color, activos.has(g.id) ? 1 : .45)), line: { color: p.background, width: 2 } } }, ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts index 4ed77e2..f597831 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.spec.ts @@ -2,6 +2,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json'; import { IndicadorDatos } from './indicadores.models'; import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario'; import { percentNumber } from './indicadores-format'; +import { recolorFigure } from './indicadores-c2-palette'; function eu7Datos() { return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos }); @@ -19,6 +20,30 @@ describe('EU7 modelo de presentación del entregable', () => { expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]); expect(data).toEqual(original); }); + it.each(['claro', 'oscuro'] as const)('conserva colores lisos en dona y barras hasta Plotly, tema %s', tema => { + const m = model(); + const expected = { + NORMAL: '#438B53', 'ASC-US': '#2879BD', LIEBG: '#AD8F20', 'ASC-H': '#7959B8', LIEAG: '#D14D78', CIS: '#AE4050', + }; + expect(Object.fromEntries(m.categorias.map(c => [c.id, c.color]))).toEqual(expected); + for (const payload of [data.general, data.escenarios]) { + payload['categorias'] = Object.fromEntries(Object.entries(payload['categorias'] as object).reverse()); + payload.filas.reverse(); + for (const row of payload.filas) if (typeof row['orden'] === 'number') row['orden'] = 10 - row['orden']; + } + expect(model().categorias.map(c => c.id)).not.toEqual(m.categorias.map(c => c.id)); + expect(Object.fromEntries(model().categorias.map(c => [c.id, c.color]))).toEqual(expected); + const pie = dona(m, {}, tema), bar = barras(m, {}, tema); + expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bar)).toBe(bar); + expect(pie.data[2]['marker']).not.toHaveProperty('pattern'); + const i = m.categorias.findIndex(c => c.id === 'LIEBG'); + expect(pie.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(173,143,32,1)']) }); + expect(bar.data[i]).toMatchObject({ uid: 'LIEBG', marker: { color: '#AD8F20' } }); + expect(bar.data[i]['marker']).not.toHaveProperty('pattern'); + const selected = dona(m, { categoria: 'LIEBG' }, tema); + expect(recolorFigure(selected)).toBe(selected); + expect(selected.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(121,89,184,0.45)']) }); + }); it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => { const m = model(); let s: Seleccion = {}; const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG'); @@ -29,7 +54,7 @@ describe('EU7 modelo de presentación del entregable', () => { s = clic(m, s, 'centro', 0); expect(s).toEqual({}); expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({}); expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({}); - expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' }); + expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' }); expect(clic(m, {}, 'otra', c)).toEqual({}); expect(clic(m, {}, 'grupos', -1)).toEqual({}); expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' }); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index fad4698..ebc3169 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -1,5 +1,6 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; -import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette'; +import { c2Theme } from './indicadores-c2-palette'; +import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette'; import { percentNumber, shareText } from './indicadores-format'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. @@ -39,10 +40,6 @@ function estado(celdas: Celda[]): Escenario['estado'] { return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; } -function rgba(hex: string, alfa: number): string { - const v = parseInt(hex.slice(1), 16); - return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; -} function catalogo(data: IndicadorDatos): Categoria[] { const cats = data['categorias'], grupos = data['grupos_de_categoria']; if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.'); @@ -129,11 +126,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe // Missing rows remain unavailable. Catalog order is used only for the accessible // list of missing categories; a partial distribution is never drawn as a donut. const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity)); - const claves = baseCategorias.map(c => c.grupo); - const bases = basesPorGrupo(claves); - const colores = paintByGroup(claves); - const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] })); - const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! })); + const categorias = baseCategorias.map(c => ({ ...c, color: cacuClinicalColor(c.id, c.color) })); + const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ + id, etiqueta: nombres[id], color: cacuGroupColor(id) ?? '#8A9199', + })); const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))])); const totals = porEscenario['totales_estrato']; if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.'); @@ -181,7 +177,7 @@ export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number): if (traza !== 'categorias') return sel; const c = m.categorias[indice]; if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel; - return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id }; + return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id }; } export function porcentaje(s: Escenario, categoria: string): number | null { const n = s.celdas[categoria]?.n; @@ -193,6 +189,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { const p = c2Theme(tema); const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0); const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0); + const alpha = (id: string) => sel.categoria && id !== sel.categoria ? .45 : 1; const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total; const rotulos = (values: number[], labels: string[], pct: boolean) => { const total = values.reduce((s, n) => s + n, 0); @@ -209,12 +206,12 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '' }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false), - textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior), - marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, + hovertext: hoverText(interior), + marker: { colors: m.grupos.map(g => cacuRgba(g.color, sel.categoria ? .45 : 1)), line: { color: p.background, width: 2 } } }, { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true), textfont: { size: 11 }, hovertext: hoverText(exterior), - marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } }, + marker: { colors: m.categorias.map(c => cacuRgba(c.color, alpha(c.id))), line: { color: p.background, width: 2 } } }, ], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } @@ -233,7 +230,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { return value === null ? null : visible ? value : 0; }); return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x, - marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } }, + marker: { color: c.color, line: { color: p.background, width: visible ? 1.5 : 0 } }, text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle', customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [], ...(visible ? { hovertemplate: `%{y}
${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})` } diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 7178e62..f0d9ef9 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -1,5 +1,6 @@ import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette'; +import { cacuCategoryColor } from './indicadores-cacu-palette'; import { sortedPeriods } from './indicadores-periodos'; export interface HistoricoFigura { @@ -203,6 +204,7 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = ? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []); const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])))); const curso = { frio: 0, calido: 0, neutro: 0 }; + const isCaCu = data.id.startsWith('cacu_'); return { figure: { data: orden.map((id, i) => { const meta = record(catalogo[id]) ? catalogo[id] : {}; @@ -211,7 +213,8 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = const slot = tono === 'neutro' ? i : curso[tono]++; const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; }); return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores, - marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}%{fullData.name}' }; + marker: { color: (isCaCu ? cacuCategoryColor(id) : undefined) ?? c2Color(color, slot, tono), + ...(isCaCu ? { line: { color: c2Theme(tema).background, width: 1 } } : {}) }, hovertemplate: '%{y}%{fullData.name}' }; }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, comoLeer: data.id === 'cama_birads_456_paciente' ? '' : CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts index 749c749..38f815e 100644 --- a/src/app/features/indicadores/indicadores-stratified.ts +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -1,6 +1,7 @@ -import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { DonutSelection } from './indicadores-donut-drilldown'; import { c2Theme, seriesColors } from './indicadores-c2-palette'; +import { cacuCategoryColor } from './indicadores-cacu-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); @@ -39,7 +40,7 @@ export function stratumOptions(data: IndicadorDatos): StratumOption[] { export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } /** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells, * unless that would leave none. */ -export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } { +export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet = new Set(), dominio?: Dominio): { figure: PlotlyFigure; cells: StratifiedCell[] } { if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) || Object.keys(data['grupos']).length !== 1 @@ -73,7 +74,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas'); const cells: StratifiedCell[] = []; const theme = c2Theme(tema); - const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); + const defaults = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); + const palette = dominio === 'cacu' ? categories.map(([id], i) => cacuCategoryColor(id) ?? defaults[i]) : defaults; // The stratum's total: the one published, or else the sum of its cells when every one is published. A share is // only drawn over a known total; a suppressed or missing total leaves the stratum without percentages. const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record[] : []; @@ -100,7 +102,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato const x = selected.map(v => porcentaje ? v.percent : v.value); return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)), customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']), - marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, + marker: { color: palette, line: { color: theme.text, width: .5 }, + ...(dominio === 'cacu' ? {} : { pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] } }) }, hovertemplate: porcentaje ? '%{y}
%{x:.1f} % (%{customdata[0]} de %{customdata[1]})%{fullData.name}' : '%{y}
%{x}%{fullData.name}' }; }), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, diff --git a/src/app/shared/plotly/plotly-controller.spec.ts b/src/app/shared/plotly/plotly-controller.spec.ts index 8ed9c3c..a9a4408 100644 --- a/src/app/shared/plotly/plotly-controller.spec.ts +++ b/src/app/shared/plotly/plotly-controller.spec.ts @@ -127,6 +127,24 @@ describe('PlotlyController async', () => { expect(plotly.react).toHaveBeenCalledTimes(1); resize.resolve(); await settle(); expect(plotly.react).toHaveBeenCalledTimes(2); }); + it('mantiene la figura si Plotly rechaza el resize de un panel oculto', async () => { + controller.setFigure(fig(1)); await settle(); + vi.mocked(plotly.Plots.resize).mockRejectedValueOnce(new Error('Resize must be passed a displayed plot div element')); + controller.resize(); await settle(); + expect(host.style.visibility).toBe('visible'); + expect(state).not.toHaveBeenCalledWith('error'); + controller.setFigure(fig(2)); await settle(); + expect(state).toHaveBeenLastCalledWith('ready'); + }); + it('reconstruye la seleccion exacta si falla la actualizacion de una figura visible', async () => { + controller.setFigure(fig(1)); await settle(); + vi.mocked(plotly.react).mockRejectedValueOnce(new Error('partial update')); + controller.setFigure(fig(2)); await settle(); + expect(plotly.purge).toHaveBeenCalledOnce(); + expect(vi.mocked(plotly.react).mock.calls[2][1][0]['y']).toEqual([2, null]); + expect(state).not.toHaveBeenCalledWith('error'); + expect(state).toHaveBeenLastCalledWith('ready'); + }); it('conserva frames y los retira al cambiar figura', async () => { controller.setFigure({ ...fig(1), frames: [{ name: 'uno', data: [] }] }); await settle(); expect(plotly.addFrames).toHaveBeenCalledWith(host, [{ name: 'uno', data: [] }]); diff --git a/src/app/shared/plotly/plotly-controller.ts b/src/app/shared/plotly/plotly-controller.ts index 5789734..a1829c4 100644 --- a/src/app/shared/plotly/plotly-controller.ts +++ b/src/app/shared/plotly/plotly-controller.ts @@ -174,8 +174,13 @@ export class PlotlyController { if (this.destroyed || version !== this.version || !this.options.animate?.() || t >= 1) break; const frame = pieFrame(from, figure, cubicInOut(t)); const copy = structuredClone(frame); - await this.plotly.react(this.host, copy.data, copy.layout, config); - this.shown = frame; + try { + await this.plotly.react(this.host, copy.data, copy.layout, config); + this.shown = frame; + } catch { + // Intermediate frames are optional. Draw the exact selection below. + break; + } } if (this.destroyed) break; if (version !== this.version) continue; @@ -183,7 +188,18 @@ export class PlotlyController { const layout = animate && this.shown && cartesianInterpolable(this.shown, figure) && figure.layout['transition'] === undefined ? { ...figure.layout, transition: { duration: TRANSITION_MS, easing: 'cubic-in-out' } } : figure.layout; - await this.plotly.react(this.host, figure.data, layout, config); + try { + await this.plotly.react(this.host, figure.data, layout, config); + } catch (error) { + if (this.destroyed || version !== this.version || !this.shown) throw error; + // An existing Plotly graph can be left in a partial state after a failed update. + if (this.listenerAttached) (this.host as EventHost).removeListener?.('plotly_click', this.handleClick); + this.listenerAttached = false; + this.plotly.purge(this.host); + this.shown = undefined; + const exact = structuredClone(target); + await this.plotly.react(this.host, exact.data, exact.layout, config); + } this.shown = target; if (!this.destroyed && !this.listenerAttached && this.click && (this.host as EventHost).on) { (this.host as EventHost).on!('plotly_click', this.handleClick); @@ -202,7 +218,12 @@ export class PlotlyController { this.state('ready'); } else { this.resizePending = false; - await this.plotly.Plots.resize(this.host); + try { + await this.plotly.Plots.resize(this.host); + } catch { + // Plotly rejects resize if a tab or panel hides the host while it is pending. + // The figure is still valid and the observer can resize it when it reappears. + } } } catch { if (this.destroyed) break;