feat(indicadores): implementar filtros hibridos y memoria UX-04
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
<section aria-label="Filtros de periodos de la figura">
|
||||
<div class="fields">
|
||||
@if (types.length > 1) {
|
||||
<mat-form-field><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]) {
|
||||
<mat-form-field><mat-label>Modalidad</mat-label>
|
||||
<mat-select [ngModel]="entry.draft.mode === 'todos' ? 'todos' : 'manual'" (ngModelChange)="changeMode($event)">
|
||||
<mat-option value="todos">Todos los {{ state.tipo === 'mes' ? 'meses' : 'semestres' }} con reporte</mat-option>
|
||||
<mat-option value="manual">Elegir periodos</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<mat-form-field><mat-label>Periodos seleccionados</mat-label>
|
||||
<mat-select multiple [ngModel]="selectedPeriods" (ngModelChange)="select($event)">
|
||||
@for (period of entry.added; track period) { <mat-option [value]="period">{{ period }}</mat-option> }
|
||||
</mat-select>
|
||||
<mat-hint>Disponibilidad desconocida hasta consultar.</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
@if (entry.draft.mode !== 'todos') {
|
||||
<p>Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.</p>
|
||||
<div class="fields">
|
||||
<mat-form-field><mat-label>Año</mat-label><input matInput [(ngModel)]="year" inputmode="numeric" maxlength="4" /></mat-form-field>
|
||||
<mat-form-field><mat-label>{{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-label>
|
||||
<mat-select [(ngModel)]="unit">
|
||||
@for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { <mat-option [value]="value">{{ value }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<button mat-stroked-button (click)="add()">Agregar periodo</button>
|
||||
</div>
|
||||
<div class="remove" aria-label="Eliminar periodos agregados">
|
||||
@for (period of entry.added; track period) {
|
||||
<button mat-button (click)="remove(period)" [attr.aria-label]="'Eliminar periodo ' + period">Eliminar {{ period }}</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@if (error) { <p class="error" role="alert">{{ error }}</p> }
|
||||
<p>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 role="status">Hay cambios sin aplicar.</p> }
|
||||
<button mat-flat-button [disabled]="!canApply" (click)="apply.emit()">Aplicar</button>
|
||||
<p>Filtros de la consulta aplicada: {{ appliedSummary }}</p>
|
||||
</section>
|
||||
@@ -0,0 +1,5 @@
|
||||
:host { display: block; margin: 1rem 0; }
|
||||
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: 1rem; }
|
||||
mat-form-field { flex: 1; min-width: 160px; }
|
||||
.error { color: var(--mat-sys-error); }
|
||||
.remove { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
@@ -0,0 +1,116 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { NgModel } from '@angular/forms';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
|
||||
describe('UX-04 control asistido', () => {
|
||||
let control: IndicadorPeriodFilters;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorPeriodFilters>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] });
|
||||
fixture = TestBed.createComponent(IndicadorPeriodFilters);
|
||||
fixture.componentRef.setInput('types', ['semestre', 'mes']);
|
||||
fixture.componentRef.setInput('state', { tipo: 'semestre', editors: {
|
||||
semestre: { added: [], draft: { mode: 'todos' } }, mes: { added: [], draft: { mode: 'empty' } },
|
||||
}, applied: { tipo: 'semestre', selection: { mode: 'todos' } } });
|
||||
fixture.detectChanges();
|
||||
control = fixture.componentInstance;
|
||||
});
|
||||
afterEach(() => fixture.destroy());
|
||||
it('UX-04A: el selector vacío no reescribe el FormControl en cada detección', async () => {
|
||||
// Bound the pre-fix reproduction: do not wait for an unstable fixture forever.
|
||||
fixture.changeDetectorRef.detach();
|
||||
control.changeMode('manual');
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
const edits = vi.spyOn(control.edited, 'emit');
|
||||
for (let i = 0; i < 4; i++) {
|
||||
fixture.detectChanges();
|
||||
await Promise.resolve();
|
||||
}
|
||||
expect(model.control.value).toEqual([]);
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
expect(edits).not.toHaveBeenCalled();
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
});
|
||||
it('UX-04A: meses vacíos se estabilizan al abrir y cerrar selección múltiple', async () => {
|
||||
control.changeTipo('mes');
|
||||
control.year = '2025'; control.unit = '01'; control.add(); control.select([]);
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
const model = select.injector.get(NgModel);
|
||||
const writes = vi.spyOn(model.control, 'setValue');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.componentInstance.panelOpen).toBe(true);
|
||||
select.componentInstance.close(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.componentInstance.panelOpen).toBe(false);
|
||||
}
|
||||
expect(writes).not.toHaveBeenCalled();
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
expect(control.state.applied?.tipo).toBe('semestre');
|
||||
expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('normaliza el año y rechaza agregar duplicados', () => {
|
||||
control.changeMode('manual');
|
||||
control.year = '1'; control.unit = 'S1'; control.add();
|
||||
expect(control.selectedPeriods).toEqual(['0001-S1']);
|
||||
control.add();
|
||||
expect(control.error).toContain('ya está agregado');
|
||||
expect(control.entry.added).toEqual(['0001-S1']);
|
||||
});
|
||||
it.each([['0', 'S1'], ['10000', 'S1'], ['2025', 'S3'], ['abc', 'S1'], ['', 'S1']])('rechaza año/unidad %s %s', (year, unit) => {
|
||||
control.changeMode('manual'); control.year = year; control.unit = unit; control.add();
|
||||
expect(control.error).toContain('unidad válida'); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it.each(['00', '13', 'S1'])('rechaza unidad mensual %s', unit => {
|
||||
control.changeTipo('mes'); control.year = '2025'; control.unit = unit; control.add();
|
||||
expect(control.entry.added).toEqual([]); expect(control.canApply).toBe(false);
|
||||
});
|
||||
it('conserva borradores independientes sin convertir periodos', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.changeTipo('mes'); control.year = '2026'; control.unit = '12'; control.add();
|
||||
control.changeTipo('semestre'); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
control.changeTipo('mes'); expect(control.selectedPeriods).toEqual(['2026-12']);
|
||||
expect(control.state.applied).toEqual({ tipo: 'semestre', selection: { mode: 'todos' } });
|
||||
});
|
||||
it('deselecciona sin eliminar opciones y elimina sin botones dentro de opciones', () => {
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
control.unit = 'S2'; control.add();
|
||||
control.select(['2025-S2']);
|
||||
expect(control.entry.added).toEqual(['2025-S1', '2025-S2']);
|
||||
control.remove('2025-S1'); expect(control.selectedPeriods).toEqual(['2025-S2']);
|
||||
fixture.detectChanges();
|
||||
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
|
||||
expect(select).toBeTruthy();
|
||||
expect(select.nativeElement.querySelector('button')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).toContain('Eliminar 2025-S2');
|
||||
fixture.nativeElement.querySelector('.remove button').click();
|
||||
fixture.detectChanges();
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
expect(fixture.nativeElement.querySelector('button[mat-flat-button]').disabled).toBe(true);
|
||||
});
|
||||
it('emite edición y aplicación por separado y explica la disponibilidad desconocida', () => {
|
||||
const edited = vi.spyOn(control.edited, 'emit');
|
||||
const apply = vi.spyOn(control.apply, 'emit');
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
expect(edited).toHaveBeenCalledTimes(2); expect(apply).not.toHaveBeenCalled();
|
||||
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');
|
||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||
expect(apply).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('no ofrece Todos en meses cuando el primero es semestre', () => {
|
||||
control.changeTipo('mes'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Todos los meses');
|
||||
control.changeMode('todos'); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.changeTipo('semestre'); control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
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 { describePeriods, newEditor, FilterState, pending, validDraft } from './indicadores-memory';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-period-filters',
|
||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
||||
templateUrl: './indicador-period-filters.html',
|
||||
styleUrl: './indicador-period-filters.scss',
|
||||
})
|
||||
export class IndicadorPeriodFilters implements OnChanges {
|
||||
@Input({ required: true }) state!: FilterState;
|
||||
@Input({ required: true }) types!: TipoPeriodo[];
|
||||
@Output() edited = new EventEmitter<void>();
|
||||
@Output() apply = new EventEmitter<void>();
|
||||
year = '';
|
||||
unit = '';
|
||||
error = '';
|
||||
readonly months = Array.from({ length: 12 }, (_, i) => String(i + 1).padStart(2, '0'));
|
||||
ngOnChanges() { this.year = this.unit = this.error = ''; }
|
||||
get entry() { return this.state.editors[this.state.tipo]!; }
|
||||
// NgModel schedules a microtask and markForCheck when its input reference changes.
|
||||
// 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 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'; }
|
||||
changeTipo(tipo: TipoPeriodo) {
|
||||
if (!this.types.includes(tipo)) return;
|
||||
this.state.tipo = tipo;
|
||||
this.state.editors[tipo] ??= newEditor(tipo, this.types[0]);
|
||||
this.year = this.unit = this.error = '';
|
||||
this.edited.emit();
|
||||
}
|
||||
changeMode(mode: 'todos' | 'manual') {
|
||||
if (mode === 'todos' && this.state.tipo !== this.types[0]) return;
|
||||
this.entry.draft = mode === 'todos' ? { mode: 'todos' } : { mode: 'empty' };
|
||||
this.error = '';
|
||||
this.edited.emit();
|
||||
}
|
||||
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;
|
||||
this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' };
|
||||
this.edited.emit();
|
||||
}
|
||||
add() {
|
||||
this.error = '';
|
||||
const year = /^\d{1,4}$/.test(this.year) ? this.year.padStart(4, '0') : '';
|
||||
const period = year + '-' + this.unit;
|
||||
if (!parsePeriodos(period, this.state.tipo)) {
|
||||
this.error = 'Introduce un año entre 0001 y 9999 y una unidad válida.';
|
||||
return;
|
||||
}
|
||||
if (this.entry.added.includes(period)) { this.error = 'Este periodo ya está agregado.'; return; }
|
||||
const selected = this.selectedPeriods;
|
||||
this.entry.added.push(period);
|
||||
this.select([...selected, period]);
|
||||
}
|
||||
remove(period: string) {
|
||||
this.entry.added = this.entry.added.filter(p => p !== period);
|
||||
// Removing an unselected option must not change the Todos mode.
|
||||
if (this.entry.draft.mode === 'explicit') this.select(this.selectedPeriods.filter(p => p !== period));
|
||||
else this.edited.emit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { FilterState, 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', () => {
|
||||
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('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);
|
||||
restored.editors.mes!.added.length = 0;
|
||||
expect(memory.restore('tea', indicador, 'f').editors.mes?.added).toEqual(['2025-01']);
|
||||
});
|
||||
it('aísla dominios, indicadores y figuras', () => {
|
||||
const state = memory.restore('tea', indicador, 'f');
|
||||
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');
|
||||
});
|
||||
it('recuerda indicador, tema y figura por indicador', () => {
|
||||
memory.remember('cacu', 'i', 'g', 'oscuro');
|
||||
memory.remember('cacu', 'otro', 'f', 'claro');
|
||||
expect(memory.navigation('cacu')).toEqual({ indicador: 'otro', tema: 'claro' });
|
||||
expect(memory.selectedFigure('cacu', 'i')).toBe('g');
|
||||
expect(memory.navigation('tea')).toBeUndefined();
|
||||
});
|
||||
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');
|
||||
memory.remember('tea', 'otro', 'g', 'oscuro');
|
||||
memory.save('tea', 'i', 'f', { tipo: 'mes', editors: { mes: { added: [], draft: { mode: 'empty' } } } });
|
||||
const fresh = new IndicadoresMemory();
|
||||
expect(fresh.navigation('tea')).toBeUndefined();
|
||||
expect(fresh.restore('tea', indicador, 'f').tipo).toBe('semestre');
|
||||
expect(localRead).not.toHaveBeenCalled(); expect(localWrite).not.toHaveBeenCalled();
|
||||
localRead.mockRestore(); localWrite.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);
|
||||
});
|
||||
});
|
||||
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);
|
||||
});
|
||||
it.each([
|
||||
['semestre', ['2025-S1']], ['semestre', ['0001-S1', '9999-S2']],
|
||||
['mes', ['2025-01']], ['mes', ['2025-01', '2025-12']],
|
||||
] as [TipoPeriodo, [string, ...string[]]][])('acepta explícitos %s %j', (tipo, periodos) => {
|
||||
expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(true);
|
||||
});
|
||||
it.each([
|
||||
['semestre', ['0000-S1']], ['mes', ['2025-00']], ['mes', ['2025-13']],
|
||||
['semestre', ['2025-S3']], ['mes', ['2025-01', '2025-S1']], ['mes', ['2025-01', '2025-01']],
|
||||
['semestre', ['2025-S1', '2025-S1']], ['mes', [' 2025-01']],
|
||||
] as [TipoPeriodo, [string, ...string[]]][])('rechaza explícitos %s %j', (tipo, periodos) => {
|
||||
expect(validDraft({ mode: 'explicit', periodos }, tipo, ['semestre', 'mes'])).toBe(false);
|
||||
});
|
||||
it('bloquea vacío, incluso un arreglo vacío forzado en tiempo de ejecución', () => {
|
||||
expect(validDraft({ mode: 'empty' }, 'semestre', ['semestre'])).toBe(false);
|
||||
expect(validDraft({ mode: 'explicit', periodos: [] as unknown as [string, ...string[]] }, 'semestre', ['semestre'])).toBe(false);
|
||||
expect(validDraft({ mode: 'explicit', periodos: ['2025-01'] }, 'mes', ['semestre'])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Dominio, Indicador, parsePeriodos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
|
||||
export type PeriodDraft =
|
||||
| { mode: 'todos' }
|
||||
| { mode: 'empty' }
|
||||
| { mode: 'explicit'; periodos: [string, ...string[]] };
|
||||
export type AppliedPeriods = Exclude<PeriodDraft, { mode: 'empty' }>;
|
||||
export interface PeriodEditor { added: string[]; draft: PeriodDraft; }
|
||||
export interface FilterState {
|
||||
tipo: TipoPeriodo;
|
||||
editors: Partial<Record<TipoPeriodo, PeriodEditor>>;
|
||||
applied?: { tipo: TipoPeriodo; selection: AppliedPeriods };
|
||||
}
|
||||
export function newEditor(tipo: TipoPeriodo, first: TipoPeriodo): PeriodEditor {
|
||||
return { added: [], draft: 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];
|
||||
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'
|
||||
: draft.mode === 'empty' ? 'Sin periodos seleccionados' : draft.periodos.join(', ');
|
||||
}
|
||||
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));
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresMemory {
|
||||
private readonly domains = new Map<Dominio, { indicador: string; tema: Tema }>();
|
||||
private readonly figures = new Map<string, string>();
|
||||
private readonly filters = new Map<string, FilterState>();
|
||||
navigation(domain: Dominio) { return this.domains.get(domain); }
|
||||
selectedFigure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); }
|
||||
remember(domain: Dominio, indicador: string, figura: string, tema: Tema) {
|
||||
this.domains.set(domain, { indicador, tema });
|
||||
this.figures.set(JSON.stringify([domain, indicador]), figura);
|
||||
}
|
||||
private key(domain: Dominio, indicador: string, figura: string) {
|
||||
return JSON.stringify([domain, indicador, figura]);
|
||||
}
|
||||
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' } };
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
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, Router } from '@angular/router';
|
||||
import { RouterTestingHarness } from '@angular/router/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { routes } from '../../app.routes';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
|
||||
describe('UX-04 navegación Angular', () => {
|
||||
let http: HttpTestingController;
|
||||
async function setup() {
|
||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
return RouterTestingHarness.create();
|
||||
}
|
||||
function load(domain: 'tea' | 'cacu' | 'cama') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(syntheticCatalogs[domain]);
|
||||
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
return req;
|
||||
}
|
||||
afterEach(() => http.verify());
|
||||
it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => {
|
||||
const harness = await setup();
|
||||
const tea = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
load('tea'); harness.detectChanges();
|
||||
const control = harness.routeDebugElement!.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
tea.applyFilters();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage); load('cacu');
|
||||
await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); load('cama');
|
||||
const restored = await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
|
||||
const req = load('tea');
|
||||
expect(req.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(restored.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 () => {
|
||||
let harness = await setup();
|
||||
const page = await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage);
|
||||
load('cacu'); harness.detectChanges();
|
||||
page.changeTema('oscuro');
|
||||
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();
|
||||
page.applyFilters();
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const url = TestBed.inject(Router).url;
|
||||
http.verify(); TestBed.resetTestingModule();
|
||||
harness = await setup();
|
||||
const restarted = await harness.navigateByUrl(url, IndicadoresPage);
|
||||
const req = load('cacu');
|
||||
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||
expect(restarted.indicadorId).toBe(syntheticCatalogs.cacu[0].id);
|
||||
expect(restarted.tema).toBe('claro');
|
||||
expect(restarted.filters?.tipo).toBe('semestre');
|
||||
expect(restarted.filters?.editors.mes?.draft.mode).toBe('empty');
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
expect(req.request.params.get('tema')).toBe('claro');
|
||||
});
|
||||
});
|
||||
@@ -33,33 +33,16 @@
|
||||
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Tipo de periodo</mat-label>
|
||||
<mat-select [ngModel]="tipoPeriodo" (ngModelChange)="changeTipoPeriodo($event)">
|
||||
@for (tipo of selected?.tipos_periodo ?? []; track tipo) {
|
||||
<mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Periodos</mat-label>
|
||||
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
|
||||
<mat-option value="todos" [disabled]="tipoPeriodo !== selected?.tipos_periodo?.[0]">Todos con reporte</mat-option>
|
||||
<mat-option value="manual">Selección manual</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Tema de la figura</mat-label>
|
||||
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
|
||||
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (periodMode === 'manual') {
|
||||
<mat-form-field class="periods" subscriptSizing="dynamic"><mat-label>{{ periodLabel }}</mat-label>
|
||||
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
|
||||
<mat-hint id="period-help">Escribe periodos del tipo seleccionado, separados por comas. Su disponibilidad depende de los reportes.</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
|
||||
<p>Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.</p>
|
||||
@if (filters; as state) {
|
||||
<app-indicador-period-filters [state]="state" [types]="selected!.tipos_periodo"
|
||||
(edited)="filtersEdited()" (apply)="applyFilters()" />
|
||||
}
|
||||
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
|
||||
</mat-card>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="selected"
|
||||
|
||||
@@ -2,11 +2,14 @@ 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 { MatSelect } from '@angular/material/select';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@@ -29,9 +32,78 @@ describe('IndicadoresPage', () => {
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function filters() {
|
||||
fixture.detectChanges();
|
||||
return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
}
|
||||
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
|
||||
it.each(['M02_sexo', 'K01_evaluacion_3_meses'])('UX-04A: Material se estabiliza al editar y restaurar %s sin HTTP', async id => {
|
||||
http.expectOne('/tea/indicadores').flush(syntheticCatalogs.tea);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
figure().flush({ data: [{ type: 'bar', y: [50, 50] }], layout: { barmode: 'stack' } });
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
if (id === 'M02_sexo') expect(page.figuraId).toBe('fig_c2_apiladas');
|
||||
const result = page.result();
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'save');
|
||||
const child = () => fixture.debugElement.query(By.directive(IndicadorPeriodFilters));
|
||||
const mode = () => child().queryAll(By.directive(MatSelect))[0].componentInstance as MatSelect;
|
||||
async function choose(value: string) {
|
||||
const select = mode();
|
||||
select.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(true);
|
||||
const option = select.options.find(o => o.value === value)!;
|
||||
(document.getElementById(option.id) as HTMLElement).click();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(false);
|
||||
}
|
||||
async function togglePanel() {
|
||||
const count = saves.mock.calls.length;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const select = mode();
|
||||
select.open(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(true);
|
||||
select.close(); fixture.detectChanges(); await fixture.whenStable();
|
||||
expect(select.panelOpen).toBe(false);
|
||||
}
|
||||
expect(saves).toHaveBeenCalledTimes(count);
|
||||
http.expectNone(() => true);
|
||||
expect(page.result()).toBe(result);
|
||||
expect(chart.figure).toBe(result.presentationFigure);
|
||||
}
|
||||
await togglePanel();
|
||||
await choose('manual');
|
||||
expect(filters().entry.draft.mode).toBe('empty');
|
||||
expect(filters().canApply).toBe(false);
|
||||
await togglePanel();
|
||||
await choose('todos');
|
||||
await choose('manual');
|
||||
expect(saves).toHaveBeenCalledTimes(3);
|
||||
// Restoring the empty pending draft must also settle.
|
||||
const other = id === 'M02_sexo' ? 'K01_evaluacion_3_meses' : 'M02_sexo';
|
||||
page.selectIndicador(other); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
const returned = figure(); expect(returned.request.params.has('periodos')).toBe(false);
|
||||
returned.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
let control = filters(); expect(control.entry.draft.mode).toBe('empty');
|
||||
control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
http.expectNone(() => true);
|
||||
expect(control.state.applied?.selection.mode).toBe('todos');
|
||||
page.selectIndicador(other); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador(id);
|
||||
const restored = figure(); expect(restored.request.params.has('periodos')).toBe(false);
|
||||
restored.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); await fixture.whenStable();
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1']);
|
||||
expect(control.hasPending).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => {
|
||||
load(); const oldFigure = figure();
|
||||
page.changeDominio('cacu');
|
||||
@@ -49,28 +121,33 @@ describe('IndicadoresPage', () => {
|
||||
expect(page.dominio).toBe('cama');
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([null, 42]);
|
||||
});
|
||||
it.each(['cacu', 'cama'] as const)('usa meses publicados y ayuda sin Wilson efectivo en %s', dominio => {
|
||||
it.each(['cacu', 'cama'] as const)('edita meses sin HTTP y conserva ayuda sin Wilson efectivo en %s', dominio => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio(dominio);
|
||||
http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]);
|
||||
const initial = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
page.changeTipoPeriodo('mes');
|
||||
expect(initial.cancelled).toBe(true);
|
||||
expect(page.periodMode).toBe('manual');
|
||||
expect(page.periodText).toBe('');
|
||||
expect(page.result().status).toBe('idle');
|
||||
page.changePeriodText('2025-01,2025-02,2025-01');
|
||||
http.expectOne('/' + dominio + '/indicadores').flush(syntheticCatalogs[dominio]);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [{ y: [null, 0] }], layout: {} });
|
||||
const control = filters();
|
||||
control.changeTipo('mes');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
expect(page.result().status).toBe('ready');
|
||||
control.year = '2025'; control.unit = '01'; control.add();
|
||||
control.unit = '02'; control.add();
|
||||
control.unit = '01'; control.add();
|
||||
expect(control.error).toContain('ya está agregado');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
page.applyFilters();
|
||||
const monthly = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02');
|
||||
page.changePeriodText('2025-13');
|
||||
control.unit = '13'; control.add();
|
||||
expect(control.error).toContain('unidad válida');
|
||||
expect(monthly.cancelled).toBe(false);
|
||||
control.changeMode('todos');
|
||||
expect(control.entry.draft.mode).toBe('explicit');
|
||||
control.changeTipo('semestre');
|
||||
expect(control.entry.draft.mode).toBe('todos');
|
||||
expect(monthly.cancelled).toBe(false);
|
||||
page.applyFilters();
|
||||
expect(monthly.cancelled).toBe(true);
|
||||
expect(page.periodError).toContain('01 al 12');
|
||||
page.changePeriodText('2025-01,2025-S1');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
page.changePeriodMode('todos');
|
||||
expect(page.periodError).toContain('primer tipo publicado');
|
||||
http.expectNone(r => r.url.includes('/figuras/'));
|
||||
page.changeTipoPeriodo('semestre');
|
||||
const semesters = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(semesters.request.params.has('periodos')).toBe(false);
|
||||
semesters.flush({ data: [{ y: [null, 0] }], layout: {} });
|
||||
@@ -91,7 +168,7 @@ describe('IndicadoresPage', () => {
|
||||
http.expectOne('/cama/indicadores').flush(future);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
page.selectIndicador('synthetic_future');
|
||||
expect(page.tipoPeriodo).toBe('mes');
|
||||
expect(page.filters?.tipo).toBe('mes');
|
||||
const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas'));
|
||||
expect(req.request.params.has('periodos')).toBe(false);
|
||||
req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } });
|
||||
@@ -189,21 +266,31 @@ describe('IndicadoresPage', () => {
|
||||
expect(page.figuraId).toBe('');
|
||||
expect(page.result().status).toBe('idle');
|
||||
page.selectIndicador('i1');
|
||||
expect(page.figuraId).toBe('f1');
|
||||
expect(page.figuraId).toBe('f2');
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('valida manuales antes del HTTP y vuelve a Todos sin query', () => {
|
||||
it('edita sin HTTP, bloquea vacío y aplica una consulta explícita o Todos', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.changePeriodMode('manual');
|
||||
expect(page.periodError).not.toBe('');
|
||||
const control = filters();
|
||||
control.changeMode('manual');
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
page.changePeriodText('2025-S1, 2025-S2');
|
||||
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();
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
page.changePeriodText('2025-S3');
|
||||
control.select([]);
|
||||
expect(manual.cancelled).toBe(false);
|
||||
expect(control.canApply).toBe(false);
|
||||
page.applyFilters();
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
control.changeMode('todos');
|
||||
page.applyFilters();
|
||||
expect(manual.cancelled).toBe(true);
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
page.changePeriodMode('todos');
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
@@ -245,4 +332,118 @@ describe('IndicadoresPage', () => {
|
||||
expect(page.catalogError()).toContain('error interno');
|
||||
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('mantiene resultado y referencia aplicada mientras se edita un borrador', () => {
|
||||
load(); figure().flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
const control = filters(); control.changeMode('manual');
|
||||
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');
|
||||
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();
|
||||
const req = figure();
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
req.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
expect(page.result().message).toContain('esta selección');
|
||||
expect(page.result().message).not.toContain('2025');
|
||||
if (periodos.length > 1) expect(page.result().message).toContain('conjunto de periodos');
|
||||
expect(control.selectedPeriods).toEqual(periodos);
|
||||
control.select([]);
|
||||
page.requestFigure();
|
||||
const retry = figure();
|
||||
expect(retry.request.params.get('periodos')).toBe(periodos.join(','));
|
||||
retry.flush({ data: [{ y: [null] }], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(control.entry.draft.mode).toBe('empty');
|
||||
});
|
||||
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: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
page.changeTema('oscuro');
|
||||
const themed = figure();
|
||||
expect(themed.request.params.get('periodos')).toBe('2025-S1');
|
||||
expect(themed.request.params.get('tema')).toBe('oscuro');
|
||||
themed.flush('error', { status: 500, statusText: 'Server Error' });
|
||||
page.requestFigure();
|
||||
const retry = figure(); expect(retry.request.params.get('periodos')).toBe('2025-S1');
|
||||
retry.flush({ data: [], layout: {} });
|
||||
expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
});
|
||||
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();
|
||||
control.unit = 'S2'; control.add();
|
||||
expect(old.cancelled).toBe(false);
|
||||
page.applyFilters(); 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: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['y']).toEqual([12]);
|
||||
});
|
||||
it('restaura borrador pendiente y consulta la aplicación al regresar a indicador y figura', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
let control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S1'; control.add();
|
||||
page.applyFilters(); figure().flush({ data: [], layout: {} });
|
||||
control.unit = 'S2'; control.add();
|
||||
page.selectFigura('f2'); figure().flush({ data: [], layout: {} });
|
||||
page.selectFigura('f1');
|
||||
const restored = figure(); expect(restored.request.params.get('periodos')).toBe('2025-S1');
|
||||
restored.flush({ data: [], layout: {} });
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
page.selectIndicador('i2'); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador('i1');
|
||||
const returned = figure(); expect(returned.request.params.get('periodos')).toBe('2025-S1');
|
||||
returned.flush({ data: [], layout: {} });
|
||||
control = filters(); expect(control.selectedPeriods).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(control.hasPending).toBe(true);
|
||||
});
|
||||
it('restaura dominio, indicador, figura y tema sin aplicar el borrador mensual pendiente', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
const id = page.indicadorId; const fig = page.figuraId;
|
||||
page.changeTema('oscuro'); http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
let control = filters(); control.changeTipo('mes'); control.year = '2025'; control.unit = '01'; control.add();
|
||||
page.changeDominio('cama');
|
||||
http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama);
|
||||
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
|
||||
page.changeDominio('cacu');
|
||||
http.expectOne('/cacu/indicadores').flush(syntheticCatalogs.cacu);
|
||||
const restored = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
expect(restored.request.params.has('periodos')).toBe(false);
|
||||
expect(restored.request.params.get('tema')).toBe('oscuro');
|
||||
restored.flush({ data: [], layout: {} });
|
||||
expect(page.indicadorId).toBe(id); expect(page.figuraId).toBe(fig);
|
||||
control = filters(); expect(control.state.tipo).toBe('mes');
|
||||
expect(control.selectedPeriods).toEqual(['2025-01']);
|
||||
expect(control.state.applied?.tipo).toBe('semestre');
|
||||
});
|
||||
it('conserva memoria al destruir y recrear la página dentro de la aplicación', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.selectIndicador('i2'); figure().flush({ data: [], layout: {} });
|
||||
const control = filters(); control.changeMode('manual'); control.year = '2025'; control.unit = 'S2'; control.add();
|
||||
fixture.destroy();
|
||||
fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance;
|
||||
load();
|
||||
const restored = figure();
|
||||
expect(restored.request.url).toContain('/i2/figuras/box');
|
||||
expect(restored.request.params.has('periodos')).toBe(false);
|
||||
restored.flush({ data: [], layout: {} });
|
||||
expect(filters().selectedPeriods).toEqual(['2025-S2']);
|
||||
expect(filters().hasPending).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,14 +6,15 @@ import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, Indicador, parsePeriodos, Tema } from './indicadores.models';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, DOMINIOS, isDominio, 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';
|
||||
|
||||
export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
|
||||
@@ -25,18 +26,18 @@ export function httpMessage(error: unknown, catalog = false): string {
|
||||
}
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard, IndicadorPeriodFilters],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly memory = inject(IndicadoresMemory);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly route = inject(ActivatedRoute, { optional: true });
|
||||
readonly dominios = DOMINIOS;
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
tipoPeriodo: TipoPeriodo = 'semestre';
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
private readonly figureRequests = new Subject<FigureSelection | null>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
@@ -45,19 +46,22 @@ export class IndicadoresPage {
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
indicadorId = '';
|
||||
figuraId = '';
|
||||
periodMode: 'todos' | 'manual' = 'todos';
|
||||
periodText = '';
|
||||
periodError = '';
|
||||
tema: Tema = 'claro';
|
||||
filters?: FilterState;
|
||||
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
|
||||
|
||||
constructor() {
|
||||
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
|
||||
if (isDominio(initialDomain)) this.dominio = initialDomain;
|
||||
this.figureRequests.pipe(switchMap(selection => selection
|
||||
? this.service.figura(selection).pipe(
|
||||
? defer(() => this.service.figura(selection)).pipe(
|
||||
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) as FigureState),
|
||||
catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)),
|
||||
catchError(error => of({
|
||||
status: 'error',
|
||||
message: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404
|
||||
&& (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));
|
||||
@@ -66,7 +70,7 @@ export class IndicadoresPage {
|
||||
this.catalogError.set('');
|
||||
this.catalog.set([]);
|
||||
this.indicadorId = this.figuraId = '';
|
||||
this.resetPeriodos('semestre');
|
||||
this.filters = undefined;
|
||||
this.figureRequests.next(null);
|
||||
return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })),
|
||||
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
|
||||
@@ -74,53 +78,68 @@ export class IndicadoresPage {
|
||||
this.catalogLoading.set(false);
|
||||
this.catalog.set(items);
|
||||
this.catalogError.set(error);
|
||||
if (items.length) this.selectIndicador(items[0].id);
|
||||
const navigation = this.memory.navigation(this.dominio);
|
||||
this.tema = navigation?.tema ?? 'claro';
|
||||
if (items.length) this.selectIndicador(items.some(i => i.id === navigation?.indicador) ? navigation!.indicador : items[0].id);
|
||||
});
|
||||
}
|
||||
filtersEdited() {
|
||||
if (!this.filters || !this.selected) return;
|
||||
this.memory.save(this.dominio, this.indicadorId, this.figuraId, this.filters);
|
||||
this.memory.remember(this.dominio, this.indicadorId, this.figuraId, this.tema);
|
||||
}
|
||||
changeDominio(dominio: Dominio) {
|
||||
if (!isDominio(dominio) || dominio === this.dominio) return;
|
||||
this.filtersEdited();
|
||||
this.dominio = dominio;
|
||||
this.catalogRequests.next();
|
||||
}
|
||||
private resetPeriodos(tipo: TipoPeriodo) {
|
||||
this.tipoPeriodo = tipo;
|
||||
this.periodText = this.periodError = '';
|
||||
this.periodMode = 'todos';
|
||||
}
|
||||
changeTipoPeriodo(tipo: TipoPeriodo) {
|
||||
if (!this.selected?.tipos_periodo.includes(tipo)) return;
|
||||
this.resetPeriodos(tipo);
|
||||
if (tipo !== this.selected.tipos_periodo[0]) this.periodMode = 'manual';
|
||||
this.requestFigure();
|
||||
}
|
||||
get periodLabel(): string { return this.tipoPeriodo === 'mes' ? 'Meses (AAAA-MM)' : 'Semestres (AAAA-S1,AAAA-S2)'; }
|
||||
retryCatalog() { this.catalogRequests.next(); }
|
||||
retryCatalog() { this.filtersEdited(); this.catalogRequests.next(); }
|
||||
selectIndicador(id: string) {
|
||||
if (!this.catalog().some(i => i.id === id)) return;
|
||||
this.filtersEdited();
|
||||
this.indicadorId = id;
|
||||
this.figuraId = this.selected?.figuras[0] ?? '';
|
||||
if (!this.selected?.tipos_periodo.includes(this.tipoPeriodo)
|
||||
|| (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0])) {
|
||||
this.resetPeriodos(this.selected?.tipos_periodo[0] ?? 'semestre');
|
||||
}
|
||||
const remembered = this.memory.selectedFigure(this.dominio, id);
|
||||
this.figuraId = this.selected!.figuras.includes(remembered ?? '') ? remembered! : this.selected!.figuras[0] ?? '';
|
||||
this.restoreFilters();
|
||||
}
|
||||
selectFigura(id: string) {
|
||||
if (!this.selected?.figuras.includes(id)) return;
|
||||
this.filtersEdited();
|
||||
this.figuraId = id;
|
||||
this.restoreFilters();
|
||||
}
|
||||
private restoreFilters() {
|
||||
this.filters = this.memory.restore(this.dominio, this.selected!, this.figuraId);
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
|
||||
changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); }
|
||||
changePeriodText(text: string) { this.periodText = text; this.requestFigure(); }
|
||||
changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); }
|
||||
applyFilters() {
|
||||
if (!this.filters || !this.selected) return;
|
||||
const draft = this.filters.editors[this.filters.tipo]!.draft;
|
||||
if (!validDraft(draft, this.filters.tipo, this.selected.tipos_periodo)) return;
|
||||
this.filters.applied = { tipo: this.filters.tipo, selection: structuredClone(draft) };
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
changeTema(tema: Tema) {
|
||||
if (tema !== 'claro' && tema !== 'oscuro') return;
|
||||
this.tema = tema;
|
||||
this.filtersEdited();
|
||||
this.requestFigure();
|
||||
}
|
||||
// Navigation, retry and theme all use the last application, never the pending editor.
|
||||
requestFigure() {
|
||||
this.periodError = '';
|
||||
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText, this.tipoPeriodo) : undefined;
|
||||
if (periodos === null) this.periodError = this.tipoPeriodo === 'mes'
|
||||
? 'Introduce meses AAAA-MM del 01 al 12 separados por comas.'
|
||||
: 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
|
||||
if (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0]) {
|
||||
this.periodError = 'Selecciona periodos explícitos para este tipo; el servicio usa solo el primer tipo publicado al omitir periodos.';
|
||||
}
|
||||
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || !this.selected.tipos_periodo.includes(this.tipoPeriodo) || periodos === null || !!this.periodError) {
|
||||
const applied = this.filters?.applied;
|
||||
if (!this.selected?.figuras.includes(this.figuraId) || !applied
|
||||
|| !validDraft(applied.selection, applied.tipo, this.selected.tipos_periodo)) {
|
||||
this.figureRequests.next(null);
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({ dominio: this.dominio, tipoPeriodo: this.tipoPeriodo, indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
|
||||
this.figureRequests.next({
|
||||
dominio: this.dominio, tipoPeriodo: applied.tipo, indicador: this.indicadorId,
|
||||
figura: this.figuraId, tema: this.tema,
|
||||
periodos: applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,3 +32,14 @@ it('deduplica meses en orden estable y valida el calendario sin mezclar tipos',
|
||||
it('no interpreta NaN ni null como porcentajes cero', () => {
|
||||
expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['0000-S1', '0000-S2', '10000-S1'])('rechaza año fuera de rango %s', value => {
|
||||
expect(parsePeriodos(value)).toBeNull();
|
||||
});
|
||||
it.each(['0000-01', '10000-01', '2025-00', '2025-13'])('rechaza mes o año fuera de rango %s', value => {
|
||||
expect(parsePeriodos(value, 'mes')).toBeNull();
|
||||
});
|
||||
it('acepta extremos canónicos de año', () => {
|
||||
expect(parsePeriodos('0001-S1,9999-S2')).toEqual(['0001-S1', '9999-S2']);
|
||||
expect(parsePeriodos('0001-01,9999-12', 'mes')).toEqual(['0001-01', '9999-12']);
|
||||
});
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo;
|
||||
export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null {
|
||||
if (tipo !== 'semestre' && tipo !== 'mes') return null;
|
||||
const parts = value.split(',').map(part => part.trim());
|
||||
return parts.length && parts.every(part => (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part))
|
||||
return parts.length && parts.every(part => part.slice(0, 4) !== '0000' && (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part))
|
||||
? [...new Set(parts)] : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -86,3 +86,16 @@ describe('IndicadoresService HTTP', () => {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UX-04 validación defensiva HTTP', () => {
|
||||
it('bloquea explícitos vacíos antes de construir una petición', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const service = TestBed.inject(IndicadoresService);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos: [] })).toThrow('Selección explícita vacía');
|
||||
for (const periodos of [['0000-S1'], ['0000-01'], ['10000-01']]) {
|
||||
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow();
|
||||
}
|
||||
http.expectNone(() => true); http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,7 +27,8 @@ export class IndicadoresService {
|
||||
}
|
||||
figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
if (selection.periodos?.length) {
|
||||
if (selection.periodos !== undefined) {
|
||||
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
|
||||
const text = selection.periodos.join(',');
|
||||
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
|
||||
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
|
||||
|
||||
Reference in New Issue
Block a user