import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { cronologico, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; type Panel = { item: Indicador; rango?: string } & ( { estado: 'cargando' | 'vacio' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura }); // Evolution of each indicator: the granularity and how many of the latest periods to show. // Nothing is requested until the tab is first opened, and each granularity is requested once. @Component({ selector: 'app-indicadores-historico', imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], template: `
Intervalo de análisis Mensual Semestral Periodos a mostrar @for (opcion of opciones(); track opcion.valor) { {{ opcion.etiqueta }} }
@for (panel of paneles(); track panel.item.id) {

{{ panel.item.titulo }}

@if (panel.rango) {

{{ panel.rango }}

} @switch (panel.estado) { @case ('cargando') { } @case ('vacio') {

Sin reportes publicados para este intervalo de análisis.

} @case ('error') {

{{ panel.mensaje }}

} @case ('listo') {

{{ panel.figura.comoLeer }}

@if (panel.figura.suprimidos.length) {

Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}

} @if (panel.figura.sinDato.length) {

Sin dato: {{ panel.figura.sinDato.join(', ') }}.

} } }
}
`, styles: ` :host { display: block; min-width: 0; } .controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } @container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } p { margin: var(--issste-space-3) 0 0; } .rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } app-plotly-chart { margin-top: var(--issste-space-3); } mat-form-field { min-width: 14rem; } `, }) export class IndicadoresHistorico { readonly dominio = input.required(); readonly catalog = input.required(); readonly tema = input.required(); readonly active = input(false); readonly tipo = signal('mes'); // How many of the latest periods to show, per granularity; 0 shows them all. private readonly ventanas = signal>>({}); readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); private readonly service = inject(IndicadoresService); private readonly periodos = inject(IndicadoresPeriodos); private readonly cargas = signal>>>({}); private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>(); private solicitada?: string; private catalogoCargado?: readonly Indicador[]; // Steps of five, up to what the indicator with the most periods has published. readonly opciones = computed(() => { const tipo = this.tipo(); const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); const opciones = []; for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }]; }); readonly paneles = computed(() => { const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(), ventana = this.ventana(); return this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(item => { const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; if (carga.estado !== 'listo') return { item, ...carga }; const periodos = cronologico(carga.datos.periodos).slice(-ventana); const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; const rango = `${periodos[0]} a ${periodos[periodos.length - 1]} (${periodos.length} ${unidad(tipo, periodos.length)})`; try { return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema) }; } catch (error) { return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } }); }); constructor() { this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo)) .map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))), takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => { this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) })); }); effect(() => { const tipo = this.tipo(), items = this.catalog(); if (!this.active() || !items.length) return; untracked(() => { if (this.catalogoCargado !== items) { this.catalogoCargado = items; this.cargas.set({}); this.solicitada = undefined; } if (this.cargas()[tipo] || this.solicitada === tipo) return; this.solicitada = tipo; this.solicitudes.next({ tipo, items }); }); }); } private cargar(item: Indicador, tipo: TipoPeriodo): Observable { return this.periodos.periodos(this.dominio(), item.id).pipe( map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)), switchMap((periodos): Observable => periodos.length ? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos }))) : of({ estado: 'vacio' })), catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); } elegirVentana(valor: number) { this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); } reintentar() { const tipo = this.tipo(); this.solicitada = tipo; this.cargas.update(({ [tipo]: _, ...resto }) => resto); this.solicitudes.next({ tipo, items: this.catalog() }); } }