feat(indicadores): habilitar dashboards Angular TEA CaCu y CaMa

This commit is contained in:
Angel Capetillo Zavala
2026-10-12 16:39:37 -06:00
parent a66205b725
commit b1c4b78f32
15 changed files with 5036 additions and 41 deletions
+2
View File
@@ -1,4 +1,6 @@
{
"/tea/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/cacu/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/cama/**": { "target": "http://127.0.0.1:5000", "secure": false },
"/health": { "target": "http://127.0.0.1:5000", "secure": false }
}
+32 -1
View File
@@ -1,6 +1,6 @@
import { routes } from './app.routes';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { Router, provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
@@ -9,8 +9,39 @@ it('permite acceso directo a /indicadores sin guard ni autenticación', async ()
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/indicadores', IndicadoresPage);
expect(TestBed.inject(Router).url).toBe('/indicadores/tea');
expect(harness.routeNativeElement?.textContent).toContain('Dashboard de indicadores');
const http = TestBed.inject(HttpTestingController);
http.expectOne('/tea/indicadores').flush([]);
http.verify();
});
for (const dominio of ['tea', 'cacu', 'cama']) {
it(`navega directamente al dominio ${dominio} y conserva la ruta compartida diferida`, async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
const page = await harness.navigateByUrl(`/indicadores/${dominio}`, IndicadoresPage);
expect(page.dominio).toBe(dominio);
const http = TestBed.inject(HttpTestingController);
http.expectOne(`/${dominio}/indicadores`).flush([]);
expect(harness.routeNativeElement?.querySelectorAll('nav a').length).toBe(3);
http.verify();
});
}
it('cancela catálogos pendientes durante navegación rápida entre dominios', async () => {
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()] });
const harness = await RouterTestingHarness.create();
const http = TestBed.inject(HttpTestingController);
await harness.navigateByUrl('/indicadores/tea', IndicadoresPage);
const tea = http.expectOne('/tea/indicadores');
await harness.navigateByUrl('/indicadores/cacu', IndicadoresPage);
const cacu = http.expectOne('/cacu/indicadores');
const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage);
expect(tea.cancelled).toBe(true);
expect(cacu.cancelled).toBe(true);
expect(() => tea.flush([])).toThrow();
http.expectOne('/cama/indicadores').flush([]);
expect(page.dominio).toBe('cama');
expect(page.catalog()).toEqual([]);
http.verify();
});
+4 -1
View File
@@ -1,5 +1,8 @@
import { Routes } from '@angular/router';
import { DOMINIOS } from './features/indicadores/indicadores.models';
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
export const routes: Routes = [
{ path: 'indicadores', loadComponent: () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage) },
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, data: { dominio }, loadComponent: loadIndicadores })),
];
@@ -1,9 +1,14 @@
<section class="dashboard" aria-labelledby="dashboard-title">
<header>
<span class="domain">Dominio TEA · Investigación</span>
<span class="domain">Dominio {{ domainLabels[dominio] }} · 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>
<p>Explora las figuras de indicadores {{ domainLabels[dominio] }} generadas por el servicio de reportes.</p>
</header>
<nav aria-label="Dominios de indicadores">
@for (domain of dominios; track domain) {
<a mat-button [routerLink]="['/indicadores', domain]" [attr.aria-current]="dominio === domain ? 'page' : null">{{ domainLabels[domain] }}</a>
}
</nav>
<p class="notice">Uso exclusivo de investigación. No usar para decisiones clínicas.</p>
@if (catalogLoading()) {
@@ -28,9 +33,16 @@
@for (figure of selected?.figuras ?? []; track $index) { <mat-option [value]="figure">{{ figure }}</mat-option> }
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Tipo de periodo</mat-label>
<mat-select [ngModel]="tipoPeriodo" (ngModelChange)="changeTipoPeriodo($event)">
@for (tipo of selected?.tipos_periodo ?? []; track tipo) {
<mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mes' : 'Semestre' }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field><mat-label>Periodos</mat-label>
<mat-select [ngModel]="periodMode" (ngModelChange)="changePeriodMode($event)">
<mat-option value="todos">Todos los periodos con reporte</mat-option>
<mat-option value="todos" [disabled]="tipoPeriodo !== selected?.tipos_periodo?.[0]">Todos con reporte</mat-option>
<mat-option value="manual">Selección manual</mat-option>
</mat-select>
</mat-form-field>
@@ -40,13 +52,14 @@
</mat-select>
</mat-form-field>
@if (periodMode === 'manual') {
<mat-form-field class="periods"><mat-label>Semestres (AAAA-S1,AAAA-S2)</mat-label>
<mat-form-field class="periods" subscriptSizing="dynamic"><mat-label>{{ periodLabel }}</mat-label>
<input matInput [ngModel]="periodText" (ngModelChange)="changePeriodText($event)" [attr.aria-invalid]="!!periodError" aria-describedby="period-help" />
<mat-hint id="period-help">Escribe los semestres a consultar. Su disponibilidad depende de los reportes.</mat-hint>
<mat-hint id="period-help">Escribe periodos del tipo seleccionado, separados por comas. Su disponibilidad depende de los reportes.</mat-hint>
</mat-form-field>
}
</div>
@if (periodError) { <p class="validation" role="alert">{{ periodError }}</p> }
<p>Sin periodos explícitos, el servicio consulta únicamente {{ selected?.tipos_periodo?.[0] }}; no combina meses y semestres.</p>
<p class="contract">Contrato: {{ selected?.contrato }} · Las figuras conservan las notas y categorías del servicio.</p>
</mat-card>
@if (selected) {
@@ -69,8 +82,8 @@
@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" />
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
<app-plotly-chart [figure]="result().presentationFigure!" />
} @else {
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
}
@@ -17,10 +17,10 @@ mat-form-field { width: 100%; min-width: 0; }
.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; }
.figure-title { display: block; 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: 850px) { .fields { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 550px) {
.fields { grid-template-columns: minmax(0, 1fr); }
.indicator { grid-column: auto; }
@@ -1,7 +1,9 @@
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 { syntheticCatalogs } from './indicadores.synthetic-fixtures';
import { PlotlyFigure } from './indicadores.models';
import { Component } from '@angular/core';
import { IndicadoresPage } from './indicadores-page';
@@ -10,16 +12,16 @@ 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: [] },
{ id: 'i1', titulo: 'Uno', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] },
{ id: 'i2', titulo: 'Dos', contrato: 'C3r', figuras: ['box'], tipos_periodo: ['semestre'] },
{ id: 'empty', titulo: 'Sin figuras', contrato: 'C1', figuras: [], tipos_periodo: ['semestre'] },
];
describe('IndicadoresPage', () => {
let page: IndicadoresPage;
let http: HttpTestingController;
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresPage);
page = fixture.componentInstance;
@@ -28,6 +30,75 @@ describe('IndicadoresPage', () => {
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('cancela figura y catálogo antiguos al cambiar dominios rápidamente', () => {
load(); const oldFigure = figure();
page.changeDominio('cacu');
expect(oldFigure.cancelled).toBe(true);
expect(page.result().figure).toBeUndefined();
expect(page.catalog()).toEqual([]);
const oldCatalog = http.expectOne('/cacu/indicadores');
page.changeDominio('cama');
expect(oldCatalog.cancelled).toBe(true);
http.expectOne('/cama/indicadores').flush(syntheticCatalogs.cama);
const current = http.expectOne(r => r.url.startsWith('/cama/indicadores/') && r.url.includes('/figuras/'));
current.flush({ data: [{ y: [null, 42] }], layout: {} });
expect(() => oldCatalog.flush(syntheticCatalogs.cacu)).toThrow();
expect(() => oldFigure.flush({ data: [{ y: [99] }], layout: {} })).toThrow();
expect(page.dominio).toBe('cama');
expect(page.result().figure?.data[0]['y']).toEqual([null, 42]);
});
it.each(['cacu', 'cama'] as const)('usa meses publicados y ayuda sin Wilson efectivo en %s', dominio => {
http.expectOne('/tea/indicadores').flush([]);
page.changeDominio(dominio);
http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]);
const initial = http.expectOne(r => r.url.includes('/figuras/'));
page.changeTipoPeriodo('mes');
expect(initial.cancelled).toBe(true);
expect(page.periodMode).toBe('manual');
expect(page.periodText).toBe('');
expect(page.result().status).toBe('idle');
page.changePeriodText('2025-01,2025-02,2025-01');
const monthly = http.expectOne(r => r.url.includes('/figuras/'));
expect(monthly.request.params.get('periodos')).toBe('2025-01,2025-02');
page.changePeriodText('2025-13');
expect(monthly.cancelled).toBe(true);
expect(page.periodError).toContain('01 al 12');
page.changePeriodText('2025-01,2025-S1');
http.expectNone(r => r.url.includes('/figuras/'));
page.changePeriodMode('todos');
expect(page.periodError).toContain('primer tipo publicado');
http.expectNone(r => r.url.includes('/figuras/'));
page.changeTipoPeriodo('semestre');
const semesters = http.expectOne(r => r.url.includes('/figuras/'));
expect(semesters.request.params.has('periodos')).toBe(false);
semesters.flush({ data: [{ y: [null, 0] }], layout: {} });
fixture.detectChanges();
const help = fixture.nativeElement.querySelector('.interpretation').textContent;
expect(help).toContain('no entregan intervalos Wilson efectivos');
expect(help).toContain('eje horizontal muestra el periodo');
expect(help).toContain('suprimidos no representan tasas observadas de 0 %');
expect(help).not.toContain('La línea vertical representa el intervalo');
});
it('acepta futuros indicadores y figuras desde catálogo sin fijar cantidades ni contratos por dominio', () => {
http.expectOne('/tea/indicadores').flush([]);
page.changeDominio('cama');
const future = [
...syntheticCatalogs.cama,
{ id: 'synthetic_future', titulo: 'Fixture futuro', contrato: 'C2', figuras: ['fig_c2_apiladas', 'fig_c1_puntos'], tipos_periodo: ['mes', 'semestre'] },
];
http.expectOne('/cama/indicadores').flush(future);
http.expectOne(r => r.url.includes('/figuras/')).flush({ data: [], layout: {} });
page.selectIndicador('synthetic_future');
expect(page.tipoPeriodo).toBe('mes');
const req = http.expectOne(r => r.url.includes('/synthetic_future/figuras/fig_c2_apiladas'));
expect(req.request.params.has('periodos')).toBe(false);
req.flush({ data: [{ type: 'bar', y: [50, null] }], layout: { barmode: 'stack' } });
expect(page.interpretation.join(' ')).toContain('composición porcentual');
page.selectFigura('fig_c1_puntos');
http.expectOne(r => r.url.includes('/fig_c1_puntos')).flush({ data: [], layout: {} });
expect(page.interpretation.join(' ')).toContain('no entregan intervalos Wilson efectivos');
});
it('presenta carga y elige una primera figura válida desde el catálogo', () => {
expect(page.catalogLoading()).toBe(true);
load();
@@ -68,7 +139,7 @@ describe('IndicadoresPage', () => {
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', () => {
it('entrega al gráfico una copia de presentación y conserva el JSON HTTP íntegro', () => {
load();
const received: PlotlyFigure = {
data: [{ type: 'scatter', x: ['grupo'], y: [100, null], error_y: { array: [0], arrayminus: [49] }, customdata: [[4, 4]], marker: { color: '#123456' } }],
@@ -80,8 +151,12 @@ describe('IndicadoresPage', () => {
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);
expect(chart.figure).toBe(page.result().presentationFigure);
expect(chart.figure).not.toBe(page.result().figure);
expect(chart.figure?.data).toEqual(received.data);
expect(chart.figure?.layout).toEqual({ ...received.layout, title: { text: '' } });
expect(JSON.stringify(page.result().figure)).toBe(original);
expect(fixture.nativeElement.querySelector('.figure-title').textContent).toBe('Uno');
});
it('muestra catálogo vacío y permite recargar', () => {
http.expectOne('/tea/indicadores').flush([]);
@@ -1,6 +1,7 @@
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -9,8 +10,9 @@ 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 { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, hasNoVisibleValues, Indicador, parsePeriodos, PlotlyFigure, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { figureTitle, presentationFigure } from './indicadores.presentation';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
export function httpMessage(error: unknown, catalog = false): string {
@@ -25,7 +27,7 @@ export function httpMessage(error: unknown, catalog = false): string {
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 %.',
'En las figuras TEA con intervalos calculados, la línea vertical representa el intervalo de confianza Wilson al 95 %. No se infieren intervalos cuando faltan.',
'Los intervalos amplios pueden deberse a denominadores pequeños.',
'Un porcentaje observado del 100 % no implica certeza poblacional.',
],
@@ -42,16 +44,21 @@ const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
};
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 };
type FigureState = { status: 'idle' | 'loading' | 'ready' | 'error'; figure?: PlotlyFigure; presentationFigure?: PlotlyFigure; message?: string };
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, PlotlyChart],
imports: [RouterLink, 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 route = inject(ActivatedRoute, { optional: true });
readonly dominios = DOMINIOS;
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' };
tipoPeriodo: TipoPeriodo = 'semestre';
private readonly catalogRequests = new Subject<void>();
private readonly figureRequests = new Subject<FigureSelection | null>();
readonly catalog = signal<Indicador[]>([]);
@@ -59,6 +66,7 @@ export class IndicadoresPage {
readonly catalogError = signal('');
readonly result = signal<FigureState>({ status: 'idle' });
readonly hasNoVisibleValues = hasNoVisibleValues;
readonly figureTitle = figureTitle;
indicadorId = '';
figuraId = '';
periodMode: 'todos' | 'manual' = 'todos';
@@ -68,15 +76,30 @@ export class IndicadoresPage {
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
get interpretation(): readonly string[] {
const contract = this.selected?.contrato;
const contract = this.figuraId.startsWith('fig_c1') ? 'C1'
: this.figuraId.startsWith('fig_c2') ? 'C2'
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
if (contract === 'C2' && this.dominio !== 'tea') return [
'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 %.',
];
if (contract === 'C1' && this.dominio !== 'tea') return [
'Los puntos representan porcentajes observados; el eje horizontal muestra el periodo.',
'Estas figuras no entregan intervalos Wilson efectivos; no se interpretan sus barras como intervalos al 95 %.',
'Los puntos suprimidos no representan tasas observadas de 0 %. Consulta las notas del servicio.',
'Un porcentaje observado del 100 % no implica certeza poblacional.',
];
return contract && Object.hasOwn(CONTRACT_INTERPRETATIONS, contract)
? CONTRACT_INTERPRETATIONS[contract] : UNKNOWN_INTERPRETATION;
? [...CONTRACT_INTERPRETATIONS[contract], 'Los puntos suprimidos no representan tasas observadas de 0 %.'] : UNKNOWN_INTERPRETATION;
}
constructor() {
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
if (isDominio(initialDomain)) this.dominio = initialDomain;
this.figureRequests.pipe(switchMap(selection => selection
? this.service.figura(selection).pipe(
map(figure => ({ status: 'ready', figure }) as FigureState),
map(figure => ({ status: 'ready', figure, presentationFigure: presentationFigure(figure, selection) }) 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))
@@ -86,8 +109,9 @@ export class IndicadoresPage {
this.catalogError.set('');
this.catalog.set([]);
this.indicadorId = this.figuraId = '';
this.resetPeriodos('semestre');
this.figureRequests.next(null);
return this.service.catalogo().pipe(map(items => ({ items, error: '' })),
return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
@@ -96,10 +120,31 @@ export class IndicadoresPage {
if (items.length) this.selectIndicador(items[0].id);
});
}
changeDominio(dominio: Dominio) {
if (!isDominio(dominio) || dominio === this.dominio) return;
this.dominio = dominio;
this.catalogRequests.next();
}
private resetPeriodos(tipo: TipoPeriodo) {
this.tipoPeriodo = tipo;
this.periodText = this.periodError = '';
this.periodMode = 'todos';
}
changeTipoPeriodo(tipo: TipoPeriodo) {
if (!this.selected?.tipos_periodo.includes(tipo)) return;
this.resetPeriodos(tipo);
if (tipo !== this.selected.tipos_periodo[0]) this.periodMode = 'manual';
this.requestFigure();
}
get periodLabel(): string { return this.tipoPeriodo === 'mes' ? 'Meses (AAAA-MM)' : 'Semestres (AAAA-S1,AAAA-S2)'; }
retryCatalog() { this.catalogRequests.next(); }
selectIndicador(id: string) {
this.indicadorId = id;
this.figuraId = this.selected?.figuras[0] ?? '';
if (!this.selected?.tipos_periodo.includes(this.tipoPeriodo)
|| (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0])) {
this.resetPeriodos(this.selected?.tipos_periodo[0] ?? 'semestre');
}
this.requestFigure();
}
selectFigura(id: string) { this.figuraId = id; this.requestFigure(); }
@@ -108,12 +153,17 @@ export class IndicadoresPage {
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) {
const periodos = this.periodMode === 'manual' ? parsePeriodos(this.periodText, this.tipoPeriodo) : undefined;
if (periodos === null) this.periodError = this.tipoPeriodo === 'mes'
? 'Introduce meses AAAA-MM del 01 al 12 separados por comas.'
: 'Introduce semestres AAAA-S1 o AAAA-S2 separados por comas.';
if (this.periodMode === 'todos' && this.tipoPeriodo !== this.selected?.tipos_periodo[0]) {
this.periodError = 'Selecciona periodos explícitos para este tipo; el servicio usa solo el primer tipo publicado al omitir periodos.';
}
if (!this.selected || !this.selected.figuras.includes(this.figuraId) || !this.selected.tipos_periodo.includes(this.tipoPeriodo) || periodos === null || !!this.periodError) {
this.figureRequests.next(null);
return;
}
this.figureRequests.next({ indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
this.figureRequests.next({ dominio: this.dominio, tipoPeriodo: this.tipoPeriodo, indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
}
}
@@ -21,3 +21,14 @@ describe('Periodos y visibilidad conservadora', () => {
expect(hasNoVisibleValues({ data: [{ type: 'heatmap', z: [] }], layout: {} })).toBe(false);
});
});
it('deduplica meses en orden estable y valida el calendario sin mezclar tipos', () => {
expect(parsePeriodos('2025-12, 2025-01,2025-12', 'mes')).toEqual(['2025-12', '2025-01']);
for (const value of ['', '2025-00', '2025-13', '2025-1', '2025-S1', '2025-01,2025-S1']) {
expect(parsePeriodos(value, 'mes')).toBeNull();
}
expect(parsePeriodos('2025-S1,2025-01', 'semestre')).toBeNull();
});
it('no interpreta NaN ni null como porcentajes cero', () => {
expect(hasNoVisibleValues({ data: [{ y: [NaN, null] }], layout: {} })).toBe(true);
});
@@ -1,8 +1,19 @@
export const DOMINIOS = ['tea', 'cacu', 'cama'] as const;
export type Dominio = typeof DOMINIOS[number];
export type TipoPeriodo = 'semestre' | 'mes';
export function isDominio(value: unknown): value is Dominio {
return typeof value === 'string' && DOMINIOS.some(domain => domain === value);
}
export function requireDominio(value: unknown): Dominio {
if (!isDominio(value)) throw new Error('Dominio no permitido');
return value;
}
export interface Indicador {
id: string;
titulo: string;
contrato: string;
figuras: string[];
tipos_periodo: TipoPeriodo[];
}
// Keep the complete HTTP figure, including future attributes and interpretation notes.
@@ -14,11 +25,12 @@ export interface PlotlyFigure {
[key: string]: unknown;
}
export type Tema = 'claro' | 'oscuro';
export interface FigureSelection { indicador: string; figura: string; tema: Tema; periodos?: string[]; }
export interface FigureSelection { dominio?: Dominio; tipoPeriodo?: TipoPeriodo; indicador: string; figura: string; tema: Tema; periodos?: string[]; }
export function parsePeriodos(value: string): string[] | null {
export function parsePeriodos(value: string, tipo: TipoPeriodo = 'semestre'): string[] | null {
if (tipo !== 'semestre' && tipo !== 'mes') return null;
const parts = value.split(',').map(part => part.trim());
return parts.length && parts.every(part => /^[0-9]{4}-S[12]$/.test(part))
return parts.length && parts.every(part => (tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(part))
? [...new Set(parts)] : null;
}
@@ -0,0 +1,45 @@
import { figureTitle, presentationFigure } from './indicadores.presentation';
import { FigureSelection, PlotlyFigure } from './indicadores.models';
const selection: FigureSelection = { dominio: 'cacu', figura: 'fig_c1_puntos', indicador: 'x', tipoPeriodo: 'mes', tema: 'claro' };
const monthly: PlotlyFigure = {
data: [{ type: 'scatter', mode: 'markers', x: ['2025-03', '2025-01', '2025-02'], y: [100, null, 0], customdata: [[1, 1], [null, null], [0, 1]] }],
layout: { title: { text: 'Título completo<br>con contexto', font: { size: 18 } }, xaxis: { gridcolor: 'gray' }, annotations: [{ text: 'Nota' }] },
frames: [{ name: 'original' }], config: { displayModeBar: true }, future: { preserved: true },
};
describe('Dashboard presentation', () => {
it.each(['cacu', 'cama'] as const)('ordena ticks mensuales de %s sin cambiar observaciones ni HTTP', dominio => {
const original = structuredClone(monthly);
const adapted = presentationFigure(monthly, { ...selection, dominio });
expect(monthly).toEqual(original);
expect(adapted.data).toEqual(original.data);
expect(adapted.data).not.toBe(monthly.data);
expect(adapted.frames).toEqual(original.frames);
expect(adapted.config).toEqual(original.config);
expect(adapted['future']).toEqual(original['future']);
expect(adapted.layout['annotations']).toEqual(original.layout['annotations']);
expect(adapted.layout['xaxis']).toEqual({ gridcolor: 'gray', type: 'category', categoryorder: 'array', categoryarray: ['2025-01', '2025-02', '2025-03'], tickmode: 'array', tickvals: ['2025-01', '2025-02', '2025-03'], ticktext: ['2025-01', '2025-02', '2025-03'], tickangle: 0, automargin: true });
expect(figureTitle(monthly, 'catálogo')).toBe('Título completo<br>con contexto');
expect(adapted.layout['title']).toEqual({ text: '', font: { size: 18 } });
});
it.each(['fig_c1_grupos', 'fig_c2_apiladas', 'fig_c3r_caja'])('preserva ejes y trazas de %s', figura => {
const adapted = presentationFigure(monthly, { ...selection, figura });
expect(adapted.layout['xaxis']).toEqual(monthly.layout['xaxis']);
expect(adapted.data).toEqual(monthly.data);
});
it('conserva semestres, TEA, representaciones binarias y figuras vacías', () => {
for (const input of [monthly, { data: [], layout: {} }, { data: [{ type: 'scatter', mode: 'markers', x: ['2025-S1', '2025-S2'], y: { dtype: 'f8', bdata: 'AAAAAAAAVEAAAAAAAABJQA==' } }], layout: { xaxis: { type: 'category' } } }] as PlotlyFigure[]) {
const original = structuredClone(input);
for (const request of [{ ...selection, tipoPeriodo: 'semestre' as const }, { ...selection, dominio: 'tea' as const }, selection]) {
const adapted = presentationFigure(input, request);
expect(adapted.data).toEqual(original.data);
if (input !== monthly || request !== selection) expect(adapted.layout['xaxis']).toEqual(original.layout['xaxis']);
}
expect(input).toEqual(original);
}
});
it('conserva títulos string y usa catálogo cuando no hay título', () => {
expect(figureTitle({ data: [], layout: { title: 'Título completo' } }, 'fallback')).toBe('Título completo');
expect(figureTitle({ data: [], layout: { title: { text: '' } } }, 'Catálogo')).toBe('Catálogo');
});
});
@@ -0,0 +1,31 @@
import { FigureSelection, PlotlyFigure } from './indicadores.models';
export function figureTitle(figure: PlotlyFigure, fallback: string): string {
const title = figure.layout['title'];
if (typeof title === 'string' && title.trim()) return title;
if (title && typeof title === 'object' && 'text' in title
&& typeof title.text === 'string' && title.text.trim()) return title.text;
return fallback;
}
// Adapt only the dashboard copy; HTTP figures and all observations stay intact.
export function presentationFigure(original: PlotlyFigure, selection: FigureSelection): PlotlyFigure {
const figure = structuredClone(original);
const title = figure.layout['title'];
figure.layout['title'] = title && typeof title === 'object' ? { ...title, text: '' } : { text: '' };
if ((selection.dominio === 'cacu' || selection.dominio === 'cama')
&& selection.figura === 'fig_c1_puntos' && selection.tipoPeriodo === 'mes'
&& figure.data.length > 0
&& figure.data.every(trace => trace['type'] === 'scatter' && trace['mode'] === 'markers'
&& Array.isArray(trace['x']) && trace['x'].length > 0
&& trace['x'].every(x => typeof x === 'string' && /^[0-9]{4}-(0[1-9]|1[0-2])$/.test(x)))) {
const periods = [...new Set(figure.data.flatMap(trace => trace['x'] as string[]))].sort();
figure.layout['xaxis'] = {
...(figure.layout['xaxis'] as Record<string, unknown> | undefined),
type: 'category', categoryorder: 'array', categoryarray: periods,
tickmode: 'array', tickvals: periods, ticktext: periods,
tickangle: 0, automargin: true,
};
}
return figure;
}
@@ -1,6 +1,8 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Dominio } from './indicadores.models';
import { syntheticCatalogs, syntheticFigures } from './indicadores.synthetic-fixtures';
import { IndicadoresService } from './indicadores.service';
describe('IndicadoresService HTTP', () => {
@@ -12,8 +14,41 @@ describe('IndicadoresService HTTP', () => {
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => {
service.catalogo(dominio).subscribe(items => {
expect(items).toEqual(syntheticCatalogs[dominio]);
expect(items.length).toBe(dominio === 'tea' ? 18 : 1);
expect(items[0].tipos_periodo).toEqual(dominio === 'tea' ? ['semestre'] : ['semestre', 'mes']);
});
http.expectOne(`/${dominio}/indicadores`).flush(syntheticCatalogs[dominio]);
});
it.each(['tea', 'cacu', 'cama'] as const)('usa la URL de figura del dominio %s', dominio => {
service.figura({ dominio, indicador: 'i', figura: 'f', tema: 'oscuro', tipoPeriodo: dominio === 'tea' ? 'semestre' : 'mes', periodos: [dominio === 'tea' ? '2025-S1' : '2025-01'] }).subscribe();
const req = http.expectOne(r => r.url === `/${dominio}/indicadores/i/figuras/f`);
expect(req.request.params.get('periodos')).toBe(dominio === 'tea' ? '2025-S1' : '2025-01');
req.flush({ data: [], layout: {} });
});
it('rechaza dominios arbitrarios y periodos mezclados antes de HTTP', () => {
expect(() => service.catalogo('otro' as Dominio)).toThrow('Dominio no permitido');
expect(() => service.figura({ dominio: '../otro' as Dominio, indicador: 'i', figura: 'f', tema: 'claro' })).toThrow();
for (const periodos of [['2025-01', '2025-S1'], ['2025-13'], ['2025-00']]) {
expect(() => service.figura({ indicador: 'i', figura: 'f', tema: 'claro', periodos })).toThrow();
}
http.expectNone(() => true);
});
it.each([{ tipos_periodo: undefined }, { tipos_periodo: [] }, { tipos_periodo: ['anual'] }, { tipos_periodo: ['mes', 'mes'] }])('rechaza tipos de periodo inválidos $tipos_periodo', ({ tipos_periodo }) => {
let error: unknown;
service.catalogo('cacu').subscribe({ error: value => error = value });
http.expectOne('/cacu/indicadores').flush([{ ...syntheticCatalogs.cacu[0], tipos_periodo }]);
expect(error).toBeInstanceOf(Error);
});
it.each(syntheticFigures)('conserva el JSON sintético $name con arrays, nulos, anotaciones y bdata', ({ figure }) => {
service.figura({ indicador: 'i', figura: 'f', tema: 'claro' }).subscribe(value => expect(value).toEqual(figure));
http.expectOne(r => r.url.includes('/figuras/')).flush(figure);
});
it('consume un arreglo directo sin hardcodear catálogo', () => {
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'] }];
const data = [{ id: 'prueba', titulo: 'Título', contrato: 'C1', figuras: ['f1', 'f2'], tipos_periodo: ['semestre'] }];
let actual: unknown;
service.catalogo().subscribe(value => actual = value);
http.expectOne('/tea/indicadores').flush(data);
@@ -1,7 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { FigureSelection, Indicador, PlotlyFigure } from './indicadores.models';
import { Dominio, 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);
@@ -9,21 +9,34 @@ function record(value: unknown): value is Record<string, unknown> {
@Injectable({ providedIn: 'root' })
export class IndicadoresService {
private readonly http = inject(HttpClient);
catalogo() {
return this.http.get<unknown>('/tea/indicadores').pipe(map(value => {
catalogo(dominio: Dominio = 'tea') {
const domain = requireDominio(dominio);
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(value => {
if (!Array.isArray(value) || !value.every(item => record(item)
&& typeof item['id'] === 'string' && typeof item['titulo'] === 'string'
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
&& item['figuras'].every((figure: unknown) => typeof figure === 'string'))) {
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
throw new Error('Respuesta de catálogo inválida');
}
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
return value as Indicador[];
}));
}
figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
if (selection.periodos?.length) {
const text = selection.periodos.join(',');
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
throw new Error('Periodos inválidos o de tipos mezclados');
}
}
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)}`;
if (selection.periodos?.length) params = params.set('periodos', [...new Set(selection.periodos.map(periodo => periodo.trim()))].join(','));
const url = `/${dominio}/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');
File diff suppressed because it is too large Load Diff
@@ -1,3 +1,4 @@
import { syntheticFigures } from '../../features/indicadores/indicadores.synthetic-fixtures';
import { vi } from 'vitest';
import { PlotlyController } from './plotly-controller';
import { PlotlyRuntime } from './plotly-runtime';
@@ -175,4 +176,23 @@ describe('PlotlyController con Plotly instalado', () => {
controller?.destroy(); host.remove();
}
});
it.each(syntheticFigures)('renderiza el JSON G7D.2B $name sin convertir nulos, IC ni bdata', async ({ figure }) => {
const host = document.createElement('div');
document.body.append(host);
const original = JSON.stringify(figure);
let controller!: PlotlyController;
try {
await new Promise<void>((resolve, reject) => {
controller = new PlotlyController(host, () => Promise.resolve(runtime), state => {
if (state === 'ready') resolve();
if (state === 'error') reject(new Error('Plotly synthetic fixture failed'));
});
controller.setFigure(figure);
});
expect(host.querySelector('.main-svg')).not.toBeNull();
expect(host.style.visibility).toBe('visible');
expect(JSON.stringify(figure)).toBe(original);
} finally { controller?.destroy(); host.remove(); }
});
});