feat(ui): incorporar filtros globales por dominio UX-06E.D.2
This commit is contained in:
@@ -4,7 +4,7 @@ import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||
import { CardActivation, IndicadoresMemory } from './indicadores-memory';
|
||||
import { CardActivation, GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { indicatorIdentity, figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
|
||||
@@ -28,7 +28,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
} @else if (expanded && figuresActivated) {
|
||||
<p class="catalog-metadata">Contrato {{ indicador.contrato }} · {{ indicador.figuras.length }} figuras publicadas</p>
|
||||
@for (figure of indicador.figuras; track panelIdentity(figure)) {
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [figuraId]="figure" [tema]="tema" />
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [figuraId]="figure" [tema]="tema" [applied]="applied" />
|
||||
} @empty { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
}
|
||||
</div>
|
||||
@@ -54,6 +54,7 @@ export class IndicadorCatalogCard implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@ViewChild('visibilityHeader', { static: true }) visibilityHeader!: ElementRef<HTMLElement>;
|
||||
readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
readonly activationChanged = output<void>();
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
@if (state.status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<p class="state" role="status">Cargando figura…</p>
|
||||
} @else if (state.status === 'incompatible') {
|
||||
<div class="state incompatible" role="status"><p>Filtro general incompatible con esta figura.</p><p>{{ state.message }}</p></div>
|
||||
} @else if (state.status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ state.message }}</p>
|
||||
<button mat-stroked-button (click)="retry.emit()">Reintentar solicitud</button></div>
|
||||
@@ -32,8 +34,12 @@
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figuraId }}</p>
|
||||
<app-plotly-chart [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="state.presentationFigure!" />
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@if (chartFigure) {
|
||||
<div [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" />
|
||||
</div>
|
||||
}
|
||||
</mat-card>
|
||||
|
||||
@@ -113,20 +113,22 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('destruye Plotly al abandonar el resultado y al destruir la card', async () => {
|
||||
ready({ data: [{ y: [42] }], layout: {} });
|
||||
await settle();
|
||||
it('D.2 mantiene Plotly oculto entre resultados y purga al destruir la card', async () => {
|
||||
ready({ data: [{ y: [42] }], layout: {} }); await settle();
|
||||
const firstHost = fixture.nativeElement.querySelector('.plot');
|
||||
expect(observe).toHaveBeenCalledWith(firstHost);
|
||||
state({ status: 'loading' });
|
||||
expect(purge).toHaveBeenCalledWith(firstHost);
|
||||
expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
ready({ data: [{ y: [50] }], layout: {} });
|
||||
await settle();
|
||||
const secondHost = fixture.nativeElement.querySelector('.plot');
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(purge).not.toHaveBeenCalled(); expect(disconnect).not.toHaveBeenCalled();
|
||||
state({ status: 'incompatible', message: 'Granularidad no publicada' });
|
||||
expect(firstHost.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('Granularidad no publicada');
|
||||
ready({ data: [{ y: [50] }], layout: {} }); await settle();
|
||||
expect(fixture.nativeElement.querySelector('.plot')).toBe(firstHost);
|
||||
expect(firstHost.closest('[hidden]')).toBeNull();
|
||||
fixture.destroy();
|
||||
expect(purge).toHaveBeenCalledWith(secondHost);
|
||||
expect(disconnect).toHaveBeenCalledTimes(2);
|
||||
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', () => {
|
||||
fixture.componentRef.setInput('figuraId', 'fig_c2_apiladas');
|
||||
|
||||
@@ -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';
|
||||
status: 'idle' | 'loading' | 'ready' | 'error' | 'incompatible';
|
||||
figure?: PlotlyFigure;
|
||||
presentationFigure?: PlotlyFigure;
|
||||
message?: string;
|
||||
@@ -45,7 +45,15 @@ const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
export class IndicadorFigureCard {
|
||||
@Input({ required: true }) state!: FigureState;
|
||||
private currentState!: FigureState;
|
||||
// Keep the mounted host's last presentation only. The template hides it whenever
|
||||
// it is not the current result; this is neither applied state nor a results cache.
|
||||
chartFigure?: PlotlyFigure;
|
||||
@Input({ required: true }) set state(value: FigureState) {
|
||||
this.currentState = value;
|
||||
if (value.status === 'ready') this.chartFigure = value.presentationFigure;
|
||||
}
|
||||
get state() { return this.currentState; }
|
||||
@Input() selected?: Indicador;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { applyGlobal, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
@@ -19,24 +20,30 @@ const catalog = [
|
||||
];
|
||||
describe('IndicadorFigurePanel', () => {
|
||||
let page: IndicadorFigurePanel;
|
||||
let state: GlobalFilterState;
|
||||
let editor: IndicadorPeriodFilters;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorFigurePanel>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel, IndicadorPeriodFilters], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
editor = new IndicadorPeriodFilters(); editor.state = state; editor.types = ['semestre'];
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
return editor;
|
||||
}
|
||||
function apply() { if (applyGlobal(state, ['semestre'])) { fixture.componentRef.setInput('applied', state.applied); fixture.detectChanges(); } }
|
||||
function load() { fixture.detectChanges(); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
|
||||
@@ -73,10 +80,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
expect(style.position).toBe('absolute'); expect(style.width).toBe('1px'); expect(style.height).toBe('1px');
|
||||
expect(style.clipPath).toBe('inset(50%)'); expect(style.overflow).toBe('hidden');
|
||||
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
|
||||
expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeTruthy();
|
||||
const result = page.result(), state = page.filters;
|
||||
expect(fixture.nativeElement.querySelector('app-indicador-period-filters')).toBeNull();
|
||||
const result = page.result(), savedState = state;
|
||||
fixture.detectChanges();
|
||||
expect(page.titleId).toBe(id); expect(page.filters).toBe(state); expect(page.result()).toBe(result);
|
||||
expect(page.titleId).toBe(id); expect(state).toBe(savedState); expect(page.result()).toBe(result);
|
||||
expect(fixture.nativeElement.querySelector('h3')).toBe(heading);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -104,22 +111,22 @@ describe('IndicadorFigurePanel', () => {
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
expect(page.filters?.applied?.selection.mode).toBe('todos');
|
||||
page.applyFilters();
|
||||
expect(state?.applied?.selection.mode).toBe('todos');
|
||||
apply();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
apply();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
page.applyFilters();
|
||||
apply();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
@@ -163,15 +170,15 @@ describe('IndicadorFigurePanel', () => {
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([0, null]);
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres con reporte');
|
||||
expect(editor.hasPending).toBe(true);
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
});
|
||||
it.each([{ periodos: ['2025-S1'] }, { periodos: ['2025-S1', '2025-S2'] }])('404 de conjunto conserva borrador y reintenta la última aplicación', ({ periodos }) => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025';
|
||||
for (const period of periodos) { control.unit = period.slice(-2); control.add(); }
|
||||
page.applyFilters();
|
||||
apply();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
@@ -193,7 +200,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
it('reintento y tema utilizan la selección aplicada aunque el borrador sea diferente', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
apply(); figure().flush({ data: [{ y: [20] }], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
fixture.componentRef.setInput('tema', 'oscuro'); fixture.detectChanges();
|
||||
const themed = figure();
|
||||
@@ -208,10 +215,10 @@ describe('IndicadorFigurePanel', () => {
|
||||
it('descarta respuestas obsoletas de aplicaciones sucesivas', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); const old = figure();
|
||||
apply(); const old = figure();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
page.applyFilters(); const current = figure();
|
||||
apply(); const current = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(current.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
current.flush({ data: [{ y: [12] }], layout: {} });
|
||||
@@ -223,14 +230,14 @@ describe('IndicadorFigurePanel', () => {
|
||||
load(); figure().flush({ data: [{ y: [42] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges();
|
||||
const result = page.result(), filterState = page.filters, snapshot = JSON.stringify(filterState);
|
||||
const result = page.result(), filterState = state, snapshot = JSON.stringify(filterState);
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle');
|
||||
for (let i = 0; i < 4; i++) { button.click(); fixture.detectChanges(); }
|
||||
http.expectNone(() => true);
|
||||
expect(page.result()).toBe(result); expect(page.filters).toBe(filterState);
|
||||
expect(JSON.stringify(page.filters)).toBe(snapshot);
|
||||
expect(page.result()).toBe(result); expect(state).toBe(filterState);
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(filters()).toBe(control);
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigureCard)).componentInstance).toBe(card);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
@@ -238,8 +245,9 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(page.filters)).toBe(snapshot);
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
expect(fixture.nativeElement.querySelector('.methodology-toggle').getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, signal, SimpleChanges } 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';
|
||||
@@ -6,21 +6,17 @@ import { Dominio, FigureSelection, Indicador, Tema } from './indicadores.models'
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { presentationFigure } from './indicadores.presentation';
|
||||
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { FilterState, IndicadoresMemory, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied, selectionKey } from './indicadores-memory';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
imports: [IndicadorPeriodFilters, IndicadorFigureCard],
|
||||
imports: [IndicadorFigureCard],
|
||||
template: `
|
||||
<section [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }} · {{ indicador.id }} · {{ indicador.titulo }} · {{ figuraId }}</h3>
|
||||
@if (filters; as state) {
|
||||
<app-indicador-period-filters [state]="state" [types]="indicador.tipos_periodo"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
}
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
[figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (retry)="requestFigure()" />
|
||||
</section>
|
||||
@@ -28,78 +24,67 @@ import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-4); border-top: 1px solid var(--issste-border); }
|
||||
.applied-summary { color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.visually-hidden {
|
||||
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class IndicadorFigurePanel implements OnChanges, OnDestroy {
|
||||
export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly figureRequests = new Subject<FigureSelection | null>();
|
||||
private identity = '';
|
||||
private readonly figureRequests = new Subject<{ selection: FigureSelection; revision: number; generation: number } | null>();
|
||||
private generation = 0;
|
||||
private currentKey = '';
|
||||
titleId = '';
|
||||
filters?: FilterState;
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin selección aplicada'; }
|
||||
constructor() {
|
||||
this.figureRequests.pipe(switchMap(selection => selection
|
||||
? defer(() => this.service.figura(selection)).pipe(
|
||||
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState),
|
||||
this.figureRequests.pipe(switchMap(request => request
|
||||
? defer(() => this.service.figura(request.selection)).pipe(
|
||||
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, request.selection) }) as FigureState),
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (selection.periodos?.length ?? 0) > 1
|
||||
&& (request.selection.periodos?.length ?? 0) > 1
|
||||
? ' La consulta corresponde al conjunto de periodos; esta respuesta no identifica un periodo concreto.' : ''),
|
||||
} as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState))
|
||||
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => this.result.set(state));
|
||||
startWith({ status: 'loading' } as FigureState),
|
||||
map(state => ({ state, revision: request.revision, generation: request.generation })))
|
||||
: of({ state: { status: 'idle' } as FigureState, revision: this.applied?.revision, generation: this.generation })), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(({ state, revision, generation }) => {
|
||||
if (generation === this.generation && revision === this.applied?.revision) this.result.set(state);
|
||||
});
|
||||
}
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId);
|
||||
if (identity !== this.identity || changes['indicador']) {
|
||||
// Save the departing identity before accepting a new catalog object.
|
||||
this.saveCurrent();
|
||||
this.identity = identity;
|
||||
this.titleId = identityElementId(identity) + '-title';
|
||||
this.filters = this.indicador.figuras.includes(this.figuraId)
|
||||
? this.memory.restore(this.dominio, this.indicador, this.figuraId) : undefined;
|
||||
this.filtersEdited();
|
||||
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();
|
||||
} else if (changes['tema']) this.requestFigure();
|
||||
}
|
||||
private saveCurrent() {
|
||||
if (!this.filters || !this.identity) return;
|
||||
const [domain, indicator, figure] = JSON.parse(this.identity) as [Dominio, string, string];
|
||||
this.memory.save(domain, indicator, figure, this.filters);
|
||||
}
|
||||
filtersEdited() { this.saveCurrent(); }
|
||||
applyFilters() {
|
||||
if (!this.filters) return;
|
||||
const draft = this.filters.editors[this.filters.tipo]!.draft;
|
||||
if (!validDraft(draft, this.filters.tipo, this.indicador.tipos_periodo)) return;
|
||||
this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) };
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
}
|
||||
requestFigure() {
|
||||
const applied = this.filters?.applied;
|
||||
if (!this.indicador.figuras.includes(this.figuraId) || !applied
|
||||
|| !validDraft(applied.selection, applied.tipo, this.indicador.tipos_periodo)) {
|
||||
const applied = this.applied;
|
||||
const compatibility = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
this.generation++;
|
||||
if (!this.indicador.figuras.includes(this.figuraId) || !compatibility.compatible) {
|
||||
this.figureRequests.next(null);
|
||||
this.result.set({ status: 'incompatible', message: !compatibility.compatible
|
||||
? compatibility.reason : 'Esta figura ya no está publicada en el catálogo.' });
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({
|
||||
this.figureRequests.next({ revision: applied.revision, generation: this.generation, selection: {
|
||||
dominio: this.dominio, indicador: this.indicador.id, figura: this.figuraId,
|
||||
tipoPeriodo: applied.tipo, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
});
|
||||
} });
|
||||
}
|
||||
ngOnDestroy() { this.saveCurrent(); }
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
<section aria-label="Filtros de periodos de la figura">
|
||||
<section aria-label="Editor de filtros generales del proyecto">
|
||||
@if (state.tipo === 'mes') { <p class="filter-help">Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.</p> }
|
||||
@if (!types.includes(state.tipo)) { <p role="status">La granularidad del borrador ya no está publicada para este proyecto. Elige una granularidad disponible.</p> }
|
||||
<div class="fields">
|
||||
@if (types.length > 1) {
|
||||
@if (types.length > 1 || !types.includes(state.tipo)) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Granularidad</mat-label>
|
||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (state.tipo === types[0]) {
|
||||
@if (state.tipo === 'semestre' && state.tipo === types[0]) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? (state.tipo === 'mes' ? 'Todos los meses con reporte' : 'Todos los semestres con reporte') : 'Elegir periodos' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos los {{ state.tipo === 'mes' ? 'meses' : 'semestres' }} con reporte</mat-option>
|
||||
<mat-select-trigger><span class="select-value">{{ entry.draft.mode === 'todos' ? 'Todos con reporte' : 'Elegir periodos' }}</span></mat-select-trigger>
|
||||
<mat-option value="todos">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodos</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@@ -46,7 +48,8 @@
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p class="draft-summary">Selección en edición: {{ summary }}</p>
|
||||
@if (!canApply) { <p role="status">Selecciona al menos un periodo válido para aplicar.</p> }
|
||||
@if (!hasPending) { <p class="pending">Sin cambios pendientes.</p> }
|
||||
@if (hasPending) { <p class="pending" role="status">Hay cambios sin aplicar.</p> }
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply" (click)="apply.emit()">Aplicar</button>
|
||||
<p class="applied-summary">Filtros de la consulta aplicada: {{ appliedSummary }}</p>
|
||||
<button class="apply-button" type="button" mat-flat-button [disabled]="!canApply || !hasPending" (click)="apply.emit()">Aplicar</button>
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('UX-04 control asistido', () => {
|
||||
afterEach(() => fixture.destroy());
|
||||
it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => {
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos los semestres con reporte');
|
||||
expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte');
|
||||
fixture.componentRef.setInput('state', {
|
||||
...control.state, editors: { ...control.state.editors, semestre: {
|
||||
added: ['2025-S1', '2025-S2'], draft: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] },
|
||||
@@ -124,7 +124,7 @@ describe('UX-04 control asistido', () => {
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar');
|
||||
expect(fixture.nativeElement.textContent).toContain('no es un inventario de reportes');
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtros de la consulta aplicada: Todos los semestres');
|
||||
expect(fixture.nativeElement.textContent).toContain('Filtro general aplicado: Todos con reporte');
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -40,7 +40,7 @@ export class IndicadorPeriodFilters implements OnChanges {
|
||||
this.edited.emit();
|
||||
}
|
||||
changeMode(mode: 'todos' | 'manual') {
|
||||
if (mode === 'todos' && this.state.tipo !== this.types[0]) return;
|
||||
if (mode === 'todos' && (this.state.tipo !== 'semestre' || this.state.tipo !== this.types[0])) return;
|
||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
||||
this.error = '';
|
||||
this.edited.emit();
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { Component } from '@angular/core';
|
||||
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 { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
class ChartStub {}
|
||||
const item = (id: string, types: TipoPeriodo[] = ['semestre', 'mes']): Indicador =>
|
||||
({ id, titulo: id, contrato: 'C1', figuras: ['f'], tipos_periodo: types });
|
||||
describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
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 editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
function open(index = 0) { cards()[index].toggle(); 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[]) {
|
||||
const control = editor(); control.changeTipo(tipo); control.changeMode('manual');
|
||||
for (const period of periods) { control.year = period.slice(0, 4); control.unit = period.slice(5); control.add(); }
|
||||
}
|
||||
function apply() { page.applyFilters(); fixture.detectChanges(); }
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('un editor general de %s antes de KPI y sin HTTP inicial', domain => {
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores'); page.changeDominio(domain); }
|
||||
load(undefined, domain);
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf<HTMLElement>;
|
||||
expect(sections[0].textContent).toContain('Filtros generales de ' + page.domainLabels[domain]);
|
||||
expect(sections[1].querySelectorAll('app-indicador-kpi-card')).toHaveLength(2);
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('edición y vacío no consultan ni cambian el resultado vigente', () => {
|
||||
load(); open(); respond(); const result = panels()[0].result();
|
||||
editor().changeMode('manual'); apply(); expect(page.filters!.applied.revision).toBe(0);
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
draft('semestre', ['2025-S1']); fixture.detectChanges();
|
||||
expect(panels()[0].result()).toBe(result); expect(page.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
|
||||
});
|
||||
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);
|
||||
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);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('aplicación equivalente conserva revisión, consumidores, hosts y resultados', () => {
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1', '2025-S2']); apply(); respond();
|
||||
const panel = panels()[0], result = panel.result(), chart = fixture.nativeElement.querySelector('app-plotly-chart'), applied = page.filters!.applied;
|
||||
editor().select(['2025-S2', '2025-S1']); apply();
|
||||
expect(page.filters!.applied).toBe(applied); expect(panel.result()).toBe(result);
|
||||
expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(chart); expect(panels()[0]).toBe(panel); http.expectNone(() => true);
|
||||
});
|
||||
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();
|
||||
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);
|
||||
});
|
||||
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);
|
||||
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(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', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(0); open(1); respond();
|
||||
const panel = panels()[0], host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('mes', ['2025-01']); apply();
|
||||
expect(panel.result().status).toBe('incompatible'); expect(panel.result().figure).toBeUndefined();
|
||||
http.expectNone(r => r.url.includes('/a/figuras/')); const r = request('b');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); expect(r.request.params.has('tipoPeriodo')).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('.incompatible').textContent).toContain('granularidad mes');
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
r.flush({ data: [], layout: {} });
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
});
|
||||
it('incompatibilidad cancela solicitud pendiente y no queda cargando', () => {
|
||||
load([item('a', ['semestre']), item('b')]); open(); const old = request('a');
|
||||
draft('mes', ['2025-01']); apply(); expect(old.cancelled).toBe(true); expect(panels()[0].result().status).toBe('incompatible');
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow(); http.expectNone(() => true);
|
||||
});
|
||||
it('dos revisiones cancelan respuestas anteriores y carga oculta resultado previo conservando host', () => {
|
||||
load(); open(); respond(); const host = fixture.nativeElement.querySelector('app-plotly-chart');
|
||||
draft('semestre', ['2025-S1']); apply(); const old = request('a');
|
||||
expect(panels()[0].result().figure).toBeUndefined(); expect((host as HTMLElement).parentElement!.hidden).toBe(true);
|
||||
editor().unit = 'S2'; editor().add(); apply(); const current = request('a');
|
||||
expect(old.cancelled).toBe(true); current.flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].result().figure!.data[0]['y']).toEqual([7]); expect(fixture.nativeElement.querySelector('app-plotly-chart')).toBe(host);
|
||||
expect((host as HTMLElement).parentElement!.hidden).toBe(false);
|
||||
});
|
||||
it('404 y reintento individual usan aplicado vigente y conservan borrador y otra figura', () => {
|
||||
load(); open(0); open(1); respond(); draft('semestre', ['2025-S1']); apply();
|
||||
request('a').flush('private', { status: 404, statusText: 'Not Found' }); request('b').flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const other = panels()[1].result(); editor().select([]); panels()[0].requestFigure();
|
||||
const retry = request('a'); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} }); expect(panels()[1].result()).toBe(other); expect(editor().entry.draft.mode).toBe('empty');
|
||||
});
|
||||
it('dominio durante carga cancela saliente y restaura borrador separado del aplicado', () => {
|
||||
load(); open(); respond(); draft('semestre', ['2025-S1']); apply(); const outgoing = request('a');
|
||||
editor().unit = 'S2'; editor().add(); page.changeDominio('cacu'); fixture.detectChanges();
|
||||
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);
|
||||
});
|
||||
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();
|
||||
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);
|
||||
});
|
||||
it('orden del catálogo no permite simular Todos mensual', () => {
|
||||
load([item('a', ['mes', 'semestre'])]); open(); expect(panels()[0].result().status).toBe('incompatible'); http.expectNone(() => true);
|
||||
draft('mes', ['2025-01']); apply(); request('a').flush({ data: [], layout: {} });
|
||||
});
|
||||
});
|
||||
@@ -1,80 +1,88 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { FilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { TipoPeriodo } from './indicadores.models';
|
||||
import { applyGlobal, domainTypes, filterCompatibility, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
|
||||
const indicador: Indicador = { id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre', 'mes'] };
|
||||
describe('UX-04 memoria temporal', () => {
|
||||
describe('D.2 memoria global por dominio', () => {
|
||||
let memory: IndicadoresMemory;
|
||||
beforeEach(() => { TestBed.configureTestingModule({}); memory = TestBed.inject(IndicadoresMemory); });
|
||||
it('inicia con Todos en el primer tipo del catálogo y vacío independiente en el otro', () => {
|
||||
const state = memory.restore('tea', indicador, 'f');
|
||||
expect(state.editors.semestre?.draft).toEqual({ mode: 'todos' });
|
||||
expect(state.editors.mes?.draft).toEqual({ mode: 'empty' });
|
||||
expect(state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
expect(pending(state)).toBe(false);
|
||||
expect(memory.restore('tea', { ...indicador, tipos_periodo: ['mes', 'semestre'] }, 'g').applied?.tipo).toBe('mes');
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('inicia %s con Todos y revisión cero', domain => {
|
||||
const state = memory.restoreGlobal(domain, ['semestre', 'mes']);
|
||||
expect(state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 });
|
||||
expect(state.editors.mes?.draft.mode).toBe('empty'); expect(pending(state)).toBe(false);
|
||||
});
|
||||
it('restaura copias de borradores y aplicación sin compartir referencias', () => {
|
||||
const state = memory.restore('tea', indicador, 'f');
|
||||
state.tipo = 'mes';
|
||||
state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } };
|
||||
memory.save('tea', 'i', 'f', state);
|
||||
state.editors.mes.added.push('2025-02');
|
||||
const restored = memory.restore('tea', indicador, 'f');
|
||||
expect(restored.editors.mes?.added).toEqual(['2025-01']);
|
||||
expect(restored.applied?.tipo).toBe('semestre');
|
||||
expect(pending(restored)).toBe(true);
|
||||
it('guarda y restaura borrador y aplicado con copias defensivas', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre', 'mes']);
|
||||
state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } };
|
||||
memory.saveGlobal('tea', state); state.editors.mes.added.push('2025-02');
|
||||
const restored = memory.restoreGlobal('tea', ['semestre', 'mes']);
|
||||
expect(restored.editors.mes?.added).toEqual(['2025-01']); expect(restored.applied.tipo).toBe('semestre');
|
||||
restored.editors.mes!.added.length = 0;
|
||||
expect(memory.restore('tea', indicador, 'f').editors.mes?.added).toEqual(['2025-01']);
|
||||
expect(memory.restoreGlobal('tea', ['semestre', 'mes']).editors.mes?.added).toEqual(['2025-01']);
|
||||
});
|
||||
it('aísla dominios, indicadores y figuras', () => {
|
||||
const state = memory.restore('tea', indicador, 'f');
|
||||
it('aísla los tres dominios sin tomar selecciones de figuras', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']);
|
||||
state.editors.semestre = { added: ['2025-S1'], draft: { mode: 'explicit', periodos: ['2025-S1'] } };
|
||||
memory.save('tea', 'i', 'f', state);
|
||||
for (const [domain, item, figure] of [
|
||||
['cacu', indicador, 'f'], ['tea', { ...indicador, id: 'otro' }, 'f'], ['tea', indicador, 'g'],
|
||||
] as const) expect(memory.restore(domain, item, figure).editors.semestre?.draft.mode).toBe('todos');
|
||||
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('distingue activación pendiente, automática y manual y aísla dominios', () => {
|
||||
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');
|
||||
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');
|
||||
memory.rememberTheme('cacu', 'oscuro');
|
||||
expect(memory.theme('cacu')).toBe('oscuro');
|
||||
expect(memory.theme('tea')).toBe('claro');
|
||||
memory.rememberActivation('cama', 'i', 'manual-open'); expect(memory.activation('cama', 'i')).toBe('manual-open');
|
||||
memory.rememberTheme('cacu', 'oscuro'); expect(memory.theme('cacu')).toBe('oscuro'); expect(memory.theme('tea')).toBe('claro');
|
||||
});
|
||||
it('una instancia nueva reinicia las selecciones y no lee ni escribe almacenamiento', () => {
|
||||
const localRead = vi.spyOn(Storage.prototype, 'getItem');
|
||||
const localWrite = vi.spyOn(Storage.prototype, 'setItem');
|
||||
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.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } });
|
||||
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.restore('tea', indicador, 'f').tipo).toBe('semestre');
|
||||
expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled();
|
||||
localRead.mockRestore(); localWrite.mockRestore();
|
||||
expect(fresh.restoreGlobal('tea', ['semestre']).applied.revision).toBe(0);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); read.mockRestore(); write.mockRestore();
|
||||
});
|
||||
it('descarta preferencias que dejaron de ser válidas en el catálogo', () => {
|
||||
const state: FilterState = { tipo: 'mes', editors: { mes: { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } } },
|
||||
applied: { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01'] } } };
|
||||
memory.save('tea', 'i', 'f', state);
|
||||
const restored = memory.restore('tea', { ...indicador, tipos_periodo: ['semestre'] }, 'f');
|
||||
expect(restored.tipo).toBe('semestre');
|
||||
expect(restored.editors.mes).toBeUndefined();
|
||||
expect(restored.applied).toBeUndefined();
|
||||
expect(pending(restored)).toBe(true);
|
||||
it('preserva selección ante pérdida de capacidades y explica incompatibilidad', () => {
|
||||
const state = memory.restoreGlobal('cacu', ['semestre', 'mes']);
|
||||
state.tipo = 'mes'; state.editors.mes = { added: ['2025-01'], draft: { mode: 'explicit', periodos: ['2025-01'] } };
|
||||
applyGlobal(state, ['semestre', 'mes']); memory.saveGlobal('cacu', state);
|
||||
const restored = memory.restoreGlobal('cacu', ['semestre']);
|
||||
expect(restored.applied).toEqual(state.applied); expect(restored.tipo).toBe('mes');
|
||||
expect(filterCompatibility(restored.applied, ['semestre']).compatible).toBe(false);
|
||||
});
|
||||
it('deduplica por semántica, incluido orden de periodos, sin incrementar revisión', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']);
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(true); const applied = state.applied;
|
||||
state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2', '2025-S1'] };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied).toBe(applied); expect(applied.revision).toBe(1);
|
||||
});
|
||||
it('rechaza vacío sin sustituirlo por Todos', () => {
|
||||
const state = memory.restoreGlobal('tea', ['semestre']); state.editors.semestre!.draft = { mode: 'empty' };
|
||||
expect(applyGlobal(state, ['semestre'])).toBe(false); expect(state.applied.revision).toBe(0);
|
||||
});
|
||||
it('oferta unión publicada ordenada sin inventar capacidades', () => {
|
||||
expect(domainTypes([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f'], tipos_periodo: ['mes', 'semestre'] }])).toEqual(['semestre', 'mes']);
|
||||
expect(domainTypes([])).toEqual([]);
|
||||
});
|
||||
it.each([{ types: [] }, { types: ['semestre'] }, { types: ['mes', 'semestre'] }] as { types: TipoPeriodo[] }[])('adapter explica incompatibilidad mensual Todos con %j', ({ types }) => {
|
||||
expect(filterCompatibility({ tipo: 'mes', selection: { mode: 'todos' }, revision: 1 }, types).compatible).toBe(false);
|
||||
});
|
||||
it('adapter no transforma ni recorta y requiere primera granularidad para Todos', () => {
|
||||
const applied: GlobalFilterState['applied'] = { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-01', '2025-02'] }, revision: 1 };
|
||||
const snapshot = JSON.stringify(applied);
|
||||
expect(filterCompatibility(applied, ['semestre', 'mes']).compatible).toBe(true);
|
||||
expect(filterCompatibility(applied, ['semestre']).compatible).toBe(false); expect(JSON.stringify(applied)).toBe(snapshot);
|
||||
expect(filterCompatibility({ tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }, ['mes', 'semestre']).compatible).toBe(false);
|
||||
});
|
||||
});
|
||||
describe('UX-04 selección discriminada', () => {
|
||||
it('permite Todos solo en el primer tipo publicado', () => {
|
||||
expect(validDraft({ mode: 'todos' }, 'semestre', ['semestre', 'mes'])).toBe(true);
|
||||
expect(validDraft({ mode: 'todos' }, 'mes', ['semestre', 'mes'])).toBe(false);
|
||||
expect(validDraft({ mode: 'todos' }, 'mes', ['mes', 'semestre'])).toBe(true);
|
||||
expect(validDraft({ mode: 'todos' }, 'mes', ['mes', 'semestre'])).toBe(false);
|
||||
});
|
||||
it.each([
|
||||
['semestre', ['2025-S1']], ['semestre', ['0001-S1', '9999-S2']],
|
||||
|
||||
@@ -12,28 +12,52 @@ export interface FilterState {
|
||||
editors: Partial<Record<TipoPeriodo, PeriodEditor>>;
|
||||
applied?: { tipo: TipoPeriodo; selection: AppliedPeriods };
|
||||
}
|
||||
export interface GlobalApplied { tipo: TipoPeriodo; selection: AppliedPeriods; revision: number; }
|
||||
export interface GlobalFilterState extends FilterState { applied: GlobalApplied; }
|
||||
export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor {
|
||||
return { added: [], draft: tipo === first ? { mode: 'todos' } : { mode: 'empty' } };
|
||||
return { added: [], draft: tipo === 'semestre' && tipo === first ? { mode: 'todos' } : { mode: 'empty' } };
|
||||
}
|
||||
export function validDraft(draft: PeriodDraft, tipo: TipoPeriodo, types: TipoPeriodo[]): draft is AppliedPeriods {
|
||||
if (!types.includes(tipo) || draft.mode === 'empty') return false;
|
||||
if (draft.mode === 'todos') return tipo === types[0];
|
||||
if (draft.mode === 'todos') return tipo === 'semestre' && tipo === types[0];
|
||||
const parsed = parsePeriodos(draft.periodos.join(','), tipo);
|
||||
return parsed !== null && parsed.length === draft.periodos.length
|
||||
&& parsed.every((p, i) => p === draft.periodos[i]);
|
||||
}
|
||||
export function describePeriods(tipo: TipoPeriodo, draft: PeriodDraft): string {
|
||||
return draft.mode === 'todos' ? 'Todos los ' + (tipo === 'mes' ? 'meses' : 'semestres') + ' con reporte'
|
||||
return draft.mode === 'todos' ? 'Todos con reporte (semestres)'
|
||||
: draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', ');
|
||||
}
|
||||
export function selectionKey(applied: Pick<GlobalApplied, 'tipo' | 'selection'>): string {
|
||||
return JSON.stringify([applied.tipo, applied.selection.mode,
|
||||
applied.selection.mode === 'explicit' ? [...applied.selection.periodos].sort() : []]);
|
||||
}
|
||||
export function pending(state: FilterState): boolean {
|
||||
const applied = state.applied;
|
||||
const draft = state.editors[state.tipo]!.draft;
|
||||
if (!applied || applied.tipo !== state.tipo || applied.selection.mode !== draft.mode) return true;
|
||||
if (draft.mode !== 'explicit' || applied.selection.mode !== 'explicit') return false;
|
||||
const periodos = applied.selection.periodos;
|
||||
return draft.periodos.length !== periodos.length
|
||||
|| draft.periodos.some(p => !periodos.includes(p));
|
||||
const draft = state.editors[state.tipo]?.draft;
|
||||
return !state.applied || !draft || draft.mode === 'empty'
|
||||
|| selectionKey(state.applied) !== selectionKey({ tipo: state.tipo, selection: draft });
|
||||
}
|
||||
export function domainTypes(items: readonly Indicador[]): TipoPeriodo[] {
|
||||
return (['semestre', 'mes'] as const).filter(tipo => items.some(item => item.tipos_periodo.includes(tipo)));
|
||||
}
|
||||
export type Compatibility = { compatible: true } | { compatible: false; reason: string };
|
||||
// Published capabilities only; this adapter never changes a selection or probes HTTP.
|
||||
// Future consumers may use the same capability list without defining a KPI contract here.
|
||||
export function filterCompatibility(applied: GlobalApplied | undefined, types: readonly TipoPeriodo[]): Compatibility {
|
||||
if (!types.length) return { compatible: false, reason: 'El catálogo no declara capacidades temporales suficientes para consultar.' };
|
||||
if (!applied) return { compatible: false, reason: 'No hay un filtro general aplicado.' };
|
||||
if (!types.includes(applied.tipo)) return { compatible: false, reason: 'Esta figura no admite la granularidad ' + applied.tipo + ' del filtro general.' };
|
||||
const mode = applied.selection.mode;
|
||||
if (!validDraft(applied.selection, applied.tipo, [...types])) return { compatible: false, reason: mode === 'todos'
|
||||
? 'Todos con reporte requiere semestre como primera granularidad publicada. Para meses elige periodos explícitos.'
|
||||
: 'Los periodos del filtro general no son válidos para esta granularidad.' };
|
||||
return { compatible: true };
|
||||
}
|
||||
export function applyGlobal(state: GlobalFilterState, types: TipoPeriodo[]): boolean {
|
||||
const draft = state.editors[state.tipo]?.draft;
|
||||
if (!draft || !validDraft(draft, state.tipo, types) || !pending(state)) return false;
|
||||
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';
|
||||
|
||||
@@ -41,7 +65,7 @@ export type CardActivation = 'pending' | 'auto-open' | 'manual-open' | 'manual-c
|
||||
export class IndicadoresMemory {
|
||||
private readonly themes = new Map<Dominio, Tema>();
|
||||
private readonly expansions = new Map<string, CardActivation>();
|
||||
private readonly filters = new Map<string, FilterState>();
|
||||
private readonly filters = new Map<Dominio, GlobalFilterState>();
|
||||
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 {
|
||||
@@ -50,28 +74,18 @@ export class IndicadoresMemory {
|
||||
rememberActivation(domain: Dominio, indicador: string, state: CardActivation) {
|
||||
this.expansions.set(JSON.stringify([domain, indicador]), state);
|
||||
}
|
||||
private key(domain: Dominio, indicador: string, figura: string) {
|
||||
return JSON.stringify([domain, indicador, figura]);
|
||||
saveGlobal(domain: Dominio, state: GlobalFilterState) {
|
||||
this.filters.set(domain, structuredClone(state));
|
||||
}
|
||||
save(domain: Dominio, indicador: string, figura: string, state: FilterState) {
|
||||
this.filters.set(this.key(domain, indicador, figura), structuredClone(state));
|
||||
}
|
||||
restore(domain: Dominio, indicador: Indicador, figura: string): FilterState {
|
||||
const stored = this.filters.get(this.key(domain, indicador.id, figura));
|
||||
const first = indicador.tipos_periodo[0];
|
||||
const state: FilterState = stored ? structuredClone(stored) : { tipo: first, editors: {} };
|
||||
if (!indicador.tipos_periodo.includes(state.tipo)) state.tipo = first;
|
||||
for (const tipo of ['semestre', 'mes'] as const) {
|
||||
if (!indicador.tipos_periodo.includes(tipo)) { delete state.editors[tipo]; continue; }
|
||||
const entry = state.editors[tipo] ?? newEditor(tipo, first);
|
||||
entry.added = [...new Set(entry.added.filter(p => parsePeriodos(p, tipo)?.[0] === p))];
|
||||
if (entry.draft.mode !== 'empty' && !validDraft(entry.draft, tipo, indicador.tipos_periodo)) entry.draft = { mode: 'empty' };
|
||||
if (entry.draft.mode === 'explicit' && entry.draft.periodos.some(p => !entry.added.includes(p))) entry.draft = { mode: 'empty' };
|
||||
state.editors[tipo] = entry;
|
||||
}
|
||||
if (state.applied && !validDraft(state.applied.selection, state.applied.tipo, indicador.tipos_periodo)) delete state.applied;
|
||||
// Only a new identity receives an initial application. A restored pending draft stays pending.
|
||||
if (!stored) state.applied = { tipo: first, selection: { mode: 'todos' } };
|
||||
restoreGlobal(domain: Dominio, types: TipoPeriodo[]): GlobalFilterState {
|
||||
const stored = this.filters.get(domain);
|
||||
const state: GlobalFilterState = stored ? structuredClone(stored) : {
|
||||
tipo: 'semestre', editors: { semestre: newEditor('semestre', 'semestre') },
|
||||
applied: { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 },
|
||||
};
|
||||
for (const tipo of types) state.editors[tipo] ??= newEditor(tipo, 'semestre');
|
||||
// Preserve an application whose capabilities changed: consumers explain incompatibility,
|
||||
// rather than silently replacing or trimming the user's temporal selection.
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
load('tea', harness); harness.detectChanges();
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
(harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters();
|
||||
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu', harness);
|
||||
@@ -78,7 +78,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
const req = load('tea', harness);
|
||||
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
|
||||
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1', '2025-S2'] });
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
|
||||
});
|
||||
it('un nuevo arranque conserva la URL de entrada y reinicia indicador, tema y filtros', async () => {
|
||||
@@ -89,7 +89,7 @@ describe('UX-04 navegación Angular', () => {
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add();
|
||||
(harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).applyFilters();
|
||||
(harness.routeDebugElement!.componentInstance as IndicadoresPage).applyFilters(); harness.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const url = TestBed.inject(Router).url;
|
||||
http.verify(); TestBed.resetTestingModule();
|
||||
@@ -99,8 +99,8 @@ describe('UX-04 navegación Angular', () => {
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).expanded).toBe(true);
|
||||
expect(restarted.tema).toBe('claro');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.tipo).toBe('semestre');
|
||||
expect((harness.routeDebugElement!.query(By.directive(IndicadorFigurePanel)).componentInstance as IndicadorFigurePanel).filters?.editors.mes?.draft.mode).toBe('empty');
|
||||
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.tipo).toBe('semestre');
|
||||
expect((harness.routeDebugElement!.componentInstance as IndicadoresPage).filters?.editors.mes?.draft.mode).toBe('empty');
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
expect(req.request.params.get('tema')).toBe('claro');
|
||||
});
|
||||
|
||||
@@ -10,6 +10,14 @@
|
||||
}
|
||||
</nav>
|
||||
|
||||
@if (!catalogLoading() && filters; as state) {
|
||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
||||
<h2 id="global-filters-title" class="section-title">Filtros generales de {{ domainLabels[dominio] }}</h2>
|
||||
<p class="section-description">La selección aplicada se comparte entre las figuras de este proyecto. Los indicadores destacados siguen pendientes de definición.</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
</section>
|
||||
}
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados — Vista preliminar</h2>
|
||||
<p class="section-description">Muestra visual de {{ domainLabels[dominio] }}. Las definiciones y fuentes de estos indicadores están pendientes.</p>
|
||||
@@ -60,7 +68,7 @@
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema"
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="filters!.applied"
|
||||
(activationChanged)="visibilityChanged()" />
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -51,3 +51,5 @@ nav a[aria-current='page'] {
|
||||
h1 { font-size: var(--mat-sys-headline-medium-size); line-height: var(--mat-sys-headline-medium-line-height); }
|
||||
nav { gap: var(--issste-space-2); padding-inline: 0; }
|
||||
}
|
||||
|
||||
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
|
||||
@@ -77,7 +77,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(grid.children).toHaveLength(2);
|
||||
expect(Array.from(grid.children).every(host => host.tagName === 'APP-INDICADOR-CATALOG-CARD')).toBe(true);
|
||||
const sections = fixture.nativeElement.querySelectorAll('.dashboard > section') as NodeListOf<HTMLElement>;
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['kpi-section-title', 'graphic-section-title']);
|
||||
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'kpi-section-title', 'graphic-section-title']);
|
||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
|
||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
|
||||
toggle(0); toggle(1); flushAll();
|
||||
@@ -157,7 +157,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
it('UX-06D retira el selector visual, inicia claro y conserva oscuro sin recargar catálogo', async () => {
|
||||
load();
|
||||
await fixture.whenStable(); fixture.detectChanges();
|
||||
expect(fixture.debugElement.query(By.directive(MatSelect))).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.global-filters mat-select')).toBeTruthy();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Tema del dominio');
|
||||
expect(page.tema).toBe('claro');
|
||||
page.changeTema('oscuro'); fixture.detectChanges();
|
||||
@@ -211,18 +211,18 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
panels()[0].requestFigure(); request('f1').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('edición y aplicación son independientes por figura y tema utiliza aplicación', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control(), b = control(1);
|
||||
it('un único borrador actualiza todas las figuras y tema usa aplicado', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control();
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
panels()[0].applyFilters(); const applied = request('f1'); expect(applied.request.params.get('periodos')).toBe('2025-S1');
|
||||
applied.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
|
||||
b.changeTipo('mes'); b.year = '2026'; b.unit = '01'; b.add();
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
const appliedA = request('f1'), appliedB = request('f2');
|
||||
expect(appliedA.request.params.get('periodos')).toBe('2025-S1'); expect(appliedB.request.params.get('periodos')).toBe('2025-S1');
|
||||
appliedA.flush({ data: [], layout: {} }); appliedB.flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
|
||||
page.changeTema('oscuro'); fixture.detectChanges();
|
||||
const themedA = request('f1'), themedB = request('f2');
|
||||
expect(themedA.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themedB.request.params.has('periodos')).toBe(false);
|
||||
expect(themedA.request.params.get('tema')).toBe('oscuro');
|
||||
expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(b.selectedPeriods).toEqual(['2026-01']);
|
||||
expect(themedA.request.params.get('periodos')).toBe('2025-S1'); expect(themedB.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themedA.request.params.get('tema')).toBe('oscuro'); expect(a.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
themedA.flush({ data: [], layout: {} }); themedB.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => {
|
||||
@@ -230,7 +230,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
const panel = panels()[0], chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance;
|
||||
const filters = control();
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(panel.filters!.applied);
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
@@ -238,18 +238,17 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(button.getAttribute('aria-expanded')).toBe(i === 0 ? 'true' : 'false');
|
||||
expect(panels()[0]).toBe(panel); expect(panel.result()).toBe(result);
|
||||
expect(fixture.debugElement.query(By.directive(ChartStub)).componentInstance).toBe(chart);
|
||||
expect(filters.entry.draft).toEqual(draft); expect(panel.filters!.applied).toEqual(applied);
|
||||
expect(filters.entry.draft).toEqual(draft); expect(page.filters!.applied).toEqual(applied);
|
||||
http.expectNone(() => true);
|
||||
}
|
||||
});
|
||||
it('cerrar y reabrir restaura borrador y aplicado por figura sin confirmar borradores', () => {
|
||||
it('cerrar y reabrir conserva borrador general y consulta aplicado en ambas figuras', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||
panels()[0].applyFilters(); request('f1').flush({ data: [], layout: {} }); a.unit = 'S2'; a.add();
|
||||
control(1).changeTipo('mes'); control(1).year = '2026'; control(1).unit = '01'; control(1).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');
|
||||
const other = request('f2'); expect(other.request.params.has('periodos')).toBe(false);
|
||||
expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']); expect(control(1).selectedPeriods).toEqual(['2026-01']);
|
||||
const restored = request('f1'), other = request('f2');
|
||||
expect(restored.request.params.get('periodos')).toBe('2025-S1'); expect(other.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(control()).toBe(a); expect(control().selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
restored.flush({ data: [], layout: {} }); other.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => {
|
||||
@@ -296,7 +295,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
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-period-filters mat-select') as HTMLElement;
|
||||
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]);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
@@ -315,7 +314,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
it.each(['cacu', 'cama'] as const)('preserva advertencias y filtros mensuales de %s', domain => {
|
||||
load([]); page.changeDominio(domain); load(syntheticCatalogs[domain], domain); toggle(); flushAll();
|
||||
const c = control(); c.changeTipo('mes'); c.year = '2025'; c.unit = '01'; c.add(); http.expectNone(() => true);
|
||||
panels()[0].applyFilters(); const r = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
page.applyFilters(); fixture.detectChanges(); const r = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('no entregan intervalos Wilson efectivos');
|
||||
expect(fixture.nativeElement.textContent).toContain('suprimidos no representan tasas observadas de 0 %');
|
||||
@@ -334,7 +333,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
c.year = '2025'; c.unit = 'S1'; c.add(); c.select([]); fixture.detectChanges(); await fixture.whenStable();
|
||||
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
|
||||
expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos');
|
||||
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save');
|
||||
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal');
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
|
||||
@@ -13,7 +13,8 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
@@ -21,7 +22,7 @@ import { httpMessage } from './indicadores-http';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard, IndicadorPeriodFilters],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -211,6 +212,14 @@ export class IndicadoresPage {
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
tema: Tema = 'claro';
|
||||
filters?: GlobalFilterState;
|
||||
readonly filterTypes = computed(() => domainTypes(this.catalog()));
|
||||
filtersEdited() { if (this.filters) this.memory.saveGlobal(this.dominio, this.filters); }
|
||||
applyFilters() {
|
||||
if (!this.filters || !applyGlobal(this.filters, this.filterTypes())) return;
|
||||
this.filtersEdited();
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); }
|
||||
constructor() {
|
||||
afterEveryRender(() => this.syncVisibility());
|
||||
@@ -220,6 +229,7 @@ export class IndicadoresPage {
|
||||
browser?.addEventListener('resize', this.viewportChanged);
|
||||
}
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.filtersEdited();
|
||||
this.visibilityDestroyed = true;
|
||||
this.clearVisibility();
|
||||
this.sizeObserver?.disconnect();
|
||||
@@ -239,13 +249,17 @@ export class IndicadoresPage {
|
||||
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
||||
this.catalogLoading.set(false);
|
||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
||||
this.catalog.set(items);
|
||||
this.filtersEdited();
|
||||
this.catalogError.set(error);
|
||||
});
|
||||
}
|
||||
changeDominio(dominio: Dominio) {
|
||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||
this.searchQuery.set('');
|
||||
this.filtersEdited();
|
||||
this.filters = undefined;
|
||||
this.dominio = dominio;
|
||||
this.tema = this.memory.theme(dominio);
|
||||
this.catalogRequests.next();
|
||||
|
||||
@@ -61,4 +61,24 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
expect(runtime.purge).toHaveBeenCalledTimes(2); expect(disconnects).toHaveLength(2);
|
||||
for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('D.2 conserva hosts reales ocultando resultados anteriores durante carga e incompatibilidad', async () => {
|
||||
respond(); await settle();
|
||||
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
const page = fixture.componentInstance;
|
||||
page.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1'] };
|
||||
page.applyFilters(); fixture.detectChanges();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance)).toEqual(charts.map(c => c.componentInstance));
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
||||
expect(runtime.purge).not.toHaveBeenCalled();
|
||||
respond(); await settle();
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeNull();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart)).map(c => c.componentInstance.host.nativeElement)).toEqual(hosts);
|
||||
// Published capability change is evaluated by each existing consumer.
|
||||
const current = page.catalog()[0];
|
||||
page.catalog.set([{ ...current, tipos_periodo: ['mes'] }]); fixture.detectChanges(); await settle();
|
||||
for (const host of hosts) expect(host.closest('[hidden]')).toBeTruthy();
|
||||
expect(fixture.nativeElement.querySelectorAll('.incompatible')).toHaveLength(2);
|
||||
expect(runtime.purge).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -140,16 +140,16 @@ describe('UX-05C búsqueda local y partición estable', () => {
|
||||
load(); cards().slice(0, 3).forEach(c => c.toggle()); 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();
|
||||
beforePanels[0].applyFilters(); request('A01').flush({ data: [{ y: [2, null] }], layout: {} });
|
||||
page.applyFilters(); fixture.detectChanges(); respond(); await settle();
|
||||
c.unit = 'S2'; c.add(); c.year = '2026';
|
||||
beforeFilters[1].changeMode('manual'); fixture.detectChanges(); await settle();
|
||||
const states = beforePanels.map(p => p.filters), results = beforePanels.map(p => p.result());
|
||||
fixture.detectChanges(); await settle();
|
||||
const states = beforePanels.map(p => p.applied), results = beforePanels.map(p => p.result());
|
||||
const titleIds = beforePanels.map(p => p.titleId);
|
||||
expect(new Set(titleIds).size).toBe(beforePanels.length);
|
||||
const snapshots = states.map(s => JSON.stringify(s)), hosts = beforeCharts.map(c => c.host.nativeElement);
|
||||
const selects = fixture.debugElement.queryAll(By.directive(MatSelect)).filter(e => e.componentInstance.multiple);
|
||||
const writes = selects.map(e => vi.spyOn(e.injector.get(NgModel).control, 'setValue'));
|
||||
const memory = TestBed.inject(IndicadoresMemory), saves = vi.spyOn(memory, 'save'), restores = vi.spyOn(memory, 'restore');
|
||||
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);
|
||||
@@ -178,7 +178,7 @@ describe('UX-05C búsqueda local y partición estable', () => {
|
||||
const heading = document.getElementById(id)!;
|
||||
expect(heading.tagName).toBe('H3'); expect(heading.parentElement!.getAttribute('aria-labelledby')).toBe(id);
|
||||
}
|
||||
beforePanels.forEach((p, i) => { expect(p.filters).toBe(states[i]); expect(JSON.stringify(p.filters)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
|
||||
beforePanels.forEach((p, i) => { expect(p.applied).toBe(states[i]); expect(JSON.stringify(p.applied)).toBe(snapshots[i]); expect(p.result()).toBe(results[i]); });
|
||||
beforeCharts.forEach((c, i) => expect(c.host.nativeElement).toBe(hosts[i]));
|
||||
expect(c.year).toBe('2026'); expect(c.unit).toBe('S2'); expect(c.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
for (const write of writes) expect(write).not.toHaveBeenCalled();
|
||||
|
||||
@@ -253,8 +253,8 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => {
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
cards()[0].toggle(); await render(); expect(requests[2].cancelled).toBe(true);
|
||||
notify(); await idle(); http.expectNone(() => true); cards()[0].toggle(); await render();
|
||||
expect(panels()[0].filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||
expect(panels()[0].filters?.applied?.selection.mode).toBe('todos'); respond();
|
||||
expect(page.filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||
expect(page.filters?.applied?.selection.mode).toBe('todos'); 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();
|
||||
@@ -307,4 +307,25 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => {
|
||||
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 () => {
|
||||
await load(); 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);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user