feat(indicadores): conectar donas jerárquicas con barras generales

Habilita el filtrado visual local de barras generales mediante selecciones jerárquicas C2, preservando datos originales, periodos, porcentajes y restauración de la distribución completa.
This commit is contained in:
Angel Capetillo Zavala
2026-10-23 10:32:40 -06:00
parent 14fd765122
commit 540506bde0
6 changed files with 353 additions and 7 deletions
@@ -15,6 +15,7 @@ import { IndicadoresSnapshots } from './indicadores-snapshots';
import { c2Capability, c2Figure } from './indicadores-c2-adapter';
import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified';
import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
@Component({
selector: 'app-indicador-figure-panel',
@@ -50,6 +51,7 @@ import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods';
<button type="button" aria-label="Periodo siguiente de la dona" [disabled]="donutPeriodIndex >= donutPages.length - 1" (click)="changeDonutPeriod(1)">›</button>
</nav>
}
@if (generalSelectionContext) { <p class="distribution-note" role="status">{{ generalSelectionContext }}</p> }
<app-indicador-figure-card [state]="result()" [selected]="indicador"
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
@if (dimension && result().status === 'ready') {
@@ -136,6 +138,9 @@ export class IndicadorFigurePanel implements OnChanges {
get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); }
get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); }
private stratifiedData?: IndicadorDatos;
private generalData?: IndicadorDatos;
private generalState?: FigureState;
generalSelectionContext?: string;
get capabilities() { return stratifiedCapabilities(this.indicador); }
get singlePeriod() { return this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1; }
changeDimension(value: DimensionEstrato | '') {
@@ -155,6 +160,16 @@ export class IndicadorFigurePanel implements OnChanges {
source: 'datos', footnotes: data.notas,
emptyMessage: this.cells.length ? 'No hay magnitudes disponibles. Consulta las celdas suprimidas y sin información en la tabla de valores.' : 'No hay categorías publicadas para esta selección.' };
}
private presentGeneral(state: FigureState, selection: FigureSelection): FigureState {
const selected = this.generalData && state.figure
? c2GeneralSelection(state.figure, this.generalData, selection, this.localSelection) : undefined;
this.generalSelectionContext = selected?.context;
const presentation = this.present(selected?.figure ?? state.figure!, selection);
// Keep the complete original figure in state. Width/profile changes and
// restoration always derive afresh, including published percentage arrays.
return { ...state, ...presentation, figure: state.figure,
footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
}
private readySelection?: FigureSelection;
private plotWidth?: number;
private readonly service = inject(IndicadoresService);
@@ -183,6 +198,11 @@ export class IndicadorFigurePanel implements OnChanges {
if (generation === this.generation && revision === this.applied?.revision) {
if (state.status === 'ready') {
this.readySelection = selection;
if (!this.dimension && this.indicador.contrato === 'C2'
&& selection?.figura === 'fig_c2_barras' && this.indicador.figuras.includes('fig_c2_donas')) {
this.generalState = state;
state = this.presentGeneral(state, selection);
}
if (!this.donutPages.length) this.activeDonutPeriod = selection?.periodos?.length === 1
? selection.periodos[0] : state.figure && donutPeriod(state.figure);
}
@@ -203,6 +223,7 @@ export class IndicadorFigurePanel implements OnChanges {
return this.snapshots.datos(selection.dominio!, selection.indicador, selection.tipoPeriodo, selection.periodos, this.indicador.version).pipe(
switchMap(data => {
if (data.contrato !== this.indicador.contrato) throw new Error('El contrato recibido no corresponde al indicador.');
if (selection.figura === 'fig_c2_barras') this.generalData = data;
const periods = selection.periodos ?? data.periodos;
if (selection.figura === 'fig_c2_donas' && periods.length > 1) {
const pages = periods.map(period => ({ period, adapted: c2Figure(periodDatos(data, period), { ...selection, periodos: [period] }) }));
@@ -260,7 +281,8 @@ export class IndicadorFigurePanel implements OnChanges {
const responsiveC2Donut = this.indicador.contrato === 'C2' && this.figuraId === 'fig_c2_donas';
if ((this.visualProfile.axisLabels?.enabled || responsiveC2Donut)
&& state.status === 'ready' && state.figure && this.readySelection) {
const presentation = this.present(state.figure, this.readySelection, state.hierarchy);
const presentation = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
: this.present(state.figure, this.readySelection, state.hierarchy);
const next = { ...state, ...presentation, footnotes: state.source === 'datos' ? state.footnotes : presentation.footnotes };
// A width change within the same label budget must not hide/repaint an
// equivalent graph (for example when only the scrollbar gutter changes).
@@ -279,10 +301,13 @@ export class IndicadorFigurePanel implements OnChanges {
if (changes['localSelection'] && this.dimension && this.stratifiedData && this.result().status === 'ready') {
try { this.result.set(this.presentStratified(this.stratifiedData)); }
catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); }
} else if (changes['localSelection'] && this.generalState && this.readySelection && this.result().status === 'ready') {
this.result.set(this.presentGeneral(this.generalState, this.readySelection));
}
const state = this.result();
if (changes['visualProfile'] && state.status === 'ready' && state.figure && this.readySelection) {
const next = this.present(state.figure, this.readySelection, state.hierarchy);
const next = this.generalState ? this.presentGeneral(this.generalState, this.readySelection)
: this.present(state.figure, this.readySelection, state.hierarchy);
this.result.set({ ...state, ...next, footnotes: state.source === 'datos' ? state.footnotes : next.footnotes });
}
return;
@@ -296,6 +321,7 @@ export class IndicadorFigurePanel implements OnChanges {
this.generation++;
this.figureRequests.next(null);
this.currentKey = '';
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
this.result.set({ status: 'deferred', message });
}
}
@@ -308,6 +334,7 @@ export class IndicadorFigurePanel implements OnChanges {
if (!this.visible) return;
this.currentKey = this.requestKey();
this.stratifiedData = undefined; this.cells = [];
this.generalState = undefined; this.generalData = undefined; this.generalSelectionContext = undefined;
this.donutPages = [];
const applied = this.applied;
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
@@ -4,8 +4,8 @@ import { c2Color, c2Theme } from './indicadores-c2-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.
// No level-3 wire format is assumed. General bars keep the complete partition;
// stratified bars have their own decoder and consume the shared local selection.
// No level-3 wire format is assumed. This decoder keeps the complete partition;
// local selection is applied to a separate, verified presentation copy.
export interface C2Node { id: string; label: string; parentId?: string; }
export interface C2Selection { path: readonly string[]; }
export function c2Descendants(nodes: readonly C2Node[], selection: C2Selection): readonly C2Node[] {
@@ -0,0 +1,98 @@
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadorFigureCard } from './indicador-figure-card';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { c2Figure } from './indicadores-c2-adapter';
import { DonutSelection } from './indicadores-donut-drilldown';
import { FigureSelection, PlotlyFigure } from './indicadores.models';
import { BASE_VISUAL_PROFILE } from './indicadores-visual-profile';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const applied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
const item = { id: 'i1', titulo: 'Distribución sintética', contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] };
describe('barras generales conectadas con la selección compartida de la dona', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>, http: HttpTestingController;
const panel = () => fixture.componentInstance;
const select = (local: DonutSelection) => { fixture.componentRef.setInput('localSelection', local); fixture.detectChanges(); };
const request = () => http.expectOne(r => r.url.endsWith('/datos'));
const displayed = () => panel().result().presentationFigure!;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadorFigurePanel); http = TestBed.inject(HttpTestingController);
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_barras', tema: 'claro', applied })) fixture.componentRef.setInput(k, v);
});
afterEach(() => { fixture.destroy(); http.verify(); });
function load() { fixture.detectChanges(); request().flush(c2Fixture()); fixture.detectChanges(); }
it('grupo → categoría → restaurar actualiza sólo la presentación, sin GET ni cambio de filtro', () => {
load(); const original = panel().result().figure, before = structuredClone(original), all = structuredClone(displayed());
const filter = structuredClone(panel().applied), host = fixture.nativeElement.querySelector('app-plotly-chart');
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']);
select({ parent: 'G2', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B', 'C']);
select({ parent: 'G2', category: 'B', period: '2025-S2' }); expect(displayed().data[0]['y']).toEqual(['B']);
expect(panel().result().figure).toBe(original); expect(original).toEqual(before);
expect(fixture.nativeElement.textContent).toContain('G2 · B · 2025-S2');
select({}); expect(displayed()).toEqual(all); expect(panel().generalSelectionContext).toBeUndefined();
expect(panel().applied).toEqual(filter); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host); http.expectNone(() => true);
});
it('una selección recibida mientras carga se aplica al terminar sin otro GET', () => {
fixture.detectChanges(); const pending = request(); select({ parent: 'G2', period: '2025-S2' });
pending.flush(c2Fixture()); fixture.detectChanges(); expect(displayed().data[0]['y']).toEqual(['B', 'C']); http.expectNone(() => true);
});
it('ancho y perfil conservan selección y notas desde el original', () => {
load(); select({ parent: 'G2', period: '2025-S2' }); panel().updatePlotWidth(320);
fixture.componentRef.setInput('visualProfile', BASE_VISUAL_PROFILE); fixture.detectChanges();
expect(displayed().data[0]['y']).toEqual(['B', 'C']); expect(panel().result().footnotes).toEqual(c2Fixture().notas);
select({}); expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
});
it.each(['unknown', 'wrong-parent', 'wrong-period', 'missing-period'])('%s restaura la presentación completa', kind => {
load(); const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
select({ parent: kind === 'unknown' ? 'desconocido' : kind === 'wrong-parent' ? 'G1' : 'G2', category: 'B', period: kind === 'missing-period' ? undefined : kind === 'wrong-period' ? '2026-S1' : '2025-S2' });
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
});
it.each(['null', 'suppressed', 'simple'])('%s mantiene la figura completa sin nuevas peticiones', kind => {
const data = c2Fixture();
if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(data['categorias'] as Record<string, Record<string, unknown>>).forEach(c => c['grupo'] = null); }
else { data.filas[0]['n'] = null; if (kind === 'suppressed') data.filas[0]['suprimido'] = 1; }
fixture.detectChanges(); request().flush(data);
if (kind !== 'simple') http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ type: 'bar', orientation: 'h', name: '2025-S2', x: [null, 3, 1], y: ['A', 'B', 'C'] }], layout: {} });
const full = structuredClone(displayed()); select({ parent: 'G2', period: '2025-S2' });
expect(displayed()).toEqual(full); expect(panel().generalSelectionContext).toBeUndefined(); http.expectNone(() => true);
});
it('un cambio de filtro invalida el periodo anterior aunque conserve las mismas etiquetas', () => {
load(); select({ parent: 'G2', category: 'B', period: '2025-S2' });
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2026-S1'] } }); fixture.detectChanges();
expect(panel().generalSelectionContext).toBeUndefined();
const data = c2Fixture(); data.periodos = ['2026-S1']; data.filas.forEach(r => r['periodo'] = '2026-S1'); request().flush(data);
expect(displayed().data[0]['y']).toEqual(['A', 'B', 'C']); http.expectNone(() => true);
});
it('la dona hermana aporta el periodo, navegar restaura todas las series y no cambia el filtro global', () => {
const periods = ['2025-S2', '2025-S1'], data = c2Fixture();
data.periodos = periods; data.filas.push(...data.filas.map(r => ({ ...r, periodo: periods[1], n: Number(r['n']) * 2 })));
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tipoPeriodo: 'semestre', tema: 'claro', periodos: [periods[0]] };
const single = c2Figure(c2Fixture(), selection); if (single.status !== 'supported') throw new Error(single.reason);
const original: PlotlyFigure = { data: [single.figure.data[0], { ...structuredClone(single.figure.data[0]), name: periods[1], x: [12, 6, 2], text: ['60%', '30%', '10%'] }], layout: single.figure.layout };
delete original.layout['meta'];
fixture.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } });
fixture.detectChanges(); request().flush(data); http.expectOne(r => r.url.includes('/figuras/')).flush(original); fixture.detectChanges();
const full = structuredClone(displayed()), donut = TestBed.createComponent(IndicadorFigurePanel);
for (const [k, v] of Object.entries({ dominio: 'cacu', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied: panel().applied })) donut.componentRef.setInput(k, v);
donut.componentInstance.hierarchySelected.subscribe(s => fixture.componentRef.setInput('localSelection', s));
donut.detectChanges(); http.expectNone(() => true);
const card = () => donut.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance as IndicadorFigureCard;
card().expandParent('G2'); fixture.detectChanges(); expect(displayed().data).toHaveLength(1); expect(displayed().data[0]['name']).toBe(periods[0]);
donut.componentInstance.changeDonutPeriod(1); donut.detectChanges(); fixture.detectChanges();
expect(displayed()).toEqual(full); expect(donut.componentInstance.donutPeriodIndex).toBe(1);
card().expandParent('G2'); card().selectCategory('B'); fixture.detectChanges();
expect(displayed().data[0]).toMatchObject({ name: periods[1], x: [6], y: ['B'], text: ['30%'] });
expect(panel().applied.selection).toEqual({ mode: 'explicit', periodos: periods }); expect(panel().result().figure).toEqual(original);
card().returnToParents(); fixture.detectChanges(); expect(displayed()).toEqual(full);
http.expectNone(() => true); donut.destroy();
});
});
@@ -0,0 +1,142 @@
import { c2Figure } from './indicadores-c2-adapter';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { c2GeneralSelection } from './indicadores-c2-general-selection';
import { FigureSelection, PlotlyFigure } from './indicadores.models';
const selection: FigureSelection = { indicador: 'i1', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
const local = { parent: 'G2', period: '2025-S2' };
function bars(data = c2Fixture()): PlotlyFigure {
const result = c2Figure(data, selection);
if (result.status !== 'supported') throw new Error(result.reason);
return result.figure;
}
describe('selección local segura de barras generales C2', () => {
it('sin selección conserva la distribución completa', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone(source);
expect(c2GeneralSelection(source, data, selection, {})).toBeUndefined();
expect(source).toEqual(before);
});
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!;
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#A4B88A', '#D0B778'] } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2 · 2025-S2');
expect({ data, source }).toEqual(before);
(view.figure.data[0]['x'] as number[])[0] = 999;
expect(source).toEqual(before.source);
});
it.each([true, false])('categoría con padre declarado: %s, conserva porcentaje original sin renormalizar', withParent => {
const data = c2Fixture(), source = bars(data);
source.data[0]['text'] = ['60%', '30%', '10%'];
source.data[0]['customdata'] = [['A', 10], ['B', 10], ['C', 10]];
source.data[0]['hovertemplate'] = '%{y}: %{x} (%{text})';
const view = c2GeneralSelection(source, data, selection, { ...local, parent: withParent ? 'G2' : undefined, category: 'B' })!;
expect(view.figure.data[0]).toMatchObject({ x: [3], y: ['B'], text: ['30%'], customdata: [['B', 10]], hovertemplate: '%{y}: %{x} (%{text})' });
expect(view.context).toContain('denominador de la distribución completa del periodo');
});
it('preserva colores escalares, arrays de errores y atributos escalares desconocidos', () => {
const data = c2Fixture(), source = bars(data);
source.data[0]['marker'] = { color: '#abcdef' };
source.data[0]['error_x'] = { array: [1, 2, 3], arrayminus: [0, 1, 2] };
source.data[0]['future'] = { retained: true };
expect(c2GeneralSelection(source, data, selection, local)!.figure.data[0]).toMatchObject({ marker: { color: '#abcdef' }, error_x: { array: [2, 3], arrayminus: [1, 2] }, future: { retained: true } });
});
it.each([
{ parent: 'inexistente', period: local.period }, { category: 'inexistente', period: local.period },
{ parent: 'G1', category: 'B', period: local.period }, { parent: 'G2' },
{ ...local, period: '2026-S1' }, { period: local.period },
])('selección inválida %j mantiene la vista completa', candidate => {
const data = c2Fixture(), source = bars(data), before = structuredClone(source);
expect(c2GeneralSelection(source, data, selection, candidate)).toBeUndefined();
expect(source).toEqual(before);
});
it.each(['simple', 'partial-hierarchy', 'missing-row', 'null', 'suppressed', 'missing-unit', 'denominator', 'ambiguous-label'])('contrato %s no produce un filtrado parcial', kind => {
const data = c2Fixture(), source = bars(data), catalog = data['categorias'] as Record<string, Record<string, unknown>>;
if (kind === 'simple') { data['grupos_de_categoria'] = {}; Object.values(catalog).forEach(c => c['grupo'] = null); }
if (kind === 'partial-hierarchy') catalog['A']['grupo'] = null;
if (kind === 'missing-row') data.filas.shift();
if (kind === 'null') data.filas[0]['n'] = null;
if (kind === 'suppressed') data.filas[0]['suprimido'] = 1;
if (kind === 'missing-unit') delete data['unidad'];
if (kind === 'denominator') data['denominador'] = 999;
if (kind === 'ambiguous-label') catalog['A']['etiqueta'] = 'B';
const before = structuredClone({ source, data });
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined();
expect({ source, data }).toEqual(before);
});
it.each(['partial', 'mismatch', 'duplicate-period', 'unnamed', 'wrong-type', 'frames', 'menu', 'unknown-array', 'short-array', 'explicit-ticks', 'normalization', 'metadata-period', 'metadata-denominator', 'secondary-axis', 'external-data'])('figura %s conserva la presentación publicada', kind => {
const data = c2Fixture(), source = bars(data);
if (kind === 'partial') { source.data[0]['x'] = [3, 1]; source.data[0]['y'] = ['B', 'C']; }
if (kind === 'mismatch') source.data[0]['x'] = [7, 3, 1];
if (kind === 'duplicate-period') source.data.push(structuredClone(source.data[0]));
if (kind === 'unnamed') delete source.data[0]['name'];
if (kind === 'wrong-type') source.data[0]['type'] = 'scatter';
if (kind === 'frames') source.frames = [{ name: 'future' }];
if (kind === 'menu') source.layout['updatemenus'] = [];
if (kind === 'unknown-array') source.data[0]['future'] = [1, 2, 3];
if (kind === 'short-array') source.data[0]['text'] = ['60%'];
if (kind === 'explicit-ticks') source.layout['yaxis'] = { tickvals: [0, 1, 2] };
if (kind === 'normalization') source.layout['barnorm'] = 'percent';
if (kind === 'metadata-period') source.layout['meta'] = { period: '2026-S1' };
if (kind === 'metadata-denominator') source.layout['meta'] = { denominator: 999 };
if (kind === 'secondary-axis') source.data[0]['yaxis'] = 'y2';
if (kind === 'external-data') source.data[0]['xsrc'] = 'remote';
const before = structuredClone(source);
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined(); expect(source).toEqual(before);
});
it('cero explícito permanece cero y no se reconstruye un valor null/suprimido', () => {
const data = c2Fixture(); data.filas[2]['n'] = 0;
const source = bars(data);
expect(c2GeneralSelection(source, data, selection, { ...local, category: 'C' })!.figure.data[0]['x']).toEqual([0]);
data.filas[2]['n'] = null; data.filas[2]['suprimido'] = 1;
source.data[0]['x'] = [6, 3, null];
expect(c2GeneralSelection(source, data, selection, local)).toBeUndefined();
expect(source.data[0]['x']).toEqual([6, 3, null]);
});
it('multiperiodo conserva únicamente la traza seleccionada y sus porcentajes, sin sumar periodos', () => {
const data = c2Fixture(), source = bars(data);
delete source.layout['meta']; // Published multiperiod bars have per-trace periods.
data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1', n: Number(r['n']) * 2 })));
const second = { ...structuredClone(source.data[0]), name: '2025-S1', x: [12, 6, 2], text: ['60%', '30%', '10%'] };
source.data.push(second);
const multiple = { ...selection, periodos: [...data.periodos] }, before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, multiple, { ...local, period: '2025-S1' })!;
expect(view.figure.data).toHaveLength(1);
expect(view.figure.data[0]).toMatchObject({ name: '2025-S1', x: [6, 2], y: ['B', 'C'], text: ['30%', '10%'] });
expect(c2GeneralSelection(source, data, selection, { ...local, period: '2025-S1' })).toBeUndefined();
expect(c2GeneralSelection(source, data, multiple, {})).toBeUndefined();
expect({ data, source }).toEqual(before);
});
it('Todos con reporte: un periodo sin traza publicada conserva la vista completa disponible', () => {
const data = c2Fixture(), source = bars(data);
data.periodos.push('2025-S1'); data.filas.push(...data.filas.map(r => ({ ...r, periodo: '2025-S1' })));
const before = structuredClone(source);
expect(c2GeneralSelection(source, data, { ...selection, periodos: undefined }, { ...local, period: '2025-S1' })).toBeUndefined();
expect(source).toEqual(before);
});
it.each([
{ id: 'cacu_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
{ id: 'cama_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Benigno', ANORMAL: 'Cáncer', SIN_DATO: 'Sin dato' },
categories: [['BENIGNO', 'Benigno', 'NO_ANORMAL'], ['CARCINOMA_IN_SITU', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA_INVASOR', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
])('$id: relaciones publicadas con conteos sintéticos, sin reglas por ID', candidate => {
const data = c2Fixture(); data.id = candidate.id; data['unidad'] = candidate.unit;
data['grupos_de_categoria'] = candidate.groups;
data['categorias'] = Object.fromEntries(candidate.categories.map(([id, etiqueta, grupo]) => [id, { etiqueta, grupo }]));
data.filas = candidate.categories.map(([categoria], orden) => ({ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, orden, n: orden + 1, suprimido: 0 }));
const s = { ...selection, indicador: candidate.id }, adapted = c2Figure(data, s);
if (adapted.status !== 'supported') throw new Error(adapted.reason);
const source = adapted.figure, parent = candidate.groups.ANORMAL;
expect(c2GeneralSelection(source, data, s, { parent, period: local.period })!.figure.data[0]['y'])
.toEqual(candidate.categories.filter(c => c[2] === 'ANORMAL').map(c => c[1]));
const category = candidate.categories.find(c => c[2] === 'ANORMAL')![1];
expect(c2GeneralSelection(source, data, s, { parent, category, period: local.period })!.figure.data[0]['y']).toEqual([category]);
// Re-identification does not change capabilities or behavior.
data.id = 'otro-identificador';
expect(c2GeneralSelection(source, data, { ...s, indicador: data.id }, { parent, period: local.period })).toBeDefined();
});
});
@@ -0,0 +1,75 @@
import { c2Figure } from './indicadores-c2-adapter';
import { DonutSelection } from './indicadores-donut-drilldown';
import { periodDatos } from './indicadores-donut-periods';
import { FigureSelection, IndicadorDatos, PlotlyFigure } from './indicadores.models';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
// Only known per-point arrays may be sliced. Unknown array semantics require
// the complete presentation, rather than risking misaligned metadata.
const pointArrays = new Set([
'x', 'y', 'text', 'hovertext', 'customdata', 'ids', 'hovertemplate', 'texttemplate', 'textposition',
'base', 'width', 'offset', 'marker.color', 'marker.opacity', 'marker.line.color', 'marker.line.width',
'marker.pattern.shape', 'marker.pattern.size', 'marker.pattern.solidity', 'marker.pattern.fgcolor', 'marker.pattern.bgcolor',
'error_x.array', 'error_x.arrayminus', 'error_y.array', 'error_y.arrayminus',
'textfont.color', 'textfont.size', 'textfont.family', 'insidetextfont.color', 'insidetextfont.size', 'insidetextfont.family',
'outsidetextfont.color', 'outsidetextfont.size', 'outsidetextfont.family',
]);
export interface C2GeneralSelection { figure: PlotlyFigure; context: string; }
// Select published observations, never recompute a denominator or interpret a
// visual parent as filas[].grupo (the latter is the statistical population).
export function c2GeneralSelection(source: PlotlyFigure, data: IndicadorDatos,
selection: FigureSelection, local: DonutSelection): C2GeneralSelection | undefined {
const period = local.period;
if (selection.figura !== 'fig_c2_barras' || (!local.parent && !local.category) || !period
|| !data.periodos.includes(period) || (selection.periodos && !selection.periodos.includes(period))
|| source.frames?.length || source.layout['sliders'] !== undefined || source.layout['updatemenus'] !== undefined
|| !!source.layout['barnorm'] || Object.keys(source.layout).some(key => /^[xy]axis\d+$/.test(key))) return;
const adapted = c2Figure(periodDatos(data, period), { ...selection, periodos: [period] });
if (adapted.status !== 'supported' || !adapted.model.parents.length || !adapted.model.categories.length) return;
const { categories, parents } = adapted.model;
const meta = source.layout['meta'];
if (record(meta) && ((meta['period'] !== undefined && meta['period'] !== period)
|| (meta['denominator'] !== undefined && meta['denominator'] !== adapted.model.total))) return;
const parent = local.parent ? parents.find(p => p.label === local.parent) : undefined;
const category = local.category ? categories.find(c => c.label === local.category) : undefined;
if ((local.parent && !parent) || (local.category && !category)
|| (parent && category && 'group:' + category.parentId !== parent.id)) return;
const selected = categories.filter(c => (!parent || 'group:' + c.parentId === parent.id) && (!category || c.id === category.id));
if (!selected.length) return;
// A trace must explicitly identify its period and match the entire verified
// partition before any categories are hidden. Never filter a partial trace.
const names = source.data.map(t => t['name']);
if (new Set(names).size !== names.length || source.data.some(t => t['type'] !== 'bar' || t['orientation'] !== 'h'
|| typeof t['name'] !== 'string' || !data.periodos.includes(t['name']))) return;
const trace = source.data.find(t => t['name'] === period);
if (!trace || !Array.isArray(trace['x']) || !Array.isArray(trace['y'])
|| ['transforms', 'xsrc', 'ysrc'].some(key => trace[key] !== undefined)
|| (trace['xaxis'] !== undefined && trace['xaxis'] !== 'x') || (trace['yaxis'] !== undefined && trace['yaxis'] !== 'y')
|| trace['x'].length !== categories.length || trace['y'].length !== categories.length
|| new Set(trace['y']).size !== categories.length) return;
const labels = trace['y'] as unknown[], values = trace['x'] as unknown[];
if (categories.some(c => { const i = labels.indexOf(c.label); return i < 0 || values[i] !== c.value; })) return;
const indices = labels.flatMap((label, i) => selected.some(c => c.label === label) ? [i] : []);
let compatible = true;
const slice = (value: unknown, path: string): unknown => {
if (Array.isArray(value)) {
if (!pointArrays.has(path) || value.length !== categories.length) { compatible = false; return value; }
return indices.map(i => structuredClone(value[i]));
}
if (record(value)) return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, slice(v, path ? path + '.' + key : key)]));
return value;
};
const filtered = slice(trace, '') as Record<string, unknown>;
if (!compatible) return;
const axis = source.layout['yaxis'];
if (record(axis) && (axis['tickvals'] !== undefined || axis['ticktext'] !== undefined
|| (axis['type'] !== undefined && axis['type'] !== 'category'))) return;
const figure = structuredClone(source);
figure.data = [filtered];
if (record(figure.layout['yaxis']) && Array.isArray(figure.layout['yaxis']['categoryarray'])) {
figure.layout['yaxis']['categoryarray'] = figure.layout['yaxis']['categoryarray'].filter(v => selected.some(c => c.label === v));
}
return { figure, context: 'Vista local de la dona: ' + [local.parent, local.category, period].filter(Boolean).join(' · ')
+ '. Sólo se muestran las categorías seleccionadas de este periodo. Los conteos y porcentajes conservan el denominador de la distribución completa del periodo.' };
}
@@ -178,16 +178,20 @@ describe('card doble, jerarquía y carga numérica diferida', () => {
expect(fixture.componentInstance.displayFigures).toEqual(['fig_c2_donas', 'fig_c2_barras']);
http.expectNone(() => true);
});
it('drill-down y restauración de dona no alteran barras, JSON original ni generan consultas', () => {
it('drill-down filtra la presentación de barras y restaurar recupera la distribución sin alterar JSON ni consultar', () => {
activate(); http.expectOne(r => r.url.endsWith('/datos')).flush({ ...c2Fixture(), id: item.id }); fixture.detectChanges();
const bars = structuredClone(panels()[1].result().figure);
const cards = fixture.debugElement.queryAll(By.directive(IndicadorFigureCard)).map(el => el.componentInstance as IndicadorFigureCard);
const before = structuredClone(panels()[0].result().figure), barState = panels()[1].result();
const parentButton = [...fixture.nativeElement.querySelectorAll('.donut-keyboard button') as NodeListOf<HTMLButtonElement>].find(button => button.textContent?.trim() === 'G2')!;
parentButton.click(); fixture.detectChanges(); expect(cards[0].activeParent).toBe('G2');
expect(panels()[1].result()).toBe(barState); expect(panels()[1].result().figure).toEqual(bars);
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B', 'C']);
expect(panels()[1].result().figure).toBe(barState.figure); expect(panels()[1].result().figure).toEqual(bars);
cards[0].selectCategory('B'); fixture.detectChanges();
expect(panels()[1].result().presentationFigure?.data[0]['y']).toEqual(['B']);
(fixture.nativeElement.querySelector('.donut-restore') as HTMLButtonElement).click(); fixture.detectChanges();
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before); http.expectNone(() => true);
expect(cards[0].activeParent).toBeUndefined(); expect(panels()[0].result().figure).toEqual(before);
expect(panels()[1].result().presentationFigure).toEqual(barState.presentationFigure); http.expectNone(() => true);
});
it('tabla abierta sólo solicita números al activar la card y comparte datos con dona', () => {
snapshots.expanded.set(true); fixture.detectChanges(); http.expectNone(() => true);