80 lines
4.1 KiB
TypeScript
80 lines
4.1 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
|
import { HttpClient } from '@angular/common/http';
|
|
import { catchError, from, map, mergeMap, Observable, of, shareReplay, toArray } from 'rxjs';
|
|
import { Dominio, Indicador, parsePeriodos, requireDominio, TipoPeriodo } from './indicadores.models';
|
|
import { httpMessage } from './indicadores-http';
|
|
import { IndicadoresRequests } from './indicadores-requests';
|
|
|
|
export interface AvailablePeriod { periodo: string; tipo: TipoPeriodo; }
|
|
export interface PeriodAvailability {
|
|
status: 'loading' | 'ready' | 'error';
|
|
byIndicator: Record<string, AvailablePeriod[]>;
|
|
options: Record<TipoPeriodo, string[]>;
|
|
errors: Record<string, string>;
|
|
}
|
|
export function emptyAvailability(status: PeriodAvailability['status'] = 'loading'): PeriodAvailability {
|
|
return { status, byIndicator: {}, options: { semestre: [], mes: [] }, errors: {} };
|
|
}
|
|
// Numeric year/unit comparison, independent of server order and report generation date.
|
|
export function periodOrder(period: string): number {
|
|
return Number(period.slice(0, 4)) * 12 + (period.includes('-S') ? Number(period.slice(6)) * 6 : Number(period.slice(5)));
|
|
}
|
|
export function sortedPeriods(periods: readonly string[]): string[] {
|
|
return [...new Set(periods)].sort((a, b) => periodOrder(b) - periodOrder(a));
|
|
}
|
|
function record(value: unknown): value is Record<string, unknown> {
|
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
}
|
|
export function parseAvailability(value: unknown, id: string): AvailablePeriod[] {
|
|
if (!record(value) || value['id'] !== id || !Array.isArray(value['periodos'])) throw new Error('Respuesta de periodos inválida');
|
|
const unique = new Map<string, AvailablePeriod>();
|
|
for (const row of value['periodos']) {
|
|
if (!record(row) || (row['tipo'] !== 'semestre' && row['tipo'] !== 'mes')
|
|
|| typeof row['periodo'] !== 'string' || parsePeriodos(row['periodo'], row['tipo'])?.[0] !== row['periodo']) {
|
|
throw new Error('Respuesta de periodos inválida');
|
|
}
|
|
unique.set(row['periodo'], { periodo: row['periodo'], tipo: row['tipo'] });
|
|
}
|
|
return [...unique.values()].sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo));
|
|
}
|
|
@Injectable({ providedIn: 'root' })
|
|
export class IndicadoresPeriodos {
|
|
private readonly http = inject(HttpClient);
|
|
private readonly requests = inject(IndicadoresRequests);
|
|
// Successful inventories live only in memory. Errors reset; cancelled HTTP is not cached.
|
|
private readonly cache = new Map<string, Observable<AvailablePeriod[]>>();
|
|
periodos(domain: Dominio, id: string) {
|
|
const dominio = requireDominio(domain);
|
|
const key = JSON.stringify([dominio, id]);
|
|
let request = this.cache.get(key);
|
|
if (!request) {
|
|
request = this.requests.run(() => this.http.get<unknown>(`/${dominio}/indicadores/${encodeURIComponent(id)}/periodos`)).pipe(
|
|
map(value => parseAvailability(value, id)), shareReplay({ bufferSize: 1, refCount: true }));
|
|
this.cache.set(key, request);
|
|
}
|
|
return request;
|
|
}
|
|
dominio(domain: Dominio, catalog: readonly Indicador[]): Observable<PeriodAvailability> {
|
|
return from(catalog).pipe(
|
|
mergeMap(item => this.periodos(domain, item.id).pipe(
|
|
map(periods => ({ id: item.id, periods: periods.filter(p => item.tipos_periodo.includes(p.tipo)), error: '' })),
|
|
catchError(error => of({ id: item.id, periods: [] as AvailablePeriod[], error: httpMessage(error) }))), 4),
|
|
toArray(),
|
|
map(results => {
|
|
const state = emptyAvailability('ready');
|
|
for (const result of results) {
|
|
if (result.error) state.errors[result.id] = result.error;
|
|
else state.byIndicator[result.id] = result.periods;
|
|
}
|
|
state.status = Object.keys(state.errors).length ? 'error' : 'ready';
|
|
// Do not publish an incomplete union as a successful inventory.
|
|
if (state.status === 'ready') {
|
|
for (const tipo of ['semestre', 'mes'] as const) {
|
|
state.options[tipo] = sortedPeriods(Object.values(state.byIndicator).flat().filter(p => p.tipo === tipo).map(p => p.periodo));
|
|
}
|
|
}
|
|
return state;
|
|
}));
|
|
}
|
|
}
|