Files
WebApp/src/app/features/indicadores/indicadores-page.ts
T
2026-10-12 23:33:40 -06:00

127 lines
6.8 KiB
TypeScript

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';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
import { Dominio, DOMINIOS, isDominio, TipoPeriodo, FigureSelection, Indicador, parsePeriodos, Tema } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { presentationFigure } from './indicadores.presentation';
import { FigureState, IndicadorFigureCard } from './indicador-figure-card';
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.';
}
@Component({
selector: 'app-indicadores-page',
imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatProgressBarModule, IndicadorFigureCard],
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[]>([]);
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
readonly result = signal<FigureState>({ status: 'idle' });
indicadorId = '';
figuraId = '';
periodMode: 'todos' | 'manual' = 'todos';
periodText = '';
periodError = '';
tema: Tema = 'claro';
get selected(): Indicador | undefined { return this.catalog().find(item => item.id === this.indicadorId); }
constructor() {
const initialDomain: unknown = this.route?.snapshot.data['dominio'];
if (isDominio(initialDomain)) this.dominio = initialDomain;
this.figureRequests.pipe(switchMap(selection => selection
? this.service.figura(selection).pipe(
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))
.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.resetPeriodos('semestre');
this.figureRequests.next(null);
return this.service.catalogo(this.dominio).pipe(map(items => ({ items, error: '' })),
catchError(error => of({ items: [] as Indicador[], error: httpMessage(error, true) })));
}), 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);
});
}
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(); }
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, 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({ dominio: this.dominio, tipoPeriodo: this.tipoPeriodo, indicador: this.indicadorId, figura: this.figuraId, tema: this.tema, periodos });
}
}