feat(indicadores): agregar prototipo de dashboard TEA
Implementa el prototipo del dashboard de indicadores TEA. - Integra catálogo y figuras mediante WebApi. - Incorpora visualizaciones interactivas con Plotly.js. - Agrega controles de indicadores, figuras, periodos y temas. - Implementa estados de carga, errores y diseño responsive. - Incluye explicaciones para los contratos C1, C2 y C3r. - Incorpora pruebas unitarias y de integración de componentes. Prototipo para investigación con datos sintéticos.
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
<section class="dashboard" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
<span class="domain">Dominio TEA · Investigación</span>
|
||||
<h1 id="dashboard-title">Dashboard de indicadores</h1>
|
||||
<p>Explora las figuras de indicadores TEA generadas por el servicio de reportes.</p>
|
||||
</header>
|
||||
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
|
||||
|
||||
@if (catalogLoading()) {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
|
||||
<p role="status">Cargando catálogo de indicadores…</p>
|
||||
} @else if (catalogError()) {
|
||||
<mat-card class="state" role="alert"><p>{{ catalogError() }}</p>
|
||||
<button mat-stroked-button (click)="retryCatalog()">Reintentar catálogo</button></mat-card>
|
||||
} @else if (!catalog().length) {
|
||||
<mat-card class="state"><p role="status">No hay indicadores disponibles en el catálogo.</p>
|
||||
<button mat-stroked-button (click)="retryCatalog()">Actualizar catálogo</button></mat-card>
|
||||
} @else {
|
||||
<mat-card class="filters" aria-label="Selección de figura">
|
||||
<div class="fields">
|
||||
<mat-form-field class="indicator"><mat-label>Indicador</mat-label>
|
||||
<mat-select [ngModel]="indicadorId" (ngModelChange)="selectIndicador($event)">
|
||||
@for (item of catalog(); track item.id) { <mat-option [value]="item.id">{{ item.titulo }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Figura</mat-label>
|
||||
<mat-select [ngModel]="figuraId" (ngModelChange)="selectFigura($event)" [disabled]="!selected?.figuras?.length">
|
||||
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Periodos</mat-label>
|
||||
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
|
||||
<mat-option value="todos">Todos los periodos con reporte</mat-option>
|
||||
<mat-option value="manual">Selección manual</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field><mat-label>Tema de la figura</mat-label>
|
||||
<mat-select [ngModel]="tema" (ngModelChange)="changeTema($event)">
|
||||
<mat-option value="claro">Claro</mat-option><mat-option value="oscuro">Oscuro</mat-option>
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (periodMode === 'manual') {
|
||||
<mat-form-field class="periods"><mat-label>Semestres (AAAA-S1,AAAA-S2)</mat-label>
|
||||
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
|
||||
<mat-hint id="period-help">Escribe los semestres a consultar. Su disponibilidad depende de los reportes.</mat-hint>
|
||||
</mat-form-field>
|
||||
}
|
||||
</div>
|
||||
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
|
||||
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
|
||||
</mat-card>
|
||||
@if (selected) {
|
||||
<section class="interpretation" aria-labelledby="interpretation-title">
|
||||
<h2 id="interpretation-title">Cómo leer esta figura · {{ selected?.contrato }}</h2>
|
||||
<ul>
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.</p>
|
||||
</section>
|
||||
}
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" aria-label="Resultado de la selección" [attr.aria-busy]="result().status === 'loading'">
|
||||
@if (result().status === 'loading') {
|
||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando figura" />
|
||||
<p class="state" role="status">Cargando figura…</p>
|
||||
} @else if (result().status === 'error') {
|
||||
<div class="state" role="alert"><p>{{ result().message }}</p>
|
||||
<button mat-stroked-button (click)="requestFigure()">Reintentar solicitud</button></div>
|
||||
} @else if (result().figure; as figure) {
|
||||
@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>
|
||||
}
|
||||
<h2 class="figure-title">{{ selected?.titulo }}</h2>
|
||||
<app-plotly-chart [figure]="figure" />
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
</mat-card>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,29 @@
|
||||
:host { display: block; }
|
||||
.dashboard { max-width: 1440px; margin: 0 auto; }
|
||||
h1 { font: var(--mat-sys-headline-large); margin: .65rem 0; }
|
||||
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
|
||||
.notice { padding: 1rem 1.25rem; border-left: 4px solid var(--mat-sys-primary); background: var(--mat-sys-surface-container); border-radius: 8px; }
|
||||
.filters { padding: 1.5rem; margin: 1.5rem 0; }
|
||||
.fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .75rem 1rem; }
|
||||
.indicator { grid-column: span 2; }
|
||||
.periods { grid-column: 1 / -1; margin-bottom: 1rem; }
|
||||
mat-form-field { width: 100%; min-width: 0; }
|
||||
.contract { color: var(--mat-sys-on-surface-variant); margin: .5rem 0 0; }
|
||||
.interpretation { padding: 1rem 1.25rem; margin-bottom: 1.5rem; border-radius: 8px; background: var(--mat-sys-surface-container-low); color: var(--mat-sys-on-surface); font: var(--mat-sys-body-medium); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.interpretation h2 { margin: 0 0 .5rem; font: var(--mat-sys-title-small); }
|
||||
.interpretation ul { margin: 0; padding-left: 1.25rem; }
|
||||
.interpretation li + li { margin-top: .25rem; }
|
||||
.period-note { margin: .75rem 0 0; color: var(--mat-sys-on-surface-variant); }
|
||||
.validation { color: var(--mat-sys-error); }
|
||||
.figure-card { overflow: hidden; min-width: 0; }
|
||||
.figure-title { display: none; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); overflow-wrap: anywhere; }
|
||||
.state { padding: 1.25rem; margin: 0; }
|
||||
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
|
||||
@media (max-width: 850px) { .figure-title { display: block; } .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@media (max-width: 550px) {
|
||||
.fields { grid-template-columns: minmax(0, 1fr); }
|
||||
.indicator { grid-column: auto; }
|
||||
.filters, .interpretation { padding: 1rem; }
|
||||
h1 { font: var(--mat-sys-headline-medium); }
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
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 { PlotlyFigure } from './indicadores.models';
|
||||
import { Component } from '@angular/core';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure'], template: '' })
|
||||
class ChartStub { figure?: PlotlyFigure; }
|
||||
const catalog = [
|
||||
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'] },
|
||||
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'] },
|
||||
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [] },
|
||||
];
|
||||
describe('IndicadoresPage', () => {
|
||||
let page: IndicadoresPage;
|
||||
let http: HttpTestingController;
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresPage);
|
||||
page = fixture.componentInstance;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
function load() { http.expectOne('/tea/indicadores').flush(catalog); }
|
||||
function figure() { return http.expectOne(req => req.url.startsWith('/tea/indicadores/') && req.url.includes('/figuras/')); }
|
||||
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
|
||||
expect(page.catalogLoading()).toBe(true);
|
||||
load();
|
||||
expect(page.indicadorId).toBe('i1');
|
||||
expect(page.figuraId).toBe('f1');
|
||||
expect(page.result().status).toBe('loading');
|
||||
const request = figure();
|
||||
expect(request.request.params.has('periodos')).toBe(false);
|
||||
request.flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay valores visibles');
|
||||
expect(fixture.nativeElement.textContent).toContain('Uso exclusivo de investigación');
|
||||
});
|
||||
it.each([
|
||||
['C1', ['proporción observada', 'Wilson al 95 %', 'denominadores pequeños', '100 % no implica certeza poblacional']],
|
||||
['C2', ['composición porcentual', 'distribución de cada grupo y periodo', 'SIN_DATO']],
|
||||
['C3r', ['Q1, mediana y Q3', 'no contiene observaciones individuales', 'min/max', 'derivados de Q1 y Q3', 'no deben interpretarse como los extremos observados de los pacientes']],
|
||||
['C4', ['No hay una explicación específica', 'no se infiere su significado estadístico']],
|
||||
['toString', ['No hay una explicación específica']],
|
||||
])('explica el contrato %s y conserva el aviso de investigación', (contract, expected) => {
|
||||
http.expectOne('/tea/indicadores').flush([{ ...catalog[0], contrato: contract }]);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
for (const text of expected) expect(help).toContain(text);
|
||||
if (contract === 'C3r') {
|
||||
expect(help).toContain('Los límites de dibujo no representan necesariamente extremos observados');
|
||||
expect(help).not.toMatch(/serving|corrección|fase independiente/i);
|
||||
}
|
||||
expect(fixture.nativeElement.querySelector('.notice').textContent).toContain('Uso exclusivo de investigación. No usar para decisiones clínicas.');
|
||||
expect(help).toContain('Un periodo puede tener reportes calculados sin valores estadísticos representables');
|
||||
});
|
||||
it('actualiza la explicación al cambiar indicador, incluso durante la carga', () => {
|
||||
load(); figure().flush({ data: [], layout: {} }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('.interpretation').textContent).toContain('Wilson');
|
||||
page.selectIndicador('i2'); fixture.detectChanges();
|
||||
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
|
||||
expect(help).toContain('min/max'); expect(help).not.toContain('Wilson');
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('entrega al gráfico el JSON íntegro sin modificarlo al presentar la ayuda', () => {
|
||||
load();
|
||||
const received: PlotlyFigure = {
|
||||
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
|
||||
layout: { yaxis: { range: [0, 100] }, annotations: [{ text: 'Nota del servicio' }], showlegend: true },
|
||||
config: { staticPlot: false }, frames: [], extra: { preserved: true },
|
||||
};
|
||||
const original = JSON.stringify(received);
|
||||
figure().flush(received); fixture.detectChanges();
|
||||
expect(JSON.stringify(received)).toBe(original);
|
||||
expect(page.result().figure).toEqual(received);
|
||||
const chart = fixture.debugElement.query(By.directive(ChartStub)).componentInstance as ChartStub;
|
||||
expect(chart.figure).toBe(page.result().figure);
|
||||
expect(JSON.stringify(chart.figure)).toBe(original);
|
||||
});
|
||||
it('muestra catálogo vacío y permite recargar', () => {
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay indicadores disponibles');
|
||||
page.retryCatalog();
|
||||
load();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cancela solicitudes previas al cambiar indicador y no muestra figura antigua', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
page.selectIndicador('i2');
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(page.figuraId).toBe('box');
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
figure().flush({ data: [{ type: 'box', median: [2] }], layout: {} });
|
||||
expect(() => old.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
|
||||
expect(page.result().figure?.data[0]['median']).toEqual([2]);
|
||||
});
|
||||
it('soporta varias figuras, volver al indicador y selección sin figuras', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.selectFigura('f2');
|
||||
expect(figure().request.url).toContain('/i1/figuras/f2');
|
||||
// Cancel the previous request and verify its cancellation explicitly below.
|
||||
page.selectIndicador('empty');
|
||||
expect(page.figuraId).toBe('');
|
||||
expect(page.result().status).toBe('idle');
|
||||
page.selectIndicador('i1');
|
||||
expect(page.figuraId).toBe('f1');
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it('valida manuales antes del HTTP y vuelve a Todos sin query', () => {
|
||||
load(); figure().flush({ data: [], layout: {} });
|
||||
page.changePeriodMode('manual');
|
||||
expect(page.periodError).not.toBe('');
|
||||
http.expectNone(req => req.url.includes('/figuras/'));
|
||||
page.changePeriodText('2025-S1, 2025-S2');
|
||||
const manual = figure();
|
||||
expect(manual.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
page.changePeriodText('2025-S3');
|
||||
expect(manual.cancelled).toBe(true);
|
||||
expect(page.result().figure).toBeUndefined();
|
||||
page.changePeriodMode('todos');
|
||||
const all = figure();
|
||||
expect(all.request.params.has('periodos')).toBe(false);
|
||||
all.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('cancela figuras al cambiar tema rápidamente', () => {
|
||||
load();
|
||||
const old = figure();
|
||||
page.changeTema('oscuro');
|
||||
const dark = figure();
|
||||
expect(old.cancelled).toBe(true);
|
||||
expect(dark.request.params.get('tema')).toBe('oscuro');
|
||||
page.changeTema('claro');
|
||||
expect(dark.cancelled).toBe(true);
|
||||
figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
it.each([
|
||||
[400, 'rechazó los parámetros'], [404, 'reportes no están disponibles'], [500, 'error interno'],
|
||||
])('controla HTTP %i con cuerpo no uniforme y permite reintentar', (status, message) => {
|
||||
load();
|
||||
figure().flush('<html>error privado</html>', { status: status as number, statusText: 'Error' });
|
||||
expect(page.result().status).toBe('error');
|
||||
expect(page.result().message).toContain(message);
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('error privado');
|
||||
page.requestFigure();
|
||||
figure().flush({ data: [], layout: {} });
|
||||
expect(page.result().status).toBe('ready');
|
||||
});
|
||||
it('distingue conexión fallida y cancela HTTP al destruirse', () => {
|
||||
load(); figure().error(new ProgressEvent('error'));
|
||||
expect(page.result().message).toContain('conectar');
|
||||
page.requestFigure();
|
||||
const pending = figure();
|
||||
fixture.destroy();
|
||||
expect(pending.cancelled).toBe(true);
|
||||
});
|
||||
it('controla errores de catálogo y puede recuperarse', () => {
|
||||
http.expectOne('/tea/indicadores').flush('Error', { status: 500, statusText: 'Error' });
|
||||
expect(page.catalogError()).toContain('error interno');
|
||||
page.retryCatalog(); load(); figure().flush({ data: [], layout: {} });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import { Component, DestroyRef, inject, signal } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
|
||||
export function httpMessage(error: unknown, catalog = false): string {
|
||||
if (!(error instanceof HttpErrorResponse)) return 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.';
|
||||
if (error.status === 0) return 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.';
|
||||
if (error.status === 400) return 'El servicio rechazó los parámetros. Revisa los periodos y la selección.';
|
||||
if (error.status === 404) return catalog ? 'El catálogo no está disponible.' : 'La figura o los reportes no están disponibles para esta selección.';
|
||||
if (error.status >= 500) return 'El servicio encontró un error interno. Intenta nuevamente más tarde.';
|
||||
return 'No se pudo completar la solicitud. Intenta nuevamente.';
|
||||
}
|
||||
// Presentation only: contract semantics documented in G3 and G5C.
|
||||
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
C1: [
|
||||
'El punto representa la proporción observada.',
|
||||
'La línea vertical representa el intervalo de confianza Wilson al 95 %.',
|
||||
'Los intervalos amplios pueden deberse a denominadores pequeños.',
|
||||
'Un porcentaje observado del 100 % no implica certeza poblacional.',
|
||||
],
|
||||
C2: [
|
||||
'Las barras muestran la composición porcentual de cada grupo y periodo.',
|
||||
'Las categorías corresponden a la distribución de cada grupo y periodo.',
|
||||
'SIN_DATO, cuando aparece, es una categoría legítima de la representación.',
|
||||
],
|
||||
C3r: [
|
||||
'La caja representa Q1, mediana y Q3; no contiene observaciones individuales.',
|
||||
'Los límites de dibujo no representan necesariamente extremos observados.',
|
||||
'Plotly puede mostrar las etiquetas min/max para límites de dibujo derivados de Q1 y Q3. Estos valores no deben interpretarse como los extremos observados de los pacientes.',
|
||||
],
|
||||
};
|
||||
const UNKNOWN_INTERPRETATION = ['No hay una explicación específica disponible para este contrato. Consulta las notas de la figura; no se infiere su significado estadístico.'];
|
||||
|
||||
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; message?: string };
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
private readonly figureRequests = new Subject<FigureSelection | null>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
readonly result = signal<FigureState>({ status: 'idle' });
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
indicadorId = '';
|
||||
figuraId = '';
|
||||
periodMode: 'todos' | 'manual' = 'todos';
|
||||
periodText = '';
|
||||
periodError = '';
|
||||
tema: Tema = 'claro';
|
||||
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
|
||||
|
||||
get interpretation(): readonly string[] {
|
||||
const contract = this.selected?.contrato;
|
||||
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
|
||||
? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.figureRequests.pipe(switchMap(selection => selection
|
||||
? this.service.figura(selection).pipe(
|
||||
map(figure => ({ status: 'ready', figure }) as FigureState),
|
||||
catchError(error => of({ status: 'error', message: httpMessage(error) } as FigureState)),
|
||||
startWith({ status: 'loading' } as FigureState))
|
||||
: of({ status: 'idle' } as FigureState)), takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(state => this.result.set(state));
|
||||
this.catalogRequests.pipe(startWith(undefined), switchMap(() => {
|
||||
this.catalogLoading.set(true);
|
||||
this.catalogError.set('');
|
||||
this.catalog.set([]);
|
||||
this.indicadorId = this.figuraId = '';
|
||||
this.figureRequests.next(null);
|
||||
return this.service.catalogo().pipe(map(items => ({ items, error: '' })),
|
||||
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
||||
this.catalogLoading.set(false);
|
||||
this.catalog.set(items);
|
||||
this.catalogError.set(error);
|
||||
if (items.length) this.selectIndicador(items[0].id);
|
||||
});
|
||||
}
|
||||
retryCatalog() { this.catalogRequests.next(); }
|
||||
selectIndicador(id: string) {
|
||||
this.indicadorId = id;
|
||||
this.figuraId = this.selected?.figuras[0] ?? '';
|
||||
this.requestFigure();
|
||||
}
|
||||
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
|
||||
changePeriodMode(mode: 'todos' | 'manual') { this.periodMode = mode; this.requestFigure(); }
|
||||
changePeriodText(text: string) { this.periodText = text; this.requestFigure(); }
|
||||
changeTema(tema: Tema) { this.tema = tema; this.requestFigure(); }
|
||||
requestFigure() {
|
||||
this.periodError = '';
|
||||
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText) : undefined;
|
||||
if (periodos === null) this.periodError = 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
|
||||
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || periodos === null) {
|
||||
this.figureRequests.next(null);
|
||||
return;
|
||||
}
|
||||
this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { hasNoVisibleValues, parsePeriodos } from './indicadores.models';
|
||||
|
||||
describe('Periodos y visibilidad conservadora', () => {
|
||||
it('normaliza espacios y duplicados sin inventar periodos', () => {
|
||||
expect(parsePeriodos('2025-S1, 2025-S2,2025-S1')).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(parsePeriodos('1900-S2')).toEqual(['1900-S2']);
|
||||
});
|
||||
it.each(['', '2025', '25-S1', '2025-S3', '2025-S1,', '2025-s1', '2025-S1 2025-S2'])('rechaza %s', value => {
|
||||
expect(parsePeriodos(value)).toBeNull();
|
||||
});
|
||||
it('detecta trazos vacíos, nulos y cajas sin mediana', () => {
|
||||
expect(hasNoVisibleValues({ data: [], layout: {} })).toBe(true);
|
||||
expect(hasNoVisibleValues({ data: [{ type: 'scatter', y: [null] }, { type: 'bar', y: [] }, { type: 'box', median: [null] }], layout: {} })).toBe(true);
|
||||
});
|
||||
it('conserva cero, supresión y medianas válidas como valores visibles', () => {
|
||||
expect(hasNoVisibleValues({ data: [{ y: [0] }], layout: {} })).toBe(false);
|
||||
expect(hasNoVisibleValues({ data: [{ type: 'box', median: [10] }], layout: {} })).toBe(false);
|
||||
});
|
||||
it('no declara vacíos los formatos desconocidos o binarios', () => {
|
||||
expect(hasNoVisibleValues({ data: [{ y: { bdata: 'AAAA', dtype: 'f8' } }], layout: {} })).toBe(false);
|
||||
expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
export interface Indicador {
|
||||
id: string;
|
||||
titulo: string;
|
||||
contrato: string;
|
||||
figuras: string[];
|
||||
}
|
||||
|
||||
// Keep the complete HTTP figure, including future attributes and interpretation notes.
|
||||
export interface PlotlyFigure {
|
||||
data: Record<string, unknown>[];
|
||||
layout: Record<string, unknown>;
|
||||
frames?: Record<string, unknown>[];
|
||||
config?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export type Tema = 'claro' | 'oscuro';
|
||||
export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; }
|
||||
|
||||
export function parsePeriodos(value: string): string[] | null {
|
||||
const parts = value.split(',').map(part => part.trim());
|
||||
return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part))
|
||||
? [...new Set(parts)] : null;
|
||||
}
|
||||
|
||||
// Only assert emptiness for known TEA 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;
|
||||
if (!Array.isArray(values)) return false;
|
||||
return !values.some(value => typeof value === 'number' && Number.isFinite(value));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
describe('IndicadoresService HTTP', () => {
|
||||
let service: IndicadoresService;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
service = TestBed.inject(IndicadoresService);
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
afterEach(() => http.verify());
|
||||
it('consume un arreglo directo sin hardcodear catálogo', () => {
|
||||
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }];
|
||||
let actual: unknown;
|
||||
service.catalogo().subscribe(value => actual = value);
|
||||
http.expectOne('/tea/indicadores').flush(data);
|
||||
expect(actual).toEqual(data);
|
||||
});
|
||||
it('acepta catálogo vacío y rechaza envelope inesperado', () => {
|
||||
service.catalogo().subscribe(value => expect(value).toEqual([]));
|
||||
http.expectOne('/tea/indicadores').flush([]);
|
||||
let error: unknown;
|
||||
service.catalogo().subscribe({ error: value => error = value });
|
||||
http.expectOne('/tea/indicadores').flush({ items: [] });
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
it('codifica segmentos y omite periodos en Todos', () => {
|
||||
service.figura({ indicador: 'a/b ü', figura: 'f?#', tema: 'claro' }).subscribe();
|
||||
const request = http.expectOne(req => req.url === '/tea/indicadores/a%2Fb%20%C3%BC/figuras/f%3F%23');
|
||||
expect(request.request.method).toBe('GET');
|
||||
expect(request.request.params.get('tema')).toBe('claro');
|
||||
expect(request.request.params.has('periodos')).toBe(false);
|
||||
request.flush({ data: [], layout: {} });
|
||||
});
|
||||
it('envía semestres y conserva atributos desconocidos, nulos y notas', () => {
|
||||
const figure = { data: [{ y: [null, 0], customdata: [null] }], layout: { annotations: [{ text: 'Uso exclusivo de investigación' }] }, extension: { future: true }, frames: [] };
|
||||
service.figura({ indicador: 'i', figura: 'f', tema: 'oscuro', periodos: ['2025-S1', '2025-S2'] })
|
||||
.subscribe(value => expect(value).toEqual(figure));
|
||||
const request = http.expectOne(req => req.url.endsWith('/i/figuras/f'));
|
||||
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(request.request.params.get('tema')).toBe('oscuro');
|
||||
request.flush(figure);
|
||||
});
|
||||
it('rechaza una figura estructuralmente inválida', () => {
|
||||
let error: unknown;
|
||||
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe({ error: value => error = value });
|
||||
http.expectOne(req => req.url.endsWith('/i/figuras/f')).flush({ data: null, layout: {} });
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models';
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class IndicadoresService {
|
||||
private readonly http = inject(HttpClient);
|
||||
catalogo() {
|
||||
return this.http.get<unknown>('/tea/indicadores').pipe(map(value => {
|
||||
if (!Array.isArray(value) || !value.every(item => record(item)
|
||||
&& typeof item['id'] === 'string' && typeof item['titulo'] === 'string'
|
||||
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
|
||||
&& item['figuras'].every((figure: unknown) => typeof figure === 'string'))) {
|
||||
throw new Error('Respuesta de catálogo inválida');
|
||||
}
|
||||
return value as Indicador[];
|
||||
}));
|
||||
}
|
||||
figura(selection: FigureSelection) {
|
||||
let params = new HttpParams().set('tema', selection.tema);
|
||||
if (selection.periodos?.length) params = params.set('periodos', selection.periodos.join(','));
|
||||
const url = `/tea/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
|
||||
return this.http.get<unknown>(url, { params }).pipe(map(value => {
|
||||
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|
||||
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
|
||||
return value as unknown as PlotlyFigure;
|
||||
}));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user