2a36397fac
`CACU-RIESGO-BANDA` is published, so its panel reads it like the others; it counts the patients of the confirmed risk batches, and is empty until one is confirmed. No CaCu history panel stays reserved.
244 lines
16 KiB
TypeScript
244 lines
16 KiB
TypeScript
// 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 { 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',
|
|
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
|
const RESERVADOS: string[] = [];
|
|
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 los nueve paneles en orden: los activos con gráfica y los 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(ACTIVOS.length);
|
|
const reservados = paneles().slice(ACTIVOS.length);
|
|
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
|
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
|
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
|
});
|
|
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
|
// 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(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
|
fixture.destroy(); TestBed.resetTestingModule();
|
|
}
|
|
});
|
|
it('no antepone ningún aviso a los paneles', () => {
|
|
// Fails if a notice about clinical validation or suppression is shown again above the history's panels.
|
|
montar();
|
|
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
|
|
expect(root().textContent).not.toContain('sujetos a validación clínica');
|
|
});
|
|
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(ACTIVOS.length);
|
|
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(ACTIVOS.length);
|
|
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.each([false, true])('acumula 5→10→Todos sin duplicados al recibir primero la segunda respuesta: %s', invertir => {
|
|
// The two expansions are disjoint. Either arrival order must preserve all twelve periods.
|
|
montar([item('ind1')], true); responder();
|
|
fixture.componentInstance.elegirVentana(10);
|
|
fixture.componentInstance.elegirVentana(0);
|
|
fixture.componentInstance.elegirVentana(0);
|
|
const ampliaciones = http.match(r => r.url.endsWith('/datos'));
|
|
const periodos = (r: TestRequest) => r.request.params.get('periodos')!.split(',');
|
|
expect(ampliaciones.map(periodos)).toEqual([MESES.slice(2, 7), MESES.slice(0, 2)]);
|
|
for (const r of invertir ? ampliaciones.reverse() : ampliaciones) {
|
|
r.flush(datos('ind1', 'mes', periodos(r)));
|
|
fixture.detectChanges();
|
|
}
|
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
|
http.expectNone(() => true);
|
|
});
|
|
it('reintenta la ampliación fallida conservando los cinco periodos y sin repetir periodos cargados', () => {
|
|
montar([item('ind1')], true); responder();
|
|
fixture.componentInstance.elegirVentana(0);
|
|
http.expectOne(r => r.url.endsWith('/datos')).flush('private', { status: 500, statusText: 'Error' });
|
|
fixture.detectChanges();
|
|
const panel = panelDe(tituloDe('ind1'));
|
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(5);
|
|
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Error');
|
|
(panel.querySelector('button') as HTMLButtonElement).click();
|
|
const reintento = http.expectOne(r => r.url.endsWith('/datos'));
|
|
expect(reintento.request.params.get('periodos')?.split(',')).toEqual(MESES.slice(0, 7));
|
|
reintento.flush(datos('ind1', 'mes', MESES.slice(0, 7)));
|
|
fixture.detectChanges();
|
|
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
|
expect(panel.querySelector('[role="alert"]')).toBeNull();
|
|
});
|
|
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(ACTIVOS.length);
|
|
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 ausente muestra «Trabajo en desarrollo» y no se consulta', () => {
|
|
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
|
|
const panel = panelDe(tituloDe('cacu_eu13'));
|
|
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
|
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
|
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
|
});
|
|
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(ACTIVOS.length - 1);
|
|
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
|
reintentar.click(); fixture.detectChanges(); responder();
|
|
expect(graficas()).toHaveLength(ACTIVOS.length);
|
|
});
|
|
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(ACTIVOS.length - 1);
|
|
});
|
|
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 medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
|
montar(RESERVADOS.map(item), true);
|
|
expect(paneles()).toHaveLength(9);
|
|
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
|
http.expectNone(() => true);
|
|
});
|
|
it('sin periodos con reportes un panel activo muestra «Sin datos»', () => {
|
|
montar([item('ind1')], true);
|
|
http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] });
|
|
fixture.detectChanges();
|
|
expect(panelDe(tituloDe('ind1')).querySelector('[role="status"]')?.textContent).toBe('Sin datos');
|
|
expect(graficas()).toHaveLength(0);
|
|
http.expectNone(() => true);
|
|
});
|
|
});
|