33 lines
1.8 KiB
TypeScript
33 lines
1.8 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
|
import { Observable, of, switchMap, throwError } from 'rxjs';
|
|
import { KpiDefinition, kpiResult } from './indicadores-kpi';
|
|
import { IndicadoresKpiQueries } from './indicadores-kpi-queries';
|
|
import { AvailablePeriod, IndicadoresPeriodos } from './indicadores-periodos';
|
|
import { Dominio, TipoPeriodo } from './indicadores.models';
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class IndicadoresInitialPeriod {
|
|
private readonly periods = inject(IndicadoresPeriodos);
|
|
private readonly queries = inject(IndicadoresKpiQueries);
|
|
|
|
find(domain: Dominio, definition: KpiDefinition, tipo: TipoPeriodo, version?: string): Observable<AvailablePeriod | undefined> {
|
|
if (definition.contrato !== 'C2') return throwError(() => new Error('El indicador ancla debe publicar C2'));
|
|
return this.periods.periodos(domain, definition.id).pipe(switchMap(available => {
|
|
// Inventories are already validated, deduplicated and sorted newest first.
|
|
const candidates = available.filter(period => period.tipo === tipo);
|
|
const search = (index: number): Observable<AvailablePeriod | undefined> => {
|
|
const candidate = candidates[index];
|
|
if (!candidate) return of(undefined);
|
|
return this.queries.datos(domain, definition.id, candidate.tipo, candidate.periodo, version).pipe(switchMap(data => {
|
|
const result = kpiResult(data, definition, domain, { tipo: candidate.tipo,
|
|
selection: { mode: 'explicit', periodos: [candidate.periodo] }, revision: 0 });
|
|
return result.state === 'Disponible' && typeof result.value === 'number' && result.value > 0
|
|
? of(candidate) : search(index + 1);
|
|
}));
|
|
};
|
|
// HTTP failures propagate; neither they nor invalid/suppressed C2 imply zero.
|
|
return search(0);
|
|
}));
|
|
}
|
|
}
|