106 lines
7.1 KiB
TypeScript
106 lines
7.1 KiB
TypeScript
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, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
|
import { MatButtonModule } from '@angular/material/button';
|
|
import { Dominio, Indicador } from './indicadores.models';
|
|
import { GlobalApplied, describePeriods, filterCompatibility, selectionKey } from './indicadores-memory';
|
|
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
|
import { IndicadorKpiCard } from './indicador-kpi-card';
|
|
import { KpiDefinition, KpiResult, kpiResult } from './indicadores-kpi';
|
|
import { PeriodAvailability, sortedPeriods } from './indicadores-periodos';
|
|
import { httpMessage } from './indicadores-http';
|
|
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
|
|
|
interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; version?: string; }
|
|
|
|
@Component({
|
|
selector: 'app-indicador-kpi-panel',
|
|
imports: [IndicadorKpiCard, MatButtonModule],
|
|
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" [notes]="result().notes ?? []" />
|
|
@if (result().state === 'Error de consulta') {
|
|
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
|
}`,
|
|
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() availability?: PeriodAvailability;
|
|
@Input() initialPresentation = false;
|
|
private readonly queries = inject(IndicadoresKpiQueries);
|
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
|
private readonly destroyRef = inject(DestroyRef);
|
|
private readonly requests = new Subject<void>();
|
|
private key = '';
|
|
readonly usedPeriod = signal<string | undefined>(undefined);
|
|
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
|
get temporalReference() {
|
|
if (this.result().earlier) return 'Último dato visible · ' + this.usedPeriod();
|
|
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
|
}
|
|
retry() { this.requests.next(); }
|
|
constructor() {
|
|
this.requests.pipe(switchMap((): Observable<KpiDisplay> => {
|
|
const applied = this.applied, definition = this.definition, domain = this.dominio;
|
|
this.usedPeriod.set(undefined);
|
|
if (!applied) return of({ state: 'Esperando filtro aplicado' });
|
|
if (this.indicador && this.indicador.contrato !== definition.contrato) return of({ state: 'Error de contrato' });
|
|
const compatible = filterCompatibility(applied, this.indicador?.tipos_periodo ?? [applied.tipo]);
|
|
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.' });
|
|
let periods: string[];
|
|
if (applied.selection.mode === 'todos') {
|
|
if (!this.indicador) return of({ state: 'Sin reportes disponibles' });
|
|
const availability = this.availability;
|
|
if (!availability || availability.status === 'loading') return of({ state: 'Consultando periodos…', loading: true });
|
|
if (availability.errors[definition.id]) return of({ state: 'Error de disponibilidad', info: 'Reintenta la consulta de periodos disponibles en los filtros generales.' });
|
|
const available = availability.byIndicator[definition.id];
|
|
if (!available) return of({ state: 'Error de disponibilidad' });
|
|
periods = sortedPeriods(available.filter(p => p.tipo === applied.tipo).map(p => p.periodo));
|
|
if (!periods.length) return of({ state: 'Sin reportes disponibles' });
|
|
if (!this.initialPresentation) periods = periods.slice(0, 1);
|
|
} else periods = applied.selection.periodos;
|
|
// One request per KPI at a time: the three configured panels start only after
|
|
// the existing availability queue (concurrency four) has finished.
|
|
const search = (index: number, latest?: KpiDisplay, allSuppressed = true): Observable<KpiDisplay> => {
|
|
const period = periods[index];
|
|
const resolved: GlobalApplied = { ...applied, selection: { mode: 'explicit', periodos: [period] } };
|
|
return this.queries.datos(domain, definition.id, applied.tipo, period, this.indicador?.version).pipe(
|
|
map(data => ({ ...kpiResult(data, definition, domain, resolved), notes: data.notas, period,
|
|
version: typeof data['version'] === 'string' ? data['version'] : undefined } as KpiDisplay)),
|
|
catchError(error => of<KpiDisplay>({ period,
|
|
state: error instanceof HttpErrorResponse && error.status === 404 ? 'Sin datos del periodo' : 'Error de consulta',
|
|
info: error instanceof HttpErrorResponse && error.status === 404 ? undefined : httpMessage(error) })),
|
|
switchMap(result => {
|
|
// Network/contract transport failures stay visible and can be retried.
|
|
if (result.state === 'Error de consulta') return of(result);
|
|
if (result.state === 'Disponible' && result.value !== undefined) return of({ ...result, earlier: index > 0,
|
|
info: [result.info, index > 0 && allSuppressed ? 'Existen reportes posteriores con datos ocultos por tamaño.' : ''].filter(Boolean).join(' ') });
|
|
const first = latest ?? result;
|
|
return index + 1 < periods.length
|
|
? search(index + 1, first, allSuppressed && result.state === 'Dato oculto por tamaño') : of(first);
|
|
}));
|
|
};
|
|
return search(0).pipe(startWith({ state: this.initialPresentation && applied.selection.mode === 'todos'
|
|
? 'Buscando último dato visible…' : 'Cargando…', loading: true }));
|
|
}), takeUntilDestroyed(this.destroyRef)).subscribe(result => {
|
|
this.usedPeriod.set(result.period);
|
|
this.result.set(result);
|
|
if (this.applied) this.snapshots.publishKpi(this.dominio, this.indicador ?? this.definition, this.applied,
|
|
{ ...result, period: this.temporalReference, unit: this.definition.unit }, result.version);
|
|
});
|
|
}
|
|
ngOnChanges() {
|
|
const key = JSON.stringify([this.dominio, this.definition.id, this.indicador, this.initialPresentation, this.applied?.revision, this.applied && selectionKey(this.applied),
|
|
this.applied?.selection.mode === 'todos' ? [this.availability?.status, this.availability?.byIndicator[this.definition.id], this.availability?.errors[this.definition.id]] : undefined]);
|
|
if (key === this.key) return;
|
|
this.key = key;
|
|
this.requests.next();
|
|
}
|
|
}
|