integrating latest dashboard changes
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { ActivatedRoute, provideRouter } from '@angular/router';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { IndicadoresNumericSummary } from './indicadores-numeric-summary';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { figureApplied } from './indicadores-figure-selection';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
||||
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de confirmación histopatológica'),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
|
||||
item('ind1', 'Pacientes con citología anómala'),
|
||||
item('ordinary', 'Otra gráfica'),
|
||||
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2'),
|
||||
];
|
||||
const periods = ['2025-S1', '2025-S2'];
|
||||
const multi: PlotlyFigure = { data: [{ type: 'scatter', x: periods, y: [null, 25],
|
||||
customdata: [[null, 0, 1], [1, 4, 0]], text: ['Suprimido', '1 de 4'], mode: 'markers' }], layout: {} };
|
||||
|
||||
describe('CaCu: oportunidad y selección independiente de todos los reportes', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } },
|
||||
provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/cacu/indicadores').flush(structuredClone(catalog));
|
||||
// Real inventory and KPI consumers: only the two published KPI request data.
|
||||
for (;;) {
|
||||
const requests = http.match(r => r.url.endsWith('/periodos'));
|
||||
if (!requests.length) break;
|
||||
for (const r of requests) r.flush({ id: r.request.url.split('/')[3],
|
||||
periodos: periods.map(periodo => ({ periodo, tipo: 'semestre' })) });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(requests.map(r => r.request.url)).toEqual([
|
||||
'/cacu/indicadores/cacu_eu7/datos', '/cacu/indicadores/cacu_dias_toma_diagnostico/datos',
|
||||
]);
|
||||
for (const r of requests) {
|
||||
const id = r.request.url.split('/')[3], contrato = id === 'cacu_eu7' ? 'C2' : 'C3r';
|
||||
r.flush({ id, contrato, tipo_periodo: 'semestre', periodos: ['2025-S2'], categorias: { A: {} },
|
||||
filas: [{ periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria: 'A', n: 5, suprimido: 0,
|
||||
mediana: 7, q1: 3, q3: 9, unidad: 'dias' }] });
|
||||
}
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
||||
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
||||
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
||||
function open(...ids: string[]) { ids.forEach(id => card(id).setVisible(true)); fixture.detectChanges(); }
|
||||
function figure(id: string) { return http.expectOne('/cacu/indicadores/' + id + '/figuras/fig_c1_puntos?tema=claro'); }
|
||||
function apply(tipo: 'mes' | 'semestre', selected: [string, ...string[]]) {
|
||||
page.filters!.tipo = tipo;
|
||||
page.filters!.editors[tipo] = { added: [], draft: { mode: 'explicit', periodos: selected } };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('encabezados, tres tarjetas en orden y placeholder inerte sin periodo, unidad ni HTTP', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
expect(kpis[2].querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('confirmación histopatológica');
|
||||
expect(card('cacu_eu13')).toBeDefined();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('EU7 primero sin alterar catálogo; búsqueda y fijación prevalecen y conservan identidades y memoria', () => {
|
||||
const original = page.catalog(), before = cards();
|
||||
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
|
||||
expect(before[0].indicador.id).toBe('cacu_eu7');
|
||||
page.togglePinned(original[0]); fixture.detectChanges();
|
||||
expect(cards()[0]).toBe(card('cacu_eu13'));
|
||||
page.changeSearchQuery('anómala'); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('ind1');
|
||||
page.changeSearchQuery(''); fixture.detectChanges();
|
||||
expect(cards()[0].indicador.id).toBe('cacu_eu13');
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(page.catalog()).toBe(original);
|
||||
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('inicializa las dos figuras en Todos con reporte aunque el filtro general ya sea mensual; conserva carga diferida', () => {
|
||||
apply('mes', ['2026-01']);
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
|
||||
open('cacu_eu13', 'ind1');
|
||||
for (const id of ['cacu_eu13', 'ind1']) {
|
||||
const r = figure(id); expect(r.request.params.has('periodos')).toBe(false);
|
||||
expect(panel(id).applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
r.flush(multi);
|
||||
}
|
||||
expect(panel('cacu_eu13').applied).not.toBe(panel('ind1').applied);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Selección independiente: Todos con reporte (semestres)');
|
||||
});
|
||||
it('Aplicar no altera selección, datos, representación, host ni GET de las independientes; las ordinarias sí cambian', () => {
|
||||
open('cacu_eu13', 'ind1', 'ordinary');
|
||||
for (const id of ['cacu_eu13', 'ind1', 'ordinary']) figure(id).flush(multi);
|
||||
fixture.detectChanges();
|
||||
const retained = ['cacu_eu13', 'ind1'].map(id => ({ id, card: card(id), panel: panel(id),
|
||||
applied: panel(id).applied, result: panel(id).result() }));
|
||||
const hosts = Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'));
|
||||
card('cacu_eu13').localSelection = { parent: 'own' };
|
||||
card('ind1').localSelection = { parent: 'different' };
|
||||
for (const [tipo, selected] of [['semestre', ['2025-S1']], ['mes', ['2026-01']]] as const) {
|
||||
apply(tipo, [...selected]);
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/(figuras|datos)\b/.test(r.url));
|
||||
const r = http.expectOne(r => r.url.includes('/ordinary/figuras/'));
|
||||
expect(r.request.params.get('periodos')).toBe(selected[0]); r.flush(multi);
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3],
|
||||
contrato: 'C2', tipo_periodo: tipo, periodos: [], filas: [] }));
|
||||
for (const old of retained) {
|
||||
expect(card(old.id)).toBe(old.card); expect(panel(old.id)).toBe(old.panel);
|
||||
expect(panel(old.id).applied).toBe(old.applied); expect(panel(old.id).result()).toBe(old.result);
|
||||
expect(panel(old.id).result().figure).toEqual(multi);
|
||||
}
|
||||
}
|
||||
expect(card('cacu_eu13').localSelection).toEqual({ parent: 'own' });
|
||||
expect(card('ind1').localSelection).toEqual({ parent: 'different' });
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-plotly-chart'))).toEqual(hosts);
|
||||
expect(panel('ind1').result().figure!.data[0]['x']).toEqual(periods);
|
||||
expect(panel('ind1').result().figure!.data[0]['y']).toEqual([null, 25]);
|
||||
});
|
||||
it('resumen abierto reutiliza snapshots propios y no consulta los periodos del filtro general', () => {
|
||||
open('cacu_eu13', 'ind1');
|
||||
figure('cacu_eu13').flush(multi); figure('ind1').flush(multi);
|
||||
TestBed.inject(IndicadoresSnapshots).expanded.set(true); fixture.detectChanges();
|
||||
const requests = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(requests).toHaveLength(2);
|
||||
for (const r of requests) {
|
||||
expect(r.request.params.has('periodos')).toBe(false);
|
||||
r.flush({ id: r.request.url.split('/')[3], contrato: 'C1', tipo_periodo: 'semestre', periodos: periods,
|
||||
filas: [{ periodo: periods[0], grupo: 'principal', estrato: null, valor: 25, numerador: 1, denominador: 4, suprimido: 0 },
|
||||
{ periodo: periods[1], grupo: 'principal', estrato: null, valor: 50, numerador: 5, denominador: 10, suprimido: 0 }] });
|
||||
}
|
||||
apply('mes', ['2026-01']);
|
||||
http.expectNone(r => /\/(cacu_eu13|ind1)\/datos/.test(r.url));
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush({ id: r.request.url.split('/')[3], contrato: 'C2', tipo_periodo: 'mes', periodos: [], filas: [] }));
|
||||
const summary = fixture.debugElement.query(By.directive(IndicadoresNumericSummary)).componentInstance as IndicadoresNumericSummary;
|
||||
for (const id of ['cacu_eu13', 'ind1']) {
|
||||
const selected = page.catalog().find(i => i.id === id)!;
|
||||
const reading = summary.snapshots.reading('cacu', selected, summary.figureSelection(selected))!;
|
||||
expect(summary.rows(reading.data!).map(row => row.period)).toEqual(periods);
|
||||
expect(reading.data!.filas.map(row => row['denominador'])).toEqual([4, 10]);
|
||||
}
|
||||
});
|
||||
it('reintento individual tras error usa Todos; una nueva versión de catálogo puede revalidar sin tocar otra selección', () => {
|
||||
open('cacu_eu13', 'ind1');
|
||||
figure('cacu_eu13').flush({}, { status: 503, statusText: 'Unavailable' }); figure('ind1').flush(multi);
|
||||
const other = panel('ind1').result();
|
||||
panel('cacu_eu13').requestFigure();
|
||||
const retry = figure('cacu_eu13'); expect(retry.request.params.has('periodos')).toBe(false); retry.flush({ data: [], layout: {} });
|
||||
expect(panel('ind1').result()).toBe(other);
|
||||
page.catalog.update(items => items.map(i => i.id === 'cacu_eu13' ? { ...i, version: '2' } : i)); fixture.detectChanges();
|
||||
const revalidated = figure('cacu_eu13'); expect(revalidated.request.params.has('periodos')).toBe(false); revalidated.flush(multi);
|
||||
expect(panel('ind1').result()).toBe(other);
|
||||
});
|
||||
it('la política por ID solo afecta CaCu y ninguna otra gráfica', () => {
|
||||
const general = page.filters!.applied;
|
||||
for (const domain of ['tea', 'cama'] as const) for (const id of ['cacu_eu13', 'ind1', 'cacu_eu7']) {
|
||||
expect(figureApplied(domain, id, general)).toBe(general);
|
||||
}
|
||||
expect(figureApplied('cacu', 'cacu_eu7', general)).toBe(general);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user