From 7aa3d2c6e63f76c7358be5f1c0c8abee442d7fdd Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:59:03 -0600 Subject: [PATCH] Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum --- .../indicadores/indicador-figure-panel.ts | 126 ++++++++++++++++-- .../indicadores-stratified-panel.spec.ts | 47 ++++++- .../indicadores-stratified.spec.ts | 51 ++++++- .../indicadores/indicadores-stratified.ts | 67 ++++++++-- .../indicadores/indicadores.models.ts | 10 +- 5 files changed, 276 insertions(+), 25 deletions(-) diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index a6bb41f..0213b44 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -16,7 +16,7 @@ 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 { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { MatTooltipModule } from '@angular/material/tooltip'; @@ -25,8 +25,48 @@ import { MatTooltipModule } from '@angular/material/tooltip'; selector: 'app-indicador-figure-panel', imports: [IndicadorFigureCard, MatTooltipModule], template: ` -
+

{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}

+ @if (sidebar) { + + }

{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}

@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) { @@ -36,7 +76,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; {{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }} } - @if (figuraId === 'fig_c2_barras' && capabilities.length) { + @if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
Distribución
@@ -49,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@for (d of capabilities; track d) { + (click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }} }
} + @if (dimension) { +
+ + +
+ }
@if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} } @@ -71,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip'; @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

}
Valores publicados -
- @for (cell of cells; track $index) { } +
CategoríaEstratoConteo
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}
+ @for (cell of cells; track $index) { }
CategoríaEstratoConteoPorcentaje del estrato
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}{{ cell.percent === null ? '—' : cell.percent + ' %' }}
@if (!cells.length) {

No hay categorías publicadas para esta selección.

} @@ -117,6 +163,30 @@ import { MatTooltipModule } from '@angular/material/tooltip'; .donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; } .donut-periods button:disabled { opacity: .45; } .donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + /* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay + shared with the neighbouring panel, so the bars line up with the donut. */ + :host { container-type: inline-size; } + .figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); } + .with-sidebar > :not(.strata-sidebar) { grid-column: 2; } + .strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0); + display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; } + .sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; } + .sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; } + .sidebar-list { display: grid; gap: .25rem; } + .sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start; + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); + color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; } + .sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; } + .sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; } + .sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; } + .sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + .sidebar-reset { margin-top: .5rem; } + .sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } + @container (max-width: 559px) { + .figure-panel.with-sidebar { display: flex; flex-direction: column; } + .strata-sidebar { position: static; } + .sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); } + } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; @@ -165,7 +235,39 @@ export class IndicadorFigurePanel implements OnChanges { return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state; } dimension: DimensionEstrato | '' = ''; + readonly etiquetaDimension = etiquetaDimension; + // Counts or each category's share of its stratum; an indicator can ask to open with the share. + private medidaElegida?: MedidaEstrato; + get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; } + changeMedida(medida: MedidaEstrato) { + if (medida === this.medida) return; + this.medidaElegida = medida; + this.representStratified(); + } cells: StratifiedCell[] = []; + /** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */ + get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; } + estratos: StratumOption[] = []; + ocultos = new Set(); + toggleEstrato(valor: string) { + const ocultos = new Set(this.ocultos); + if (ocultos.has(valor)) ocultos.delete(valor); + else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor); + else return; + this.ocultos = ocultos; + this.representStratified(); + } + mostrarTodos() { + if (!this.ocultos.size) return; + this.ocultos = new Set(); + this.representStratified(); + } + private representStratified() { + if (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.' }); } + } + } get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } private stratifiedData?: IndicadorDatos; @@ -177,14 +279,18 @@ export class IndicadorFigurePanel implements OnChanges { changeDimension(value: DimensionEstrato | '') { if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return; if (this.dimension === value) return; - this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure(); + this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set(); + this.requestFigure(); } chooseStratified() { if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]); } private presentStratified(data: IndicadorDatos): FigureState { const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {}; - const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local); + 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); 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 }), @@ -349,7 +455,9 @@ export class IndicadorFigurePanel implements OnChanges { } } ngOnChanges(changes: SimpleChanges) { - if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = ''; + if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) { + this.dimension = ''; this.estratos = []; this.ocultos = new Set(); + } const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; } this.titleId = identityElementId(identity) + '-title'; diff --git a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts index 39f831c..3b8432d 100644 --- a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts @@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{ toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); expect(fixture.componentInstance.dimension).toBe('grupo_edad'); expect(toggle[1].getAttribute('aria-checked')).toBe('true'); - expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2); + // The dimensions, apart from the counts or percentage toggle that follows them. + expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2); + expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2); for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); } }); it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{ @@ -93,3 +95,46 @@ describe('Barras estratificadas: activación y caché',()=>{ expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general()); }); }); + +describe('Barra lateral de estratificación', () => { + // Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una + // barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un + // valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar. + let fixture:ReturnType>, http:HttpTestingController; + const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]}; + const general=()=>({...c2Fixture(),id:item.id,version:item.version}); + 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:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v); + }); + afterEach(()=>{fixture.destroy();http.verify();}); + const request=()=>http.expectOne(r=>r.url.endsWith('/datos')); + const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement; + it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{ + fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); + expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull(); + const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[]; + expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']); + opciones[1].click(); request().flush(age); fixture.detectChanges(); + const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[]; + expect(valores()).toHaveLength(age.valores_estrato.length); + valores()[0].click(); fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('<25'); + expect(valores()[0].getAttribute('aria-pressed')).toBe('false'); + for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges(); + expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1); + (aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length); + http.expectNone(()=>true); + }); + it('cambiar de estratificador muestra de nuevo todos los valores',()=>{ + fixture.detectChanges(); request().flush(general()); + fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age); + fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1); + fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status); + expect(fixture.componentInstance.ocultos.size).toBe(0); + expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.spec.ts b/src/app/features/indicadores/indicadores-stratified.spec.ts index 9a1b389..3104625 100644 --- a/src/app/features/indicadores/indicadores-stratified.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified.spec.ts @@ -1,6 +1,6 @@ import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; -import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified'; +import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified'; import { DimensionEstrato, Indicador } from './indicadores.models'; const age = { ...ageJson, tipo_periodo: 'semestre' as const }; @@ -61,3 +61,52 @@ describe('Contratos simulados de estratificación de los analistas', () => { expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow(); }); }); + +// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total. +const porEtapa = () => ({ + id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa', + valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' }, + grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } }, + totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 }, + { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }], + filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]] + .map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })), +}); +describe('Porcentaje en cada estrato', () => { + it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => { + // Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total. + const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje'); + expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]); + expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]); + expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato'); + expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]); + }); + it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => { + // Fails if a new stratifier is offered without its published label, or CaCu's wording changes. + const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'], + filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] }, + { estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] }; + expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']); + expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)'); + expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad'); + }); +}); + +describe('Estratos ocultos', () => { + // Fija: ocultar valores de un estrato quita sus series y sus celdas, cada estrato conserva su trama y nunca se + // quedan todas fuera. Falla si el filtro deja de aplicarse, si las tramas se recorren o si se puede vaciar la figura. + it('quita las series ocultas, conserva la trama de cada estrato y no deja la figura vacía', () => { + const todos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro'); + const patron = (f: typeof todos.figure, nombre: string) => (f.data.find(t => t['name'] === nombre)!['marker'] as Record>)['pattern']['shape']; + const algunos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(['<25', '35-44'])); + expect(algunos.figure.data.map(t => t['name'])).toEqual(['25-34', '45-54', '55-64', '65+', 'Sin dato']); + expect(new Set(algunos.cells.map(c => c.stratum))).toEqual(new Set(['25-34', '45-54', '55-64', '65+', 'Sin dato'])); + for (const nombre of ['25-34', '65+', 'Sin dato']) expect(patron(algunos.figure, nombre)).toEqual(patron(todos.figure, nombre)); + const ninguno = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(age.valores_estrato)); + expect(ninguno.figure.data).toHaveLength(todos.figure.data.length); + }); + it('lista los valores del estrato con su etiqueta, en el orden publicado', () => { + expect(stratumOptions(age).map(e => e.etiqueta)).toEqual(['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'Sin dato']); + expect(stratumOptions(age).at(-1)).toEqual({ valor: 'sin_dato', etiqueta: 'Sin dato' }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts index 76404a8..9339969 100644 --- a/src/app/features/indicadores/indicadores-stratified.ts +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -4,30 +4,53 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut. +const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa']; +/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */ +export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string { + if (d === 'grupo_edad') return 'Por grupo de edad'; + if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento'; + const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta; + return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d); +} +export type MedidaEstrato = 'conteo' | 'porcentaje'; export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { return item.contrato === 'C2' && Array.isArray(item.filtros) - ? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d + ? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; } -export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } -export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } { +/** A stratum a reader can show or hide: its published value and label, in the published order. */ +export interface StratumOption { valor: string; etiqueta: string; } +export function stratumOptions(data: IndicadorDatos): StratumOption[] { + const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : []; + const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {}; + return valores.filter((v): v is string => typeof v === 'string') + .map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor })); +} +// `percent`: the cell's share of its stratum, when the stratum's total is known. +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[] } { 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 || !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length || !data['valores_estrato'].every(v => typeof v === 'string') || new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida'); - const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; + const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; + const shown = published.filter(s => !hidden.has(s)); + const strata = shown.length ? shown : published; const statisticalGroup = Object.keys(data['grupos'])[0]; - if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); + if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); const catalog = data['categorias'], groups = data['grupos_de_categoria']; const entries = new Map(); const rows = new Map>(); for (const row of data.filas) { const id = row['categoria'], stratum = row['estrato'], n = row['n']; if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id - || typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) + || typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) || ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida'); const key = JSON.stringify([id, stratum]); if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas'); @@ -44,21 +67,39 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato const cells: StratifiedCell[] = []; const theme = c2Theme(tema); const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); - const figure: PlotlyFigure = { data: strata.map((s, series) => { + // 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[] : []; + const totalDe = (s: string): number | null => { + const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup); + if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null; + const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s]))); + if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null; + const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0); + return suma > 0 ? suma : null; + }; + const porcentaje = medida === 'porcentaje'; + const figure: PlotlyFigure = { data: strata.map(s => { + const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden const selected = categories.map(([id, c]) => { const row = rows.get(JSON.stringify([id, s])); const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; const value = status === 'Publicado' ? row!['n'] as number : null; - cells.push({ category: c.label, stratum: labels[s] as string, value, status }); - return value; + const total = totalDe(s); + const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null; + cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status }); + return { value, percent, total }; }); - return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), + 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 } }, - hovertemplate: '%{y}
%{x}%{fullData.name}' }; - }), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true, + 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, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, - xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, + xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid } + : { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true }, legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } }; return { figure, cells }; diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 70071b4..44d15a2 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -18,8 +18,16 @@ export interface Indicador { filtros?: IndicadorFiltro[]; // Tabs that show it; without this field, all of them. vistas?: string[]; + // Interactive donut and bars by one stratum, like CaCu's EU7. + escenario?: VistaEscenario; + // How the breakdown by stratum opens: counts, or each category's share of its stratum. + medida_estrato?: 'conteo' | 'porcentaje'; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads'; +// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest. +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'estadio' | 'tamano' | 'etapa'; +export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'estadio', 'tamano', 'etapa']; +// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico». +export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; } export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }