feat(indicadores): CaMa history tab with the charts the published contracts support

A Histórico tab between Resumen and Seguimiento, for CaMa only: monthly or semestral interval, how many periods to show, and a custom period dialog. Counts are stacked, rates draw their confidence band and medians their quartile band; suppressed periods are shaded and listed, and a rate over no denominator or a median over no observations is no value. Five charts use published indicators; the three whose indicator the catalog does not publish are drawn as pending panels.

(cherry picked from commit 268d7443e0a89da8d6bc67ecb2b5db2715236f93)
This commit is contained in:
Angel Capetillo Zavala
2026-11-12 01:06:56 -06:00
parent 5e16f5454b
commit 2982d482bf
10 changed files with 774 additions and 14 deletions
@@ -5,8 +5,9 @@ import { Tema } from './indicadores.models';
export const C2_PALETTE = Object.freeze({
series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }),
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }),
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
});
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
export function c2Color(published: string | undefined, index: number): string {
@@ -0,0 +1,113 @@
// Covers how the history charts read each contract: what is drawn, what is shaded as suppressed, and what is
// never turned into a number. Fixtures are synthetic rows shaped like /cama/indicadores/<id>/datos.
import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures';
import { IndicadorDatos } from './indicadores.models';
type Fig = { data: Record<string, unknown>[]; layout: Record<string, unknown> };
const figura = (d: IndicadorDatos) => historicoFigura(d, 'claro');
const fig = (d: IndicadorDatos) => figura(d).figure as unknown as Fig;
const base = (contrato: string, periodos: string[], filas: Record<string, unknown>[], extra: Record<string, unknown> = {}) =>
({ id: 'x', contrato, tipo_periodo: 'mes', periodos, filas, ...extra }) as unknown as IndicadorDatos;
const fila = (periodo: string, campos: Record<string, unknown>): Record<string, unknown> => ({ periodo, grupo: 'TOTAL', estrato: null, suprimido: 0, ...campos });
const MESES = ['2025-01', '2025-02', '2025-03', '2025-04'];
describe('Histórico: etiquetas y orden de periodos', () => {
it('los meses se leen «mar 2024» y los semestres «2024 S1»', () => {
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024'); expect(etiquetaPeriodo('2024-S1')).toBe('2024 S1');
});
it('el tiempo corre de izquierda a derecha aunque el servidor ordene al revés', () => {
expect(cronologico(['2025-03', '2024-12', '2025-01'])).toEqual(['2024-12', '2025-01', '2025-03']);
});
});
describe('Histórico: C3r (mediana y cuartiles)', () => {
const d = (filas: Record<string, unknown>[], extra = {}) => base('C3r', MESES, filas, { unidad: 'examen', ...extra });
const ok = (p: string, mediana: number, n = 9) => fila(p, { mediana, q1: mediana - 1, q3: mediana + 2, n, unidad: 'dias' });
it('dibuja la banda de cuartiles y la línea de medianas con la unidad que publica el indicador', () => {
const f = fig(d([ok('2025-01', 10), ok('2025-02', 12), ok('2025-03', 8), ok('2025-04', 9)]));
expect(f.data.map(t => t['name'])).toEqual(['Primer a tercer cuartil', 'Mediana']);
expect(f.data[1]['y']).toEqual([10, 12, 8, 9]);
expect(JSON.stringify(f.data[1]['text'])).toContain('9 mastografías');
expect(figura(d([ok('2025-01', 10)], { unidad: 'paciente' })).comoLeer).toContain('pacientes');
expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Días');
});
it('un periodo suprimido se sombrea y se lista, sin valor; la banda no cruza el hueco', () => {
// Fails if a suppressed period is drawn as a number, or if the band bridges the gap.
const r = figura(d([ok('2025-01', 10), fila('2025-02', { suprimido: 1, mediana: null, q1: null, q3: null, n: null }), ok('2025-03', 8), ok('2025-04', 9)]));
const f = r.figure as unknown as Fig;
expect(f.data[1]['y']).toEqual([10, null, 8, 9]);
expect(r.suprimidos).toEqual(['feb 2025']); expect(r.sinDato).toEqual([]);
expect((f.layout['shapes'] as unknown[]).length).toBe(1);
expect((f.data[0]['x'] as (string | null)[]).includes(null)).toBe(true);
});
it('una mediana sin observaciones o una fila ausente es «sin dato», no cero', () => {
const r = figura(d([ok('2025-01', 10), fila('2025-02', { mediana: 0, q1: 0, q3: 0, n: 0, unidad: 'dias' }), ok('2025-03', 0), ok('2025-04', 9)].filter(f => f['periodo'] !== '2025-04')));
expect((r.figure as unknown as Fig).data[1]['y']).toEqual([10, null, 0, null]);
expect(r.sinDato).toEqual(['feb 2025', 'abr 2025']);
});
});
describe('Histórico: C1 (porcentaje con intervalo)', () => {
const d = (filas: Record<string, unknown>[]) => base('C1', MESES, filas);
const tasa = (p: string, valor: number, num: number, den: number) => fila(p, { grupo: 'total', valor, numerador: num, denominador: den, ic_bajo: Math.max(0, valor - 10), ic_alto: Math.min(100, valor + 10) });
it('línea y banda de confianza en una escala de 0 a 100 %', () => {
const f = fig(d([tasa('2025-01', 40, 4, 10), tasa('2025-02', 50, 5, 10), tasa('2025-03', 60, 6, 10), tasa('2025-04', 55, 11, 20)]));
expect(f.data.map(t => t['name'])).toEqual(['Intervalo de confianza', 'Porcentaje']);
expect(f.data[1]['y']).toEqual([40, 50, 60, 55]);
expect((f.layout['yaxis'] as { range: number[]; ticksuffix: string })).toMatchObject({ range: [0, 100], ticksuffix: ' %' });
});
it('un cero con denominador positivo es un valor; 0 de 0 y un valor nulo no se dibujan como cero', () => {
// Fails if a rate over nobody is drawn as 0 %, or a real 0 % is dropped.
const r = figura(d([tasa('2025-01', 0, 0, 8), tasa('2025-02', 0, 0, 0), fila('2025-03', { grupo: 'total', valor: null, numerador: null, denominador: null }), tasa('2025-04', 50, 5, 10)]));
expect((r.figure as unknown as Fig).data[1]['y']).toEqual([0, null, null, 50]);
expect(r.sinDato).toEqual(['feb 2025', 'mar 2025']);
});
it('un periodo suprimido se lista como suprimido y no como sin dato', () => {
const r = figura(d([tasa('2025-01', 40, 4, 10), fila('2025-02', { grupo: 'total', suprimido: 1, valor: null }), tasa('2025-03', 60, 6, 10), tasa('2025-04', 55, 11, 20)]));
expect(r.suprimidos).toEqual(['feb 2025']); expect(r.sinDato).toEqual([]);
});
});
describe('Histórico: C2 (conteos por categoría)', () => {
const categorias = { B4: { etiqueta: 'B4', color: null }, B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2' } };
const celda = (p: string, categoria: string, n: number | null, orden: number, suprimido = 0) => fila(p, { categoria, n, orden, suprimido });
const d = (filas: Record<string, unknown>[], extra = {}) => base('C2', MESES, filas, { categorias, unidad: 'paciente', ...extra });
const completo = MESES.flatMap(p => [celda(p, 'B5', 4, 0), celda(p, 'B4', 6, 1), celda(p, 'SIN_DATO', 0, 2)]);
it('apila las categorías en el orden que publica el indicador, con sus colores y etiquetas', () => {
const f = fig(d(completo));
expect(f.data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
expect((f.data[0]['marker'] as { color: string }).color).toBe('#B55A1F');
expect(f.data[0]['y']).toEqual([4, 4, 4, 4]);
expect(f.layout['barmode']).toBe('stack');
expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
});
it('el eje y el texto hablan de mastografías cuando la unidad es el examen', () => {
const r = figura(d(completo, { unidad: 'examen' }));
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías');
});
it('un periodo con una celda suprimida se sombrea completo y sus barras no se dibujan como cero', () => {
// Fails if the known cells of a partly suppressed period pass for its total.
const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f);
const r = figura(d(filas));
expect(r.suprimidos).toEqual(['feb 2025']);
expect((r.figure as unknown as Fig).data[1]['y']).toEqual([6, null, 6, 6]);
});
it('una celda sin valor y sin suprimir es «sin dato»', () => {
const filas = completo.map(f => f['periodo'] === '2025-03' && f['categoria'] === 'B5' ? { ...f, n: null } : f);
const r = figura(d(filas));
expect(r.sinDato).toEqual(['mar 2025']); expect(r.suprimidos).toEqual([]);
});
});
describe('Histórico: datos inválidos', () => {
it.each([
['supresión que no es 0 ni 1', () => base('C3r', MESES, [fila('2025-01', { suprimido: 2, mediana: 1 })])],
['dos filas del mismo periodo', () => base('C3r', MESES, [fila('2025-01', { mediana: 1, q1: 0, q3: 2, n: 3 }), fila('2025-01', { mediana: 2, q1: 0, q3: 2, n: 3 })])],
['categoría repetida', () => base('C2', MESES, [fila('2025-01', { categoria: 'A', n: 1, orden: 0 }), fila('2025-01', { categoria: 'A', n: 1, orden: 0 })])],
['categoría sin orden', () => base('C2', MESES, [fila('2025-01', { categoria: 'A', n: 1 })])],
['contrato no soportado', () => base('C9', MESES, [])],
])('lanza error con %s', (_nombre, datos) => {
expect(() => historicoFigura(datos(), 'claro')).toThrow();
});
});
@@ -0,0 +1,150 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
export interface HistoricoFigura {
contrato: string;
figure: PlotlyFigure;
comoLeer: string;
suprimidos: string[];
sinDato: string[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic'];
// «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years.
export function etiquetaPeriodo(periodo: string): string {
const [anio, resto] = periodo.split('-');
return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`;
}
// What the unit the kit publishes is called in the charts' texts.
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
};
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'casos', eje: 'Casos' };
function validar(data: IndicadorDatos) {
for (const row of data.filas) {
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
}
return cronologico(data.periodos);
}
function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string) {
const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo);
// A label for every month does not fit: one per quarter is still readable, with the full period on hover.
return {
autosize: true, height: 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text },
margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false },
xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0,
title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % 3 === 0) },
yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false },
// Shaded, because an empty space alone reads as zero. Text below the figure says the same.
shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 },
x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })),
};
}
// One polygon per run of consecutive values: a band must not bridge a gap in the line.
function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) {
const x: (string | null)[] = [], y: (number | null)[] = [];
let run: number[] = [];
const cerrar = () => {
if (run.length) {
if (x.length) { x.push(null); y.push(null); }
x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i]));
y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i]));
}
run = [];
};
periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); });
cerrar();
return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' };
}
// Separate rows from what is missing or suppressed; a period is judged by its only row.
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
const filas = new Map(data.filas.map(row => [row['periodo'] as string, row]));
if (filas.size !== data.filas.length) throw new Error('Filas ambiguas');
const suprimidos: string[] = [], sinDato: string[] = [];
const validas = periodos.map(periodo => {
const row = filas.get(periodo);
if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; }
if (!row || !valor(row)) { sinDato.push(periodo); return null; }
return row;
});
return { validas, suprimidos, sinDato };
}
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
type Trazo = Omit<HistoricoFigura, 'contrato'>;
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data);
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = c2Theme(tema).line;
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos casos.',
suprimidos, sinDato,
};
}
function mediana(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data), unidad = unidadDe(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const linea = c2Theme(tema).line;
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: ejes(data, periodos, suprimidos, tema, 'Días') },
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de las ${unidad.plural}.`,
suprimidos, sinDato,
};
}
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
for (const row of data.filas) {
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida');
celdas.set(key, row);
categorias.set(id, row['orden']);
}
const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id);
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
return {
figure: { data: orden.map((id, i) => {
const meta = record(catalogo[id]) ? catalogo[id] : {};
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, i) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
suprimidos, sinDato,
};
}
// The kit publishes a 4 without subcategory as «B4», with no colour.
function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
const publicada = typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : '';
return publicada && publicada !== id ? publicada : id === 'B4' ? 'BI-RADS 4 (sin subcategoría)' : id;
}
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
// and medians do not, so those two are never stacked.
export function historicoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
: data.contrato === 'C3r' ? mediana(data, tema) : undefined;
if (!figura) throw new Error('Representación no soportada');
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
}
@@ -0,0 +1,58 @@
import { Component, computed, inject, signal } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog';
import { etiquetaPeriodo } from './indicadores-historico-figures';
import { TipoPeriodo } from './indicadores.models';
export interface PeriodosDialogoDatos { tipo: TipoPeriodo; periodos: readonly string[]; elegidos: readonly string[]; }
// The periods of the chosen analysis interval, by year. Closes with the chosen ones, oldest first, or with nothing if cancelled.
@Component({
selector: 'app-indicadores-historico-periodos',
imports: [MatButtonModule, MatCheckboxModule, MatDialogModule],
template: `
<h2 mat-dialog-title>Elegir {{ datos.tipo === 'mes' ? 'meses' : 'semestres' }}</h2>
<mat-dialog-content>
<div class="acciones">
<button type="button" mat-button (click)="elegidos.set(todos)">Elegir todos</button>
<button type="button" mat-button (click)="elegidos.set([])">Quitar todos</button>
</div>
@for (grupo of anios; track grupo.anio) {
<fieldset>
<legend>{{ grupo.anio }}</legend>
@for (periodo of grupo.periodos; track periodo) {
<mat-checkbox [checked]="elegidos().includes(periodo)" (change)="alternar(periodo)">{{ etiqueta(periodo) }}</mat-checkbox>
}
</fieldset>
}
</mat-dialog-content>
<mat-dialog-actions align="end">
<span class="cuenta" role="status">{{ cuenta() }}</span>
<button type="button" mat-button mat-dialog-close>Cancelar</button>
<button type="button" mat-flat-button [disabled]="!elegidos().length" (click)="aplicar()">Aplicar</button>
</mat-dialog-actions>
`,
styles: `
.acciones { display: flex; gap: .5rem; margin-bottom: .5rem; }
fieldset { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); gap: 0 .5rem; margin: 0 0 .75rem; padding: .25rem .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
legend { padding-inline: .25rem; font-weight: 600; }
.cuenta { margin-inline-end: auto; padding-inline-start: .75rem; font: var(--mat-sys-body-medium); }
`,
})
export class IndicadoresHistoricoPeriodos {
readonly datos = inject<PeriodosDialogoDatos>(MAT_DIALOG_DATA);
private readonly dialogo = inject<MatDialogRef<IndicadoresHistoricoPeriodos, string[]>>(MatDialogRef);
readonly etiqueta = etiquetaPeriodo;
readonly todos = [...this.datos.periodos];
readonly elegidos = signal<readonly string[]>(this.datos.elegidos);
readonly anios = [...new Set(this.todos.map(p => p.slice(0, 4)))].map(anio => ({ anio, periodos: this.todos.filter(p => p.startsWith(anio)) }));
readonly cuenta = computed(() => {
const n = this.elegidos().length, mes = this.datos.tipo === 'mes';
return n === 1 ? (mes ? '1 mes elegido' : '1 semestre elegido') : `${n} ${mes ? 'meses elegidos' : 'semestres elegidos'}`;
});
alternar(periodo: string) {
this.elegidos.update(actual => actual.includes(periodo) ? actual.filter(p => p !== periodo) : [...actual, periodo]);
}
aplicar() { this.dialogo.close(this.todos.filter(p => this.elegidos().includes(p))); }
}
@@ -0,0 +1,60 @@
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresMemory } from './indicadores-memory';
import { Dominio } from './indicadores.models';
const item = (id: string, contrato: string) => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
describe('Pestaña Histórico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
const root = () => fixture.nativeElement as HTMLElement;
const tabs = () => [...root().querySelectorAll('[role=tab]')].map(e => e.textContent?.trim());
function abrir(domain: Dominio, catalog: unknown[]) {
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
http.match(() => true);
}
it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
});
it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
// Fails if CaMa's tab leaks into the other domains.
abrir(domain === 'tea' ? 'cacu' : 'cama', []);
abrir(domain, [item(domain + '_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
});
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
const panel = () => root().querySelector('#panel-historico') as HTMLElement;
expect(panel().hidden).toBe(true);
fixture.componentInstance.changeSection('historico'); fixture.detectChanges();
expect(panel().hidden).toBe(false);
// The period inventory is shared with the page, so the panel is seen waiting for it, not as a new request.
expect(panel().querySelector('article.panel[aria-busy="true"]')).not.toBeNull();
fixture.componentInstance.changeSection('resumen'); fixture.detectChanges();
expect(panel().hidden).toBe(true);
});
it('cambiar de dominio vuelve a Resumen', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
fixture.componentInstance.changeSection('historico'); fixture.detectChanges();
abrir('cacu', [item('cacu_x', 'C2')]);
expect(fixture.componentInstance.activeSection()).toBe('resumen');
});
});
@@ -0,0 +1,142 @@
// Covers CaMa's history tab: what it requests and when, the controls (interval, periods to show, custom
// periods), the pending panels for indicators the catalog does not publish, and error handling. Responses are
// synthetic, shaped like /cama/indicadores/<id>/periodos and /datos.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { of } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { HISTORICO_CAMA, IndicadoresHistorico } from './indicadores-historico';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { figure?: { data: { name?: string }[] }; label?: string; }
const MESES = ['2025-01', '2025-02', '2025-03', '2025-04', '2025-05', '2025-06', '2025-07'];
const SEMESTRES = ['2024-S2', '2025-S1'];
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
// What 18080 publishes for CaMa, including biopsias, which the history does not draw.
const CATALOGO = [item('cama_biopsias', 'C2'), item('cama_birads_456_mastografia', 'C2'), item('cama_birads_456_paciente', 'C2'),
item('cama_confirmacion_birads45', 'C1'), item('cama_dias_toma_diagnostico', 'C3r'), item('cama_eu38a', 'C3r')];
const PUBLICADOS = CATALOGO.filter(i => i.id !== 'cama_biopsias');
function datos(id: string, contrato: string, tipo: string, periodos: string[]) {
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
const filas = contrato === 'C2'
? periodos.flatMap(p => [fila(p, { categoria: 'B5', n: 7, orden: 0 }), fila(p, { categoria: 'B4', n: 5, orden: 1 })])
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 50, numerador: 5, denominador: 10, ic_bajo: 30, ic_alto: 70 }))
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' && id.includes('paciente') ? 'paciente' : 'examen', filas,
categorias: { B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, B4: { etiqueta: 'B4', color: null } } };
}
describe('Histórico de CaMa', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
const abrirDialogo = vi.fn();
function montar(catalog: Indicador[] = CATALOGO, active = false) {
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
fixture.detectChanges();
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
// Answers in waves, because the shared request queue runs four at a time.
function responder(fallo?: (r: TestRequest) => boolean) {
const vistos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
const url = r.request.url; vistos.push(url + (r.request.params.get('periodos') ? '?' + r.request.params.get('periodos') : ''));
const id = url.split('/').at(-2)!, entrada = CATALOGO.find(i => i.id === id)!;
if (fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
else {
const periodos = r.request.params.get('periodos')!.split(',');
r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos));
}
}
fixture.detectChanges();
}
return vistos;
}
const root = () => fixture.nativeElement as HTMLElement;
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
it('no pide nada hasta que la pestaña está activa, y entonces solo los indicadores de la lista que el catálogo publica', () => {
// Fails if the tab loads data while hidden, or if biopsias (not in the history) is requested.
montar();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const vistos = responder();
const ids = new Set(vistos.map(u => u.split('/').at(-2)));
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
});
it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
});
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
montar(CATALOGO, true); responder();
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
});
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
montar(CATALOGO, true); responder();
const toggle = fixture.debugElement.query(By.css('mat-button-toggle-group'));
toggle.triggerEventHandler('change', { value: 'semestre' }); fixture.detectChanges();
const semestrales = responder();
expect(semestrales.length).toBeGreaterThan(0);
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
http.expectNone(() => true);
});
it('«Periodos a mostrar» ofrece pasos de cinco y «Todos»; elegir los últimos cinco recorta cada gráfica', () => {
montar(CATALOGO, true); responder();
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
});
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
montar(CATALOGO, true); responder();
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(['2025-02', '2025-05']) });
fixture.componentInstance.elegirVentana(-1); fixture.detectChanges();
expect(abrirDialogo).toHaveBeenCalledTimes(1);
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
});
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
montar(CATALOGO, true);
responder(r => r.request.url.includes('cama_eu38a/periodos'));
const panel = paneles().find(p => p.querySelector('h2')!.textContent === 'Días de la toma de la mastografía a su resultado')!;
expect(panel.querySelector('[role=alert]')).not.toBeNull();
expect(panel.textContent).not.toContain('private');
expect(graficas()).toHaveLength(4);
(panel.querySelector('[role=alert] button') as HTMLButtonElement).click(); fixture.detectChanges();
const nuevos = responder();
expect(nuevos.length).toBeGreaterThan(0);
expect(paneles().some(p => p.querySelector('[role=alert]'))).toBe(false);
expect(graficas()).toHaveLength(5);
});
it('sin ningún indicador de la lista en el catálogo no hay paneles ni consultas', () => {
montar([item('cama_biopsias', 'C2')], true);
http.expectNone(() => true);
expect(paneles()).toHaveLength(0);
});
});
@@ -0,0 +1,220 @@
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDialog } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
import { httpMessage } from './indicadores-http';
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { id: string; titulo: string; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura });
const PERSONALIZADO = -1;
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico por categoría BI-RADS' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
];
// Evolution of each indicator: the granularity and how many of the latest periods to show.
// Nothing is requested until the tab is first opened, and each granularity is requested once.
@Component({
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
</div>
<div class="paneles">
@for (panel of paneles(); track panel.id) {
<article class="panel" [attr.aria-busy]="panel.estado === 'cargando'">
<h2>{{ panel.titulo }}</h2>
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
@switch (panel.estado) {
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.titulo" /> }
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
@case ('error') {
<div role="alert"><p>{{ panel.mensaje }}</p>
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
}
@case ('listo') {
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
[label]="'Histórico de ' + panel.titulo + (panel.rango ? ', ' + panel.rango : '')" />
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.suprimidos.length) {
<p class="nota">Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.figura.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
}
</article>
}
</div>
`,
styles: `
:host { display: block; min-width: 0; }
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
app-plotly-chart { margin-top: var(--issste-space-3); }
mat-form-field { min-width: 18rem; }
`,
})
export class IndicadoresHistorico {
readonly dominio = input.required<Dominio>();
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators of the list the catalog publishes.
private readonly publicados = computed(() => HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)));
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
readonly tipo = computed<TipoPeriodo>(() => {
const elegido = this.elegido(), tipos = this.tipos();
return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes';
});
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
readonly PERSONALIZADO = PERSONALIZADO;
// The periods the user picked in the dialog, per granularity.
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
private readonly dialogo = inject(MatDialog);
private readonly selector = viewChild<MatSelect>('selector');
// Every period published for the granularity by any indicator.
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
if (ventana !== PERSONALIZADO) return ventana ? orden.slice(-ventana) : orden;
const elegidos = this.personalizados()[this.tipo()] ?? [];
return orden.filter(p => elegidos.includes(p));
}
private readonly service = inject(IndicadoresService);
private readonly periodos = inject(IndicadoresPeriodos);
private readonly cargas = signal<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>();
private solicitada?: string;
private catalogoCargado?: readonly Indicador[];
// Steps of five, up to what the indicator with the most periods has published.
readonly opciones = computed(() => {
const tipo = this.tipo();
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
const opciones = [];
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
const elegidos = this.personalizados()[tipo]?.length;
return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' },
...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])];
});
readonly paneles = computed<Panel[]>(() => {
const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema();
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
const item = this.catalog().find(i => i.id === entrada.id);
if (!item) return { ...entrada, estado: 'pendiente' };
if (!item.tipos_periodo.includes(tipo)) return { ...entrada, estado: 'vacio' };
const carga = cargas?.[item.id];
if (!carga) return { ...entrada, estado: 'cargando' };
if (carga.estado !== 'listo') return { ...entrada, ...carga };
const periodos = this.recortar(carga.datos.periodos);
if (!periodos.length) return { ...entrada, estado: 'vacio' };
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
try {
return { ...entrada, rango, estado: 'listo', figura: historicoFigura(datos, tema) };
} catch (error) {
return { ...entrada, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
});
});
constructor() {
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => {
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
});
effect(() => {
const tipo = this.tipo(), items = this.publicados();
if (!this.active() || !items.length) return;
untracked(() => {
if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; }
if (this.cargas()[tipo] || this.solicitada === tipo) return;
this.solicitada = tipo;
this.solicitudes.next({ tipo, items });
});
});
}
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
return this.periodos.periodos(this.dominio(), item.id).pipe(
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
switchMap((periodos): Observable<Carga> => periodos.length
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
: of({ estado: 'vacio' })),
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
}
elegirVentana(valor: number) {
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
}
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
// Starts from what's on screen, so the user only adjusts it.
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos;
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
.afterClosed().subscribe(resultado => {
if (resultado?.length) {
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
}
// Cancelled, the selector goes back to what's on screen.
this.selector()?.writeValue(this.ventana());
});
}
reintentar() {
const tipo = this.tipo();
this.solicitada = tipo;
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
this.solicitudes.next({ tipo, items: this.publicados() });
}
}
@@ -143,6 +143,12 @@
</section>
</div>
@if (conHistorico) {
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
</section>
}
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
@@ -28,22 +28,28 @@ import { httpMessage } from './indicadores-http';
import { IndicadoresInitialPeriod } from './indicadores-initial-period';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadoresTracking } from './indicadores-tracking';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel';
type DashboardSection = 'resumen' | 'seguimiento' | 'datos';
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
const SECCIONES: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]];
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel],
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
readonly sections: readonly { id: DashboardSection; label: string }[] = [
{ id: 'resumen', label: 'Resumen' },
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// The history tab is CaMa's; the other domains keep their three sections.
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; }
get conHistorico() { return this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
setFichaPacienteAbierta(open: boolean) {
@@ -31,14 +31,16 @@ describe('Secciones compartidas por dominio', () => {
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => {
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']);
// CaMa also has Histórico, between Resumen and Seguimiento.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
// Upstream moved domain selection to its own App shell; ours keeps it on
// the page itself (see indicadores-page.html), since our shell is shared
@@ -50,7 +52,9 @@ describe('Secciones compartidas por dominio', () => {
expect(panel.hidden).toBe(tab.id !== 'tab-resumen');
}
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tabs[1].click(); harness.detectChanges();
// By id, since CaMa has one more tab.
const pestana = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
pestana('seguimiento').click(); harness.detectChanges();
if (domain === 'cacu') {
http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
@@ -67,7 +71,7 @@ describe('Secciones compartidas por dominio', () => {
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
}
tabs[2].click(); harness.detectChanges();
pestana('datos').click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tabs[0].click(); harness.detectChanges();
expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards);