feat(ui): mejorar presentacion y disponibilidad inicial de KPI
This commit is contained in:
@@ -29,6 +29,22 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
fixture.destroy();
|
||||
});
|
||||
it('separa valor y unidad y reúne descripción y notas útiles en una sola línea', () => {
|
||||
const fixture = TestBed.createComponent(IndicadorKpiCard);
|
||||
fixture.componentRef.setInput('title', 'Días de la toma al resultado');
|
||||
fixture.componentRef.setInput('value', 7.5);
|
||||
fixture.componentRef.setInput('unit', 'días (mediana)');
|
||||
fixture.componentRef.setInput('additionalInfo', '98 mastografías; Q1 a Q3: 3 a 11 días.');
|
||||
fixture.componentRef.setInput('notes', ['La referencia de 60 días es provisional.', 'La referencia de 60 días es provisional.']);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.value').firstChild.textContent.trim()).toBe('7.5');
|
||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('días (mediana)');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.value span')).marginInlineStart).toBe('0.3em');
|
||||
expect(fixture.nativeElement.querySelectorAll('.additional-info')).toHaveLength(1);
|
||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('98 mastografías; Q1 a Q3: 3 a 11 días. La referencia de 60 días es provisional.');
|
||||
fixture.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,14 +9,12 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<mat-card [attr.aria-busy]="loading">
|
||||
<h3>{{ title }}</h3>
|
||||
@if (loading) { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + title" /> }
|
||||
@if (provisional) { <p class="provisional">Definición provisional</p> }
|
||||
@if (value !== null && value !== undefined) {
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
@if (additionalInfo) { <p class="additional-info">{{ additionalInfo }}</p> }
|
||||
@for (note of notes; track $index) { <p class="additional-info">{{ note }}</p> }
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
@@ -28,8 +26,8 @@ import { MatCardModule } from '@angular/material/card';
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.provisional { border-left: 3px solid var(--issste-text-secondary); padding-left: .75rem; font-weight: 600; }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -38,8 +36,11 @@ export class IndicadorKpiCard {
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
@Input() loading = false;
|
||||
@Input() provisional = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
@Input() additionalInfo?: string;
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
return [...new Set(lines)].join(' ');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
|
||||
describe('KPI búsqueda inicial del último dato visible', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorKpiPanel>>;
|
||||
let http: HttpTestingController;
|
||||
const definition = KPI_BY_DOMAIN.cacu[0];
|
||||
const periods = ['2025-S2', '2025-S1', '2024-S2'];
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorKpiPanel], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadorKpiPanel);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
const availability = emptyAvailability('ready');
|
||||
availability.byIndicator[definition.id] = [periods[2], '2026-01', periods[0], periods[1]].map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' }));
|
||||
fixture.componentRef.setInput('dominio', 'cacu');
|
||||
fixture.componentRef.setInput('definition', definition);
|
||||
fixture.componentRef.setInput('indicador', { id: definition.id, contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: [], titulo: definition.title });
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
fixture.componentRef.setInput('initialPresentation', true);
|
||||
fixture.componentRef.setInput('availability', availability);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function request(period: string) {
|
||||
return http.expectOne(r => r.url.endsWith('/datos') && r.params.get('periodos') === period);
|
||||
}
|
||||
function data(period: string, kind: 'visible' | 'suppressed' | 'incomplete' | 'null' = 'visible', value = 5) {
|
||||
return { id: definition.id, contrato: 'C2', tipo_periodo: 'semestre', periodos: [period],
|
||||
categorias: kind === 'incomplete' ? { A: {}, B: {} } : { A: {} },
|
||||
filas: [{ periodo: period, grupo: 'TOTAL', categoria: 'A', n: kind === 'null' ? null : value, suprimido: kind === 'suppressed' ? 1 : 0 }] };
|
||||
}
|
||||
it('consulta secuencialmente por granularidad, detiene al visible y explica supresión posterior', () => {
|
||||
const latest = request(periods[0]); http.expectNone(() => true);
|
||||
expect(fixture.componentInstance.result().loading).toBe(true);
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().value).toBe(5);
|
||||
expect(fixture.nativeElement.textContent).toContain('Último dato visible · 2025-S1');
|
||||
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('recorre varios suprimidos sin consultar todos los periodos a la vez', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
const second = request(periods[1]); http.expectNone(() => true);
|
||||
second.flush(data(periods[1], 'suppressed'));
|
||||
request(periods[2]).flush(data(periods[2]));
|
||||
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible · 2024-S2');
|
||||
expect(fixture.componentInstance.result().info).toContain('datos ocultos por tamaño');
|
||||
});
|
||||
it('agotado el inventario conserva el estado del último reporte', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush(data(periods[1], 'incomplete'));
|
||||
request(periods[2]).flush(data(periods[2], 'null'));
|
||||
expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño');
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]);
|
||||
});
|
||||
it('acepta cero legítimo del último periodo y termina sin retroceder', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'visible', 0));
|
||||
expect(fixture.componentInstance.result().value).toBe(0);
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['incomplete', 'null', 'missing'] as const)('no muestra %s ni afirma supresión si encuentra un anterior', kind => {
|
||||
const latest = request(periods[0]);
|
||||
if (kind === 'missing') latest.flush('', { status: 404, statusText: 'Not Found' });
|
||||
else latest.flush(data(periods[0], kind));
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
expect(fixture.componentInstance.result().value).toBe(5);
|
||||
expect(fixture.componentInstance.result().info).not.toContain('datos ocultos por tamaño');
|
||||
});
|
||||
it('un error HTTP detiene, se comunica y reintenta sin repetir datos resueltos', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
request(periods[1]).flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.result().state).toBe('Error de consulta');
|
||||
expect(fixture.componentInstance.result().value).toBeUndefined();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('datos ocultos por tamaño');
|
||||
http.expectNone(() => true);
|
||||
(fixture.nativeElement.querySelector('button') as HTMLButtonElement).click();
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
expect(fixture.componentInstance.result().value).toBe(5); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar Todos durante la búsqueda cancela el pasado y recupera solo el último reporte', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed'));
|
||||
const old = request(periods[1]);
|
||||
fixture.componentRef.setInput('initialPresentation', false); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(fixture.componentInstance.result().state).toBe('Dato oculto por tamaño');
|
||||
expect(fixture.componentInstance.temporalReference).toBe(periods[0]); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicar explícito cancela el recorrido e impide sobrescritura antigua', () => {
|
||||
request(periods[0]).flush(data(periods[0], 'suppressed')); const old = request(periods[1]);
|
||||
fixture.componentRef.setInput('initialPresentation', false);
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: [periods[2]] }, revision: 1 }); fixture.detectChanges();
|
||||
expect(old.cancelled).toBe(true); request(periods[2]).flush(data(periods[2], 'visible', 0));
|
||||
expect(fixture.componentInstance.result().value).toBe(0); expect(fixture.componentInstance.temporalReference).toBe(periods[2]);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('comparte el límite cuatro entre periodos y datos; cancela trabajos en cola', () => {
|
||||
const latest = request(periods[0]);
|
||||
const service = TestBed.inject(IndicadoresPeriodos);
|
||||
const subscriptions = ['a', 'b', 'c', 'd', 'e'].map(id => service.periodos('cacu', id).subscribe());
|
||||
const inventory = http.match(r => r.url.endsWith('/periodos'));
|
||||
expect(inventory).toHaveLength(3);
|
||||
subscriptions[4].unsubscribe();
|
||||
latest.flush(data(periods[0], 'suppressed'));
|
||||
const fourth = http.expectOne('/cacu/indicadores/d/periodos');
|
||||
http.expectNone(() => true);
|
||||
inventory[0].flush({ id: 'a', periodos: [] });
|
||||
request(periods[1]).flush(data(periods[1]));
|
||||
inventory.slice(1).forEach((r, i) => r.flush({ id: ['b', 'c'][i], periodos: [] }));
|
||||
fourth.flush({ id: 'd', periodos: [] }); http.expectNone('/cacu/indicadores/e/periodos');
|
||||
subscriptions.forEach(subscription => subscription.unsubscribe());
|
||||
});
|
||||
});
|
||||
@@ -17,10 +17,10 @@ describe('KPI integración con autoridad global', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function load(domain: Dominio, missing = false) {
|
||||
function load(domain: Dominio, missing = false, periods = ['2025-S1']) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] });
|
||||
for (const request of http.match(r => r.url.endsWith('/periodos'))) request.flush({ id: request.request.url.split('/').at(-2), periodos: periods.map(periodo => ({ tipo: 'semestre', periodo })) });
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
@@ -33,8 +33,9 @@ describe('KPI integración con autoridad global', () => {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('TEA conserva dos preliminares y no consulta datos', () => {
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
it('TEA sin definiciones oculta toda la sección y no consulta datos', () => {
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(0); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
@@ -42,14 +43,15 @@ describe('KPI integración con autoridad global', () => {
|
||||
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges();
|
||||
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']);
|
||||
expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.querySelector('.provisional').textContent).toBe('Definición provisional');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
});
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(3);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(0);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3);
|
||||
@@ -68,8 +70,130 @@ describe('KPI integración con autoridad global', () => {
|
||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||
});
|
||||
it('ID ausente bloquea sólo esa tarjeta sin sustituir ni consultar otro indicador', () => {
|
||||
load('cacu', true); expect(panels()[0].result().state).toBe('Indicador no publicado'); expect(panels()[0].result().info).toContain('cacu_eu7');
|
||||
it('el catálogo gráfico no determina membresía de los KPI destacados', () => {
|
||||
load('cacu', true); expect(panels().map(p => p.definition.id)).toEqual(KPI_BY_DOMAIN.cacu.map(d => d.id));
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
|
||||
const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
});
|
||||
it.each([0, 1, 2])('retirar definiciones deja %i tarjetas y conserva filtros y valores retenidos', count => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
const page = fixture.componentInstance, before = panels(), state = page.filters!;
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
const snapshot = structuredClone(state), definitions = page.kpisByDomain.cacu;
|
||||
try {
|
||||
page.kpisByDomain.cacu = definitions.slice(0, count); page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(count); panels().forEach((panel, i) => expect(panel).toBe(before[i]));
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7].slice(0, count));
|
||||
expect(page.filters).toBe(state); expect(state).toEqual(snapshot);
|
||||
const grid = fixture.nativeElement.querySelector('.kpi-grid') as HTMLElement | null;
|
||||
if (count) {
|
||||
expect(grid!.children).toHaveLength(count);
|
||||
expect(grid!.style.getPropertyValue('--kpi-count')).toBe(String(count));
|
||||
} else expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
page.kpisByDomain.cacu = definitions; page.catalog.set([...page.catalog()]); fixture.detectChanges();
|
||||
const added = requests(); expect(added).toHaveLength(0);
|
||||
added.forEach((r, i) => r.flush(response(count + i)));
|
||||
expect(panels()).toHaveLength(3); expect(state).toEqual(snapshot);
|
||||
} finally { page.kpisByDomain.cacu = definitions; }
|
||||
});
|
||||
it('retirar un ID del catálogo gráfico conserva todos los KPI configurados', () => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
const page = fixture.componentInstance, before = panels(), filters = structuredClone(page.filters);
|
||||
page.catalog.set(page.catalog().slice(1)); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before); expect(page.filters).toEqual(filters);
|
||||
expect(panels()).toHaveLength(3); http.expectNone(() => true);
|
||||
});
|
||||
it('CaCu no presenta KPI disponibles durante carga/error y reintenta sin confirmar vacío', () => {
|
||||
const page = fixture.componentInstance; page.changeDominio('cacu'); fixture.detectChanges();
|
||||
expect(page.catalogLoading()).toBe(true); expect(panels()).toHaveLength(3);
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando catálogo');
|
||||
http.expectOne('/cacu/indicadores').flush('private', { status: 503, statusText: 'Unavailable' }); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBeTruthy(); expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section')).toBeTruthy(); expect(panels()).toHaveLength(3);
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog(); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges();
|
||||
expect(page.catalogError()).toBe(''); expect(page.catalogLoading()).toBe(false);
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); expect(panels()).toHaveLength(3);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin filas'] as const)('KPI publicado con resultado %s conserva tarjeta y definición', scenario => {
|
||||
load('cacu'); const before = panels();
|
||||
const data = response(1);
|
||||
if (scenario === 'suprimido') data.filas[0]['suprimido'] = 1;
|
||||
if (scenario === 'nulo') data.filas[0]['valor'] = null;
|
||||
if (scenario === 'sin filas') { data.filas = []; data.periodos = []; }
|
||||
requests().forEach((r, i) => r.flush(i === 1 ? data : response(i))); fixture.detectChanges();
|
||||
expect(panels()).toEqual(before); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(3);
|
||||
expect(panels()[1].result().state).toBe(scenario === 'suprimido' ? 'Dato oculto por tamaño' : scenario === 'nulo' ? 'Sin valor disponible' : 'Sin filas utilizables');
|
||||
expect(panels()[1].result().value).toBeUndefined(); http.expectNone(() => true);
|
||||
});
|
||||
it('KPI publicado sin periodos con reporte mantiene sus tres tarjetas sin consultar datos', () => {
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(KPI_BY_DOMAIN.cacu.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre'] })));
|
||||
http.match(r => r.url.endsWith('/periodos')).forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [] })); fixture.detectChanges();
|
||||
expect(panels()).toHaveLength(3); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
const req = requests(); expect(req).toHaveLength(3);
|
||||
req.forEach((r, i) => r.flush(response(i, domain)));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', '%', 'días (mediana)']);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(['Disponible', 'Disponible', 'Disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'), expect.stringContaining('2 de 5'),
|
||||
expect.stringContaining(`5 ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: 3 a 9 días.`),
|
||||
]));
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||
}
|
||||
});
|
||||
it('Aplicar equivalente termina el modo inicial sin cambiar revisión, borrador o selección', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1']);
|
||||
requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
requests().forEach((r, i) => r.flush(response(i))); fixture.detectChanges();
|
||||
expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true);
|
||||
const page = fixture.componentInstance, applied = page.filters!.applied, snapshot = structuredClone(page.filters);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(false);
|
||||
(fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click(); fixture.detectChanges();
|
||||
expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied); expect(page.filters).toEqual(snapshot);
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.temporalReference === '2025-S2')).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); http.expectNone(() => true);
|
||||
load('cama'); requests().forEach((r, i) => r.flush(response(i, 'cama'))); expect(page.initialKpiPresentation).toBe(true);
|
||||
load('cacu'); expect(page.initialKpiPresentation).toBe(false); expect(panels()).toHaveLength(3);
|
||||
expect(panels().every(p => p.temporalReference === '2025-S2' && p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('primera entrada independiente y regreso inicial reutilizan datos, sin reiniciar filtros', () => {
|
||||
load('cacu'); requests().forEach((r, i) => r.flush(response(i)));
|
||||
load('cama'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true); requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); expect(fixture.componentInstance.initialKpiPresentation).toBe(true);
|
||||
expect(panels().map(p => p.result().value)).toEqual([5, '40.0', 7]); http.expectNone(() => true);
|
||||
});
|
||||
it('salir durante el recorrido cancela periodos antiguos y volver reutiliza últimos resueltos', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1']);
|
||||
requests().forEach((r, i) => { const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
const old = requests(); expect(old).toHaveLength(3);
|
||||
load('cama'); expect(old.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); const resumed = requests(); expect(resumed).toHaveLength(3);
|
||||
resumed.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(response(i)); });
|
||||
expect(panels().every(p => p.temporalReference === 'Último dato visible · 2025-S1')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('aplicado explícito y luego Todos nunca buscan periodos anteriores', () => {
|
||||
load('cacu', false, ['2025-S2', '2025-S1']); const outgoing = requests();
|
||||
apply(['2025-S1']); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
requests().forEach((r, i) => { const data = response(i); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño')).toBe(true); http.expectNone(() => true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'todos' };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
const latest = requests(); expect(latest).toHaveLength(3);
|
||||
latest.forEach((r, i) => { expect(r.request.params.get('periodos')).toBe('2025-S2'); const data = response(i, 'cacu', '2025-S2'); data.filas[0]['suprimido'] = 1; r.flush(data); });
|
||||
expect(panels().every(p => p.temporalReference === '2025-S2')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Dominio, Indicador } from './indicadores.models';
|
||||
import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi';
|
||||
import { PeriodAvailability, sortedPeriods } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
|
||||
interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; }
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-panel',
|
||||
imports: [IndicadorKpiCard],
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [provisional]="definition.provisional ?? false" [notes]="result().notes ?? []" />`,
|
||||
[loading]="result().loading ?? false" [notes]="result().notes ?? []" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@@ -24,46 +30,68 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input() indicador?: Indicador;
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() catalogPending = false;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
@Input() initialPresentation = false;
|
||||
private readonly queries = inject(IndicadoresKpiQueries);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly requests = new Subject<void>();
|
||||
private key = '';
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiResult>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() { return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); }
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
}
|
||||
retry() { this.requests.next(); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => {
|
||||
this.requests.pipe(switchMap((): Observable<KpiDisplay> => {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
this.usedPeriod.set(undefined);
|
||||
if (this.catalogPending) return of({ state: 'Esperando catálogo' });
|
||||
if (!this.indicador) return of({ state: 'Indicador no publicado', info: 'No está disponible en el catálogo: ' + definition.id });
|
||||
if (this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
||||
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' });
|
||||
let resolved = applied;
|
||||
let periods: string[];
|
||||
if (applied.selection.mode === 'todos') {
|
||||
if (!this.indicador) return of({ state: 'Sin reportes disponibles' });
|
||||
const availability = this.availability;
|
||||
if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true });
|
||||
if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' });
|
||||
const periods = availability.byIndicator[definition.id];
|
||||
if (!periods) return of({ state: 'Error de disponibilidad' });
|
||||
const latest = sortedPeriods(periods.filter(p => p.tipo === applied.tipo).map(p => p.periodo))[0];
|
||||
if (!latest) return of({ state: 'Sin reportes disponibles' });
|
||||
resolved = { ...applied, selection: { mode: 'explicit', periodos: [latest] } };
|
||||
}
|
||||
const periodos = resolved.selection.mode === 'explicit' ? resolved.selection.periodos : undefined;
|
||||
this.usedPeriod.set(periodos?.[0]);
|
||||
return defer(() => this.service.datos(domain, definition.id, applied.tipo, periodos)).pipe(
|
||||
map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas })),
|
||||
catchError(error => of({ state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
||||
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
||||
startWith({ state: 'Cargando…', loading: true }));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => this.result.set(result));
|
||||
const available = availability.byIndicator[definition.id];
|
||||
if (!available) return of({ state: 'Error de disponibilidad' });
|
||||
periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo));
|
||||
if (!periods.length) return of({ state: 'Sin reportes disponibles' });
|
||||
if (!this.initialPresentation) periods = periods.slice(0, 1);
|
||||
} else periods = applied.selection.periodos;
|
||||
// One request per KPI at a time: the three configured panels start only after
|
||||
// the existing availability queue (concurrency four) has finished.
|
||||
const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable<KpiDisplay> => {
|
||||
const period = periods[index];
|
||||
const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } };
|
||||
return this.queries.datos(domain, definition.id, applied.tipo, period).pipe(
|
||||
map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period } as KpiDisplay)),
|
||||
catchError(error => of<KpiDisplay>({ period,
|
||||
state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
||||
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
||||
switchMap(result => {
|
||||
// Network/contract transport failures stay visible and can be retried.
|
||||
if (result.state === 'Error de consulta') return of(result);
|
||||
if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0,
|
||||
info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') });
|
||||
const first = latest ?? result;
|
||||
return index + 1 < periods.length
|
||||
? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first);
|
||||
}));
|
||||
};
|
||||
return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos'
|
||||
? 'Buscando último dato visible…' : 'Cargando…', loading: true }));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => {
|
||||
this.usedPeriod.set(result.period);
|
||||
this.result.set(result);
|
||||
});
|
||||
}
|
||||
ngOnChanges() {
|
||||
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.catalogPending, this.applied && selectionKey(this.applied),
|
||||
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied && selectionKey(this.applied),
|
||||
this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]);
|
||||
if (key === this.key) return;
|
||||
this.key = key;
|
||||
|
||||
@@ -61,6 +61,6 @@
|
||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || !hasPending" (click)="apply.emit()">Aplicar</button>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || (!hasPending && !initialPresentation)" (click)="apply.emit()">Aplicar</button>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
|
||||
@@ -18,6 +18,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
@Input({ required: true }) state!: FilterState;
|
||||
@Input({ required: true }) types!: TipoPeriodo[];
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
@Output() retryAvailability = new EventEmitter<void>();
|
||||
@Output() edited = new EventEmitter<void>();
|
||||
@Output() apply = new EventEmitter<void>();
|
||||
|
||||
@@ -43,15 +43,26 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
}
|
||||
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s antes de KPI y sin HTTP inicial', domain => {
|
||||
it('Aplicar Todos inicial equivalente no cambia el filtro gráfico ni repite su HTTP', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio('cacu'); load(undefined, 'cacu'); open(); respond();
|
||||
const applied = page.filters!.applied, before = panels()[0].result();
|
||||
expect(page.initialKpiPresentation).toBe(true);
|
||||
apply();
|
||||
expect(page.initialKpiPresentation).toBe(false); expect(page.filters!.applied).toBe(applied);
|
||||
expect(applied.revision).toBe(0); expect(panels()[0].result()).toBe(before); http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s sin KPI no publicados ni HTTP inicial', domain => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
load(undefined, domain);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf<HTMLElement>;
|
||||
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
|
||||
expect(sections[1].querySelectorAll('app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 2 : 3);
|
||||
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 0 : 3);
|
||||
expect(sections[domain === 'tea' ? 1 : 2].getAttribute('aria-labelledby')).toBe('graphic-section-title');
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(domain === 'tea');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
||||
@@ -135,7 +146,9 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
expect(outgoing.cancelled).toBe(true); load(undefined, 'cacu'); expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
draft('mes', ['2026-01']); apply(); page.changeDominio('tea'); load();
|
||||
expect(editor().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(page.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||
expect(cards()[0].visible).toBe(false); http.expectNone(() => true);
|
||||
expect(cards()[0].visible).toBe(false);
|
||||
http.match(r => r.url.endsWith('/datos')).filter(r => !r.cancelled).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => {
|
||||
load(); draft('mes', ['2025-01']); apply(); open(); respond();
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { Observable, shareReplay } from 'rxjs';
|
||||
import { Dominio, IndicadorDatos, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadoresRequests } from './indicadores-requests';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresKpiQueries {
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly requests = inject(IndicadoresRequests);
|
||||
// Only resolved KPI payloads survive navigation. Errors and cancelled requests reset.
|
||||
private readonly cache = new Map<string, Observable<IndicadorDatos>>();
|
||||
datos(domain: Dominio, id: string, tipo: TipoPeriodo, period: string) {
|
||||
const key = JSON.stringify([domain, id, tipo, period]);
|
||||
let request = this.cache.get(key);
|
||||
if (!request) {
|
||||
request = this.requests.run(() => this.service.datos(domain, id, tipo, [period])).pipe(
|
||||
shareReplay({ bufferSize: 1, refCount: true }));
|
||||
this.cache.set(key, request);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; provisional?: boolean; }
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; }
|
||||
const definitions = (): KpiDefinition[] => [
|
||||
{ id: '', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%', provisional: true },
|
||||
{ id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%' },
|
||||
{ id: '', title: 'Días de la toma al resultado', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
];
|
||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
@@ -46,7 +46,7 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
if (!rows.every(row => count(row['n']))) return empty;
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Pacientes con mastografía tomada en el periodo.' };
|
||||
return { state: 'Disponible', value, info: 'Conteo de pacientes únicos en el periodo.' };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
|
||||
@@ -62,6 +62,9 @@ export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boo
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresMemory {
|
||||
private readonly manuallyApplied = new Set<Dominio>();
|
||||
initialKpiPresentation(domain: Dominio) { return !this.manuallyApplied.has(domain); }
|
||||
finishInitialKpiPresentation(domain: Dominio) { this.manuallyApplied.add(domain); }
|
||||
private readonly pinnedIndicators = signal<ReadonlySet<string>>(new Set());
|
||||
isPinned(domain: Dominio, indicador: string) {
|
||||
return this.pinnedIndicators().has(JSON.stringify([domain, indicador]));
|
||||
|
||||
@@ -96,6 +96,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const url = TestBed.inject(Router).url;
|
||||
http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' }));
|
||||
http.verify(); TestBed.resetTestingModule();
|
||||
harness = await setup();
|
||||
const restarted = await harness.navigateByUrl(url, IndicadoresPage);
|
||||
|
||||
@@ -14,25 +14,24 @@
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||
<p class="section-description">La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()"
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialKpiPresentation"
|
||||
(retryAvailability)="retryAvailability()"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
</section>
|
||||
}
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados{{ dominio === 'tea' ? ' — Vista preliminar' : '' }}</h2>
|
||||
<p class="section-description">{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Todos con reporte muestra el último periodo disponible de cada indicador. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.' }}</p>
|
||||
<div class="kpi-grid">
|
||||
@if (dominio === 'tea') {
|
||||
@for (preview of kpiPreviewsByDomain.tea; track preview.id) { <app-indicador-kpi-card [title]="preview.title" /> }
|
||||
} @else {
|
||||
@for (definition of kpisByDomain[dominio]; track dominio + ':' + definition.id) {
|
||||
@let kpis = availableKpis;
|
||||
@if (kpis.length) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados</h2>
|
||||
<p class="section-description">La vista inicial busca el último dato visible de cada indicador. Al aplicar Todos con reporte se toma el último reporte disponible. Un periodo explícito consulta ese periodo; varios periodos no se consolidan.</p>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [catalogPending]="catalogLoading() || !!catalogError()" />
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="initialKpiPresentation" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||
<div class="catalog-heading">
|
||||
|
||||
@@ -21,7 +21,7 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.catalog-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
|
||||
.search-result { color: var(--mat-sys-on-surface-variant); font: var(--mat-sys-body-medium); text-align: right;
|
||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
nav {
|
||||
@@ -54,4 +54,4 @@ nav a[aria-current='page'] {
|
||||
|
||||
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid:has(app-indicador-kpi-panel) { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
@@ -32,7 +32,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
afterEach(() => { http.match(r => r.url.endsWith('/datos')).forEach(r => r.flush('missing', { status: 404, statusText: 'Not Found' })); fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
@@ -43,34 +43,26 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); }
|
||||
function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; }
|
||||
|
||||
it.each(['tea'] as const)('D.1 muestra dos KPI pendientes propios de %s fuera del catálogo', domain => {
|
||||
if (domain !== 'tea') {
|
||||
const initial = http.expectOne('/tea/indicadores');
|
||||
page.changeDominio(domain); expect(initial.cancelled).toBe(true);
|
||||
}
|
||||
fixture.detectChanges();
|
||||
const section = fixture.nativeElement.querySelector('.kpi-section') as HTMLElement;
|
||||
expect(section.dataset['domain']).toBe(domain);
|
||||
expect(section.querySelector('h2')?.textContent).toBe('Indicadores destacados — Vista preliminar');
|
||||
expect(section.textContent).toContain('Muestra visual de ' + page.domainLabels[domain]);
|
||||
const kpis = section.querySelectorAll('app-indicador-kpi-card');
|
||||
expect(Array.from(kpis).map(kpi => kpi.querySelector('h3')?.textContent)).toEqual(['Indicador destacado 1', 'Indicador destacado 2']);
|
||||
expect(Array.from(kpis).map(kpi => kpi.querySelector('.kpi-state')?.textContent)).toEqual(['Pendiente de definición', 'Pendiente de definición']);
|
||||
expect(section.querySelector('.value, button, input, app-plotly-chart')).toBeNull();
|
||||
expect(section.textContent).not.toContain('publicados');
|
||||
load([], domain); expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
|
||||
http.expectNone(() => true);
|
||||
it('KPI-DYNAMIC TEA no deja sección, encabezado, tarjetas ni grid residual', () => {
|
||||
load();
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section, #kpi-section-title, .kpi-grid, app-indicador-kpi-card')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Indicadores destacados');
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('D.1 conserva KPI durante carga, error, reintento y catálogo vacío sin HTTP propio', () => {
|
||||
it('KPI-DYNAMIC distingue carga, error y catálogo vacío confirmado', () => {
|
||||
fixture.detectChanges();
|
||||
const kpis = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'));
|
||||
expect(kpis).toHaveLength(2);
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Cargando catálogo');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles');
|
||||
http.expectOne('/tea/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges();
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
|
||||
page.retryCatalog(); fixture.detectChanges();
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
|
||||
load([]); expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card'))).toEqual(kpis);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-count')).toBeNull(); http.expectNone(() => true);
|
||||
expect(page.catalogError()).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('[role="alert"]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog(); fixture.detectChanges(); load([]);
|
||||
expect(page.catalogLoading()).toBe(false); expect(page.catalogError()).toBe('');
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-section')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('D.1 separa secciones y conserva tarjetas, orden, identidades y figuras dentro del grid', () => {
|
||||
load(); const before = cards();
|
||||
@@ -79,7 +71,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
expect(grid.children).toHaveLength(2);
|
||||
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
|
||||
const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf<HTMLElement>;
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']);
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
|
||||
toggle(0); toggle(1); flushAll();
|
||||
|
||||
@@ -13,19 +13,18 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard, IndicadorKpiPanel, IndicadorPeriodFilters],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorPeriodFilters],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -171,10 +170,8 @@ export class IndicadoresPage {
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
readonly kpisByDomain = KPI_BY_DOMAIN;
|
||||
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
|
||||
// TEA has no approved KPI definitions; its previews never request data.
|
||||
readonly kpiPreviewsByDomain: { tea: readonly { id: string; title: string }[] } = {
|
||||
tea: [{ id: 'preview-1', title: 'Indicador destacado 1' }, { id: 'preview-2', title: 'Indicador destacado 2' }],
|
||||
};
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio]; }
|
||||
get initialKpiPresentation() { return !!this.availableKpis.length && this.memory.initialKpiPresentation(this.dominio); }
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly searchQuery = signal('');
|
||||
@@ -207,7 +204,12 @@ export class IndicadoresPage {
|
||||
filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); }
|
||||
applyFilters() {
|
||||
this.evaluateVisibility();
|
||||
if (!this.filters || !applyGlobal(this.filters, this.filterTypes())) return;
|
||||
if (!this.filters) return;
|
||||
const draft = this.filters.editors[this.filters.tipo]?.draft;
|
||||
if (!draft || !validDraft(draft, this.filters.tipo, this.filterTypes())) return;
|
||||
const initial = this.initialKpiPresentation;
|
||||
this.memory.finishInitialKpiPresentation(this.dominio);
|
||||
if (!applyGlobal(this.filters, this.filterTypes()) && !initial) return;
|
||||
this.filtersEdited();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
|
||||
@@ -56,8 +56,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
expect(fixture.componentInstance.filters!.applied.revision).toBe(0);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('supresión del último no busca periodos anteriores ni sustituye cifras', () => {
|
||||
it('tras Aplicar Todos, supresión del último no busca periodos anteriores ni sustituye cifras', () => {
|
||||
load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2']));
|
||||
const initial = http.match(r => r.url.endsWith('/datos'));
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
expect(initial.every(r => r.cancelled)).toBe(true);
|
||||
const requests = flushDatos('cacu', true);
|
||||
expect(requests.every(r => r.request.params.get('periodos') === '2026-S2')).toBe(true);
|
||||
expect(panels().every(p => p.result().state === 'Dato oculto por tamaño' && p.result().value === undefined)).toBe(true);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { HttpClient } from '@angular/common/http';
|
||||
import { catchError, from, map, mergeMap, Observable, of, shareReplay, toArray } from 'rxjs';
|
||||
import { Dominio, Indicador, parsePeriodos, requireDominio, TipoPeriodo } from './indicadores.models';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresRequests } from './indicadores-requests';
|
||||
|
||||
export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; }
|
||||
export interface PeriodAvailability {
|
||||
@@ -39,6 +40,7 @@ export function parseAvailability(value: unknown, id: string): AvailablePeriod[]
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresPeriodos {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly requests = inject(IndicadoresRequests);
|
||||
// Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached.
|
||||
private readonly cache = new Map<string, Observable<AvailablePeriod[]>>();
|
||||
periodos(domain: Dominio, id: string) {
|
||||
@@ -46,7 +48,7 @@ export class IndicadoresPeriodos {
|
||||
const key = JSON.stringify([dominio, id]);
|
||||
let request = this.cache.get(key);
|
||||
if (!request) {
|
||||
request = this.http.get<unknown>(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`).pipe(
|
||||
request = this.requests.run(() => this.http.get<unknown>(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`)).pipe(
|
||||
map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true }));
|
||||
this.cache.set(key, request);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { defer, finalize, Observable, Subscription } from 'rxjs';
|
||||
|
||||
// Shared by availability and KPI data; figure requests retain their existing lifecycle.
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresRequests {
|
||||
private active = 0;
|
||||
private readonly queue: (() => void)[] = [];
|
||||
run<T>(request: () => Observable<T>): Observable<T> {
|
||||
return new Observable<T>(subscriber => {
|
||||
let started = false;
|
||||
let subscription: Subscription | undefined;
|
||||
const start = () => {
|
||||
started = true;
|
||||
this.active++;
|
||||
subscription = defer(request).pipe(finalize(() => {
|
||||
this.active--;
|
||||
this.drain();
|
||||
})).subscribe(subscriber);
|
||||
};
|
||||
if (this.active < 4) start();
|
||||
else this.queue.push(start);
|
||||
return () => {
|
||||
if (!started) {
|
||||
const index = this.queue.indexOf(start);
|
||||
if (index >= 0) this.queue.splice(index, 1);
|
||||
}
|
||||
subscription?.unsubscribe();
|
||||
};
|
||||
});
|
||||
}
|
||||
private drain() {
|
||||
while (this.active < 4 && this.queue.length) this.queue.shift()!();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user