diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss
index 292f360..fe52754 100644
--- a/src/app/features/indicadores/indicadores-page.scss
+++ b/src/app/features/indicadores/indicadores-page.scss
@@ -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)); } }
diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts
index 4b0f265..0dc65d8 100644
--- a/src/app/features/indicadores/indicadores-page.spec.ts
+++ b/src/app/features/indicadores/indicadores-page.spec.ts
@@ -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;
- 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();
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts
index 3375ef2..90fbfdc 100644
--- a/src/app/features/indicadores/indicadores-page.ts
+++ b/src/app/features/indicadores/indicadores-page.ts
@@ -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 = { 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();
readonly catalog = signal([]);
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();
}
diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts
index 6256449..a02b251 100644
--- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts
+++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts
@@ -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);
diff --git a/src/app/features/indicadores/indicadores-periodos.ts b/src/app/features/indicadores/indicadores-periodos.ts
index fc4031b..f5fca93 100644
--- a/src/app/features/indicadores/indicadores-periodos.ts
+++ b/src/app/features/indicadores/indicadores-periodos.ts
@@ -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>();
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(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`).pipe(
+ request = this.requests.run(() => this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`)).pipe(
map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true }));
this.cache.set(key, request);
}
diff --git a/src/app/features/indicadores/indicadores-requests.ts b/src/app/features/indicadores/indicadores-requests.ts
new file mode 100644
index 0000000..f96a7db
--- /dev/null
+++ b/src/app/features/indicadores/indicadores-requests.ts
@@ -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(request: () => Observable): Observable {
+ return new Observable(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()!();
+ }
+}