feat(cacu): add configurable historical indicators dashboard

CaCu gets the Histórico tab, built on CaMa's through a per-domain config
(indicadores-historico-config.ts): panel list and order, expected contract,
unit labels, initial period window and a notice.

Six panels read the measures dev publishes: EU7, IND1, EU13, biopsy result
after high-grade cytology, days from sample to result and to diagnosis.
Three more (time to treatment, time from diagnosis to treatment, CIN2+ risk
bands) are reserved: they show a title, a description and their state, and
never request a report, whatever the catalog publishes.

Adapter and figures: the primary group of a C1 is read as `total` in every
domain, CaCu composition reports keep their units so the history can fail on
categories that do not add up, periods without units are «sin dato» for CaCu
only, and `examen` reads «citologías» there. Only the latest five periods are
requested at first; wider windows request what is missing.

The recorded FHIR mapping is regenerated for these two additions.
This commit is contained in:
Angel Capetillo Zavala
2026-11-21 22:39:24 -06:00
parent 1fef7812b4
commit ab10cc9025
11 changed files with 638 additions and 62 deletions
@@ -46,6 +46,10 @@
"version": "0.1.2",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 1
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -384,7 +388,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -410,7 +414,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -423,7 +427,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 1,
@@ -463,7 +467,7 @@
"<25": "<25"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -489,7 +493,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "25-34",
"suprimido": 0,
"numerador": 0,
@@ -502,7 +506,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "35-44",
"suprimido": 0,
"numerador": 0,
@@ -515,7 +519,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "45-54",
"suprimido": 0,
"numerador": 1,
@@ -528,7 +532,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "55-64",
"suprimido": 0,
"numerador": 0,
@@ -541,7 +545,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "<25",
"suprimido": 0,
"numerador": 0,
@@ -573,7 +577,7 @@
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -599,7 +603,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "PRE_COLPOSCOPIA",
"suprimido": 0,
"numerador": 1,
@@ -662,6 +666,10 @@
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 89
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -747,6 +755,10 @@
"version": "0.1.0",
"contrato": "C2",
"unidad": "paciente",
"unidades_periodo": {
"2021-S1": 0,
"2025-S2": 0
},
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
@@ -845,7 +857,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -871,7 +883,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -884,7 +896,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 19,
@@ -15,6 +15,8 @@ import {
} from './indicadores-cama-fhir';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
const esMedidaCacu = (measureId: string | undefined): boolean => measureId !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measureId);
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
// by the same rules as before.
@@ -235,7 +237,9 @@ function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id), cacu = esMedidaCacu(measure.id);
// What each period's report says its units are (CaCu's compositions): the history checks its categories against them.
const unidadesPeriodo: Record<string, number> = {};
const declaradas = categorias(measure);
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
@@ -251,10 +255,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
: { ...declaradas,
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
const totales: Record<string, unknown>[] = [];
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
// The page names the primary group of a proportion `total`; the WebApi names it `principal`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = nombre(code(g.code));
@@ -306,6 +310,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
if (cacu && units !== null) unidadesPeriodo[periodo] = units;
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
@@ -338,6 +343,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}),
grupos,
categorias: cats,
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
@@ -0,0 +1,166 @@
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
import { Bundle, resources } from './fhir';
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { disponibilidadDe, HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
import measuresData from './fixtures/cacu_fhir_measures.json';
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const medida = (id: string) => publicadas.find(m => m.id === id)!;
const cod = (c: string) => ({ coding: [{ code: c }] });
const pob = (c: string, count: number) => ({ code: cod(c), count });
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
} as unknown as Report);
// A composition: the categories as the first stratifier, the units as the initial population.
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
} as unknown as Report);
// A duration: the median and the quartiles as extensions of the score.
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
resourceType: 'MeasureReport', id: 'r', period,
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
} as unknown as Report);
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
// selector of the total drops every row, which left EU13's panel empty.
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
const figura = historicoFigura(datos, 'claro');
expect(traza(datos, 1).y).toEqual([0]);
expect(figura.sinDato).toEqual([]);
});
it('IND1 se publica como `ind1` y conserva su valor', () => {
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
expect(datos.id).toBe('ind1');
expect(traza(datos, 1).y).toEqual([25, 25]);
});
it('un denominador cero es «sin dato», no un cero', () => {
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
expect(traza(datos, 1).y).toEqual([null, 25]);
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
});
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
});
it('en CaMa el grupo principal sigue siendo `total`', () => {
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
});
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
// the page gives it, and with the contract the panel expects.
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
const activos = HISTORICO_CACU.filter(p => disponibilidadDe(p) === 'activo');
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
for (const panel of activos) {
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
}
});
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
const reservados = HISTORICO_CACU.filter(p => disponibilidadDe(p) !== 'activo');
expect(reservados.map(p => [p.id, p.fhir, disponibilidadDe(p)])).toEqual([
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'integracion_pendiente'],
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'integracion_pendiente'],
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'pendiente_validacion'],
]);
// The risk bands are in the catalog and stay reserved.
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
});
});
describe('Histórico de CaCu: composiciones (C2)', () => {
const eu7 = () => medida('CACU-EU7');
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
const figura = historicoFigura(datos, 'claro', CACU);
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
expect(figura.sinDato).toEqual([]);
});
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
});
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
const figura = historicoFigura(datos, 'claro', CACU);
expect(figura.sinDato).toEqual(['2025 S1']);
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
});
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
// Regression: the rule is the domain's, not the figure module's.
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
const figura = historicoFigura(datos, 'claro');
expect(figura.sinDato).toEqual([]);
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
});
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
});
});
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
const figura = historicoFigura(datos, 'claro', CACU);
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
expect(figura.comoLeer).toContain('las citologías');
expect(figura.comoLeer).not.toContain('mastograf');
// A period without observations is missing, not zero.
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
expect(figura.sinDato).toEqual(['2025 S2']);
});
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
});
});
@@ -0,0 +1,204 @@
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
// the notice. Responses are synthetic, shaped like /cacu/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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresHistorico } from './indicadores-historico';
import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
const contrato = opciones.contrato ?? CONTRATOS[id];
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
const vacio = (p: string) => p === opciones.sinPoblacion;
const filas = contrato === 'C2'
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
: 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' ? 'paciente' : 'examen', filas,
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
}
describe('Histórico de CaCu', () => {
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', 'cacu'); 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. `pedidos` keeps what each data request asked for.
const pedidos: { id: string; periodos: string[] }[] = [];
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
const url = r.request.url, id = url.split('/').at(-2)!;
if (opciones.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(',');
pedidos.push({ id, periodos });
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
}
}
fixture.detectChanges();
}
}
beforeEach(() => { pedidos.length = 0; });
const root = () => fixture.nativeElement as HTMLElement;
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!;
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
montar();
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const vistos = new Set<string>();
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
vistos.add(r.request.url.split('/').at(-2)!);
const id = r.request.url.split('/').at(-2)!;
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
}
fixture.detectChanges();
}
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
});
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
expect(paneles()).toHaveLength(9);
expect(graficas()).toHaveLength(6);
const reservados = paneles().slice(6);
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
expect(reservados.map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
expect(reservados[0].textContent).toContain('Integración pendiente');
expect(reservados[2].textContent).toContain('Pendiente de validación');
// Title and description, no figures, no invented numbers.
expect(reservados[2].textContent).toContain('banda de riesgo de CIN2+');
expect(reservados.every(p => !/\d+ de \d+|0 %|rango/i.test(p.querySelector('p.rango')?.textContent ?? ''))).toBe(true);
});
it('un panel reservado sigue reservado aunque el catálogo no lo publique ni lo publique', () => {
// Pins down: the state of a reserved panel comes from the config alone.
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
montar(catalogo, true); responder();
expect(paneles().slice(6).map(p => p.querySelector('[data-reservado]')?.getAttribute('data-reservado'))).toEqual(['integracion', 'integracion', 'validacion']);
fixture.destroy(); TestBed.resetTestingModule();
}
});
it('el aviso de validación clínica y supresión se ve siempre', () => {
montar();
const aviso = root().querySelector('[data-aviso="historico"]')!;
expect(aviso.textContent).toBe(AVISO_CACU);
expect(aviso.textContent).toContain('validación clínica');
expect(aviso.textContent).toContain('supresión');
});
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
montar(CATALOGO, true); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
});
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
montar(CATALOGO, true); responder();
pedidos.length = 0;
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
// Going back to five is local: nothing is asked again.
pedidos.length = 0;
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
expect(pedidos).toEqual([]);
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
});
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
montar(CATALOGO, true); responder();
pedidos.length = 0;
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
expect(pedidos).toHaveLength(6);
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
pedidos.length = 0;
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
expect(pedidos).toEqual([]);
});
it('una medida activa que el catálogo no publica es «Integración pendiente» y no se consulta', () => {
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
const panel = panelDe(tituloDe('cacu_eu13'));
expect(panel.textContent).toContain('Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.');
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
expect(graficas()).toHaveLength(5);
});
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
montar(CATALOGO, true);
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
const panel = panelDe(tituloDe('cacu_eu13'));
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
expect(panel.textContent).not.toContain('private');
expect(graficas()).toHaveLength(5);
const reintentar = panel.querySelector('button') as HTMLButtonElement;
reintentar.click(); fixture.detectChanges(); responder();
expect(graficas()).toHaveLength(6);
});
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
const panel = panelDe(tituloDe('cacu_eu7'));
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
expect(graficas()).toHaveLength(5);
});
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
const eu7 = panelDe(tituloDe('cacu_eu7'));
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
expect(eu7.textContent).toContain('oct 2025');
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
});
it('los tiempos hablan de citologías', () => {
montar(CATALOGO, true); responder();
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
}
});
it('sin ninguna medida activa en el catálogo no hay paneles ni consultas', () => {
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
expect(paneles()).toEqual([]);
http.expectNone(() => true);
});
});
@@ -0,0 +1,97 @@
import { Dominio } from './indicadores.models';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
// its whole catalog.
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
// `activo`: the tab asks for its data when the catalog publishes it. The other two are reserved: the panel shows its
// title, its description and the reason, and never asks for a report, whatever the catalog publishes. Activating a
// reserved panel is an explicit edit of this table, once its contract, its tests and its approval are in place.
export type DisponibilidadPanel = 'activo' | 'integracion_pendiente' | 'pendiente_validacion';
export interface PanelHistorico {
// The page's id of the measure (what `indicadorId` gives).
id: string;
titulo: string;
contrato?: ContratoHistorico;
grafica?: GraficaHistorico;
estado?: DisponibilidadPanel;
descripcion?: string;
// The FHIR ids the measure is expected to have, for the reserved panels whose measure is not in the catalog yet.
fhir?: readonly string[];
}
export interface UnidadHistorico { plural: string; eje: string }
export interface HistoricoDominio {
paneles: readonly PanelHistorico[];
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
unidades?: Readonly<Record<string, UnidadHistorico>>;
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
periodosIniciales?: number;
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
conciliarC2?: boolean;
// A composition period with no units is «sin dato», not a bar of zeros.
c2SinPoblacionSinDato?: boolean;
// Shown above the panels.
aviso?: string;
}
// 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' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ 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' },
];
// Whether CaCu offers the history tab. The panels carry no clinical validation and no suppression policy yet (see
// `AVISO_CACU`): while they wait, this is the switch that takes the tab out.
export const HISTORICO_CACU_HABILITADO = true;
export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. '
+ 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.';
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
export const HISTORICO_CACU: readonly PanelHistorico[] = [
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'],
descripcion: 'Días de la toma de la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', estado: 'integracion_pendiente',
fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'],
descripcion: 'Días del diagnóstico que resuelve la citología al primer tratamiento. La medida no está en el catálogo de dev.' },
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', estado: 'pendiente_validacion',
fhir: ['CACU-RIESGO-BANDA'],
descripcion: 'Pacientes de la cohorte de vigilancia por banda de riesgo de CIN2+. El horizonte, el modelo y los cortes no están aprobados.' },
];
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
cama: { paneles: HISTORICO_CAMA },
cacu: {
paneles: HISTORICO_CACU,
// `examen` is the citology here.
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
periodosIniciales: 5,
conciliarC2: true,
c2SinPoblacionSinDato: true,
aviso: AVISO_CACU,
},
};
// The domain's declared history, if it has one and the tab is on.
export function historicoDeDominio(dominio: Dominio): HistoricoDominio | undefined {
return dominio === 'cacu' && !HISTORICO_CACU_HABILITADO ? undefined : HISTORICOS[dominio];
}
export const disponibilidadDe = (panel: PanelHistorico): DisponibilidadPanel => panel.estado ?? 'activo';
@@ -31,12 +31,19 @@ export interface HistoricoOpciones {
// Same vertical scale across small charts, so their heights compare.
yMax?: number;
pequena?: boolean;
// The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's).
unidades?: Readonly<Record<string, { plural: string; eje: string }>>;
// A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error.
conciliarC2?: boolean;
// A composition period with no units is «sin dato», not a bar of zeros.
c2SinPoblacionSinDato?: boolean;
}
// What the unit a measure 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: 'pacientes', eje: 'Pacientes' };
const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) =>
propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
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');
@@ -115,7 +122,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
};
}
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data);
const periodos = validar(data), unidad = unidadDe(data, opciones.unidades);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const trazo = colorDeLinea(data.id, tema);
return {
@@ -137,8 +144,8 @@ const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
};
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo {
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades);
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']]);
@@ -151,7 +158,22 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(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'])));
// The units each report says it has, when the adapter kept them: what the categories of a period must add up to.
const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined;
const suma = (p: string) => {
const valores = estadoDe(p).map(row => row?.['n']);
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
};
if (opciones.conciliarC2 && unidades) {
for (const p of periodos) {
const total = unidades[p], contado = suma(p);
if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
}
// A period with no units is not a period of zeros: it is drawn as a gap and listed.
const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato
? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []);
const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))));
const curso = { frio: 0, calido: 0, neutro: 0 };
return {
figure: { data: orden.map((id, i) => {
@@ -159,7 +181,7 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
const slot = tono === 'neutro' ? i : curso[tono]++;
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; });
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
@@ -176,7 +198,7 @@ function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
// 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, opciones: HistoricoOpciones = {}): HistoricoFigura {
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema)
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : 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) };
@@ -38,12 +38,13 @@ describe('Pestaña Histórico', () => {
expect(root().querySelector('#panel-analisis')).toBeNull();
http.expectNone(request => request.url.startsWith('/cama/analisis'));
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
it('cacu tiene Histórico y no Análisis epidemiológico', () => {
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
abrir('cama', []);
abrir('cacu', [item('cacu_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
abrir('cama', []);
@@ -14,27 +14,25 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
import { disponibilidadDe, DisponibilidadPanel, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
export { HISTORICO_CAMA };
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 = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
// `disponibles` is every period the indicator publishes for the interval, kept when only the latest were requested.
type Carga = { estado: 'listo'; datos: IndicadorDatos; disponibles?: string[] } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato']; descripcion?: string }; rango?: string } & (
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'reservado'; disponibilidad: Exclude<DisponibilidadPanel, 'activo'> } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
const CASOS = 'M28_casos_por_estado';
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' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ 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' },
];
// What two answers for the same indicator give together: the periods, rows and reports of both.
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), ...(Array.isArray(b['reportes']) ? b['reportes'] : [])];
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
return { ...a, periodos: [...a.periodos, ...b.periodos.filter(p => !a.periodos.includes(p))], filas: [...a.filas, ...b.filas],
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
}
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
@@ -62,6 +60,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
@if (aviso(); as texto) { <p class="aviso" role="note" data-aviso="historico">{{ texto }}</p> }
<div class="controles compacto">
<h2>Filtros</h2>
<div class="controles-fila">
@@ -88,6 +87,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
@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 ('reservado') {
@if (panel.item.descripcion) { <p>{{ panel.item.descripcion }}</p> }
@if (panel.disponibilidad === 'pendiente_validacion') {
<p role="status" data-reservado="validacion">Pendiente de validación. Este indicador no se consulta hasta que su contrato, sus pruebas y su autorización estén aprobados.</p>
} @else {
<p role="status" data-reservado="integracion">Integración pendiente. Este indicador no se consulta hasta que su integración se active de forma explícita.</p>
}
}
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
@case ('error') {
@@ -130,6 +137,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
@use '@angular/material' as mat;
:host { display: block; min-width: 0; }
.aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); }
.controles { display: flex; flex-direction: column; align-items: stretch; 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); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
@@ -171,9 +180,17 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => this.dominio() === 'cama'
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
private readonly config = computed(() => historicoDeDominio(this.dominio()));
readonly aviso = computed(() => this.config()?.aviso);
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
// the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes.
private readonly publicados = computed(() => {
const config = this.config();
return config
? config.paneles.filter(entrada => disponibilidadDe(entrada) === 'activo').flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
: this.catalog();
});
// 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);
@@ -183,15 +200,23 @@ export class IndicadoresHistorico {
});
// 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);
// Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all.
readonly ventana = computed(() => {
const elegida = this.ventanas()[this.tipo()];
if (elegida !== undefined) return elegida;
const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles();
return inicial && (!total || total > inicial) ? inicial : 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 : [])));
private readonly disponibles = computed(() => cronologico([...new Set(Object.values(this.cargas()[this.tipo()] ?? {})
.flatMap(carga => carga.estado === 'listo' ? carga.disponibles ?? carga.datos.periodos : []))]));
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
.map(carga => carga.estado === 'listo' ? (carga.disponibles ?? carga.datos.periodos).length : 0)));
// The periods on screen, out of those an indicator publishes.
private recortar(periodos: readonly string[]) {
const orden = cronologico(periodos), ventana = this.ventana();
@@ -209,7 +234,7 @@ export class IndicadoresHistorico {
// 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 total = this.totalDisponibles();
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;
@@ -236,16 +261,26 @@ export class IndicadoresHistorico {
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 { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
const esperado = this.config()?.paneles.find(entrada => entrada.id === item.id)?.contrato;
if (esperado && datos.contrato !== esperado) throw new Error(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
const propias = this.config();
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, opciones), datos };
} catch (error) {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
};
if (this.dominio() === 'cama') {
const config = this.config();
if (config) {
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
return config.paneles.map((entrada: PanelHistorico): Panel => {
const disponibilidad = disponibilidadDe(entrada);
// Reserved: title, description and reason, whatever the catalog says. Nothing is requested for it.
if (disponibilidad !== 'activo') return { item: { id: entrada.id, titulo: entrada.titulo, descripcion: entrada.descripcion }, estado: 'reservado', disponibilidad };
const item = this.catalog().find(i => i.id === entrada.id);
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
const visible = { id: entrada.id, titulo: entrada.titulo };
return item ? { ...panelDe(item), item: { ...visible, contrato: item.contrato } } : { item: visible, estado: 'pendiente' };
});
}
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
@@ -268,17 +303,49 @@ export class IndicadoresHistorico {
});
});
}
// The periods the window on screen needs out of those published: all of them, unless the domain declares an
// initial window, in which case only those. Choosing a wider window later requests the rest (`ampliar`).
private necesarios(disponibles: readonly string[]): string[] {
if (!this.config()?.periodosIniciales) return [...disponibles];
const orden = cronologico(disponibles), ventana = this.ventana();
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[this.tipo()] ?? []).includes(p));
return ventana ? orden.slice(-ventana) : orden;
}
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
const limitada = !!this.config()?.periodosIniciales;
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 })))
? this.service.datos(this.dominio(), item.id, tipo, this.necesarios(periodos)).pipe(
map(datos => ({ estado: 'listo', datos, ...(limitada ? { disponibles: periodos } : {}) })))
: of({ estado: 'vacio' })),
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
}
// The window got wider than what was requested: asks only for the periods that are missing, and adds them.
private ampliar() {
const tipo = this.tipo(), cargas = this.cargas()[tipo];
if (!cargas || !this.config()?.periodosIniciales) return;
for (const item of this.publicados()) {
const carga = cargas[item.id];
if (carga?.estado !== 'listo' || !carga.disponibles) continue;
const faltan = this.necesarios(carga.disponibles).filter(p => !carga.datos.periodos.includes(p));
if (!faltan.length) continue;
this.service.datos(this.dominio(), item.id, tipo, faltan).pipe(takeUntilDestroyed(this.destruccion)).subscribe({
next: datos => this.cargas.update(actual => {
const vigente = actual[tipo]?.[item.id];
return vigente?.estado === 'listo' && vigente === carga
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { ...vigente, datos: unir(vigente.datos, datos) } } } : actual;
}),
error: error => this.cargas.update(actual => actual[tipo]?.[item.id] === carga
? { ...actual, [tipo]: { ...actual[tipo], [item.id]: { estado: 'error', mensaje: httpMessage(error) } } } : actual),
});
}
}
private readonly destruccion = inject(DestroyRef);
elegirVentana(valor: number) {
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
this.ampliar();
}
abrirPersonalizado() {
const tipo = this.tipo(), periodos = this.disponibles();
@@ -290,6 +357,7 @@ export class IndicadoresHistorico {
if (resultado?.length) {
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
this.ampliar();
}
// Cancelled, the selector goes back to what's on screen.
this.selector()?.writeValue(this.ventana());
@@ -31,6 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { historicoDeDominio } from './indicadores-historico-config';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
@@ -40,7 +41,7 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'seguimiento', label: 'Análisis de riesgos' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
// TEA, CaMa and CaCu (while its tab is on, see `HISTORICO_CACU_HABILITADO`) have a history; the epidemiological analysis is CaMa's,
// between its history and its follow-up list.
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
@@ -58,7 +59,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
@@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
dominio === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
@@ -39,9 +39,8 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; the follow-up tab is named Análisis de riesgos in every domain; CaCu keeps its three tabs.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones'];
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
const esperadas = ['Resumen', 'Histórico', 'Análisis de riesgos', '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)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;