diff --git a/src/app/features/indicadores/indicador-catalog-card.spec.ts b/src/app/features/indicadores/indicador-catalog-card.spec.ts index 6ac8bd9..0327366 100644 --- a/src/app/features/indicadores/indicador-catalog-card.spec.ts +++ b/src/app/features/indicadores/indicador-catalog-card.spec.ts @@ -16,11 +16,12 @@ describe('UX-06E.D.2.1 selector de representación', () => { let http: HttpTestingController; const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 }; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); create(['f', 'g']); }); - afterEach(() => { fixture.destroy(); http.verify(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function create(figuras: string[], domain = 'cacu') { fixture = TestBed.createComponent(IndicadorCatalogCard); fixture.componentRef.setInput('dominio', domain); @@ -28,9 +29,9 @@ describe('UX-06E.D.2.1 selector de representación', () => { fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges(); } function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).filter(e => e.componentInstance.result().status !== 'deferred'); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); } - function open() { fixture.componentInstance.toggle(); fixture.detectChanges(); } + function open() { fixture.componentInstance.setVisible(true); fixture.detectChanges(); } it('una opción publicada está deshabilitada y sólo consulta esa figura', () => { fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true); expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true); @@ -45,20 +46,21 @@ describe('UX-06E.D.2.1 selector de representación', () => { request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges(); expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true); }); - it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva apertura diferida', () => { + it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva carga diferida', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']); - expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.awaitingFigures).toBe(true); http.expectNone(() => true); - fixture.componentInstance.activateVisible(); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); + expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.visible).toBe(false); http.expectNone(() => true); + fixture.componentInstance.setVisible(true); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f'); fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f'); }); - it('cambio de aplicado conserva elección y consulta sólo su representación; cierre manual prevalece', () => { + it('cambio de aplicado conserva elección y consulta sólo su representación; fuera de vista cancela revisión obsoleta', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} }); fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges(); const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f')); - fixture.componentInstance.toggle(); fixture.detectChanges(); expect(current.cancelled).toBe(true); - fixture.componentInstance.activateVisible(); fixture.detectChanges(); expect(panels()).toHaveLength(0); http.expectNone(() => true); + fixture.componentInstance.setVisible(false); fixture.detectChanges(); + fixture.componentRef.setInput('applied', { ...applied, revision: 3 }); fixture.detectChanges(); expect(current.cancelled).toBe(true); + expect(panels()).toHaveLength(0); http.expectNone(() => true); }); it('opciones ajenas al catálogo y selección repetida no consultan', () => { open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); @@ -66,7 +68,7 @@ describe('UX-06E.D.2.1 selector de representación', () => { }); }); -it('C2 sin magnitudes mantiene nota de supresión del servicio fuera del host Plotly y no cambia trazas', () => { +it('C2 sin magnitudes elimina la copia HTML de la nota y no cambia trazas Plotly', () => { TestBed.configureTestingModule({ imports: [IndicadorFigureCard] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); const fixture = TestBed.createComponent(IndicadorFigureCard); @@ -74,7 +76,7 @@ it('C2 sin magnitudes mantiene nota de supresión del servicio fuera del host Pl fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) }); fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] }); fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges(); - expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]').textContent).toContain('Valores ocultos por supresión.'); + expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores'); expect(figure.data[0].values).toEqual([null, null]); fixture.destroy(); }); diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 7da0e6f..4fc63e5 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -1,4 +1,3 @@ -import { DOCUMENT } from '@angular/common'; import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; @@ -6,7 +5,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; import { MatIconModule } from '@angular/material/icon'; import { Dominio, Indicador, Tema } from './indicadores.models'; -import { CardActivation, GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities'; import { IndicadorFigurePanel } from './indicador-figure-panel'; @@ -15,26 +14,20 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel], template: ` -
+

{{ indicador.titulo }}

{{ indicador.id }}

-
-
- @if (awaitingFigures) { - - } @else if (expanded && figuresActivated) { - - @if (selectedFigure) { +
+ + @if (selectedFigure) { Representación gráfica {{ figure }} } +
@for (figure of [selectedFigure]; track panelIdentity(figure)) { - + } - } @else {

El indicador no tiene figuras disponibles.

} - } +
+ } @else {

El indicador no tiene figuras disponibles.

}
`, @@ -54,12 +48,12 @@ import { IndicadorFigurePanel } from './indicador-figure-panel'; :host { display: block; min-width: 0; margin: var(--issste-space-4) 0; } mat-card { padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } - header { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: start; gap: var(--issste-space-3); } + header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } + .graphic-region { min-height: 620px; } .card-identity { min-width: 0; } h2, p { overflow-wrap: anywhere; } h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; } .indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } - header button { justify-self: end; flex-shrink: 0; min-width: 48px; min-height: 48px; color: var(--issste-text); } .pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto; min-width: 48px; min-height: 48px; color: var(--issste-text); } .pin-toggle mat-icon { flex-shrink: 0; } @@ -77,20 +71,12 @@ export class IndicadorCatalogCard implements OnChanges { @Input({ required: true }) applied!: GlobalApplied; @Input() pinned = false; readonly pinChanged = output(); - @ViewChild('visibilityHeader', { static: true }) visibilityHeader!: ElementRef; + @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; readonly host = inject>(ElementRef); - readonly activationChanged = output(); - @ViewChild('toggleButton', { read: ElementRef }) toggleButton!: ElementRef; - @ViewChild('content') content!: ElementRef; private readonly changeDetector = inject(ChangeDetectorRef); private readonly memory = inject(IndicadoresMemory); - private readonly document = inject(DOCUMENT); private identity = ''; - private state: CardActivation = 'pending'; - figuresActivated = false; - get expanded() { return this.state === 'auto-open' || this.state === 'manual-open'; } - get awaitingFigures() { return this.expanded && !this.figuresActivated; } - get awaitingVisibility() { return this.state === 'pending' || this.awaitingFigures; } + visible = false; titleId = ''; contentId = ''; panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); } @@ -110,29 +96,11 @@ export class IndicadorCatalogCard implements OnChanges { const id = identityElementId(identity); this.titleId = id + '-title'; this.contentId = id + '-content'; - this.state = this.memory.activation(this.dominio, this.indicador.id); - this.figuresActivated = false; + this.visible = false; } - activateVisible() { - // Recheck the decision at commit time, including manual changes after observation. - if (!this.awaitingVisibility) return; - if (this.state === 'pending') { - this.state = 'auto-open'; - this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); - } - this.figuresActivated = true; - this.changeDetector.markForCheck(); - } - toggle() { - if (this.expanded && !this.awaitingFigures && this.content.nativeElement.contains(this.document.activeElement)) { - this.toggleButton.nativeElement.focus(); - } - // A restored open preference first shows its figures; the next click closes. - const opening = !this.expanded || this.awaitingFigures; - this.state = opening ? 'manual-open' : 'manual-closed'; - this.figuresActivated = opening; - this.memory.rememberActivation(this.dominio, this.indicador.id, this.state); - this.activationChanged.emit(); + setVisible(visible: boolean) { + if (this.visible === visible) return; + this.visible = visible; this.changeDetector.markForCheck(); } } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 51d2a46..e295488 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -1,28 +1,26 @@ @if (selected) { -
-

Cómo leer esta figura · {{ selected?.contrato }}

-
    - @for (line of visibleInterpretation; track $index) {
  • {{ line }}
  • } -
- @if (methodologyDetail.length) { - -
- @for (line of methodologyDetail; track $index) {

{{ line }}

} -
- } -

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
+ +
+
    + @for (line of interpretation; track $index) {
  • {{ line }}
  • } +
+

Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.

+
} @if (state.status === 'loading') { -

Cargando figura…

+

Cargando figura…

+ } @else if (state.status === 'deferred') { +

{{ state.message }}

} @else if (state.status === 'incompatible') {

Filtro general incompatible con esta figura.

{{ state.message }}

} @else if (state.status === 'error') { @@ -32,12 +30,6 @@ @if (hasNoVisibleValues(figure)) {

No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.

} - @if (serviceNotes.length) { -
-

Notas de la figura

- @for (note of serviceNotes; track $index) {

} -
- }

Figura: {{ figuraId }}

} @else { diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 0faff13..ac364c4 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -1,19 +1,20 @@ :host { display: block; min-width: 0; } .interpretation { - padding: var(--issste-space-4); margin-bottom: var(--issste-space-4); - border-left: 3px solid var(--issste-accent); color: var(--issste-text); font-family: var(--issste-font-body); line-height: 1.5; overflow-wrap: anywhere; } -.interpretation h2 { margin: 0 0 .5rem; font-family: var(--issste-font-heading); font-size: 1.125rem; } +.methodology-detail { + margin-top: var(--issste-space-3); + padding: var(--issste-space-4); + border-left: 3px solid var(--issste-accent); +} .interpretation ul { margin: 0; padding-left: 1.25rem; } .interpretation li + li { margin-top: .25rem; } .period-note { margin: .75rem 0 0; color: var(--issste-text-secondary); } .methodology-toggle { margin-top: var(--issste-space-3); min-height: 44px; max-width: 100%; height: auto; white-space: normal; } -.methodology-detail { margin-top: var(--issste-space-3); } .methodology-detail p { margin: 0; } .methodology-detail p + p { margin-top: var(--issste-space-2); } .methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } @@ -22,8 +23,11 @@ .state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; } .dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; } .figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; } -@media (max-width: 550px) { .interpretation { padding: var(--issste-space-3); } } +@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; } + +.figure-skeleton { min-height: 620px; display: flex; flex-direction: column; } +.skeleton { flex: 1; margin: 0 1.25rem 1.25rem; border-radius: var(--issste-radius); background: var(--issste-border); opacity: .35; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index 5a80856..80640b2 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -130,53 +130,70 @@ describe('IndicadorFigureCard', () => { expect(purge).toHaveBeenCalledWith(firstHost); expect(purge).toHaveBeenCalledTimes(1); expect(disconnect).toHaveBeenCalledTimes(1); }); - it('UX-06E.B1 integra composición y detalle complementario local C2 y mantiene advertencias visibles', () => { + it('UX-06E.P0.2 inicia cerrado y despliega toda la explicación con estado accesible', () => { fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); state({ status: 'idle' }); const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; - expect(section.querySelector('ul')?.textContent).not.toContain('Las barras muestran la composición porcentual'); + expect(section.textContent).toContain('Cómo leer'); + expect(section.querySelector('h2')).toBeNull(); + expect(section.classList.contains('expanded')).toBe(false); + expect(section.querySelector('.methodology-detail ul')).not.toBeNull(); + expect(section.querySelector('ul')?.closest('[hidden]')).not.toBeNull(); expect(section.querySelectorAll('button')).toHaveLength(1); expect(section.querySelectorAll('[hidden]')).toHaveLength(1); - expect(section.querySelector('ul')?.textContent).toContain('SIN_DATO'); - expect(section.querySelector('ul')?.textContent).toContain('suprimidos no representan tasas'); - expect(section.querySelector('.period-note')?.textContent).toContain('no permite determinar la disponibilidad'); const button = section.querySelector('button')!; const detail = section.querySelector('[id]') as HTMLElement; expect(button.getAttribute('aria-expanded')).toBe('false'); expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual([ - 'Las barras muestran la composición porcentual de cada grupo y periodo.', - 'Las categorías corresponden a la distribución de cada grupo y periodo.', - ]); - expect([...section.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.visibleInterpretation); + expect(button.tagName).toBe('BUTTON'); + expect(button.nextElementSibling?.classList.contains('methodology-detail')).toBe(true); + button.focus(); + expect(document.activeElement).toBe(button); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('suprimidos no representan tasas'); + expect(detail.textContent).toContain('no permite determinar la disponibilidad'); + expect([...detail.querySelectorAll('li')].map(li => li.textContent)).toEqual(fixture.componentInstance.interpretation); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(false); expect(button.getAttribute('aria-expanded')).toBe('true'); state({ status: 'loading' }); expect(detail.hidden).toBe(false); button.click(); fixture.detectChanges(); expect(detail.hidden).toBe(true); + expect(section.querySelector('.methodology-detail[hidden]')).toBe(detail); }); - it.each(['fig_c3r_cajas', 'desconocida'])('UX-06D mantiene íntegra la interpretación %s sin separación insegura', figura => { + it('UX-06E.P0.2 muestra el contenido de la figura seleccionada al cambiarla', () => { + fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); + state({ status: 'idle' }); + const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; + button.click(); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('composición porcentual'); + fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); + fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('.methodology-detail').textContent).toContain('La caja representa Q1'); + expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-controls')) + .toBe(fixture.nativeElement.querySelector('.methodology-detail').id); + }); + it.each(['fig_c3r_cajas', 'desconocida'])('UX-06E.P0.2 mantiene íntegra la interpretación %s dentro de la ayuda', figura => { fixture.componentRef.setInput('figuraId', figura); if (figura === 'desconocida') fixture.componentRef.setInput('selected', { ...selected, contrato: 'desconocido' }); state({ status: 'idle' }); - expect(fixture.nativeElement.querySelector('.methodology-toggle')).toBeNull(); - expect([...fixture.nativeElement.querySelectorAll('.interpretation li')].map((li: any) => li.textContent)) + expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); + expect([...fixture.nativeElement.querySelectorAll('.methodology-detail li')].map((li: any) => li.textContent)) .toEqual(fixture.componentInstance.interpretation); }); - it.each(['cacu', 'cama'])('UX-06E.B1 conserva advertencias C2 de %s y pliega solo composición', dominio => { + it.each(['cacu', 'cama'])('UX-06E.P0.2 conserva advertencias C2 de %s en ayuda cerrada', dominio => { fixture.componentRef.setInput('dominio', dominio); fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); state({ status: 'loading' }); expect(fixture.nativeElement.querySelector('.methodology-toggle')).not.toBeNull(); const detail = fixture.nativeElement.querySelector('[hidden]') as HTMLElement; expect(detail.hidden).toBe(true); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual(['Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.']); - expect(fixture.nativeElement.querySelector('.interpretation > ul').textContent).toContain('SIN_DATO'); - expect(fixture.nativeElement.querySelector('.interpretation > ul').textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); + expect(detail.textContent).toContain('Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.'); + expect(detail.textContent).toContain('SIN_DATO'); + expect(detail.textContent).toContain('nulos o suprimidos no representan porcentajes observados de 0 %'); }); - it('UX-06D conserva completas todas las anotaciones, sin clasificar ni plegar notas del backend', async () => { + it('UX-06E.P0.2 quita el panel redundante y preserva todas las anotaciones en Plotly', async () => { const figure: PlotlyFigure = { data: [{ y: [null, 0] }], layout: { annotations: [ { text: 'Denominador pequeño
Intervalos no disponibles' }, { text: 'Uso exclusivo de investigación. No usar para decisiones clínicas.' }, @@ -184,12 +201,26 @@ describe('IndicadorFigureCard', () => { ] }, frames: [] }; const snapshot = JSON.stringify(figure); ready(figure); await settle(); - const notes = fixture.nativeElement.querySelector('.notes') as HTMLElement; - expect(notes.closest('[hidden]')).toBeNull(); - expect([...notes.querySelectorAll('p')].map(p => p.innerHTML)).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.figure.layout['annotations']).toEqual(figure.layout['annotations']); + expect(chart.notes).toEqual((figure.layout['annotations'] as { text: string }[]).map(a => a.text)); expect(JSON.stringify(figure)).toBe(snapshot); expect(fixture.nativeElement.querySelector('.plot-viewport')?.getAttribute('tabindex')).toBe('0'); }); + it.each(['claro', 'oscuro'] as const)('UX-06E.P0.2 conserva el tema %s sin duplicar anotaciones en HTML', async tema => { + fixture.componentRef.setInput('tema', tema); + const annotation = 'Advertencia metodológica única de la figura.'; + const original: PlotlyFigure = { data: [{ y: [1] }], layout: { annotations: [{ text: annotation }] } }; + ready(original); await settle(); + const card = fixture.nativeElement.querySelector('.figure-card'); + expect(card.classList.contains('dark')).toBe(tema === 'oscuro'); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain(annotation); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; + expect(chart.notes).toEqual([annotation]); + expect(JSON.stringify(original)).toContain(annotation); + }); it('UX-06D mantiene relaciones de detalle únicas incluso con separadores en IDs publicados', () => { fixture.componentRef.setInput('selected', { ...selected, contrato: 'C2', id: 'a--b' }); fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas'); @@ -219,8 +250,8 @@ describe('IndicadorFigureCard', () => { expect(button.getAttribute('aria-label')).toBe('Cómo leer esta figura: Indicador de prueba · ' + dominio + ' · fig_c1_puntos'); expect(button.getAttribute('aria-expanded')).toBe('false'); expect(button.getAttribute('aria-controls')).toBe(detail.id); expect(detail.hidden).toBe(true); - const warnings = section.querySelector('ul')!; - expect(warnings.closest('[hidden]')).toBeNull(); + const warnings = detail.querySelector('ul')!; + expect(warnings.closest('[hidden]')).not.toBeNull(); expect(warnings.textContent).toContain('100 % no implica certeza poblacional'); expect(warnings.textContent).toContain('suprimidos no representan tasas observadas de 0 %'); if (dominio === 'tea') { @@ -228,8 +259,7 @@ describe('IndicadorFigureCard', () => { expect(warnings.textContent).toContain('No se infieren intervalos cuando faltan'); expect(warnings.textContent).toContain('denominadores pequeños'); } else expect(warnings.textContent).toContain('no entregan intervalos Wilson efectivos'); - expect([...detail.querySelectorAll('p')].map(p => p.textContent)).toEqual([fixture.componentInstance.interpretation[0]]); - expect([...detail.querySelectorAll('p'), ...warnings.querySelectorAll('li')].map(p => p.textContent)) + expect([...warnings.querySelectorAll('li')].map(p => p.textContent)) .toEqual(fixture.componentInstance.interpretation); button.focus(); button.click(); fixture.detectChanges(); expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(false); @@ -237,31 +267,30 @@ describe('IndicadorFigureCard', () => { button.click(); fixture.detectChanges(); expect(document.activeElement).toBe(button); expect(detail.hidden).toBe(true); }); - it('UX-06E.B1 mantiene la oración mixta C3r y todos sus límites visibles', () => { + it('UX-06E.P0.2 mantiene la oración mixta C3r y sus límites en ayuda cerrada', () => { fixture.componentRef.setInput('figuraId', 'fig_c3r_cajas'); state({ status: 'idle' }); const section = fixture.nativeElement.querySelector('.interpretation') as HTMLElement; - expect(section.querySelector('[hidden]')).toBeNull(); - expect(section.querySelector('button')).toBeNull(); - expect([...section.querySelectorAll('li')].map(p => p.textContent)).toEqual([ + expect(section.querySelector('[hidden]')).not.toBeNull(); + expect(section.querySelector('button')).not.toBeNull(); + expect([...section.querySelectorAll('.methodology-detail li')].map(p => p.textContent)).toEqual([ 'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.', 'Los límites de dibujo no representan necesariamente extremos observados.', 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', 'Los puntos suprimidos no representan tasas observadas de 0 %.', ]); }); - it('UX-06E.B1 al alternar ayuda conserva Plotly, JSON, notas y observadores sin react ni purge', async () => { + it('UX-06E.P0.2 al alternar ayuda conserva Plotly, JSON y observadores sin react ni purge', async () => { const original: PlotlyFigure = { data: [{ y: [42, null] }], layout: { annotations: [{ text: 'Advertencia íntegra del servicio' }] } }; const copy = ready(original); await settle(); const snapshot = JSON.stringify(original), copySnapshot = JSON.stringify(copy); const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance; - const host = fixture.nativeElement.querySelector('.plot'), notes = fixture.nativeElement.querySelector('.notes'); + const host = fixture.nativeElement.querySelector('.plot'); const button = fixture.nativeElement.querySelector('.methodology-toggle'); const calls = react.mock.calls.length, observers = observe.mock.calls.length; for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); await settle(); } expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); expect(fixture.nativeElement.querySelector('.plot')).toBe(host); - expect(fixture.nativeElement.querySelector('.notes')).toBe(notes); - expect(notes.closest('[hidden]')).toBeNull(); + expect(fixture.nativeElement.querySelector('.notes')).toBeNull(); expect(react).toHaveBeenCalledTimes(calls); expect(observe).toHaveBeenCalledTimes(observers); expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled(); expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index 3f71dfc..b5eb099 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -10,7 +10,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; // The panel owns requests; the card receives the original and its presentation copy. export interface FigureState { - status: 'idle' | 'loading' | 'ready' | 'error' | 'incompatible'; + status: 'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string; @@ -35,7 +35,7 @@ const CONTRACT_INTERPRETATIONS: Readonly> = { 'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.', ], }; -const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.']; +const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las anotaciones de Plotly; no se infiere su significado estadístico.']; @Component({ selector: 'app-indicador-figure-card', @@ -81,11 +81,6 @@ export class IndicadorFigureCard { get visibleInterpretation(): readonly string[] { return this.interpretation.slice(this.complementaryLineCount); } - get serviceNotes(): string[] { - const annotations = this.state.figure?.layout['annotations']; - return Array.isArray(annotations) ? annotations.flatMap(note => - note && typeof note.text === 'string' ? [note.text] : []) : []; - } readonly hasNoVisibleValues = hasNoVisibleValues; readonly figureTitle = figureTitle; diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 338482c..b605e7b 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -1,4 +1,4 @@ -import { Component, DestroyRef, inject, Input, OnChanges, signal, SimpleChanges } from '@angular/core'; +import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs'; @@ -37,6 +37,7 @@ export class IndicadorFigurePanel implements OnChanges { @Input({ required: true }) figuraId!: string; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>(); @@ -62,16 +63,31 @@ export class IndicadorFigurePanel implements OnChanges { if (generation === this.generation && revision === this.applied?.revision) this.result.set(state); }); } - ngOnChanges(changes: SimpleChanges) { + ngOnChanges() { const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); this.titleId = identityElementId(identity) + '-title'; - const key = JSON.stringify([identity, this.tema, this.applied?.revision, this.applied && selectionKey(this.applied)]); - if (key !== this.currentKey || changes['indicador']) { - this.currentKey = key; - this.requestFigure(); + const key = this.requestKey(); + if (key === this.currentKey) return; + if (this.visible) this.requestFigure(); + else { + // Cancel stale work immediately but retain the panel and its Plotly host. + const message = this.generation === 0 + ? 'Figura pendiente: se cargará al acercarse a esta región.' + : 'Actualización pendiente: se consultará al volver a esta región.'; + this.generation++; + this.figureRequests.next(null); + this.currentKey = ''; + this.result.set({ status: 'deferred', message }); } } + private requestKey() { + return JSON.stringify([figureIdentity(this.dominio, this.indicador.id, this.figuraId), + this.tema, this.applied?.revision, this.applied && selectionKey(this.applied), + this.indicador.tipos_periodo, this.indicador.figuras.includes(this.figuraId)]); + } requestFigure() { + if (!this.visible) return; + this.currentKey = this.requestKey(); const applied = this.applied; const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo); this.generation++; diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 0bad38d..8cb546a 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -20,6 +20,7 @@ describe('KPI integración con autoridad global', () => { function load(domain: Dominio, missing = false) { 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' }] }); fixture.detectChanges(); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); } diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts index 6c7cc5b..ac78114 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -7,6 +7,7 @@ import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } fro import { IndicadoresService } from './indicadores.service'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi'; +import { PeriodAvailability, sortedPeriods } from './indicadores-periodos'; import { httpMessage } from './indicadores-http'; @Component({ @@ -22,32 +23,48 @@ export class IndicadorKpiPanel implements OnChanges { @Input({ required: true }) definition!: KpiDefinition; @Input() indicador?: Indicador; @Input() applied?: GlobalApplied; + @Input() availability?: PeriodAvailability; @Input() catalogPending = false; private readonly service = inject(IndicadoresService); private readonly destroyRef = inject(DestroyRef); private readonly requests = new Subject(); private key = ''; + readonly usedPeriod = signal(undefined); readonly result = signal({ state: 'Esperando catálogo' }); - get temporalReference() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'; } + get temporalReference() { return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'); } constructor() { this.requests.pipe(switchMap(() => { 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 (!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.' }); - return defer(() => this.service.datos(domain, definition.id, applied.tipo, - applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined)).pipe( - map(data => ({ ...kpiResult(data, definition, domain, applied), notes: data.notas })), + let resolved = applied; + if (applied.selection.mode === 'todos') { + 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)); } 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.catalogPending, 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; this.requests.next(); diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 2341c9f..5aa1025 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -22,13 +22,24 @@ Periodos seleccionados {{ selectedPeriods.join(', ') }} - @for (period of entry.added; track period) { {{ period }} } + @for (period of options; track period) { {{ period }} } + @if (availability) { + @for (period of unavailableSelection; track period) { {{ period }} — disponibilidad no confirmada } + } - Disponibilidad desconocida hasta consultar. + {{ availability ? 'Existe reporte en al menos un indicador del dominio; la cobertura puede variar.' : 'Disponibilidad desconocida hasta consultar.' }} }
-@if (entry.draft.mode !== 'todos') { +@if (availability) { + @if (availability.status === 'loading') {

Consultando periodos disponibles…

} + @else if (availability.status === 'error') { +

No se pudo completar la consulta de periodos disponibles.

+ + } @else if (!options.length) {

Sin reportes disponibles para esta granularidad.

} + @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {

La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.

} +} +@if (!availability && entry.draft.mode !== 'todos') {

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

Año diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts index e05d478..1dd7369 100644 --- a/src/app/features/indicadores/indicador-period-filters.ts +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -5,6 +5,7 @@ import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; import { parsePeriodos, TipoPeriodo } from './indicadores.models'; +import { PeriodAvailability } from './indicadores-periodos'; import { describePeriods, newEditor, FilterState, pending, validDraft } from './indicadores-memory'; @Component({ @@ -16,6 +17,8 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './ export class IndicadorPeriodFilters implements OnChanges { @Input({ required: true }) state!: FilterState; @Input({ required: true }) types!: TipoPeriodo[]; + @Input() availability?: PeriodAvailability; + @Output() retryAvailability = new EventEmitter(); @Output() edited = new EventEmitter(); @Output() apply = new EventEmitter(); year = ''; @@ -28,7 +31,13 @@ export class IndicadorPeriodFilters implements OnChanges { // Keep the empty multiple-select value stable so an unchanged draft can settle. private readonly emptyPeriods: string[] = []; get selectedPeriods() { return this.entry.draft.mode === 'explicit' ? this.entry.draft.periodos : this.emptyPeriods; } - get canApply() { return validDraft(this.entry.draft, this.state.tipo, this.types); } + get options() { return this.availability ? this.availability.options[this.state.tipo] : this.entry.added; } + get unavailableSelection() { return this.selectedPeriods.filter(p => !this.options.includes(p)); } + get canApply() { + return validDraft(this.entry.draft, this.state.tipo, this.types) + && (!this.availability || this.entry.draft.mode === 'todos' + || (this.availability.status === 'ready' && !this.unavailableSelection.length)); + } get hasPending() { return pending(this.state); } get summary() { return describePeriods(this.state.tipo, this.entry.draft); } get appliedSummary() { return this.state.applied ? describePeriods(this.state.applied.tipo, this.state.applied.selection) : 'Todavía no hay selección aplicada'; } @@ -47,7 +56,7 @@ export class IndicadorPeriodFilters implements OnChanges { } select(values: string[]) { const unique = [...new Set(values)]; - if (unique.some(p => !this.entry.added.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return; + if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return; this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' }; this.edited.emit(); } diff --git a/src/app/features/indicadores/indicadores-global-filters.spec.ts b/src/app/features/indicadores/indicadores-global-filters.spec.ts index 18b18ff..b73cbf3 100644 --- a/src/app/features/indicadores/indicadores-global-filters.spec.ts +++ b/src/app/features/indicadores/indicadores-global-filters.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -21,18 +22,19 @@ describe('D.2 integración de autoridad global y consumidores', () => { let page: IndicadoresPage; let http: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); + 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(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function load(items = [item('a'), item('b')], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } - function open(index = 0) { cards()[index].toggle(); fixture.detectChanges(); } + function open(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(id: string) { return http.expectOne(r => r.url.endsWith('/' + id + '/figuras/f')); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [42, null, 0] }], layout: {} })); fixture.detectChanges(); } function draft(tipo: TipoPeriodo, periods: string[]) { @@ -62,7 +64,7 @@ describe('D.2 integración de autoridad global y consumidores', () => { it('aplicar actualiza todas las activadas sin abrir pendientes ni KPI', () => { load([item('a'), item('b'), item('c')]); open(0); open(1); respond(); const before = cards(); draft('semestre', ['2025-S1']); apply(); - expect(cards()).toEqual(before); expect(cards()[2].expanded).toBe(false); + expect(cards()).toEqual(before); expect(cards()[2].visible).toBe(false); const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); for (const r of requests) { expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); } expect(page.filters!.applied.revision).toBe(1); expect(panels().every(p => p.applied === page.filters!.applied)).toBe(true); @@ -77,20 +79,21 @@ describe('D.2 integración de autoridad global y consumidores', () => { }); it('tarjeta activada después recibe el último aplicado y solo su primera consulta', () => { load(); draft('semestre', ['2025-S2']); apply(); http.expectNone(() => true); - cards()[1].activateVisible(); fixture.detectChanges(); + cards()[1].setVisible(true); fixture.detectChanges(); const r = request('b'); expect(r.request.params.get('periodos')).toBe('2025-S2'); r.flush({ data: [], layout: {} }); - cards()[1].activateVisible(); fixture.detectChanges(); http.expectNone(() => true); + cards()[1].setVisible(true); fixture.detectChanges(); http.expectNone(() => true); }); - it('cierre manual queda protegido al aplicar y reabrir usa aplicado vigente', () => { - load(); open(); respond(); open(); draft('semestre', ['2025-S1']); apply(); - cards()[0].activateVisible(); fixture.detectChanges(); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + it('fuera del viewport difiere aplicado y al volver usa revisión vigente', () => { + load(); open(); respond(); const panel = panels()[0]; + cards()[0].setVisible(false); fixture.detectChanges(); draft('semestre', ['2025-S1']); apply(); + expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); expect(panel.result().status).toBe('deferred'); http.expectNone(() => true); open(); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); }); it('restaurada abierta espera visibilidad y usa revisión vigente al activarse', () => { load(); open(); respond(); page.changeDominio('cacu'); load(undefined, 'cacu'); page.changeDominio('tea'); load(); - expect(cards()[0].awaitingFigures).toBe(true); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true); - cards()[0].activateVisible(); fixture.detectChanges(); + expect(cards()[0].visible).toBe(false); draft('semestre', ['2025-S1']); apply(); http.expectNone(() => true); + cards()[0].setVisible(true); fixture.detectChanges(); expect(panels()[0].applied.revision).toBe(1); const r = request('a'); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush({ data: [], layout: {} }); }); it('mensual compartido consulta compatibles y retira resultado anterior del incompatible', () => { @@ -132,13 +135,13 @@ 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].awaitingFigures).toBe(true); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); http.expectNone(() => true); }); it('catálogo nuevo revalida sin recortar ni sustituir mensual aplicado', () => { load(); draft('mes', ['2025-01']); apply(); open(); respond(); page.retryCatalog(); fixture.detectChanges(); load([item('a', ['semestre'])]); expect(page.filters!.applied.tipo).toBe('mes'); expect(page.filters!.applied.revision).toBe(1); - cards()[0].activateVisible(); fixture.detectChanges(); + cards()[0].setVisible(true); fixture.detectChanges(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true); expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true); editor().changeTipo('semestre'); apply(); request('a').flush({ data: [], layout: {} }); expect(page.filters!.applied.revision).toBe(2); diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index b1b0826..8ef623b 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -25,22 +25,20 @@ describe('D.2 memoria global por dominio', () => { applyGlobal(state, ['semestre']); memory.saveGlobal('tea', state); for (const domain of ['cacu', 'cama'] as const) expect(memory.restoreGlobal(domain, ['semestre']).applied.selection.mode).toBe('todos'); }); - it('mantiene activación por dominio e indicador y tema independiente', () => { - expect(memory.activation('tea', 'i')).toBe('pending'); - memory.rememberActivation('tea', 'i', 'manual-closed'); memory.rememberActivation('cacu', 'i', 'auto-open'); - expect(memory.activation('tea', 'i')).toBe('manual-closed'); expect(memory.activation('cacu', 'i')).toBe('auto-open'); - expect(memory.activation('tea', 'otro')).toBe('pending'); - memory.rememberActivation('cama', 'i', 'manual-open'); expect(memory.activation('cama', 'i')).toBe('manual-open'); + it('mantiene figura por dominio e indicador y tema independiente', () => { + memory.rememberFigure('tea', 'i', 'f'); memory.rememberFigure('cacu', 'i', 'g'); + expect(memory.figure('tea', 'i')).toBe('f'); expect(memory.figure('cacu', 'i')).toBe('g'); + expect(memory.figure('cama', 'i')).toBeUndefined(); memory.rememberTheme('cacu', 'oscuro'); expect(memory.theme('cacu')).toBe('oscuro'); expect(memory.theme('tea')).toBe('claro'); }); it('nueva instancia reinicia memoria sin almacenamiento persistente', () => { const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem'); - memory.rememberTheme('tea', 'oscuro'); memory.rememberActivation('tea', 'i', 'manual-closed'); + memory.rememberTheme('tea', 'oscuro'); const saved = memory.restoreGlobal('tea', ['semestre', 'mes']); saved.tipo = 'mes'; saved.editors.mes!.draft = { mode: 'explicit', periodos: ['2025-01'] }; applyGlobal(saved, ['semestre', 'mes']); memory.saveGlobal('tea', saved); const fresh = new IndicadoresMemory(); - expect(fresh.theme('tea')).toBe('claro'); expect(fresh.activation('tea', 'i')).toBe('pending'); + expect(fresh.theme('tea')).toBe('claro'); expect(fresh.restoreGlobal('tea', ['semestre']).applied.revision).toBe(0); expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); read.mockRestore(); write.mockRestore(); }); diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index 97c58ae..a63dc8c 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -59,7 +59,6 @@ export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boo state.applied = { tipo: state.tipo, selection: structuredClone(draft), revision: state.applied.revision + 1 }; return true; } -export type CardActivation = 'pending' | 'auto-open' | 'manual-open' | 'manual-closed'; @Injectable({ providedIn: 'root' }) export class IndicadoresMemory { @@ -81,16 +80,9 @@ export class IndicadoresMemory { rememberFigure(domain: Dominio, indicador: string, figure: string) { this.figures.set(JSON.stringify([domain, indicador]), figure); } - private readonly expansions = new Map(); private readonly filters = new Map(); theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; } rememberTheme(domain: Dominio, tema: Tema) { this.themes.set(domain, tema); } - activation(domain: Dominio, indicador: string): CardActivation { - return this.expansions.get(JSON.stringify([domain, indicador])) ?? 'pending'; - } - rememberActivation(domain: Dominio, indicador: string, state: CardActivation) { - this.expansions.set(JSON.stringify([domain, indicador]), state); - } saveGlobal(domain: Dominio, state: GlobalFilterState) { this.filters.set(domain, structuredClone(state)); } diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index b158b38..82670bc 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -21,7 +22,8 @@ class ChartStub { figure?: PlotlyFigure; } describe('UX-04 navegación Angular', () => { let http: HttpTestingController; async function setup() { - TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); return RouterTestingHarness.create(); @@ -29,13 +31,15 @@ describe('UX-04 navegación Angular', () => { function load(domain: 'tea' | 'cacu' | 'cama', harness: RouterTestingHarness) { http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]); harness.detectChanges(); + const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; + vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; - if (!card.expanded || card.awaitingFigures) { card.toggle(); harness.detectChanges(); } + if (!card.visible) { card.setVisible(true); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); return req; } - afterEach(() => http.verify()); + afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); it.each(['tea', 'cacu', 'cama'] as const)('navegación %s mantiene tres enlaces, estado, decoración y foco independiente', async domain => { const harness = await setup(); await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); @@ -97,7 +101,7 @@ describe('UX-04 navegación Angular', () => { const restarted = await harness.navigateByUrl(url, IndicadoresPage); const req = load('cacu', harness); expect(TestBed.inject(Router).url).toBe('/indicadores/cacu'); - expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).expanded).toBe(true); + expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).visible).toBe(true); expect(restarted.tema).toBe('claro'); expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.tipo).toBe('semestre'); expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.mes?.draft.mode).toBe('empty'); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 7e1728d..5a68abb 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -14,20 +14,21 @@

Filtros generales de {{ domainLabels[dominio] }}

La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.

-
}

Indicadores destacados{{ dominio === 'tea' ? ' — Vista preliminar' : '' }}

-

{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Valores del filtro general aplicado. Selecciona un único periodo para evitar consolidaciones sin una regla aprobada.' }}

+

{{ 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.' }}

@if (dominio === 'tea') { @for (preview of kpiPreviewsByDomain.tea; track preview.id) { } } @else { @for (definition of kpisByDomain[dominio]; track dominio + ':' + definition.id) { + [applied]="filters?.applied" [availability]="availability()" [catalogPending]="catalogLoading() || !!catalogError()" /> } }
@@ -74,7 +75,7 @@
@for (item of searchResults().items; track cardIdentity(item)) { + [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> }
} diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index 7d053f0..4b0f265 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -20,23 +21,24 @@ import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; class ChartStub { figure?: PlotlyFigure; } const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] }; const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] }; -describe('UX-05B catálogo expandible', () => { +describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + 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(); }); + afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); function load(items: Indicador[] = [item, second], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } - function toggle(index = 0) { cards()[index].toggle(); fixture.detectChanges(); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } + function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } 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; } @@ -83,48 +85,23 @@ describe('UX-05B catálogo expandible', () => { toggle(0); toggle(1); flushAll(); expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]); expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']); - expect(cards()).toEqual(before); expect(cards().every(card => card.expanded)).toBe(true); + expect(cards()).toEqual(before); expect(cards().every(card => card.visible)).toBe(true); http.expectNone(() => true); }); - it('UX-06C: tarjeta contraída contiene solo identidad y flecha decorativa en un botón nativo', () => { - load(); - const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement; - const header = host.querySelector('header')!; - expect(header.querySelector('h2')?.textContent).toBe('Uno'); - expect(header.querySelector('.indicator-id')?.textContent).toBe('i1'); - expect(host.textContent).not.toContain('Contrato'); - expect(host.textContent).not.toContain('figuras publicadas'); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0); - const button = header.querySelector('button')!; - expect(button.type).toBe('button'); - expect(button.tabIndex).toBe(0); - expect(button.getAttribute('aria-expanded')).toBe('false'); - expect(button.getAttribute('aria-label')).toContain('Expandir tea · i1 · Uno'); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more'); - expect(button.querySelector('mat-icon')?.getAttribute('aria-hidden')).toBe('true'); - http.expectNone(() => true); + it('D.3.A muestra identidad, selector y skeleton sin control de expansión ni HTTP', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + expect(host.querySelector('h2').textContent).toBe('Uno'); + expect(host.querySelector('header button')).toBeNull(); + expect(host.querySelector('mat-select')).toBeTruthy(); + expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente'); + expect(host.textContent).toContain('Contrato C1'); http.expectNone(() => true); }); - it('UX-06C: conserva encabezado, botón y relación accesible al abrir varias figuras y contraer', () => { - load(); - const host = fixture.nativeElement.querySelector('app-indicador-catalog-card') as HTMLElement; - const header = host.querySelector('header')!; - const button = header.querySelector('button')!; - const contentId = button.getAttribute('aria-controls')!; - button.click(); fixture.detectChanges(); flushAll(); - expect(host.querySelector('header')).toBe(header); - expect(header.querySelector('button')).toBe(button); - expect(button.getAttribute('aria-controls')).toBe(contentId); - expect(button.getAttribute('aria-expanded')).toBe('true'); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_less'); - expect(button.getAttribute('aria-label')).toContain('Contraer tea · i1 · Uno'); - expect(header.textContent).not.toContain('Contrato'); - expect(host.querySelector('.catalog-metadata')?.textContent).toContain('Contrato C1 · 2 figuras publicadas'); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(1); - button.click(); fixture.detectChanges(); - expect(host.querySelector('.catalog-metadata')).toBeNull(); - expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0); - expect(button.querySelector('mat-icon')?.textContent?.trim()).toBe('expand_more'); - http.expectNone(() => true); + it('D.3.A conserva encabezado y contenido al salir del viewport', () => { + load(); const host = fixture.nativeElement.querySelector('app-indicador-catalog-card'); + const header = host.querySelector('header'); toggle(); flushAll(); + const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges(); + expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel); + expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true); }); it('UX-06C: conserva título largo completo y el control separado de la identidad', () => { const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive'; @@ -132,8 +109,8 @@ describe('UX-05B catálogo expandible', () => { const header = fixture.nativeElement.querySelector('app-indicador-catalog-card header') as HTMLElement; expect(header.querySelector('h2')?.textContent).toBe(title); expect(header.querySelector('.card-identity button')).toBeNull(); - expect(header.lastElementChild?.tagName).toBe('BUTTON'); - expect(header.querySelector('button')?.getAttribute('aria-label')).toContain(title); + expect(header.querySelector('button')).toBeNull(); + expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title); http.expectNone(() => true); }); it('UX-06B conserva una navegación con rutas y estado activo en los tres dominios', () => { @@ -162,29 +139,29 @@ describe('UX-05B catálogo expandible', () => { expect(page.tema).toBe('claro'); page.changeTema('oscuro'); fixture.detectChanges(); expect(page.tema).toBe('oscuro'); - expect(cards().every(card => !card.expanded)).toBe(true); + expect(cards().every(card => !card.visible)).toBe(true); http.expectNone(() => true); }); it.each([0, 1, 2, 18, 37])('catálogo de %i conserva orden y no consulta figuras inicialmente', count => { const items = Array.from({ length: count }, (_, i) => ({ ...item, id: 'id-' + i })); load(items); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); - expect(cards().every(c => !c.expanded)).toBe(true); + expect(cards().every(c => !c.visible)).toBe(true); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/')); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); - it('abrir manualmente consulta exactamente una vez la primera figura publicada', () => { - load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(1); + it('activar visibilidad consulta exactamente una vez la primera figura publicada', () => { + load([item]); toggle(); expect(cards()[0].visible).toBe(true); expect(panels()).toHaveLength(1); request('f1').flush({ data: [], layout: {} }); fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true); }); - it('el cierre manual se conserva al volver sin consultar figuras', () => { - load([item]); toggle(); flushAll(); toggle(); - fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; - load([item]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); + it('volver al dominio espera nueva visibilidad sin memoria de cierre', () => { + load([item]); toggle(); flushAll(); + fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); + load([item]); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); }); it('indicador sin figuras informa y no consulta HTTP', () => { - load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].expanded).toBe(true); + load([{ ...item, figuras: [] }]); toggle(); expect(cards()[0].visible).toBe(true); expect(fixture.nativeElement.textContent).toContain('no tiene figuras disponibles'); expect(panels()).toHaveLength(0); http.expectNone(() => true); }); @@ -194,11 +171,12 @@ describe('UX-05B catálogo expandible', () => { c.flush({ data: [{ y: [3] }], layout: {} }); a.flush({ data: [{ y: [1] }], layout: {} }); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [3]]); - expect(cards().every(c => c.expanded)).toBe(true); + expect(cards().every(c => c.visible)).toBe(true); }); - it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => { + it('retirar una tarjeta cancela solo su solicitud y destruye su panel', () => { load(); toggle(); toggle(1); const a = request('f1'), c = request('g'); - toggle(); expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false); + page.catalog.set([second]); fixture.detectChanges(); + expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false); expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} }); expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]); @@ -242,16 +220,14 @@ describe('UX-05B catálogo expandible', () => { http.expectNone(() => true); } }); - it('cerrar y reabrir conserva borrador general y consulta aplicado en la figura seleccionada', () => { + it('salir y volver al viewport conserva borrador, aplicado y resultado sin HTTP redundante', () => { load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); page.applyFilters(); fixture.detectChanges(); flushAll(); a.unit = 'S2'; a.add(); - toggle(); toggle(); - const restored = request('f1'); - expect(restored.request.params.get('periodos')).toBe('2025-S1'); + cards()[0].setVisible(false); fixture.detectChanges(); toggle(); expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); - restored.flush({ data: [], layout: {} }); + http.expectNone(() => true); }); - it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => { + it('tema solo consulta paneles visibles, cancela los anteriores y no repite el mismo tema', () => { load(); toggle(); const a = request('f1'); page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); const darkA = request('f1'); @@ -267,17 +243,17 @@ describe('UX-05B catálogo expandible', () => { expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll(); expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama'); }); - it('restaura expansión y tema de dominio sin aplicar borrador pendiente', () => { + it('restaura representación y tema de dominio sin aplicar borrador pendiente', () => { load(); toggle(); flushAll(); control().changeMode('manual'); page.changeTema('oscuro'); fixture.detectChanges(); flushAll(); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); toggle(); flushAll(); toggle(); page.changeDominio('tea'); fixture.detectChanges(); load(); - expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false); - expect(page.tema).toBe('oscuro'); expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); expect(cards()[1].visible).toBe(false); + expect(page.tema).toBe('oscuro'); expect(cards()[0].visible).toBe(false); http.expectNone(() => true); toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false); expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu'); - expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); + expect(cards()[0].visible).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true); }); it('identidades estables conservan componentes al reordenar el catálogo', () => { load(); toggle(); flushAll(); const card = cards()[0], panel = panels()[0]; @@ -285,22 +261,16 @@ describe('UX-05B catálogo expandible', () => { expect(cards()[1]).toBe(card); expect(panels()[0]).toBe(panel); http.expectNone(() => true); }); it('identidad eliminada no se monta aunque exista preferencia anterior', () => { - TestBed.inject(IndicadoresMemory).rememberActivation('tea', 'removed', 'manual-open'); + TestBed.inject(IndicadoresMemory).rememberFigure('tea', 'removed', 'f1'); load([second]); expect(cards().map(c => c.indicador.id)).toEqual(['i2']); flushAll(); }); - it('botones semánticos anuncian expansión, IDs únicos y devuelven foco al contraer contenido', () => { - load(); - const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; - expect(buttons[0].tagName).toBe('BUTTON'); expect(buttons[0].getAttribute('aria-expanded')).toBe('false'); - buttons[0].click(); fixture.detectChanges(); flushAll(); - expect(buttons[0].getAttribute('aria-expanded')).toBe('true'); - expect(document.getElementById(buttons[0].getAttribute('aria-controls')!)).toBeTruthy(); - const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle') as HTMLElement; - input.focus(); expect(document.activeElement).toBe(input); cards()[0].toggle(); fixture.detectChanges(); - expect(document.activeElement).toBe(buttons[0]); + it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => { + load(); toggle(); flushAll(); + const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle'); + input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input); const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf).map(e => e.id); expect(new Set(ids).size).toBe(ids.length); - expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); }); it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => { load(); toggle(0); toggle(1); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } }; @@ -354,9 +324,9 @@ describe('UX-05B catálogo expandible', () => { const a = http.expectOne(r => r.url.endsWith('/i1/figuras/f1')); const b = http.expectOne(r => r.url.endsWith('/i2/figuras/f1')); a.flush({ data: [{ y: [1] }], layout: {} }); b.flush({ data: [{ y: [2] }], layout: {} }); fixture.detectChanges(); - const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button') as NodeListOf; - expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label')); - expect(buttons[0].tabIndex).toBe(0); expect(buttons[1].tabIndex).toBe(0); + const buttons = fixture.nativeElement.querySelectorAll('app-indicador-catalog-card mat-select') as NodeListOf; + expect(panels()[0].titleId).not.toBe(panels()[1].titleId); + expect(buttons[0].tabIndex).toBe(-1); expect(buttons[1].tabIndex).toBe(-1); expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2]]); }); }); diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index b83eb0c..3375ef2 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -20,6 +20,7 @@ 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({ @@ -34,7 +35,7 @@ export class IndicadoresPage { private readonly injector = inject(Injector); private readonly searchInput = viewChild>('searchInput'); private readonly graphicCards = viewChildren(IndicadorCatalogCard); - private readonly observedHeaders = new Map(); + private readonly observedRegions = new Map(); private renderedCards: readonly IndicadorCatalogCard[] = []; private visibilityObserver?: IntersectionObserver; private sizeObserver?: ResizeObserver; @@ -42,11 +43,9 @@ export class IndicadoresPage { private frame?: number; private stickyHeight = -1; private visibilityDestroyed = false; - private confirmation?: { cards: IndicadorCatalogCard[]; trigger: IndicadorCatalogCard; top: number; left: number; width: number; height: number; viewportWidth: number; viewportHeight: number }; private readonly viewportChanged = () => this.visibilityChanged(); visibilityChanged() { - this.confirmation = undefined; this.queueVisibility(); } private queueVisibility() { @@ -60,31 +59,34 @@ export class IndicadoresPage { private clearVisibility() { this.visibilityObserver?.disconnect(); this.visibilityObserver = undefined; - this.observedHeaders.clear(); + this.observedRegions.clear(); this.renderedCards = []; - this.confirmation = undefined; if (this.frame !== undefined) this.document.defaultView?.cancelAnimationFrame(this.frame); this.frame = undefined; } private syncVisibility() { - if (this.visibilityDestroyed || typeof IntersectionObserver === 'undefined' || !this.document.defaultView) return; + if (this.visibilityDestroyed || !this.document.defaultView) return; const cards = this.graphicCards(); + if (typeof IntersectionObserver === 'undefined') { + for (const card of cards) card.setVisible(true); + return; + } const orderChanged = cards.length !== this.renderedCards.length || cards.some((card, i) => card !== this.renderedCards[i]); this.renderedCards = [...cards]; this.refreshVisibilityObserver(); let changed = orderChanged; - for (const [header, card] of this.observedHeaders) { - if (!cards.includes(card) || !card.awaitingVisibility) { - this.visibilityObserver?.unobserve(header); - this.observedHeaders.delete(header); + for (const [region, card] of this.observedRegions) { + if (!cards.includes(card) || card.visibilityRegion?.nativeElement !== region) { + this.visibilityObserver?.unobserve(region); + this.observedRegions.delete(region); changed = true; } } for (const card of cards) { - const header = card.visibilityHeader.nativeElement; - if (card.awaitingVisibility && !this.observedHeaders.has(header)) { - this.observedHeaders.set(header, card); - this.visibilityObserver?.observe(header); + const region = card.visibilityRegion?.nativeElement; + if (region && !this.observedRegions.has(region)) { + this.observedRegions.set(region, card); + this.visibilityObserver?.observe(region); changed = true; } } @@ -106,58 +108,29 @@ export class IndicadoresPage { if (this.visibilityObserver && Math.abs(height - this.stickyHeight) < 1) return; this.stickyHeight = height; this.visibilityObserver?.disconnect(); - this.confirmation = undefined; const observer = new IntersectionObserver(entries => { // Callbacks from a replaced observer or retired target cannot authorize activation. if (this.visibilityDestroyed || this.visibilityObserver !== observer) return; - if (entries.some(entry => this.observedHeaders.has(entry.target))) this.queueVisibility(); - }, { root: null, rootMargin: `-${height}px 0px 0px 0px`, threshold: 0.25 }); + if (entries.some(entry => this.observedRegions.has(entry.target))) this.queueVisibility(); + }, { root: null, rootMargin: `-${height}px 0px 200px 0px`, threshold: 0 }); this.visibilityObserver = observer; - for (const header of this.observedHeaders.keys()) observer.observe(header); + for (const region of this.observedRegions.keys()) observer.observe(region); } private evaluateVisibility() { const browser = this.document.defaultView; if (!browser || this.visibilityDestroyed || !this.visibilityObserver) return; this.refreshVisibilityObserver(); const width = browser.innerWidth, height = browser.innerHeight; - const rows: { top: number; cards: IndicadorCatalogCard[] }[] = []; - // Read the current DOM geometry; never retain index pairs or observer entry rectangles. + // Reread connected graphic regions after scroll/reorder; old observer rectangles + // cannot activate a card that has since moved outside the current viewport. for (const card of this.renderedCards) { - if (card.dominio !== this.dominio || !card.host.nativeElement.isConnected) continue; - const top = card.host.nativeElement.getBoundingClientRect().top; - const row = rows.find(row => row.cards.length < 2 && Math.abs(row.top - top) <= 1); - if (row) row.cards.push(card); else rows.push({ top, cards: [card] }); + const region = card.visibilityRegion?.nativeElement; + if (!region || card.dominio !== this.dominio || !region.isConnected) continue; + const rect = region.getBoundingClientRect(); + card.setVisible(rect.width > 0 && rect.height > 0 && rect.right > 0 + && rect.left < width && rect.bottom > this.stickyHeight && rect.top < height + 200); } - rows.sort((a, b) => a.top - b.top); - for (const row of rows) { - const trigger = row.cards.find(card => { - if (!card.awaitingVisibility || !this.observedHeaders.has(card.visibilityHeader.nativeElement)) return false; - const rect = card.visibilityHeader.nativeElement.getBoundingClientRect(); - const visibleWidth = Math.max(0, Math.min(rect.right, width) - Math.max(rect.left, 0)); - const visibleHeight = Math.max(0, Math.min(rect.bottom, height) - Math.max(rect.top, this.stickyHeight)); - return rect.width > 0 && rect.height > 0 && visibleWidth * visibleHeight / (rect.width * rect.height) >= 0.25; - }); - if (!trigger) continue; - const rect = trigger.visibilityHeader.nativeElement.getBoundingClientRect(); - const previous = this.confirmation; - const stable = previous && previous.trigger === trigger && previous.cards.length === row.cards.length - && row.cards.every((card, i) => card === previous.cards[i]) - && Math.abs(previous.top - rect.top) <= 1 && Math.abs(previous.left - rect.left) <= 1 - && Math.abs(previous.width - rect.width) <= 1 && Math.abs(previous.height - rect.height) <= 1 - && previous.viewportWidth === width && previous.viewportHeight === height; - if (!stable) { - this.confirmation = { cards: row.cards, trigger, top: rect.top, left: rect.left, width: rect.width, height: rect.height, viewportWidth: width, viewportHeight: height }; - this.queueVisibility(); - return; - } - this.confirmation = undefined; - for (const card of row.cards) card.activateVisible(); - this.changeDetector.markForCheck(); - // Wait for Angular's height change before considering any lower row. - afterNextRender(() => this.queueVisibility(), { injector: this.injector }); - return; - } - this.confirmation = undefined; + this.changeDetector.markForCheck(); } clearSearch() { this.changeSearchQuery(''); @@ -166,13 +139,11 @@ export class IndicadoresPage { changeSearchQuery(query: string) { this.preserveCardFocus(); this.searchQuery.set(query); - this.confirmation = undefined; } isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); } togglePinned(item: Indicador) { this.preserveCardFocus(); this.memory.togglePinned(this.dominio, item.id); - this.confirmation = undefined; } private preserveCardFocus() { const focused = this.document.activeElement; @@ -189,6 +160,9 @@ export class IndicadoresPage { } private readonly changeDetector = inject(ChangeDetectorRef); private readonly service = inject(IndicadoresService); + private readonly periodService = inject(IndicadoresPeriodos); + private readonly availabilityRequests = new Subject(); + readonly availability = signal(emptyAvailability()); private readonly memory = inject(IndicadoresMemory); private readonly destroyRef = inject(DestroyRef); private readonly route = inject(ActivatedRoute, { optional: true }); @@ -229,8 +203,10 @@ export class IndicadoresPage { tema: Tema = 'claro'; filters?: GlobalFilterState; readonly filterTypes = computed(() => domainTypes(this.catalog())); + retryAvailability() { this.availabilityRequests.next(); } filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); } applyFilters() { + this.evaluateVisibility(); if (!this.filters || !applyGlobal(this.filters, this.filterTypes())) return; this.filtersEdited(); this.changeDetector.markForCheck(); @@ -255,11 +231,16 @@ export class IndicadoresPage { const initialDomain: unknown = this.route?.snapshot.data['dominio']; if (isDominio(initialDomain)) this.dominio = initialDomain; this.tema = this.memory.theme(this.dominio); + this.availabilityRequests.pipe(switchMap(() => { + this.availability.set(emptyAvailability()); + return this.periodService.dominio(this.dominio, this.catalog()); + }), takeUntilDestroyed(this.destroyRef)).subscribe(state => this.availability.set(state)); this.catalogRequests.pipe(startWith(undefined), switchMap(() => { this.clearVisibility(); this.catalogLoading.set(true); this.catalogError.set(''); this.catalog.set([]); + this.availabilityRequests.next(); return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })), catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) }))); }), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => { @@ -268,6 +249,7 @@ export class IndicadoresPage { this.catalog.set(items); this.filtersEdited(); this.catalogError.set(error); + this.availabilityRequests.next(); }); } changeDominio(dominio: Dominio) { @@ -282,6 +264,7 @@ export class IndicadoresPage { retryCatalog() { this.catalogRequests.next(); } changeTema(tema: Tema) { if ((tema !== 'claro' && tema !== 'oscuro') || tema === this.tema) return; + this.evaluateVisibility(); this.tema = tema; this.memory.rememberTheme(this.dominio, tema); 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 new file mode 100644 index 0000000..6256449 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -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 { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { KPI_BY_DOMAIN } from './indicadores-kpi'; +import { Dominio, IndicadorDatos } from './indicadores.models'; + +describe('P0.1 selección publicada y último periodo por KPI', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + const payload = (id: string, periods: string[]) => ({ id, periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes' })) }); + function catalog(domain: Dominio) { + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }))); + fixture.detectChanges(); + return http.match(r => r.url.endsWith('/periodos')); + } + function load(domain: Dominio, periods: string[][]) { + catalog(domain).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN[domain][i].id, periods[i]))); + fixture.detectChanges(); + } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel); } + function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } + function data(index: number, domain: Dominio, period: string, suppressed = false): IndicadorDatos { + const d = KPI_BY_DOMAIN[domain][index]; + return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [{ + periodo: period, grupo: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', + n: 0, valor: 0, numerador: 0, denominador: 5, mediana: 0, q1: 0, q3: 0, unidad: 'dias', suprimido: suppressed ? 1 : 0, + }] }; + } + function flushDatos(domain: Dominio, suppressed = false) { + const requests = http.match(r => r.url.endsWith('/datos')); + requests.forEach(r => { + const index = KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')); + r.flush(data(index, domain, r.request.params.get('periodos')!, suppressed)); + }); + fixture.detectChanges(); return requests; + } + it.each(['cacu', 'cama'] as const)('%s usa últimos periodos propios, conserva ceros y no altera Todos aplicado', domain => { + load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); + const requests = flushDatos(domain); + expect(requests.map(r => r.request.params.get('periodos'))).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.temporalReference)).toEqual(['2026-S1', '2026-S2', '2025-S2']); + expect(panels().map(p => p.result().value)).toEqual([0, '0.0', 0]); + expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'todos' }); + 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', () => { + load('cacu', Array(3).fill(['2024-S1', '2026-S2', '2025-S2'])); + 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); + expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); + }); + it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { + load('cama', [[], ['2025-S2'], ['2025-S1']]); const requests = flushDatos('cama'); + expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); + expect(panels()[0].result().value).toBeUndefined(); + }); + it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { + load('cacu', Array(3).fill(['2026-S2', '2025-02', '2025-10', '2026-01'])); flushDatos('cacu'); + const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges(); + expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']); + expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull(); + expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + const single = flushDatos('cacu'); expect(single).toHaveLength(3); + expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true); + control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true); + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + expect(panels().every(p => p.result().state === 'Selección no consolidable' && p.result().value === undefined)).toBe(true); + http.expectNone(() => true); + control.select(['2025-02', '2025-10']); fixture.componentInstance.applyFilters(); fixture.detectChanges(); + http.expectNone(() => true); + await fixture.whenStable(); + }); + it('error de disponibilidad ofrece reintento sin sustituir la selección y conserva éxitos en caché', () => { + const requests = catalog('cacu'); + requests[0].flush('private', { status: 503, statusText: 'Unavailable' }); + requests.slice(1).forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cacu[i + 1].id, ['2025-S2']))); + fixture.detectChanges(); flushDatos('cacu'); + expect(panels()[0].result().state).toBe('Error de disponibilidad'); + expect(fixture.nativeElement.textContent).toContain('No se pudo completar la consulta'); + expect(fixture.nativeElement.textContent).not.toContain('private'); + const control = editor(); control.changeMode('manual'); control.select(['2025-S2']); + expect(control.canApply).toBe(false); + fixture.componentInstance.retryAvailability(); fixture.detectChanges(); + const retry = http.expectOne('/cacu/indicadores/cacu_eu7/periodos'); + http.expectNone(r => r.url.endsWith('/periodos')); + retry.flush(payload('cacu_eu7', ['2025-S2'])); fixture.detectChanges(); flushDatos('cacu'); + expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); + }); + it('cambio de dominio cancela inventarios y evita opciones o valores obsoletos', () => { + const outgoing = catalog('cacu'); const incoming = catalog('cama'); + expect(outgoing.every(r => r.cancelled)).toBe(true); + expect(() => outgoing[0].flush(payload('cacu_eu7', ['2099-S2']))).toThrow(); + incoming.forEach((r, i) => r.flush(payload(KPI_BY_DOMAIN.cama[i].id, ['2025-S1']))); + fixture.detectChanges(); const requests = flushDatos('cama'); + expect(requests.every(r => r.request.url.startsWith('/cama/') && r.request.params.get('periodos') === '2025-S1')).toBe(true); + expect(editor().options).toEqual(['2025-S1']); + }); + it('error y catálogo vacío no inventan opciones ni consultas KPI', () => { + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush('private', { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(fixture.componentInstance.catalogError()).toBeTruthy(); http.expectNone(() => true); + fixture.componentInstance.retryCatalog(); http.expectOne('/cacu/indicadores').flush([]); fixture.detectChanges(); + expect(fixture.componentInstance.availability().options.semestre).toEqual([]); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.spec.ts b/src/app/features/indicadores/indicadores-periodos.spec.ts new file mode 100644 index 0000000..7dc3808 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.spec.ts @@ -0,0 +1,83 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Indicador, TipoPeriodo } from './indicadores.models'; +import { IndicadoresPeriodos, parseAvailability, PeriodAvailability, sortedPeriods } from './indicadores-periodos'; + +const item = (id: string, tipos_periodo: TipoPeriodo[] = ['semestre', 'mes']): Indicador => ({ id, titulo: id, contrato: 'C1', figuras: [], tipos_periodo }); +const payload = (id: string, periods: string[]) => ({ id, version: 'test', periodos: periods.map(periodo => ({ periodo, tipo: periodo.includes('-S') ? 'semestre' : 'mes', report_id: 1 })) }); +describe('P0.1 inventarios publicados de periodos', () => { + let service: IndicadoresPeriodos, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + service = TestBed.inject(IndicadoresPeriodos); http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + it('une coberturas diferentes, deduplica y separa mes/semestre con orden numérico', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2026-S2', '2025-S1', '2025-02', '2025-10'])); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2024-S2', '2025-10', '2026-01'])); + expect(result.status).toBe('ready'); + expect(result.options).toEqual({ semestre: ['2026-S2', '2025-S1', '2024-S2'], mes: ['2026-01', '2025-10', '2025-02'] }); + expect(result.byIndicator['b'].some(p => p.periodo === '2026-S2')).toBe(false); + }); + it('respeta capacidades individuales y no mezcla dominios en caché', () => { + let result!: PeriodAvailability; + service.dominio('tea', [item('a', ['semestre'])]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', ['2025-S1', '2025-01'])); + expect(result.options.mes).toEqual([]); + service.dominio('cama', [item('a')]).subscribe(); + http.expectOne('/cama/indicadores/a/periodos').flush(payload('a', [])); + }); + it('limita a cuatro consultas simultáneas y cancela también la cola', () => { + const sub = service.dominio('tea', Array.from({ length: 9 }, (_, i) => item('i' + i))).subscribe(); + const first = http.match(r => r.url.endsWith('/periodos')); expect(first).toHaveLength(4); + first[0].flush(payload('i0', [])); + const next = http.expectOne('/tea/indicadores/i4/periodos'); + sub.unsubscribe(); + expect(first.slice(1).every(r => r.cancelled)).toBe(true); expect(next.cancelled).toBe(true); + http.expectNone(r => r.url.includes('/i5/')); + }); + it('reutiliza inventarios exitosos sin HTTP y reintenta únicamente errores sin publicar unión parcial', () => { + let result!: PeriodAvailability; + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectOne('/cacu/indicadores/a/periodos').flush(payload('a', ['2025-S1'])); + http.expectOne('/cacu/indicadores/b/periodos').flush('private', { status: 503, statusText: 'Unavailable' }); + expect(result.status).toBe('error'); expect(result.options.semestre).toEqual([]); + expect(result.errors['b']).not.toContain('private'); expect(result.byIndicator['a']).toHaveLength(1); + service.dominio('cacu', [item('a'), item('b')]).subscribe(value => result = value); + http.expectNone('/cacu/indicadores/a/periodos'); + http.expectOne('/cacu/indicadores/b/periodos').flush(payload('b', ['2025-S2'])); + expect(result.options.semestre).toEqual(['2025-S2', '2025-S1']); + service.dominio('cacu', [item('a'), item('b')]).subscribe(); http.expectNone(() => true); + }); + it('un inventario cancelado no entrega respuestas obsoletas ni se conserva como éxito', () => { + const delivered = vi.fn(); + const sub = service.dominio('tea', [item('a')]).subscribe(delivered); + const old = http.expectOne('/tea/indicadores/a/periodos'); sub.unsubscribe(); + expect(old.cancelled).toBe(true); expect(delivered).not.toHaveBeenCalled(); + expect(() => old.flush(payload('a', ['2025-S1']))).toThrow(); + service.dominio('tea', [item('a')]).subscribe(delivered); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(delivered).toHaveBeenCalledOnce(); + }); + it('catálogo vacío y lista vacía son éxito sin periodos inventados', () => { + let result!: PeriodAvailability; + service.dominio('tea', []).subscribe(value => result = value); + expect(result.status).toBe('ready'); expect(result.options.semestre).toEqual([]); http.expectNone(() => true); + service.dominio('tea', [item('a')]).subscribe(value => result = value); + http.expectOne('/tea/indicadores/a/periodos').flush(payload('a', [])); + expect(result.byIndicator['a']).toEqual([]); + }); + it.each([ + null, { id: 'wrong', periodos: [] }, { id: 'a' }, payload('a', ['2025-13']), + { id: 'a', periodos: [{ periodo: '2025-S1', tipo: 'mes' }] }, + ])('rechaza respuestas inválidas sin inventar disponibilidad: %j', value => { + expect(() => parseAvailability(value, 'a')).toThrow(); + }); + it('ordena cambios de año y unidades sin usar el orden accidental', () => { + expect(sortedPeriods(['2026-S1', '2025-S2', '2026-S2'])).toEqual(['2026-S2', '2026-S1', '2025-S2']); + expect(sortedPeriods(['2025-02', '2024-12', '2025-10', '2026-01'])).toEqual(['2026-01', '2025-10', '2025-02', '2024-12']); + }); +}); diff --git a/src/app/features/indicadores/indicadores-periodos.testing.ts b/src/app/features/indicadores/indicadores-periodos.testing.ts new file mode 100644 index 0000000..adabe64 --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.testing.ts @@ -0,0 +1,18 @@ +import { of } from 'rxjs'; +import { Indicador } from './indicadores.models'; +import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; + +// Existing figure/search/visibility suites isolate their HTTP from availability. +// The new P0.1 suites exercise the real availability HTTP separately. +export const periodAvailabilityProvider = { + provide: IndicadoresPeriodos, + useValue: { dominio: (_domain: unknown, catalog: Indicador[]) => { + const state = emptyAvailability('ready'); + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = [2024, 2025, 2026].flatMap(year => + (tipo === 'semestre' ? ['S1', 'S2'] : Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0'))).map(unit => year + '-' + unit)); + } + for (const item of catalog) state.byIndicator[item.id] = item.tipos_periodo.flatMap(tipo => state.options[tipo].map(periodo => ({ tipo, periodo }))); + return of(state); + } }, +}; diff --git a/src/app/features/indicadores/indicadores-periodos.ts b/src/app/features/indicadores/indicadores-periodos.ts new file mode 100644 index 0000000..fc4031b --- /dev/null +++ b/src/app/features/indicadores/indicadores-periodos.ts @@ -0,0 +1,77 @@ +import { inject, Injectable } from '@angular/core'; +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'; + +export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; } +export interface PeriodAvailability { + status: 'loading' | 'ready' | 'error'; + byIndicator: Record; + options: Record; + errors: Record; +} +export function emptyAvailability(status: PeriodAvailability['status'] = 'loading'): PeriodAvailability { + return { status, byIndicator: {}, options: { semestre: [], mes: [] }, errors: {} }; +} +// Numeric year/unit comparison, independent of server order and report generation date. +export function periodOrder(period: string): number { + return Number(period.slice(0, 4)) * 12 + (period.includes('-S') ? Number(period.slice(6)) * 6 : Number(period.slice(5))); +} +export function sortedPeriods(periods: readonly string[]): string[] { + return [...new Set(periods)].sort((a, b) => periodOrder(b) - periodOrder(a)); +} +function record(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function parseAvailability(value: unknown, id: string): AvailablePeriod[] { + if (!record(value) || value['id'] !== id || !Array.isArray(value['periodos'])) throw new Error('Respuesta de periodos inválida'); + const unique = new Map(); + for (const row of value['periodos']) { + if (!record(row) || (row['tipo'] !== 'semestre' && row['tipo'] !== 'mes') + || typeof row['periodo'] !== 'string' || parsePeriodos(row['periodo'], row['tipo'])?.[0] !== row['periodo']) { + throw new Error('Respuesta de periodos inválida'); + } + unique.set(row['periodo'], { periodo: row['periodo'], tipo: row['tipo'] }); + } + return [...unique.values()].sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo)); +} +@Injectable({ providedIn: 'root' }) +export class IndicadoresPeriodos { + private readonly http = inject(HttpClient); + // Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached. + private readonly cache = new Map>(); + periodos(domain: Dominio, id: string) { + const dominio = requireDominio(domain); + const key = JSON.stringify([dominio, id]); + let request = this.cache.get(key); + if (!request) { + request = this.http.get(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`).pipe( + map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true })); + this.cache.set(key, request); + } + return request; + } + dominio(domain: Dominio, catalog: readonly Indicador[]): Observable { + return from(catalog).pipe( + mergeMap(item => this.periodos(domain, item.id).pipe( + map(periods => ({ id: item.id, periods: periods.filter(p => item.tipos_periodo.includes(p.tipo)), error: '' })), + catchError(error => of({ id: item.id, periods: [] as AvailablePeriod[], error: httpMessage(error) }))), 4), + toArray(), + map(results => { + const state = emptyAvailability('ready'); + for (const result of results) { + if (result.error) state.errors[result.id] = result.error; + else state.byIndicator[result.id] = result.periods; + } + state.status = Object.keys(state.errors).length ? 'error' : 'ready'; + // Do not publish an incomplete union as a successful inventory. + if (state.status === 'ready') { + for (const tipo of ['semestre', 'mes'] as const) { + state.options[tipo] = sortedPeriods(Object.values(state.byIndicator).flat().filter(p => p.tipo === tipo).map(p => p.periodo)); + } + } + return state; + })); + } +} diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 969f630..8906a5e 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -21,15 +22,15 @@ describe('UX-06E.D.3.B fijación temporal', () => { let http: HttpTestingController; const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); - vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); load(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); - function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); } + function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); } function load(domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function card(id: string) { return cards().find(c => c.indicador.id === id)!; } @@ -100,20 +101,20 @@ describe('UX-06E.D.3.B fijación temporal', () => { expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control); await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true); }); - it('preserva figura seleccionada, apertura, cierre manual, panel y host Plotly', async () => { - card('i3').toggle(); fixture.detectChanges(); respond(); await settle(); + it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => { + card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle(); card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle(); - card('i1').toggle(); fixture.detectChanges(); respond(); card('i1').toggle(); fixture.detectChanges(); await settle(); - const before = cards(), panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance; + + const before = cards(), panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied; const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length; for (const id of ['i3', 'i1', 'i3']) { await pin(id); for (const c of before) expect(card(c.indicador.id)).toBe(c); - expect(card('i3').expanded).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').figuresActivated).toBe(true); - expect(card('i1').expanded).toBe(false); expect(TestBed.inject(IndicadoresMemory).activation('tea', 'i1')).toBe('manual-closed'); - expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); + expect(card('i3').visible).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').visible).toBe(true); + expect(card('i1').visible).toBe(false); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart); expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied); http.expectNone(() => true); @@ -121,10 +122,10 @@ describe('UX-06E.D.3.B fijación temporal', () => { expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges); }); it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => { - card('i4').toggle(); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); - const panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance; + card('i4').setVisible(true); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f')); + const panel = fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance; await pin('i4'); expect(request.cancelled).toBe(false); - expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); http.expectNone(() => true); + expect(fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).find(e => e.componentInstance.visible)!.componentInstance).toBe(panel); http.expectNone(() => true); request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]); }); }); diff --git a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts index 42174a3..f02e6a9 100644 --- a/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts +++ b/src/app/features/indicadores/indicadores-plotly-lifecycle.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -14,6 +15,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const disconnects: ReturnType[] = []; beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); disconnects.length = 0; runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { @@ -21,12 +23,13 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => // Material outline labels also observe size; track only Plotly hosts here. observe = vi.fn((target: Element) => { if (target.classList.contains('plot')) disconnects.push(this.disconnect); }); }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + fixture = TestBed.createComponent(IndicadoresPage); + vi.spyOn(fixture.componentInstance as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); http = TestBed.inject(HttpTestingController); http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]); fixture.detectChanges(); - for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).toggle(); + for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).setVisible(true); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); @@ -42,7 +45,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () => expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f'); expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g'); const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; - card.toggle(); fixture.detectChanges(); + fixture.componentInstance.catalog.set(fixture.componentInstance.catalog().slice(1)); fixture.detectChanges(); expect(runtime.purge).toHaveBeenCalledWith(hosts[0]); expect(runtime.purge).not.toHaveBeenCalledWith(hosts[1]); expect(disconnects[0]).toHaveBeenCalledTimes(1); expect(disconnects[1]).not.toHaveBeenCalled(); diff --git a/src/app/features/indicadores/indicadores-search.spec.ts b/src/app/features/indicadores/indicadores-search.spec.ts index 540d2e5..660a706 100644 --- a/src/app/features/indicadores/indicadores-search.spec.ts +++ b/src/app/features/indicadores/indicadores-search.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -29,11 +30,12 @@ describe('UX-05C búsqueda local y partición estable', () => { const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } }; const disconnect = vi.fn(); beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); vi.resetAllMocks(); runtime.react.mockResolvedValue(undefined); runtime.Plots.resize.mockResolvedValue(undefined); vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = disconnect; }); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; + 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.unstubAllGlobals(); }); @@ -41,7 +43,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); } function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } - function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); } + function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function filters() { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters)).map(e => e.componentInstance as IndicadorPeriodFilters); } function charts() { return fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(e => e.componentInstance as PlotlyChart); } function input(): HTMLInputElement { return fixture.nativeElement.querySelector('.catalog-search input'); } @@ -57,7 +59,7 @@ describe('UX-05C búsqueda local y partición estable', () => { it.each([0, 1, 4, 5, 18, 37])('muestra búsqueda exclusivamente desde cinco: catálogo de %i', count => { load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i }))); expect(!!input()).toBe(count >= 5); expect(cards()).toHaveLength(count); - expect(cards().every(c => !c.expanded)).toBe(true); + expect(cards().every(c => !c.visible)).toBe(true); http.expectNone(() => true); if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles'); }); @@ -79,7 +81,7 @@ describe('UX-05C búsqueda local y partición estable', () => { expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); for (const card of cards()) { expect(card).toBe(before.find(c => c.indicador.id === card.indicador.id)); - expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.expanded).toBe(false); + expect(card.indicador).toBe(original.find(i => i.id === card.indicador.id)); expect(card.visible).toBe(false); } if (query === 'imposible') expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); if (!(query as string).trim()) expect(fixture.nativeElement.querySelector('#catalog-search-result').textContent.trim()).toBe(''); @@ -137,7 +139,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectNone(() => true); }); it('tres tarjetas abiertas conservan paneles, borrador/aplicado, Forms, memoria y hosts Plotly sin react/purge', async () => { - load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); respond(); await settle(); + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); respond(); await settle(); const beforeCards = cards(), beforePanels = panels(), beforeFilters = filters(), beforeCharts = charts(); const c = beforeFilters[0]; c.changeMode('manual'); c.year = '2025'; c.unit = 'S1'; c.add(); page.applyFilters(); fixture.detectChanges(); respond(); await settle(); @@ -152,13 +154,13 @@ describe('UX-05C búsqueda local y partición estable', () => { const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'saveGlobal'), restores = vi.spyOn(memory, 'restoreGlobal'); const reacts = runtime.react.mock.calls.length; const helps = [...fixture.nativeElement.querySelectorAll('.methodology-toggle')] as HTMLButtonElement[]; - expect(helps).toHaveLength(3); + expect(helps).toHaveLength(5); const helpIds = helps.map(button => button.getAttribute('aria-controls')!); - expect(new Set(helpIds).size).toBe(3); + expect(new Set(helpIds).size).toBe(5); for (const id of helpIds) expect(document.getElementById(id)?.hidden).toBe(true); helps[0].click(); fixture.detectChanges(); await settle(); - expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false']); - expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true]); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); + expect(helpIds.map(id => document.getElementById(id)?.hidden)).toEqual([false, true, true, true, true]); for (const query of ['sexo', 'evaluacion', '']) { if (query) await search(query); else { fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle(); } @@ -167,9 +169,9 @@ describe('UX-05C búsqueda local y partición estable', () => { beforeFilters.forEach(c => expect(filters().find(f => f.state === c.state)).toBe(c)); beforeCharts.forEach(c => expect(charts().find(chart => chart.host.nativeElement === c.host.nativeElement)).toBe(c)); } - expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.expanded)).toBe(true); + expect(cards()).toEqual(beforeCards); expect(beforeCards.slice(0, 3).every(c => c.visible)).toBe(true); for (const button of helps) expect(button.isConnected).toBe(true); - expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false']); + expect(helps.map(button => button.getAttribute('aria-expanded'))).toEqual(['true', 'false', 'false', 'false', 'false']); helps[0].click(); fixture.detectChanges(); await settle(); expect(document.getElementById(helpIds[0])?.hidden).toBe(true); expect(panels()).toEqual(beforePanels); expect(filters()).toEqual(beforeFilters); expect(charts()).toEqual(beforeCharts); @@ -187,7 +189,7 @@ describe('UX-05C búsqueda local y partición estable', () => { http.expectNone(() => true); }); it('reordenar conserva un panel cargando y otro con error; completar y reintentar siguen siendo independientes', async () => { - load(); cards().slice(0, 3).forEach(c => c.toggle()); fixture.detectChanges(); + load(); cards().slice(0, 3).forEach(c => c.setVisible(true)); fixture.detectChanges(); const before = panels(), a = request('A01'), b = request('B02'), c = request('M02_sexo'); b.flush('private', { status: 404, statusText: 'Not Found' }); c.flush({ data: [{ y: [3] }], layout: {} }); await settle(); await search('sexo'); expect(a.cancelled).toBe(false); expect(before[0].result().status).toBe('loading'); expect(before[1].result().status).toBe('error'); @@ -196,27 +198,27 @@ describe('UX-05C búsqueda local y partición estable', () => { const other = before[2].result(); before[1].requestFigure(); request('B02').flush({ data: [{ y: [2] }], layout: {} }); expect(before[2].result()).toBe(other); await search(''); expect(panels()).toEqual(before); http.expectNone(() => true); }); - it('mover una tarjeta abierta mantiene el foco en su control existente', async () => { - load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + it('reordenar el catálogo conserva foco en el selector global existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); fixture.detectChanges(); await settle(); - const field = fixture.nativeElement.querySelector('app-indicador-period-filters input') as HTMLInputElement; + const field = Array.from(fixture.nativeElement.querySelectorAll('app-indicador-period-filters mat-select') as NodeListOf).at(-1)!; field.focus(); expect(document.activeElement).toBe(field); page.changeSearchQuery('sexo'); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); expect(field.isConnected).toBe(true); page.changeSearchQuery(''); fixture.detectChanges(); await settle(); expect(document.activeElement).toBe(field); http.expectNone(() => true); }); - it('cambiar de dominio limpia búsqueda y volver conserva expansión y borrador mediante memoria existente', async () => { - load(); cards()[2].toggle(); fixture.detectChanges(); respond(); await settle(); + it('cambiar de dominio limpia búsqueda y volver conserva figura y borrador mediante memoria existente', async () => { + load(); cards()[2].setVisible(true); fixture.detectChanges(); respond(); await settle(); filters()[0].changeMode('manual'); filters()[0].year = '2025'; filters()[0].unit = 'S1'; filters()[0].add(); await search('sexo'); page.changeDominio('cacu'); fixture.detectChanges(); expect(page.searchQuery()).toBe(''); - load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].expanded).toBe(false); + load([{ ...items[0], figuras: [] }], 'cacu'); expect(input()).toBeNull(); expect(cards()[0].visible).toBe(false); page.changeDominio('tea'); fixture.detectChanges(); load(); expect(page.searchQuery()).toBe(''); - expect(cards().map(c => c.expanded)).toEqual([false, false, true, false, false]); - http.expectNone(() => true); cards()[2].toggle(); fixture.detectChanges(); + expect(cards().map(c => c.visible)).toEqual([false, false, false, false, false]); + http.expectNone(() => true); cards()[2].setVisible(true); fixture.detectChanges(); const r = request('M02_sexo'); expect(r.request.params.has('periodos')).toBe(false); r.flush({ data: [], layout: {} }); expect(filters()[0].selectedPeriods).toEqual(['2025-S1']); - await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; load(); respond(); + await search('sexo'); fixture.destroy(); fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); load(); respond(); expect(page.searchQuery()).toBe(''); expect(cards().map(c => c.indicador.id)).toEqual(items.map(i => i.id)); }); }); diff --git a/src/app/features/indicadores/indicadores-visibility.spec.ts b/src/app/features/indicadores/indicadores-visibility.spec.ts index a4ac0c2..eae5fea 100644 --- a/src/app/features/indicadores/indicadores-visibility.spec.ts +++ b/src/app/features/indicadores/indicadores-visibility.spec.ts @@ -1,3 +1,4 @@ +import { periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -44,7 +45,7 @@ class ResizeControl { emit() { this.callback([], this as unknown as ResizeObserver); } } -describe('UX-06E.D.1.1 visibilidad controlada', () => { +describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => { let fixture: ReturnType>; let page: IndicadoresPage; let http: HttpTestingController; @@ -68,7 +69,7 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { sticky = document.createElement('header'); sticky.className = 'institutional-header'; document.body.append(sticky); geometry.set(sticky, rect(0, 0, 1440, 100)); runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); create(); @@ -88,7 +89,7 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { function positions(values: number[][]) { cards().forEach((card, i) => { geometry.set(card.host.nativeElement, rect(values[i][0], values[i][1])); - geometry.set(card.visibilityHeader.nativeElement, rect(values[i][0] + 16, values[i][1])); + geometry.set(card.visibilityRegion!.nativeElement, rect(values[i][0], values[i][1], 600, 620)); }); } function observer() { return IntersectionControl.instances.at(-1)!; } @@ -96,252 +97,125 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => { const callbacks = [...frames.values()]; frames.clear(); callbacks.forEach(callback => callback(0)); await render(); } async function confirm() { await frame(); await frame(); } - function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityHeader.nativeElement, intersects); } + function notify(index = 0, intersects = true) { observer().emit(cards()[index].visibilityRegion!.nativeElement, intersects); } function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); } async function idle() { for (let i = 0; i < 6 && frames.size; i++) await frame(); expect(frames.size).toBe(0); } - it('D.3.B fijar invalida la fila pendiente y aplica visibilidad actual sin anticipar carga', async () => { - await load(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - const original = cards(); - original[4].host.nativeElement.querySelector('.pin-toggle')!.click(); await render(); - expect(cards()[0]).toBe(original[4]); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - http.expectNone(() => true); await frame(); http.expectNone(() => true); - await frame(); expect(cards()[0].expanded).toBe(true); expect(original[0].expanded).toBe(false); - http.expectOne(r => r.url.endsWith('/i4/figuras/f')).flush({ data: [], layout: {} }); await idle(); - cards()[0].toggle(); await render(); - original[0].host.nativeElement.querySelector('.pin-toggle')!.click(); await render(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); await confirm(); respond(); await idle(); - expect(original[4].expanded).toBe(false); expect(memory.activation('tea', 'i4')).toBe('manual-closed'); - http.expectNone(() => true); - }); - - it('observa sólo cabeceras gráficas con viewport, umbral y margen sticky medido', async () => { - await load(); - expect(observer().options).toEqual({ root: null, threshold: 0.25, rootMargin: '-100px 0px 0px 0px' }); - expect([...observer().targets]).toEqual(cards().map(card => card.visibilityHeader.nativeElement)); - expect([...observer().targets].every(target => target.tagName === 'HEADER')).toBe(true); - expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); - await idle(); http.expectNone(() => true); - }); - it('exige dos frames y activa una sola vez sin autocierre ni nuevas consultas', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); - await frame(); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - await frame(); expect(memory.activation('tea', 'i0')).toBe('auto-open'); expect(panels()).toHaveLength(1); respond(); - const panel = panels()[0], result = panel.result(); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); - observer().emit(cards()[0].visibilityHeader.nativeElement, false); await idle(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(true); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); http.expectNone(() => true); - }); - it('abre juntas dos tarjetas de la fila real sin abrir filas inferiores', async () => { - await load(); positions([[200, 0], [200.5, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); - expect(panels()).toHaveLength(2); respond(); await idle(); http.expectNone(() => true); - }); - it('en una columna no asocia dos indicadores por índice', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it('una intersección fugaz y una entrada antigua no abren una tarjeta ya fuera', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - positions([[900, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); - notify(); await idle(); expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); - }); - it('un desplazamiento rápido invalida la confirmación geométrica previa', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - positions([[400, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); await frame(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); await idle(); - }); - it('procesa primero la fila superior y descarta inferiores desplazadas por reflow', async () => { - await load(); positions([[200, 0], [200, 650], [400, 0], [400, 650], [1000, 0]]); notify(2); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); respond(); - positions([[200, 0], [200, 650], [1100, 0], [1100, 650], [1300, 0]]); await idle(); - expect(cards()[2].expanded).toBe(false); http.expectNone(() => true); - }); - it('las filas todavía visibles se activan en nuevas evaluaciones después de render', async () => { - await load(); positions([[200, 0], [200, 650], [450, 0], [450, 650], [1000, 0]]); notify(); await confirm(); respond(); - await confirm(); expect(cards().map(card => card.expanded)).toEqual([true, true, true, true, false]); respond(); await idle(); - }); - it('recalcula asociaciones responsive entre los dos frames', async () => { - await load(); positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await frame(); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); window.dispatchEvent(new Event('resize')); - await frame(); expect(cards().every(card => !card.expanded)).toBe(true); - await frame(); expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it('excluye cabeceras detrás de sticky y mide sus cambios de altura', async () => { - await load(); positions([[0, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); http.expectNone(() => true); - const old = observer(); geometry.set(sticky, rect(0, 0, 1440, 50)); ResizeControl.instances.find(instance => instance.targets.has(sticky))!.emit(); - await frame(); expect(old.disconnect).toHaveBeenCalled(); expect(observer().options.rootMargin).toBe('-50px 0px 0px 0px'); - await frame(); expect(cards()[0].expanded).toBe(true); respond(); await idle(); - }); - it('una cabecera parcialmente visible por debajo del umbral no se activa', async () => { - await load(); positions([[770, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - }); - it('cierre manual prevalece sobre una confirmación pendiente y permite reapertura', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - cards()[0].toggle(); await render(); const request = http.expectOne(r => r.url.includes('/figuras/')); - cards()[0].toggle(); await render(); expect(request.cancelled).toBe(true); - notify(); await idle(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - cards()[0].toggle(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); - }); - it('una compañera cerrada manualmente permanece cerrada', async () => { - memory.rememberActivation('tea', 'i1', 'manual-closed'); await load(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); - expect(cards().map(card => card.expanded)).toEqual([true, false, false, false, false]); respond(); await idle(); - }); - it.each(['tea', 'cacu', 'cama'] as const)('singleton %s espera visibilidad antes de consultar', async domain => { + it.each([{ domain: 'tea', count: 18 }, { domain: 'cacu', count: 8 }] as const)('%s no descarga todas las figuras al abrir', async ({ domain, count }) => { if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); } - await load([items[0]], domain); await idle(); http.expectNone(() => true); expect(cards()[0].expanded).toBe(false); - positions([[200, 0]]); notify(); await confirm(); expect(memory.activation(domain, 'i0')).toBe('auto-open'); respond(); await idle(); + await load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'i' + i })), domain); + await idle(); expect(cards()).toHaveLength(count); expect(panels()).toHaveLength(count); + expect(panels().every(p => p.result().status === 'deferred')).toBe(true); http.expectNone(() => true); + expect(fixture.nativeElement.querySelectorAll('app-indicador-catalog-card header button')).toHaveLength(0); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(count); + positions(cards().map((_, i) => [i < 2 ? 200 : 1200 + i * 1000, i === 1 ? 650 : 0])); notify(); await confirm(); + const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(2); + requests.forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); await render(); await idle(); http.expectNone(() => true); }); - it('regresar conserva abierto sin montar fuera del viewport, y carga al entrar', async () => { - await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); - page.changeDominio('cacu'); await load([items[0]], 'cacu'); await idle(); - expect(cards()[0].expanded).toBe(false); - page.changeDominio('tea'); await load([items[0]]); await idle(); - expect(cards()[0].expanded).toBe(true); expect(cards()[0].awaitingFigures).toBe(true); expect(panels()).toHaveLength(0); http.expectNone(() => true); - expect(fixture.nativeElement.textContent).toContain('Apertura recordada'); - positions([[200, 0]]); notify(); await confirm(); expect(panels()).toHaveLength(1); respond(); await idle(); - expect(memory.activation('tea', 'i0')).toBe('auto-open'); - }); - it('fallback manual permite mostrar figuras restauradas al primer clic y cerrar al siguiente', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); memory.rememberActivation('tea', 'i0', 'auto-open'); - await load([items[0]]); expect(IntersectionControl.instances).toHaveLength(0); http.expectNone(() => true); - const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; - expect(button.getAttribute('aria-expanded')).toBe('true'); expect(button.getAttribute('aria-label')).toContain('Mostrar figuras'); - button.focus(); button.click(); await render(); expect(document.activeElement).toBe(button); expect(panels()).toHaveLength(1); respond(); - button.click(); await render(); expect(button.getAttribute('aria-expanded')).toBe('false'); expect(panels()).toHaveLength(0); http.expectNone(() => true); - button.click(); await render(); expect(panels()).toHaveLength(1); respond(); - }); - it('búsqueda activa indirectamente una pendiente visible y conserva cierre manual al limpiar', async () => { - memory.rememberActivation('tea', 'i0', 'manual-closed'); await load(); await idle(); - const original = cards(); page.changeSearchQuery('Indicador 4'); await render(); - expect(cards()[0]).toBe(original[4]); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - http.expectNone(() => true); notify(); await confirm(); respond(); - page.changeSearchQuery(''); await render(); expect(cards()).toEqual(original); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); expect(cards()[4].expanded).toBe(true); http.expectNone(() => true); - }); - it('reordenar una pendiente fuera de vista no autoriza carga con callback antiguo', async () => { - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); const target = cards()[0].visibilityHeader.nativeElement; - notify(); await frame(); page.changeSearchQuery('Indicador 4'); await render(); - positions([[1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); observer().emit(target); await idle(); - expect(cards().every(card => !card.expanded)).toBe(true); http.expectNone(() => true); - }); - it('retirar tarjetas desobserva sus cabeceras y descarta callbacks tardíos', async () => { - await load(); const retired = cards()[0].visibilityHeader.nativeElement, active = observer(); - page.catalog.set(items.slice(1)); await render(); - expect(active.unobserve).toHaveBeenCalledWith(retired); active.emit(retired); await idle(); http.expectNone(() => true); - }); - it('cambiar de dominio cancela HTTP e ignora el observer saliente', async () => { - await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); - const request = http.expectOne(r => r.url.includes('/figuras/')), old = observer(), target = cards()[0].visibilityHeader.nativeElement; - page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); - expect(old.disconnect).toHaveBeenCalled(); old.emit(target); await idle(); http.expectNone(() => true); - }); - it('destruir desconecta observers, cancela frames y hace inocuos callbacks tardíos', async () => { - await load(); const active = observer(), target = cards()[0].visibilityHeader.nativeElement; - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame(); - const sizeObserver = ResizeControl.instances.find(instance => instance.targets.has(sticky))!; - const scheduled = new Set(frames.keys()); - const cancellations = vi.mocked(window.cancelAnimationFrame).mock.calls.length; - fixture.destroy(); expect(active.disconnect).toHaveBeenCalled(); expect(sizeObserver.disconnect).toHaveBeenCalled(); - const cancelled = vi.mocked(window.cancelAnimationFrame).mock.calls.slice(cancellations).map(([id]) => id); - expect(cancelled.some(id => scheduled.has(id))).toBe(true); - for (const id of cancelled) expect(frames.has(id)).toBe(false); - // Angular/Material can own another global frame; late page callbacks must add none. - const remaining = frames.size; - active.emit(target); sizeObserver.emit(); window.dispatchEvent(new Event('scroll')); - expect(frames.size).toBe(remaining); http.expectNone(() => true); - }); - it('apertura automática monta sólo la primera figura y el cierre cancela la seleccionada', async () => { - await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); - const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(1); - requests[0].flush('private', { status: 500, statusText: 'Error' }); await render(); - expect(panels().map(panel => panel.result().status)).toEqual(['error']); - cards()[0].selectFigure('g'); await render(); - const current = http.expectOne(r => r.url.endsWith('/figuras/g')); - cards()[0].toggle(); await render(); expect(current.cancelled).toBe(true); - notify(); await idle(); http.expectNone(() => true); cards()[0].toggle(); await render(); - expect(panels()[0].figuraId).toBe('g'); respond(); - }); - it('fallback sin observers permite la apertura y cierre de una tarjeta pendiente', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', undefined); create(); - await load([items[0]]); expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - const button = fixture.nativeElement.querySelector('app-indicador-catalog-card header button') as HTMLButtonElement; - for (const key of ['Tab', 'Enter', ' ']) { - const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }); - button.dispatchEvent(event); expect(event.defaultPrevented).toBe(false); - } - button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-open'); respond(); - button.click(); await render(); expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - }); - it('la activación protegida nunca sobrescribe una decisión manual', async () => { - memory.rememberActivation('tea', 'i0', 'manual-closed'); memory.rememberActivation('tea', 'i1', 'manual-open'); await load(); - cards()[0].activateVisible(); cards()[1].activateVisible(); await render(); - expect(memory.activation('tea', 'i0')).toBe('manual-closed'); expect(cards()[0].expanded).toBe(false); - expect(memory.activation('tea', 'i1')).toBe('manual-open'); expect(cards()[1].figuresActivated).toBe(true); respond(); - cards()[1].activateVisible(); await render(); http.expectNone(() => true); - }); - it('scroll progresivo reactiva evaluación sin mantener un bucle cuando todo está fuera', async () => { - await load(); await idle(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); - positions([[-1000, 0], [200, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); respond(); await idle(); - expect(cards().map(card => card.expanded)).toEqual([true, true, false, false, false]); http.expectNone(() => true); - }); - it('búsqueda reconstruye la fila visual usando las mismas instancias', async () => { - await load(); await idle(); const before = cards(); page.changeSearchQuery('Indicador 4'); await render(); - positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); notify(); await confirm(); respond(); await idle(); - expect(memory.activation('tea', 'i4')).toBe('auto-open'); expect(memory.activation('tea', 'i0')).toBe('auto-open'); - expect(memory.activation('tea', 'i1')).toBe('pending'); - expect(cards().every(card => before.includes(card))).toBe(true); http.expectNone(() => true); - }); - it('una cabecera fuera horizontalmente no se considera visible', async () => { - await load([items[0]]); positions([[200, 1500]]); notify(); await idle(); - expect(cards()[0].expanded).toBe(false); http.expectNone(() => true); - }); - it('visibilidad y búsqueda conservan hosts Plotly, resultados y foco sin react ni purge repetidos', async () => { - http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), - { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); - await load(); positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - const input = fixture.nativeElement.querySelector('.catalog-search input') as HTMLInputElement; input.focus(); notify(); await confirm(); respond(); await render(); - for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); - const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart; - const host = chart.host.nativeElement, panel = panels()[0], result = panel.result(), reacts = runtime.react.mock.calls.length; - expect(reacts).toBe(1); expect(document.activeElement).toBe(input); - page.changeSearchQuery('Indicador 0'); await render(); notify(); await idle(); - expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.host.nativeElement).toBe(host); - expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); expect(document.activeElement).toBe(input); - expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true); - }); - it('D.2 aplicar fuera de pantalla no activa tarjetas y scroll consulta la revisión vigente una sola vez', async () => { + it('observa regiones gráficas permanentemente con margen de anticipación y sticky', async () => { await load(); await idle(); + expect(observer().options).toEqual({ root: null, threshold: 0, rootMargin: '-100px 0px 200px 0px' }); + expect([...observer().targets]).toEqual(cards().map(c => c.visibilityRegion!.nativeElement)); + positions([[900, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + expect(observer().targets.size).toBe(5); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelectorAll('.figure-skeleton')).toHaveLength(4); + }); + it('salir y volver conserva panel, resultado y selección sin HTTP redundante', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], result = panel.result(); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(0, false); await idle(); + expect(cards()[0].visible).toBe(false); expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await idle(); + expect(panel.result()).toBe(result); http.expectNone(() => true); + }); + it('filtro fuera de vista conserva host y consulta únicamente el último aplicado al regresar', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); respond(); await render(); + const panel = panels()[0], chart = fixture.nativeElement.querySelector('app-plotly-chart'); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); await idle(); const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; - filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); - page.applyFilters(); await render(); await idle(); - expect(cards().every(card => !card.figuresActivated)).toBe(true); http.expectNone(() => true); - positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); - const first = http.expectOne(r => r.url.includes('/i0/figuras/')); - expect(first.request.params.get('periodos')).toBe('2025-S1'); first.flush({ data: [], layout: {} }); - expect(panels()[0].applied.revision).toBe(1); await idle(); - cards()[0].toggle(); await render(); - filters.unit = 'S2'; filters.add(); page.applyFilters(); await render(); await idle(); - expect(memory.activation('tea', 'i0')).toBe('manual-closed'); http.expectNone(() => true); - positions([[-1000, 0], [200, 0], [1200, 0], [1400, 0], [1600, 0]]); - window.dispatchEvent(new Event('scroll')); await confirm(); - const second = http.expectOne(r => r.url.includes('/i1/figuras/')); - expect(second.request.params.get('periodos')).toBe('2025-S1,2025-S2'); second.flush({ data: [], layout: {} }); - expect(panels()[0].applied.revision).toBe(2); await idle(); - notify(1); await idle(); page.applyFilters(); await render(); http.expectNone(() => true); + filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add(); page.applyFilters(); await render(); + filters.unit = 'S2'; filters.add(); page.applyFilters(); page.changeTema('oscuro'); await render(); await idle(); + expect(panels()[0]).toBe(panel); expect(panel.result().status).toBe('deferred'); + expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/i0/figuras/')); + expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2'); expect(request.request.params.get('tema')).toBe('oscuro'); + request.flush({ data: [{ y: [2] }], layout: {} }); await render(); notify(); await idle(); http.expectNone(() => true); + }); + it('aplicar antes del frame de scroll relee geometría y cancela petición obsoleta sin nueva descarga', async () => { + await load(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.includes('/i0/figuras/')); + positions([[-1000, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); window.dispatchEvent(new Event('scroll')); + page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] }; page.applyFilters(); await render(); + expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('deferred'); http.expectNone(() => true); + expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); await idle(); + }); + it('cambio rápido de representación cancela saliente y fuera de vista difiere seleccionada', async () => { + await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm(); + const old = http.expectOne(r => r.url.endsWith('/figuras/f')); cards()[0].selectFigure('g'); await render(); + expect(old.cancelled).toBe(true); const next = http.expectOne(r => r.url.endsWith('/figuras/g')); + cards()[0].selectFigure('h'); await render(); expect(next.cancelled).toBe(true); + http.expectOne(r => r.url.endsWith('/figuras/h')).flush({ data: [], layout: {} }); await render(); + expect(panels()).toHaveLength(1); positions([[-1000, 0]]); notify(0, false); await idle(); + cards()[0].selectFigure('g'); await render(); http.expectNone(() => true); expect(panels()[0].result().status).toBe('deferred'); + positions([[200, 0]]); notify(); await confirm(); http.expectOne(r => r.url.endsWith('/figuras/g')).flush({ data: [], layout: {} }); + }); + it('fijación y búsqueda conservan componentes y descartan callbacks con geometría antigua', async () => { + await load(); const before = cards(); positions([[200, 0], [1200, 0], [1400, 0], [1600, 0], [1800, 0]]); + const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render(); + page.changeSearchQuery('Indicador 3'); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0])); + observer().emit(target); await idle(); http.expectNone(() => true); + expect(cards()[0]).toBe(before[3]); expect(cards()[1]).toBe(before[4]); expect(cards().every(c => before.includes(c))).toBe(true); + positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm(); + http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render(); + expect(cards()[0].selectedFigure).toBe('f'); + }); + it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush(figure); await render(); + expect(panels()[0].result().status).toBe('ready'); expect(panels()[0].result().figure).toEqual(figure); + expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); + if (figure.layout.annotations) expect(panels()[0].result().figure?.layout['annotations']).toEqual(figure.layout.annotations); + }); + it('error HTTP termina skeleton y reintenta sólo la figura visible', async () => { + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); + http.expectOne(r => r.url.includes('/figuras/')).flush('private', { status: 503, statusText: 'Unavailable' }); await render(); + expect(panels()[0].result().status).toBe('error'); expect(fixture.nativeElement.querySelector('.figure-skeleton')).toBeNull(); + panels()[0].requestFigure(); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + }); + it('fallback sin IntersectionObserver muestra las figuras sin interacción manual', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); create(); + await load([items[0]]); respond(); await render(); expect(panels()[0].result().status).toBe('ready'); + expect(fixture.nativeElement.querySelector('app-indicador-catalog-card header button')).toBeNull(); http.expectNone(() => true); + }); + it('dominio cancela solicitudes, desobserva tarjetas retiradas e ignora callback antiguo', async () => { + await load(); const oldObserver = observer(), retired = cards()[0].visibilityRegion!.nativeElement; + page.catalog.set(items.slice(1)); await render(); expect(oldObserver.unobserve).toHaveBeenCalledWith(retired); + oldObserver.emit(retired); await idle(); http.expectNone(() => true); + positions([[200, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await confirm(); + const request = http.expectOne(r => r.url.includes('/figuras/')); + page.changeDominio('cama'); await load([items[0]], 'cama'); expect(request.cancelled).toBe(true); + expect(oldObserver.disconnect).toHaveBeenCalled(); oldObserver.emit(retired); await idle(); http.expectNone(() => true); + }); + it('destrucción desconecta observers, cancela frame y vuelve inocuos callbacks tardíos', async () => { + await load(); const active = observer(), target = cards()[0].visibilityRegion!.nativeElement; + notify(); const pending = [...frames.keys()]; fixture.destroy(); + expect(active.disconnect).toHaveBeenCalled(); expect(ResizeControl.instances.some(o => o.disconnect.mock.calls.length)).toBe(true); + expect(pending.some(id => vi.mocked(window.cancelAnimationFrame).mock.calls.some(call => call[0] === id))).toBe(true); + const remaining = frames.size; active.emit(target); window.dispatchEvent(new Event('scroll')); expect(frames.size).toBe(remaining); + }); + it('hosts Plotly permanecen montados fuera de vista y se purgan al destruir', async () => { + http.expectOne('/tea/indicadores'); fixture.destroy(); TestBed.resetTestingModule(); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); create(); + await load([items[0]]); positions([[200, 0]]); notify(); await confirm(); respond(); await render(); + for (let i = 0; i < 12; i++) await Promise.resolve(); await render(); + const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart, host = chart.host.nativeElement; + expect(runtime.react).toHaveBeenCalledTimes(1); positions([[-1000, 0]]); notify(0, false); await idle(); + expect(chart.host.nativeElement).toBe(host); expect(runtime.purge).not.toHaveBeenCalled(); + positions([[200, 0]]); notify(); await idle(); expect(runtime.react).toHaveBeenCalledTimes(1); http.expectNone(() => true); + fixture.destroy(); expect(runtime.purge).toHaveBeenCalledWith(host); }); });