feat(ui): incorporar selector de figuras KPI y fijacion de indicadores
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
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 { By } from '@angular/platform-browser';
|
||||
import { MatSelect } from '@angular/material/select';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresMemory, GlobalApplied } from './indicadores-memory';
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
describe('UX-06E.D.2.1 selector de representación', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadorCatalogCard>>;
|
||||
let http: HttpTestingController;
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); create(['f', 'g']);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function create(figuras: string[], domain = 'cacu') {
|
||||
fixture = TestBed.createComponent(IndicadorCatalogCard);
|
||||
fixture.componentRef.setInput('dominio', domain);
|
||||
fixture.componentRef.setInput('indicador', { id: 'i', titulo: 'I', contrato: 'C2', figuras, tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('applied', applied); fixture.detectChanges();
|
||||
}
|
||||
function select() { return fixture.debugElement.query(By.directive(MatSelect)).componentInstance as MatSelect; }
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)); }
|
||||
function request(id: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + id)); }
|
||||
function open() { fixture.componentInstance.toggle(); fixture.detectChanges(); }
|
||||
it('una opción publicada está deshabilitada y sólo consulta esa figura', () => {
|
||||
fixture.destroy(); create(['f']); open(); expect(select().disabled).toBe(true);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
|
||||
});
|
||||
it('múltiples opciones habilitan el selector, mantienen una representación y cancelan cambios rápidos', () => {
|
||||
open(); const first = request('f'); expect(select().disabled).toBe(false);
|
||||
expect(select().options.map(o => o.value)).toEqual(['f', 'g']); expect(panels()).toHaveLength(1);
|
||||
select().selectionChange.emit({ source: select(), value: 'g' }); fixture.detectChanges();
|
||||
const next = request('g'); expect(first.cancelled).toBe(true); expect(panels()).toHaveLength(1);
|
||||
expect(next.request.params.get('periodos')).toBe('2025-S1');
|
||||
fixture.componentInstance.selectFigure('f'); fixture.detectChanges(); expect(next.cancelled).toBe(true);
|
||||
request('f').flush({ data: [{ y: [7] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].componentInstance.result().figure.data[0].y).toEqual([7]); http.expectNone(() => true);
|
||||
});
|
||||
it('restaura memoria por dominio e indicador sólo si sigue publicada y conserva apertura diferida', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges();
|
||||
request('g').flush({ data: [], layout: {} }); fixture.destroy(); create(['f', 'g']);
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('g'); expect(fixture.componentInstance.awaitingFigures).toBe(true); http.expectNone(() => true);
|
||||
fixture.componentInstance.activateVisible(); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.destroy(); create(['f', 'g'], 'cama'); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
fixture.destroy(); create(['f']); expect(fixture.componentInstance.selectedFigure).toBe('f');
|
||||
});
|
||||
it('cambio de aplicado conserva elección y consulta sólo su representación; cierre manual prevalece', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('g'); fixture.detectChanges(); request('g').flush({ data: [], layout: {} });
|
||||
fixture.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); fixture.detectChanges();
|
||||
const current = request('g'); expect(current.request.params.get('periodos')).toBe('2025-S2'); http.expectNone(r => r.url.endsWith('/figuras/f'));
|
||||
fixture.componentInstance.toggle(); fixture.detectChanges(); expect(current.cancelled).toBe(true);
|
||||
fixture.componentInstance.activateVisible(); fixture.detectChanges(); expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('opciones ajenas al catálogo y selección repetida no consultan', () => {
|
||||
open(); request('f').flush({ data: [], layout: {} }); fixture.componentInstance.selectFigure('bad'); fixture.componentInstance.selectFigure('f'); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.selectedFigure).toBe('f'); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
it('C2 sin magnitudes mantiene nota de supresión del servicio fuera del host Plotly y no cambia trazas', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigureCard] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
const fixture = TestBed.createComponent(IndicadorFigureCard);
|
||||
const figure = { data: [{ type: 'pie', values: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } };
|
||||
fixture.componentRef.setInput('state', { status: 'ready', figure, presentationFigure: structuredClone(figure) });
|
||||
fixture.componentRef.setInput('selected', { id: 'i', titulo: 'I', contrato: 'C2', figuras: ['fig_c2_donas'], tipos_periodo: ['semestre'] });
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('figuraId', 'fig_c2_donas'); fixture.componentRef.setInput('tema', 'claro'); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('[aria-label="Advertencias y notas del servicio"]').textContent).toContain('Valores ocultos por supresión.');
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles'); expect(fixture.nativeElement.textContent).toContain('Los sectores');
|
||||
expect(figure.data[0].values).toEqual([null, null]); fixture.destroy();
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import { DOCUMENT } from '@angular/common';
|
||||
import { ChangeDetectorRef, Component, ElementRef, inject, Input, OnChanges, output, ViewChild } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||
import { CardActivation, GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
@@ -10,7 +12,7 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header #visibilityHeader>
|
||||
@@ -22,14 +24,28 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
[attr.aria-controls]="contentId" [attr.aria-label]="(awaitingFigures ? 'Mostrar figuras de ' : expanded ? 'Contraer ' : 'Expandir ') + dominio + ' · ' + indicador.id + ' · ' + indicador.titulo"
|
||||
(click)="toggle()"><mat-icon aria-hidden="true">{{ expanded && !awaitingFigures ? 'expand_less' : 'expand_more' }}</mat-icon></button>
|
||||
</header>
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ' · ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
<div #content [id]="contentId" [attr.aria-labelledby]="titleId">
|
||||
@if (awaitingFigures) {
|
||||
<p class="catalog-metadata">Apertura recordada. Las figuras se cargarán al entrar en pantalla o al pulsar «Mostrar figuras».</p>
|
||||
} @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" [applied]="applied" />
|
||||
} @empty { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
@if (selectedFigure) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Representación gráfica</mat-label>
|
||||
<mat-select [value]="selectedFigure" [disabled]="indicador.figuras.length === 1"
|
||||
[attr.aria-label]="'Representación gráfica de ' + indicador.titulo" (selectionChange)="selectFigure($event.value)">
|
||||
@for (figure of indicador.figuras; track figure) { <mat-option [value]="figure">{{ figure }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@for (figure of [selectedFigure]; track panelIdentity(figure)) {
|
||||
<app-indicador-figure-panel [dominio]="dominio" [indicador]="indicador" [figuraId]="figure" [tema]="tema" [applied]="applied" />
|
||||
}
|
||||
} @else { <p role="status">El indicador no tiene figuras disponibles.</p> }
|
||||
}
|
||||
</div>
|
||||
</mat-card>
|
||||
@@ -44,7 +60,11 @@ import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 700; font-size: 1.5rem; line-height: 1.25; }
|
||||
.indicator-id { margin: var(--issste-space-1) 0 0; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
header button { justify-self: end; flex-shrink: 0; min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
mat-form-field { width: 100%; margin-top: var(--issste-space-4); }
|
||||
.catalog-metadata { margin: var(--issste-space-4) 0 0; padding-top: var(--issste-space-4);
|
||||
border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font: var(--mat-sys-body-small); }
|
||||
@media (max-width: 550px) { h2 { font-size: 1.25rem; } header { gap: var(--issste-space-2); } }
|
||||
@@ -55,6 +75,8 @@ export class IndicadorCatalogCard implements OnChanges {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() pinned = false;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityHeader', { static: true }) visibilityHeader!: ElementRef<HTMLElement>;
|
||||
readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
|
||||
readonly activationChanged = output<void>();
|
||||
@@ -72,7 +94,16 @@ export class IndicadorCatalogCard implements OnChanges {
|
||||
titleId = '';
|
||||
contentId = '';
|
||||
panelIdentity(figure: string) { return figureIdentity(this.dominio, this.indicador.id, figure); }
|
||||
selectedFigure?: string;
|
||||
selectFigure(figure: string) {
|
||||
if (!this.indicador.figuras.includes(figure) || figure === this.selectedFigure) return;
|
||||
this.selectedFigure = figure;
|
||||
this.memory.rememberFigure(this.dominio, this.indicador.id, figure);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnChanges() {
|
||||
const remembered = this.memory.figure(this.dominio, this.indicador.id);
|
||||
this.selectedFigure = remembered && this.indicador.figuras.includes(remembered) ? remembered : this.indicador.figuras[0];
|
||||
const identity = indicatorIdentity(this.dominio, this.indicador.id);
|
||||
if (identity === this.identity) return;
|
||||
this.identity = identity;
|
||||
|
||||
@@ -32,6 +32,12 @@
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.</p>
|
||||
}
|
||||
@if (serviceNotes.length) {
|
||||
<section class="notes" aria-label="Advertencias y notas del servicio">
|
||||
<h2>Notas de la figura</h2>
|
||||
@for (note of serviceNotes; track $index) { <p [innerHTML]="note"></p> }
|
||||
</section>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figuraId }}</p>
|
||||
} @else {
|
||||
@@ -39,7 +45,7 @@
|
||||
}
|
||||
@if (chartFigure) {
|
||||
<div [hidden]="state.status !== 'ready'">
|
||||
<app-plotly-chart [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" />
|
||||
<app-plotly-chart [showNotes]="false" [label]="dominio + ' · ' + selected?.id + ' · ' + figuraId" [figure]="chartFigure" />
|
||||
</div>
|
||||
}
|
||||
</mat-card>
|
||||
|
||||
@@ -23,3 +23,7 @@
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
|
||||
@media (max-width: 550px) { .interpretation { padding: var(--issste-space-3); } }
|
||||
|
||||
.notes { padding: 1rem; overflow-wrap: anywhere; }
|
||||
.notes h2 { font-size: 1rem; }
|
||||
.notes p { line-height: 1.5; }
|
||||
|
||||
@@ -81,13 +81,20 @@ export class IndicadorFigureCard {
|
||||
get visibleInterpretation(): readonly string[] {
|
||||
return this.interpretation.slice(this.complementaryLineCount);
|
||||
}
|
||||
get serviceNotes(): string[] {
|
||||
const annotations = this.state.figure?.layout['annotations'];
|
||||
return Array.isArray(annotations) ? annotations.flatMap(note =>
|
||||
note && typeof note.text === 'string' ? [note.text] : []) : [];
|
||||
}
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
|
||||
get interpretation(): readonly string[] {
|
||||
const contract = this.contract;
|
||||
if (contract === 'C2' && this.dominio !== 'tea') return [
|
||||
'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.',
|
||||
this.state.figure?.data.some(trace => trace['type'] === 'pie')
|
||||
? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.'
|
||||
: 'Las barras muestran la composición porcentual de las categorías publicadas para cada periodo.',
|
||||
'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
|
||||
'Los valores nulos o suprimidos no representan porcentajes observados de 0 %.',
|
||||
];
|
||||
|
||||
@@ -11,7 +11,7 @@ import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-card',
|
||||
imports: [MatCardModule],
|
||||
imports: [MatCardModule, MatProgressBarModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<mat-card [attr.aria-busy]="loading">
|
||||
<h3>{{ title }}</h3>
|
||||
@if (loading) { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + title" /> }
|
||||
@if (provisional) { <p class="provisional">Definición provisional</p> }
|
||||
@if (value !== null && value !== undefined) {
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state">{{ state }}</p>
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
@if (additionalInfo) { <p class="additional-info">{{ additionalInfo }}</p> }
|
||||
@for (note of notes; track $index) { <p class="additional-info">{{ note }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
styles: `
|
||||
@@ -24,6 +28,7 @@ import { MatCardModule } from '@angular/material/card';
|
||||
h3, p { overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.provisional { border-left: 3px solid var(--issste-text-secondary); padding-left: .75rem; font-weight: 600; }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
`,
|
||||
})
|
||||
@@ -32,6 +37,9 @@ export class IndicadorKpiCard {
|
||||
@Input() value?: string | number | null;
|
||||
@Input() unit?: string;
|
||||
@Input() temporalReference?: string;
|
||||
@Input() loading = false;
|
||||
@Input() provisional = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
@Input() additionalInfo?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorDatos, Dominio } from './indicadores.models';
|
||||
describe('KPI integración con autoridad global', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function load(domain: Dominio, missing = false) {
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(KPI_BY_DOMAIN[domain].slice(missing ? 1 : 0).map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel); }
|
||||
function requests() { return http.match(r => r.url.endsWith('/datos')); }
|
||||
function response(index: number, domain: Dominio = 'cacu', period = '2025-S1'): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: period.includes('-S') ? 'semestre' : 'mes', periodos: [period], categorias: { A: {} }, filas: [
|
||||
{ periodo: period, grupo: index === 1 ? 'total' : 'TOTAL', estrato: null, categoria: 'A', n: 5, valor: 40, numerador: 2, denominador: 5, mediana: 7, q1: 3, q3: 9, unidad: 'dias', suprimido: 0 }] };
|
||||
}
|
||||
function apply(periods: string[], tipo: 'mes' | 'semestre' = 'semestre') {
|
||||
const state = fixture.componentInstance.filters!; state.tipo = tipo; state.editors[tipo]!.draft = { mode: 'explicit', periodos: periods as [string, ...string[]] };
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges();
|
||||
}
|
||||
it('TEA conserva dos preliminares y no consulta datos', () => {
|
||||
expect(fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')).toHaveLength(2); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('tres tarjetas independientes manejan 404, error y éxito sin cifras anteriores', () => {
|
||||
load('cacu'); const req = requests(); expect(req).toHaveLength(3); expect(panels().every(p => p.result().loading)).toBe(true);
|
||||
for (const r of req) { expect(r.request.params.has('tipoPeriodo')).toBe(false); expect(r.request.params.has('tema')).toBe(false); }
|
||||
req[0].flush('private', { status: 404, statusText: 'Not Found' }); req[1].flush('private', { status: 503, statusText: 'Unavailable' }); req[2].flush(response(2)); fixture.detectChanges();
|
||||
expect(panels().map(p => p.result().state)).toEqual(['Sin datos del periodo', 'Error de consulta', 'Disponible']);
|
||||
expect(panels()[2].result().value).toBe(7); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.querySelector('.provisional').textContent).toBe('Definición provisional');
|
||||
apply(['2025-S2']); expect(panels().every(p => p.result().value === undefined)).toBe(true); requests().forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
});
|
||||
it('borrador no consulta; aplicar equivalente tampoco; revisión distinta cancela las tres anteriores', () => {
|
||||
load('cacu'); const initial = requests(); initial.forEach((r,i) => r.flush(response(i)));
|
||||
const editor = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
editor.changeMode('manual'); editor.year = '2025'; editor.unit = 'S1'; editor.add(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const single = requests(); expect(single).toHaveLength(3);
|
||||
expect(single.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
apply(['2025-S2']); expect(single.every(r => r.cancelled)).toBe(true); const next = requests(); expect(next).toHaveLength(3);
|
||||
next.forEach((r,i) => r.flush(response(i, 'cacu', '2025-S2')));
|
||||
apply(['2025-S2']); http.expectNone(() => true);
|
||||
});
|
||||
it('selección múltiple cancela, no consulta ni suma meses para un semestre', () => {
|
||||
load('cacu'); const pending = requests(); apply(['2025-01', '2025-02'], 'mes');
|
||||
expect(pending.every(r => r.cancelled)).toBe(true); expect(panels().every(p => p.result().state === 'Selección no consolidable')).toBe(true); http.expectNone(() => true);
|
||||
apply(['2025-01'], 'mes'); requests().forEach((r,i) => { expect(r.request.params.get('periodos')).toBe('2025-01'); r.flush(response(i, 'cacu', '2025-01')); });
|
||||
});
|
||||
it('dominio cancela solicitudes salientes y restaura aplicado independiente del borrador', () => {
|
||||
load('cacu'); const outgoing = requests(); apply(['2025-S1']); const applied = requests(); expect(outgoing.every(r => r.cancelled)).toBe(true);
|
||||
fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] };
|
||||
load('cama'); expect(applied.every(r => r.cancelled)).toBe(true); const cama = requests(); expect(cama.every(r => r.request.url.startsWith('/cama/'))).toBe(true); cama.forEach((r,i) => r.flush(response(i, 'cama')));
|
||||
load('cacu'); const restored = requests(); expect(restored.every(r => r.request.params.get('periodos') === '2025-S1')).toBe(true);
|
||||
expect(fixture.componentInstance.filters!.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S2'] }); restored.forEach((r,i) => r.flush(response(i)));
|
||||
});
|
||||
it('ID ausente bloquea sólo esa tarjeta sin sustituir ni consultar otro indicador', () => {
|
||||
load('cacu', true); expect(panels()[0].result().state).toBe('Indicador no publicado'); expect(panels()[0].result().info).toContain('cacu_eu7');
|
||||
const req = requests(); expect(req).toHaveLength(2); req.forEach((r,i) => r.flush(response(i+1)));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Component, DestroyRef, inject, Input, OnChanges, signal } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, defer, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, Indicador } from './indicadores.models';
|
||||
import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-kpi-panel',
|
||||
imports: [IndicadorKpiCard],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [provisional]="definition.provisional ?? false" [notes]="result().notes ?? []" />`,
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) definition!: KpiDefinition;
|
||||
@Input() indicador?: Indicador;
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() catalogPending = false;
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly requests = new Subject<void>();
|
||||
private key = '';
|
||||
readonly result = signal<KpiResult>({ state: 'Esperando catálogo' });
|
||||
get temporalReference() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado'; }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => {
|
||||
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
||||
if (this.catalogPending) return of({ state: 'Esperando catálogo' });
|
||||
if (!this.indicador) return of({ state: 'Indicador no publicado', info: 'No está disponible en el catálogo: ' + definition.id });
|
||||
if (this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
||||
const compatible = filterCompatibility(applied, this.indicador.tipos_periodo);
|
||||
if (!compatible.compatible || !applied) return of({ state: 'Filtro incompatible', info: !compatible.compatible ? compatible.reason : '' });
|
||||
if (applied.selection.mode === 'explicit' && applied.selection.periodos.length !== 1) return of({ state: 'Selección no consolidable', info: 'Elige un único periodo; no hay una regla aprobada para consolidarlos.' });
|
||||
return defer(() => this.service.datos(domain, definition.id, applied.tipo,
|
||||
applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined)).pipe(
|
||||
map(data => ({ ...kpiResult(data, definition, domain, applied), notes: data.notas })),
|
||||
catchError(error => of({ state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
||||
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
||||
startWith({ state: 'Cargando…', loading: true }));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => this.result.set(result));
|
||||
}
|
||||
ngOnChanges() {
|
||||
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.catalogPending, this.applied && selectionKey(this.applied)]);
|
||||
if (key === this.key) return;
|
||||
this.key = key;
|
||||
this.requests.next();
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ 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: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const item = (id: string, types: TipoPeriodo[] = ['semestre', 'mes']): Indicador =>
|
||||
({ id, titulo: id, contrato: 'C1', figuras: ['f'], tipos_periodo: types });
|
||||
@@ -47,7 +47,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
|
||||
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(sections[1].querySelectorAll('app-indicador-kpi-card')).toHaveLength(domain === 'tea' ? 2 : 3);
|
||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||
expect(fixture.nativeElement.querySelector('.apply-button').disabled).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||
const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 };
|
||||
function data(domain: Dominio, index: number, filas: Record<string, unknown>[]): IndicadorDatos {
|
||||
const d = KPI_BY_DOMAIN[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas };
|
||||
}
|
||||
describe.each(['cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
const run = (index: number, rows: Record<string, unknown>[]) => kpiResult(data(domain, index, rows), KPI_BY_DOMAIN[domain][index], domain, applied);
|
||||
it('C2 suma categorías disjuntas del único TOTAL incluyendo SIN_DATO y cero', () => {
|
||||
expect(run(0, [{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'SIN_DATO', n: 0 }]).value).toBe(5);
|
||||
expect(run(0, [{ ...total, categoria: 'A', n: 0 }]).value).toBe(0);
|
||||
});
|
||||
it('C1 consume porcentaje sin recalcular y muestra numerador y denominador', () => {
|
||||
const result = run(1, [{ ...total, grupo: 'total', valor: 33.36, numerador: 2, denominador: 6 }]);
|
||||
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
|
||||
expect(run(1, [{ ...total, grupo: 'total', valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
|
||||
});
|
||||
it('C3r conserva mediana cero y Q1/Q3, referencia provisional', () => {
|
||||
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
|
||||
expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días'); expect(result.info).toContain('provisional');
|
||||
});
|
||||
it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => {
|
||||
expect(run(index, [{ ...total, grupo: index === 1 ? 'total' : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
});
|
||||
it.each([0, 1, 2])('nulos en %s no se convierten en cero', index => {
|
||||
const result = run(index, [{ ...total, grupo: index === 1 ? 'total' : 'TOTAL', categoria: 'A', n: null, valor: null, mediana: null }]);
|
||||
expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible');
|
||||
});
|
||||
it('no suma grupos superpuestos, estratos ni categorías duplicadas', () => {
|
||||
for (const rows of [[{ ...total, categoria: 'A', n: 5 }, { ...total, grupo: 'OTHER', categoria: 'A', n: 5 }],
|
||||
[{ ...total, categoria: 'A', n: 5 }, { ...total, categoria: 'A', n: 5 }], [{ ...total, categoria: 'A', n: 5, estrato: 'edad' }]]) {
|
||||
expect(run(0, rows).state).toBe('Selección no consolidable');
|
||||
}
|
||||
});
|
||||
it('Todos con reporte con varios periodos es no consolidable, aun si uno no tiene filas', () => {
|
||||
const d = data(domain, 0, [{ ...total, categoria: 'A', n: 5 }]); d.periodos.push('2025-S2');
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, { ...applied, selection: { mode: 'todos' } }).state).toBe('Selección no consolidable');
|
||||
});
|
||||
it('sin filas tiene estado explícito y contrato equivocado no produce cifra', () => {
|
||||
expect(run(0, []).state).toBe('Sin filas utilizables'); const d = data(domain, 0, []); d.contrato = 'C1';
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN[domain][0], domain, applied).state).toBe('Error de contrato');
|
||||
});
|
||||
});
|
||||
|
||||
it('categorías incompletas nunca producen un total parcial', () => {
|
||||
const d = data('cacu', 0, [{ ...total, categoria: 'A', n: 5 }]); d['categorias'] = { A: {}, B: {} };
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN.cacu[0], 'cacu', applied).value).toBeUndefined();
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; provisional?: boolean; }
|
||||
const definitions = (): KpiDefinition[] => [
|
||||
{ id: '', title: 'Pacientes evaluadas', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: '', title: 'Confirmación histopatológica', contrato: 'C1', unit: '%', provisional: true },
|
||||
{ id: '', title: 'Días de la toma al resultado', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
];
|
||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
tea: [],
|
||||
cacu: definitions().map((d, i) => ({ ...d, id: ['cacu_eu7', 'cacu_eu13', 'cacu_eu_tiempo_reporte'][i] })),
|
||||
cama: definitions().map((d, i) => ({ ...d, id: ['cama_birads', 'cama_confirmacion_birads45', 'cama_eu38a'][i] })),
|
||||
};
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; }
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
||||
|
||||
// C2 definitions count each patient once per period, in disjoint categories of TOTAL.
|
||||
// C1/C3r publish a single total row. Never combine totals, strata, or periods.
|
||||
export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domain: Dominio, applied: GlobalApplied): KpiResult {
|
||||
if (data.id !== definition.id || data.contrato !== definition.contrato || data.tipo_periodo !== applied.tipo) {
|
||||
return { state: 'Error de contrato', info: 'Los datos recibidos no corresponden al indicador o periodo aplicado.' };
|
||||
}
|
||||
if (!data.periodos.length && !data.filas.length) return { state: 'Sin filas utilizables' };
|
||||
if (data.periodos.length !== 1 || new Set(data.filas.map(row => row['periodo'])).size > 1) return unscoped;
|
||||
const period = data.periodos[0];
|
||||
if (applied.selection.mode === 'explicit' && (applied.selection.periodos.length !== 1 || applied.selection.periodos[0] !== period)) return unscoped;
|
||||
const rows = data.filas;
|
||||
if (!rows.length) return { state: 'Sin filas utilizables' };
|
||||
const group = definition.contrato === 'C1' ? 'total' : 'TOTAL';
|
||||
if (rows.some(row => row['periodo'] !== period || row['grupo'] !== group || row['estrato'] != null)) return unscoped;
|
||||
if (definition.contrato !== 'C2' && rows.length !== 1) return unscoped;
|
||||
if (rows.some(row => finite(row['suprimido']) && row['suprimido'] !== 0)) return { state: 'Dato oculto por tamaño' };
|
||||
if (rows.some(row => row['suprimido'] !== 0)) return { state: 'Sin filas utilizables', info: 'No se puede determinar el estado de supresión.' };
|
||||
const empty = { state: 'Sin valor disponible' };
|
||||
const row = rows[0];
|
||||
if (definition.contrato === 'C2') {
|
||||
const categories = rows.map(row => row['categoria']);
|
||||
if (categories.some(c => typeof c !== 'string' || !c) || new Set(categories).size !== categories.length) return unscoped;
|
||||
const catalog = data['categorias'];
|
||||
if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return { state: 'Error de contrato', info: 'Falta el catálogo de categorías para verificar el total.' };
|
||||
const expected = Object.keys(catalog);
|
||||
if (expected.length !== categories.length || expected.some(c => !categories.includes(c))) return { state: 'Sin filas utilizables', info: 'Las categorías recibidas no permiten verificar un total completo.' };
|
||||
if (!rows.every(row => count(row['n']))) return empty;
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Pacientes con mastografía tomada en el periodo.' };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
return { state: 'Disponible', value: row['valor'].toFixed(1), info: domain === 'cacu'
|
||||
? `${row['numerador']} de ${row['denominador']} pacientes con lesión de alto grado o mayor en biopsia.`
|
||||
: `${row['numerador']} de ${row['denominador']} mastografías BI-RADS 4 y 5 con reporte de biopsia.` };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
return { state: 'Disponible', value: row['mediana'], info: `${row['n']} ${domain === 'cacu' ? 'citologías' : 'mastografías'}; Q1 a Q3: ${row['q1']} a ${row['q3']} días. La referencia de 60 días es provisional.` };
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Injectable, signal } from '@angular/core';
|
||||
import { Dominio, Indicador, parsePeriodos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
|
||||
export type PeriodDraft =
|
||||
@@ -63,7 +63,24 @@ export type CardActivation = 'pending' | 'auto-open' | 'manual-open' | 'manual-c
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresMemory {
|
||||
private readonly pinnedIndicators = signal<ReadonlySet<string>>(new Set());
|
||||
isPinned(domain: Dominio, indicador: string) {
|
||||
return this.pinnedIndicators().has(JSON.stringify([domain, indicador]));
|
||||
}
|
||||
togglePinned(domain: Dominio, indicador: string) {
|
||||
const key = JSON.stringify([domain, indicador]);
|
||||
this.pinnedIndicators.update(current => {
|
||||
const next = new Set(current);
|
||||
if (next.has(key)) next.delete(key); else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
private readonly themes = new Map<Dominio, Tema>();
|
||||
private readonly figures = new Map<string, string>();
|
||||
figure(domain: Dominio, indicador: string) { return this.figures.get(JSON.stringify([domain, indicador])); }
|
||||
rememberFigure(domain: Dominio, indicador: string, figure: string) {
|
||||
this.figures.set(JSON.stringify([domain, indicador]), figure);
|
||||
}
|
||||
private readonly expansions = new Map<string, CardActivation>();
|
||||
private readonly filters = new Map<Dominio, GlobalFilterState>();
|
||||
theme(domain: Dominio): Tema { return this.themes.get(domain) ?? 'claro'; }
|
||||
|
||||
@@ -15,7 +15,7 @@ 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', 'label'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
|
||||
describe('UX-04 navegación Angular', () => {
|
||||
|
||||
@@ -13,17 +13,22 @@
|
||||
@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>
|
||||
<p class="section-description">La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.</p>
|
||||
<app-indicador-period-filters [state]="state" [types]="filterTypes()"
|
||||
(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>
|
||||
<h2 id="kpi-section-title" class="section-title">Indicadores destacados{{ dominio === 'tea' ? ' — Vista preliminar' : '' }}</h2>
|
||||
<p class="section-description">{{ dominio === 'tea' ? 'Muestra visual de TEA. Las definiciones y fuentes de estos indicadores están pendientes.' : 'Valores del filtro general aplicado. Selecciona un único periodo para evitar consolidaciones sin una regla aprobada.' }}</p>
|
||||
<div class="kpi-grid">
|
||||
@for (preview of kpiPreviewsByDomain[dominio]; track dominio + ':' + preview.id) {
|
||||
<app-indicador-kpi-card [title]="preview.title" />
|
||||
@if (dominio === 'tea') {
|
||||
@for (preview of kpiPreviewsByDomain.tea; track preview.id) { <app-indicador-kpi-card [title]="preview.title" /> }
|
||||
} @else {
|
||||
@for (definition of kpisByDomain[dominio]; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [catalogPending]="catalogLoading() || !!catalogError()" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
@@ -61,7 +66,7 @@
|
||||
@if (searchResults().count) {
|
||||
{{ searchResults().count }} coincidencias de {{ catalog().length }} indicadores. Todos permanecen disponibles.
|
||||
} @else {
|
||||
No se encontraron coincidencias. El catálogo completo permanece disponible en su orden original.
|
||||
No se encontraron coincidencias. El catálogo completo permanece disponible; los indicadores fijados aparecen primero.
|
||||
}
|
||||
}
|
||||
</p>
|
||||
@@ -69,7 +74,7 @@
|
||||
<div class="catalog-grid">
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="filters!.applied"
|
||||
(activationChanged)="visibilityChanged()" />
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" (activationChanged)="visibilityChanged()" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -53,3 +53,5 @@ nav a[aria-current='page'] {
|
||||
}
|
||||
|
||||
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
|
||||
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid:has(app-indicador-kpi-panel) { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
|
||||
@@ -16,7 +16,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const item: Indicador = { id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const second: Indicador = { ...item, id: 'i2', titulo: 'Dos', figuras: ['g'] };
|
||||
@@ -41,7 +41,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
function flushAll() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [0, null] }], layout: {} })); fixture.detectChanges(); }
|
||||
function control(index = 0) { return fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))[index].componentInstance as IndicadorPeriodFilters; }
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('D.1 muestra dos KPI pendientes propios de %s fuera del catálogo', domain => {
|
||||
it.each(['tea'] as const)('D.1 muestra dos KPI pendientes propios de %s fuera del catálogo', domain => {
|
||||
if (domain !== 'tea') {
|
||||
const initial = http.expectOne('/tea/indicadores');
|
||||
page.changeDominio(domain); expect(initial.cancelled).toBe(true);
|
||||
@@ -81,8 +81,8 @@ describe('UX-05B catálogo expandible', () => {
|
||||
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();
|
||||
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([2, 1]);
|
||||
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'f2', 'g']);
|
||||
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]);
|
||||
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']);
|
||||
expect(cards()).toEqual(before); expect(cards().every(card => card.expanded)).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -119,7 +119,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(button.getAttribute('aria-label')).toContain('Contraer tea · i1 · Uno');
|
||||
expect(header.textContent).not.toContain('Contrato');
|
||||
expect(host.querySelector('.catalog-metadata')?.textContent).toContain('Contrato C1 · 2 figuras publicadas');
|
||||
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(2);
|
||||
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(1);
|
||||
button.click(); fixture.detectChanges();
|
||||
expect(host.querySelector('.catalog-metadata')).toBeNull();
|
||||
expect(host.querySelectorAll('app-indicador-figure-panel')).toHaveLength(0);
|
||||
@@ -173,9 +173,9 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(panels()).toHaveLength(0); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
if (!count) expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
||||
});
|
||||
it('abrir manualmente un indicador consulta exactamente una vez cada figura publicada', () => {
|
||||
load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(2);
|
||||
request('f1').flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} });
|
||||
it('abrir manualmente consulta exactamente una vez la primera figura publicada', () => {
|
||||
load([item]); toggle(); expect(cards()[0].expanded).toBe(true); expect(panels()).toHaveLength(1);
|
||||
request('f1').flush({ data: [], layout: {} });
|
||||
fixture.detectChanges(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
});
|
||||
it('el cierre manual se conserva al volver sin consultar figuras', () => {
|
||||
@@ -189,22 +189,22 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(panels()).toHaveLength(0); http.expectNone(() => true);
|
||||
});
|
||||
it('varias tarjetas y figuras abiertas mantienen solicitudes concurrentes independientes', () => {
|
||||
load(); toggle(0); const a = request('f1'), b = request('f2'); toggle(1); const c = request('g');
|
||||
expect(a.cancelled).toBe(false); expect(b.cancelled).toBe(false);
|
||||
b.flush({ data: [{ y: [2] }], layout: {} }); c.flush({ data: [{ y: [3] }], layout: {} });
|
||||
load(); toggle(0); const a = request('f1'); toggle(1); const c = request('g');
|
||||
expect(a.cancelled).toBe(false);
|
||||
c.flush({ data: [{ y: [3] }], layout: {} });
|
||||
a.flush({ data: [{ y: [1] }], layout: {} });
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [2], [3]]);
|
||||
expect(panels().map(p => p.result().figure?.data[0]['y'])).toEqual([[1], [3]]);
|
||||
expect(cards().every(c => c.expanded)).toBe(true);
|
||||
});
|
||||
it('contraer cancela solo sus figuras, descarta respuestas y destruye paneles', () => {
|
||||
load(); toggle(); toggle(1); const a = request('f1'), b = request('f2'), c = request('g');
|
||||
toggle(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true); expect(c.cancelled).toBe(false);
|
||||
load(); toggle(); toggle(1); const a = request('f1'), c = request('g');
|
||||
toggle(); expect(a.cancelled).toBe(true); expect(c.cancelled).toBe(false);
|
||||
expect(() => a.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(panels()).toHaveLength(1); c.flush({ data: [{ y: [3] }], layout: {} });
|
||||
expect(panels()[0].result().figure?.data[0]['y']).toEqual([3]);
|
||||
});
|
||||
it('404 y reintento afectan solo una figura y 200 sin puntos sigue siendo resultado', () => {
|
||||
load([item]); toggle(); const a = request('f1'), b = request('f2');
|
||||
load(); toggle(); toggle(1); const a = request('f1'), b = request('g');
|
||||
a.flush('private', { status: 404, statusText: 'Not Found' });
|
||||
b.flush({ data: [{ y: [null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(panels()[0].result().status).toBe('error'); expect(panels()[1].result().status).toBe('ready');
|
||||
@@ -216,14 +216,14 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||
a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add(); http.expectNone(() => true);
|
||||
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();
|
||||
const appliedA = request('f1');
|
||||
expect(appliedA.request.params.get('periodos')).toBe('2025-S1');
|
||||
appliedA.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.get('periodos')).toBe('2025-S1');
|
||||
const themedA = request('f1');
|
||||
expect(themedA.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: {} });
|
||||
themedA.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('UX-06D expandir metodología conserva panel, figura y borrador sin generar HTTP', () => {
|
||||
load([{ ...item, contrato: 'C2', figuras: ['fig_c2_apiladas'] }]); toggle(); flushAll();
|
||||
@@ -242,27 +242,27 @@ describe('UX-05B catálogo expandible', () => {
|
||||
http.expectNone(() => true);
|
||||
}
|
||||
});
|
||||
it('cerrar y reabrir conserva borrador general y consulta aplicado en ambas figuras', () => {
|
||||
it('cerrar y reabrir conserva borrador general y consulta aplicado en la figura seleccionada', () => {
|
||||
load([item]); toggle(); flushAll(); const a = control(); a.changeMode('manual'); a.year = '2025'; a.unit = 'S1'; a.add();
|
||||
page.applyFilters(); fixture.detectChanges(); flushAll(); a.unit = 'S2'; a.add();
|
||||
toggle(); toggle();
|
||||
const restored = request('f1'), other = request('f2');
|
||||
expect(restored.request.params.get('periodos')).toBe('2025-S1'); expect(other.request.params.get('periodos')).toBe('2025-S1');
|
||||
const restored = request('f1');
|
||||
expect(restored.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: {} });
|
||||
restored.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('tema solo consulta paneles abiertos, cancela los anteriores y no repite el mismo tema', () => {
|
||||
load(); toggle(); const a = request('f1'), b = request('f2');
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true);
|
||||
const darkA = request('f1'), darkB = request('f2');
|
||||
load(); toggle(); const a = request('f1');
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); expect(a.cancelled).toBe(true);
|
||||
const darkA = request('f1');
|
||||
expect(darkA.request.params.get('tema')).toBe('oscuro'); http.expectNone(r => r.url.endsWith('/g'));
|
||||
darkA.flush({ data: [], layout: {} }); darkB.flush({ data: [], layout: {} });
|
||||
darkA.flush({ data: [], layout: {} });
|
||||
page.changeTema('oscuro'); fixture.detectChanges(); http.expectNone(() => true);
|
||||
toggle(1); const later = request('g'); expect(later.request.params.get('tema')).toBe('oscuro'); later.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('salir del dominio cancela paneles y catálogos obsoletos', () => {
|
||||
load(); toggle(); const a = request('f1'), b = request('f2');
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(a.cancelled).toBe(true); expect(b.cancelled).toBe(true);
|
||||
load(); toggle(); const a = request('f1');
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); expect(a.cancelled).toBe(true);
|
||||
const oldCatalog = http.expectOne('/cacu/indicadores'); page.changeDominio('cama'); fixture.detectChanges();
|
||||
expect(oldCatalog.cancelled).toBe(true); load(syntheticCatalogs.cama, 'cama'); flushAll();
|
||||
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow(); expect(page.dominio).toBe('cama');
|
||||
@@ -275,7 +275,7 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(cards()[0].expanded).toBe(true); expect(cards()[1].expanded).toBe(false);
|
||||
expect(page.tema).toBe('oscuro'); expect(cards()[0].awaitingFigures).toBe(true); http.expectNone(() => true);
|
||||
toggle(); const a = request('f1'); expect(a.request.params.has('periodos')).toBe(false);
|
||||
expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} }); request('f2').flush({ data: [], layout: {} });
|
||||
expect(control().entry.draft.mode).toBe('empty'); a.flush({ data: [], layout: {} });
|
||||
page.changeDominio('cacu'); fixture.detectChanges(); load(syntheticCatalogs.cacu, 'cacu');
|
||||
expect(cards()[0].expanded).toBe(false); expect(page.tema).toBe('claro'); http.expectNone(() => true);
|
||||
});
|
||||
@@ -303,8 +303,8 @@ describe('UX-05B catálogo expandible', () => {
|
||||
expect(buttons[0].getAttribute('aria-label')).not.toBe(buttons[1].getAttribute('aria-label'));
|
||||
});
|
||||
it('copia de presentación y gráficos independientes conservan JSON binario, notas, ceros y nulos', () => {
|
||||
load([item]); toggle(); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } };
|
||||
const before = JSON.stringify(raw); request('f1').flush(raw); request('f2').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges();
|
||||
load(); toggle(0); toggle(1); const raw = { data: [{ y: { dtype: 'f8', bdata: 'AAAAAAAAAAA=' }, customdata: [[0, null]] }], layout: { annotations: [{ text: 'Nota' }] } };
|
||||
const before = JSON.stringify(raw); request('f1').flush(raw); request('g').flush({ data: [{ y: [0, null] }], layout: {} }); fixture.detectChanges();
|
||||
expect(JSON.stringify(raw)).toBe(before); expect(panels()[0].result().figure).toEqual(raw);
|
||||
const charts = fixture.debugElement.queryAll(By.directive(ChartStub)); expect(charts).toHaveLength(2);
|
||||
expect(charts[0].componentInstance.figure).not.toBe(charts[1].componentInstance.figure);
|
||||
|
||||
@@ -16,13 +16,15 @@ import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { indicatorIdentity } from './indicadores-identities';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard, IndicadorPeriodFilters],
|
||||
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiCard, IndicadorKpiPanel, IndicadorPeriodFilters],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -162,9 +164,18 @@ export class IndicadoresPage {
|
||||
this.searchInput()?.nativeElement.focus({ preventScroll: true });
|
||||
}
|
||||
changeSearchQuery(query: string) {
|
||||
const focused = this.document.activeElement;
|
||||
this.preserveCardFocus();
|
||||
this.searchQuery.set(query);
|
||||
this.confirmation = undefined;
|
||||
}
|
||||
isPinned(item: Indicador) { return this.memory.isPinned(this.dominio, item.id); }
|
||||
togglePinned(item: Indicador) {
|
||||
this.preserveCardFocus();
|
||||
this.memory.togglePinned(this.dominio, item.id);
|
||||
this.confirmation = undefined;
|
||||
}
|
||||
private preserveCardFocus() {
|
||||
const focused = this.document.activeElement;
|
||||
if (focused instanceof HTMLElement && this.element.nativeElement.contains(focused)
|
||||
&& focused.closest('app-indicador-catalog-card')) {
|
||||
// Moving a retained view can blur its control. Restore only that connected control,
|
||||
@@ -184,11 +195,11 @@ export class IndicadoresPage {
|
||||
readonly dominios = DOMINIOS;
|
||||
dominio: Dominio = 'tea';
|
||||
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
|
||||
// Presentation samples only. Each domain can replace its own future configuration.
|
||||
readonly kpiPreviewsByDomain: Record<Dominio, readonly { id: string; title: string }[]> = {
|
||||
readonly kpisByDomain = KPI_BY_DOMAIN;
|
||||
kpiIndicator(id: string) { return this.catalog().find(item => item.id === id); }
|
||||
// TEA has no approved KPI definitions; its previews never request data.
|
||||
readonly kpiPreviewsByDomain: { tea: readonly { id: string; title: string }[] } = {
|
||||
tea: [{ id: 'preview-1', title: 'Indicador destacado 1' }, { id: 'preview-2', title: 'Indicador destacado 2' }],
|
||||
cacu: [{ id: 'preview-1', title: 'Indicador destacado 1' }, { id: 'preview-2', title: 'Indicador destacado 2' }],
|
||||
cama: [{ id: 'preview-1', title: 'Indicador destacado 1' }, { id: 'preview-2', title: 'Indicador destacado 2' }],
|
||||
};
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
@@ -197,14 +208,18 @@ export class IndicadoresPage {
|
||||
readonly searchResults = computed(() => {
|
||||
const items = this.catalog();
|
||||
const query = this.normalizeSearch(this.searchQuery());
|
||||
if (!query) return { items, active: false, count: 0 };
|
||||
const prioritize = (group: Indicador[]) => [
|
||||
...group.filter(item => this.isPinned(item)),
|
||||
...group.filter(item => !this.isPinned(item)),
|
||||
];
|
||||
if (!query) return { items: prioritize(items), active: false, count: 0 };
|
||||
const matches: Indicador[] = [];
|
||||
const remaining: Indicador[] = [];
|
||||
for (const item of items) {
|
||||
const matchesQuery = [item.titulo, item.id].some(value => this.normalizeSearch(value).includes(query));
|
||||
(matchesQuery ? matches : remaining).push(item);
|
||||
}
|
||||
return { items: matches.length ? [...matches, ...remaining] : items, active: true, count: matches.length };
|
||||
return { items: [...prioritize(matches), ...prioritize(remaining)], active: true, count: matches.length };
|
||||
});
|
||||
private normalizeSearch(value: string) {
|
||||
return value.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().trim();
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
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 { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
const items: Indicador[] = ['Edad', 'Evaluación inicial', 'Sexo', 'Seguimiento', 'Evaluación final'].map((titulo, i) => ({
|
||||
id: 'i' + i, titulo, contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'],
|
||||
}));
|
||||
|
||||
describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
const runtime = { react: vi.fn(), purge: vi.fn(), Plots: { resize: vi.fn() } };
|
||||
beforeEach(() => {
|
||||
runtime.react.mockReset().mockResolvedValue(undefined); runtime.purge.mockReset(); runtime.Plots.resize.mockReset().mockResolvedValue(undefined);
|
||||
vi.stubGlobal('IntersectionObserver', undefined);
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
create(); load();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
function create() { fixture = TestBed.createComponent(IndicadoresPage); page = fixture.componentInstance; http = TestBed.inject(HttpTestingController); }
|
||||
function load(domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); }
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
function card(id: string) { return cards().find(c => c.indicador.id === id)!; }
|
||||
function ids() { return cards().map(c => c.indicador.id); }
|
||||
function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; }
|
||||
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
|
||||
async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); }
|
||||
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
|
||||
|
||||
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => {
|
||||
const control = button('i3');
|
||||
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0);
|
||||
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
expect(control.getAttribute('aria-label')).toContain('Fijar indicador');
|
||||
for (const key of ['Enter', ' ']) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
|
||||
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
||||
expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador');
|
||||
await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => {
|
||||
const original = page.catalog(), snapshot = JSON.stringify(original);
|
||||
await pin('i4'); await pin('i2'); await pin('i0');
|
||||
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']);
|
||||
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
|
||||
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
|
||||
});
|
||||
it('coincidencias preceden a los fijados no coincidentes y la fijación resuelve cada grupo', async () => {
|
||||
await pin('i3'); await pin('i4');
|
||||
page.changeSearchQuery(' EVALUACION '); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i4', 'i1', 'i3', 'i0', 'i2']);
|
||||
expect(page.searchResults().count).toBe(2); expect(page.searchResults().active).toBe(true);
|
||||
await pin('i1'); expect(ids()).toEqual(['i1', 'i4', 'i3', 'i0', 'i2']);
|
||||
expect(cards()).toHaveLength(items.length); http.expectNone(() => true);
|
||||
});
|
||||
it('limpiar mediante el buscador restaura fijados primero y mantiene foco', async () => {
|
||||
await pin('i3'); page.changeSearchQuery('Edad'); fixture.detectChanges(); await settle();
|
||||
expect(ids()[0]).toBe('i0');
|
||||
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
|
||||
expect(page.searchQuery()).toBe(''); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
|
||||
expect(document.activeElement).toBe(fixture.nativeElement.querySelector('.catalog-search input')); http.expectNone(() => true);
|
||||
});
|
||||
it('búsqueda sin coincidencias conserva todo el catálogo con prioridad de fijados', async () => {
|
||||
await pin('i2'); page.changeSearchQuery('inexistente'); fixture.detectChanges(); await settle();
|
||||
expect(ids()).toEqual(['i2', 'i0', 'i1', 'i3', 'i4']); expect(page.searchResults().count).toBe(0);
|
||||
expect(fixture.nativeElement.textContent).toContain('El catálogo completo permanece disponible'); http.expectNone(() => true);
|
||||
});
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
await pin('i4'); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
||||
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
||||
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
||||
});
|
||||
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
|
||||
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
|
||||
await pin('i2'); expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i2')).toBe(true);
|
||||
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
|
||||
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
|
||||
});
|
||||
it('mover la tarjeta conserva foco en su botón existente', async () => {
|
||||
const control = button('i4'); control.focus(); await pin('i4');
|
||||
expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control);
|
||||
await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true);
|
||||
});
|
||||
it('preserva figura seleccionada, apertura, cierre manual, panel y host Plotly', async () => {
|
||||
card('i3').toggle(); fixture.detectChanges(); respond(); await settle();
|
||||
card('i3').selectFigure('g'); fixture.detectChanges(); respond(); await settle();
|
||||
card('i1').toggle(); fixture.detectChanges(); respond(); card('i1').toggle(); fixture.detectChanges(); await settle();
|
||||
const before = cards(), panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance;
|
||||
const chart = fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance as PlotlyChart;
|
||||
const host = chart.host.nativeElement, result = panel.result(), applied = page.filters!.applied;
|
||||
const reacts = runtime.react.mock.calls.length, purges = runtime.purge.mock.calls.length;
|
||||
for (const id of ['i3', 'i1', 'i3']) {
|
||||
await pin(id);
|
||||
for (const c of before) expect(card(c.indicador.id)).toBe(c);
|
||||
expect(card('i3').expanded).toBe(true); expect(card('i3').selectedFigure).toBe('g'); expect(card('i3').figuresActivated).toBe(true);
|
||||
expect(card('i1').expanded).toBe(false); expect(TestBed.inject(IndicadoresMemory).activation('tea', 'i1')).toBe('manual-closed');
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel);
|
||||
expect(fixture.debugElement.query(By.directive(PlotlyChart)).componentInstance).toBe(chart);
|
||||
expect(chart.host.nativeElement).toBe(host); expect(panel.result()).toBe(result); expect(page.filters!.applied).toBe(applied);
|
||||
http.expectNone(() => true);
|
||||
}
|
||||
expect(runtime.react).toHaveBeenCalledTimes(reacts); expect(runtime.purge).toHaveBeenCalledTimes(purges);
|
||||
});
|
||||
it('mover un panel cargando conserva su petición sin cancelar ni duplicar', async () => {
|
||||
card('i4').toggle(); fixture.detectChanges(); const request = http.expectOne(r => r.url.endsWith('/i4/figuras/f'));
|
||||
const panel = fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance;
|
||||
await pin('i4'); expect(request.cancelled).toBe(false);
|
||||
expect(fixture.debugElement.query(By.directive(IndicadorFigurePanel)).componentInstance).toBe(panel); http.expectNone(() => true);
|
||||
request.flush({ data: [{ y: [7] }], layout: {} }); await settle(); expect(panel.result().figure.data[0].y).toEqual([7]);
|
||||
});
|
||||
});
|
||||
@@ -24,9 +24,9 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }]);
|
||||
http.expectOne('/tea/indicadores').flush([{ id: 'i', titulo: 'I', contrato: 'C1', figuras: ['f', 'g'], tipos_periodo: ['semestre'] }, { id: 'j', titulo: 'J', contrato: 'C1', figuras: ['g'], tipos_periodo: ['semestre'] }]);
|
||||
fixture.detectChanges();
|
||||
(fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard).toggle();
|
||||
for (const entry of fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard))) (entry.componentInstance as IndicadorCatalogCard).toggle();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
@@ -40,12 +40,27 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
expect(charts).toHaveLength(2); expect(runtime.react).toHaveBeenCalledTimes(2);
|
||||
const hosts = charts.map(c => c.componentInstance.host.nativeElement);
|
||||
expect(hosts[0]).not.toBe(hosts[1]); expect(hosts[0].getAttribute('aria-label')).toBe('tea · i · f');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea · i · g');
|
||||
expect(hosts[1].getAttribute('aria-label')).toBe('tea · j · g');
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.toggle(); fixture.detectChanges();
|
||||
for (const host of hosts) expect(runtime.purge).toHaveBeenCalledWith(host);
|
||||
for (const disconnect of disconnects) expect(disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(0);
|
||||
expect(runtime.purge).toHaveBeenCalledWith(hosts[0]);
|
||||
expect(runtime.purge).not.toHaveBeenCalledWith(hosts[1]);
|
||||
expect(disconnects[0]).toHaveBeenCalledTimes(1); expect(disconnects[1]).not.toHaveBeenCalled();
|
||||
expect(fixture.debugElement.queryAll(By.directive(PlotlyChart))).toHaveLength(1);
|
||||
});
|
||||
it('cambiar representación purga el host saliente y conserva el host del otro indicador', async () => {
|
||||
respond(); await settle();
|
||||
const charts = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
const outgoing = charts[0].componentInstance.host.nativeElement;
|
||||
const other = charts[1].componentInstance.host.nativeElement;
|
||||
const card = fixture.debugElement.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
card.selectFigure('g'); fixture.detectChanges();
|
||||
expect(runtime.purge).toHaveBeenCalledWith(outgoing); expect(runtime.purge).not.toHaveBeenCalledWith(other);
|
||||
http.expectOne(r => r.url.endsWith('/i/figuras/g')).flush({ data: [{ y: [3] }], layout: {} }); await settle();
|
||||
const current = fixture.debugElement.queryAll(By.directive(PlotlyChart));
|
||||
expect(current[0].componentInstance.host.nativeElement).not.toBe(outgoing);
|
||||
expect(current[1].componentInstance.host.nativeElement).toBe(other);
|
||||
expect(runtime.react.mock.calls.filter(c => c[0] === other)).toHaveLength(1);
|
||||
});
|
||||
it('un error de renderizado y su reintento no afectan la otra instancia', async () => {
|
||||
runtime.react.mockRejectedValueOnce(new Error('render'));
|
||||
@@ -76,7 +91,7 @@ describe('UX-05B ciclo de vida con componentes Plotly y runtime simulado', () =>
|
||||
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();
|
||||
page.catalog.set(page.catalog().map(item => ({ ...item, 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);
|
||||
|
||||
@@ -14,7 +14,7 @@ import { Indicador } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label'], template: '' })
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub {}
|
||||
const items: Indicador[] = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: 'i' + i, titulo: 'Indicador ' + i, contrato: 'C1', figuras: ['f'], tipos_periodo: ['semestre', 'mes'],
|
||||
@@ -103,6 +103,23 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => {
|
||||
expect(frames.size).toBe(0);
|
||||
}
|
||||
|
||||
it('D.3.B fijar invalida la fila pendiente y aplica visibilidad actual sin anticipar carga', async () => {
|
||||
await load();
|
||||
positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]); notify(); await frame();
|
||||
const original = cards();
|
||||
original[4].host.nativeElement.querySelector<HTMLButtonElement>('.pin-toggle')!.click(); await render();
|
||||
expect(cards()[0]).toBe(original[4]);
|
||||
positions([[200, 0], [1000, 0], [1200, 0], [1400, 0], [1600, 0]]);
|
||||
http.expectNone(() => true); await frame(); http.expectNone(() => true);
|
||||
await frame(); expect(cards()[0].expanded).toBe(true); expect(original[0].expanded).toBe(false);
|
||||
http.expectOne(r => r.url.endsWith('/i4/figuras/f')).flush({ data: [], layout: {} }); await idle();
|
||||
cards()[0].toggle(); await render();
|
||||
original[0].host.nativeElement.querySelector<HTMLButtonElement>('.pin-toggle')!.click(); await render();
|
||||
positions([[200, 0], [200, 650], [1000, 0], [1000, 650], [1200, 0]]); await confirm(); respond(); await idle();
|
||||
expect(original[4].expanded).toBe(false); expect(memory.activation('tea', 'i4')).toBe('manual-closed');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
it('observa sólo cabeceras gráficas con viewport, umbral y margen sticky medido', async () => {
|
||||
await load();
|
||||
expect(observer().options).toEqual({ root: null, threshold: 0.25, rootMargin: '-100px 0px 0px 0px' });
|
||||
@@ -244,17 +261,16 @@ describe('UX-06E.D.1.1 visibilidad controlada', () => {
|
||||
active.emit(target); sizeObserver.emit(); window.dispatchEvent(new Event('scroll'));
|
||||
expect(frames.size).toBe(remaining); http.expectNone(() => true);
|
||||
});
|
||||
it('varias figuras mantienen errores y resultados independientes y se cancelan al cerrar', async () => {
|
||||
it('apertura automática monta sólo la primera figura y el cierre cancela la seleccionada', async () => {
|
||||
await load([{ ...items[0], figuras: ['f', 'g', 'h'] }]); positions([[200, 0]]); notify(); await confirm();
|
||||
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(3);
|
||||
requests[0].flush('private', { status: 500, statusText: 'Error' }); requests[1].flush({ data: [{ y: [2] }], layout: {} }); await render();
|
||||
expect(panels().map(panel => panel.result().status)).toEqual(['error', 'ready', 'loading']);
|
||||
const filters = fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters;
|
||||
filters.changeMode('manual'); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
cards()[0].toggle(); await render(); expect(requests[2].cancelled).toBe(true);
|
||||
const requests = http.match(r => r.url.includes('/figuras/')); expect(requests).toHaveLength(1);
|
||||
requests[0].flush('private', { status: 500, statusText: 'Error' }); await render();
|
||||
expect(panels().map(panel => panel.result().status)).toEqual(['error']);
|
||||
cards()[0].selectFigure('g'); await render();
|
||||
const current = http.expectOne(r => r.url.endsWith('/figuras/g'));
|
||||
cards()[0].toggle(); await render(); expect(current.cancelled).toBe(true);
|
||||
notify(); await idle(); http.expectNone(() => true); cards()[0].toggle(); await render();
|
||||
expect(page.filters?.editors.semestre?.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] });
|
||||
expect(page.filters?.applied?.selection.mode).toBe('todos'); respond();
|
||||
expect(panels()[0].figuraId).toBe('g'); respond();
|
||||
});
|
||||
it('fallback sin observers permite la apertura y cierre de una tarjeta pendiente', async () => {
|
||||
http.expectOne('/tea/indicadores'); fixture.destroy(); vi.stubGlobal('IntersectionObserver', undefined); vi.stubGlobal('ResizeObserver', undefined); create();
|
||||
|
||||
@@ -43,3 +43,17 @@ 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']);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ type: 'bar', orientation: 'h', x: [null], y: ['grupo'] }, true],
|
||||
[{ type: 'bar', orientation: 'h', x: [0], y: ['grupo'] }, false],
|
||||
[{ type: 'bar', y: [null], x: ['grupo'] }, true],
|
||||
[{ type: 'bar', y: [0] }, false],
|
||||
[{ type: 'pie', values: [null] }, true],
|
||||
[{ type: 'pie', values: [0] }, false],
|
||||
[{ type: 'pie', values: { bdata: 'AAAA' } }, false],
|
||||
[{ type: 'bar', orientation: 'unknown', y: [null] }, false],
|
||||
[{ type: 'bar', y: ['unknown'] }, false],
|
||||
])('interpreta magnitudes de forma conservadora %j', (trace, empty) => {
|
||||
expect(hasNoVisibleValues({ data: [trace as Record<string, unknown>], layout: {} })).toBe(empty);
|
||||
});
|
||||
|
||||
@@ -34,15 +34,27 @@ export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): st
|
||||
? [...new Set(parts)] : null;
|
||||
}
|
||||
|
||||
// Only assert emptiness for known TEA traces with ordinary arrays. Unknown/binary
|
||||
// Only assert emptiness for known traces with ordinary arrays. Unknown/binary
|
||||
// representations remain indeterminate; never infer counts or suppression causes.
|
||||
export function hasNoVisibleValues(figure: PlotlyFigure): boolean {
|
||||
return figure.data.every(trace => {
|
||||
if (trace['visible'] === false || trace['visible'] === 'legendonly') return true;
|
||||
const type = trace['type'] ?? 'scatter';
|
||||
const values = type === 'box' ? trace['median'] ?? trace['y']
|
||||
: type === 'scatter' || type === 'bar' ? trace['y'] : undefined;
|
||||
: type === 'bar' ? (trace['orientation'] === 'h' ? trace['x'] : trace['orientation'] === undefined || trace['orientation'] === 'v' ? trace['y'] : undefined)
|
||||
: type === 'pie' ? trace['values']
|
||||
: type === 'scatter' ? trace['y'] : undefined;
|
||||
if (!Array.isArray(values)) return false;
|
||||
return !values.some(value => typeof value === 'number' && Number.isFinite(value));
|
||||
return values.every(value => value === null || value === undefined || (typeof value === 'number' && !Number.isFinite(value)));
|
||||
});
|
||||
}
|
||||
|
||||
export interface IndicadorDatos {
|
||||
id: string;
|
||||
contrato: string;
|
||||
tipo_periodo: TipoPeriodo;
|
||||
periodos: string[];
|
||||
filas: Record<string, unknown>[];
|
||||
notas?: string[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -99,3 +99,22 @@ describe('UX-04 validación defensiva HTTP', () => {
|
||||
http.expectNone(() => true); http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
describe('contrato datos exclusivo de KPI', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
|
||||
it('envía sólo periodos explícitos sin granularidad ni tema y conserva filas y notas', () => {
|
||||
const http = TestBed.inject(HttpTestingController); let result: unknown;
|
||||
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
|
||||
const req = http.expectOne(r => r.url === '/cacu/indicadores/cacu_eu7/datos');
|
||||
expect(req.request.params.keys()).toEqual(['periodos']); expect(req.request.params.get('periodos')).toBe('2025-01');
|
||||
const payload = { id: 'cacu_eu7', contrato: 'C2', tipo_periodo: 'mes', periodos: ['2025-01'], filas: [{ n: null, suprimido: 1 }], notas: ['Nota'] };
|
||||
req.flush(payload); expect(result).toEqual(payload); http.verify();
|
||||
});
|
||||
it('Todos omite periodos y rechaza respuesta de otro indicador', () => {
|
||||
const http = TestBed.inject(HttpTestingController); let error: unknown;
|
||||
TestBed.inject(IndicadoresService).datos('cama', 'cama_eu38a', 'semestre').subscribe({ error: e => error = e });
|
||||
const req = http.expectOne('/cama/indicadores/cama_eu38a/datos'); expect(req.request.params.keys()).toEqual([]);
|
||||
req.flush({ id: 'otro', contrato: 'C3r', tipo_periodo: 'semestre', periodos: [], filas: [] });
|
||||
expect(error).toBeInstanceOf(Error); http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { Dominio, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
|
||||
import { Dominio, IndicadorDatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
@@ -26,6 +26,24 @@ export class IndicadoresService {
|
||||
return value as Indicador[];
|
||||
}));
|
||||
}
|
||||
datos(dominio: Dominio, indicador: string, tipo: 'semestre' | 'mes', periodos?: string[]) {
|
||||
const domain = requireDominio(dominio);
|
||||
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
|
||||
throw new Error('Periodos inválidos');
|
||||
}
|
||||
let params = new HttpParams();
|
||||
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
|
||||
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }).pipe(map(value => {
|
||||
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|
||||
|| !['mes', 'semestre'].includes(value['tipo_periodo'] as string)
|
||||
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|
||||
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|
||||
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
|
||||
throw new Error('Respuesta de datos inválida');
|
||||
}
|
||||
return value as unknown as IndicadorDatos;
|
||||
}));
|
||||
}
|
||||
figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
if (selection.periodos !== undefined) {
|
||||
|
||||
@@ -15,7 +15,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
<button mat-stroked-button (click)="retry()">Reintentar renderizado</button></div>
|
||||
}
|
||||
<div class="plot-viewport" tabindex="0" role="region" [attr.aria-label]="label + ' · Área de figura'"><div #host class="plot" role="img" [attr.aria-label]="label" [attr.aria-hidden]="status() !== 'ready'"></div></div>
|
||||
@if (status() === 'ready' && notes.length) {
|
||||
@if (showNotes && status() === 'ready' && notes.length) {
|
||||
<section class="notes" aria-label="Notas completas de la figura">
|
||||
<h2>Notas de la figura</h2>
|
||||
@for (note of notes; track $index) { <p [innerHTML]="note"></p> }
|
||||
@@ -25,6 +25,7 @@ import { PLOTLY_LOADER } from './plotly-runtime';
|
||||
styles: `:host { display: block; min-width: 0; } .plot-viewport { min-width: 0; overflow-x: auto; } .plot-viewport:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .plot { width: 100%; min-height: 620px; visibility: hidden; } [role=alert] { padding: 1rem; } .notes { padding: 1rem; overflow-wrap: anywhere; } .notes h2 { font-size: 1rem; } .notes p { line-height: 1.5; }`,
|
||||
})
|
||||
export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
||||
@Input() showNotes = true;
|
||||
@Input() label = 'Figura estadística';
|
||||
@Input({ required: true }) figure!: PlotlyFigure;
|
||||
@ViewChild('host', { static: true }) host!: ElementRef<HTMLElement>;
|
||||
|
||||
Reference in New Issue
Block a user