import { inject, Injectable, signal } from '@angular/core'; import { catchError, defer, map, Observable, of, shareReplay, startWith, tap } from 'rxjs'; import { DatosScope, Dominio, Indicador, IndicadorDatos, TipoPeriodo } from './indicadores.models'; import { GlobalApplied, selectionKey } from './indicadores-memory'; import { IndicadoresRequests } from './indicadores-requests'; import { IndicadoresService } from './indicadores.service'; import { KpiResult } from './indicadores-kpi'; import { httpMessage } from './indicadores-http'; export type NumericSnapshot = { status: 'loading' | 'error' | 'ready'; data?: IndicadorDatos; message?: string; sourceKey?: string }; export interface KpiSnapshot extends KpiResult { period: string; unit: string; sourceKey?: string; } // Dimension and filters are explicit scopes; stratified payloads cannot replace // the general KPI/summary reading. Applied revision belongs to the // reading snapshot; identical immutable HTTP payloads can be reused across revisions. export function snapshotKey(domain: Dominio, item: Pick, applied: GlobalApplied, scope: DatosScope = {}) { return JSON.stringify([domain, item.id, item.version ?? null, selectionKey(applied), scope.estrato ?? null, applied.revision, [...(scope.filtros ?? [])].sort()]); } @Injectable({ providedIn: 'root' }) export class IndicadoresSnapshots { private readonly service = inject(IndicadoresService); private readonly queue = inject(IndicadoresRequests); private readonly cache = new Map>(); private readonly payloads = signal>(new Map()); readonly numeric = signal>(new Map()); readonly kpis = signal>(new Map()); readonly expanded = signal(false); readonly retries = signal(0); private transportKey(domain: Dominio, id: string, tipo: TipoPeriodo, periods?: readonly string[], version?: string, scope: DatosScope = {}) { return JSON.stringify([domain, id, version ?? null, tipo, periods ? [...new Set(periods)].sort() : null, scope.estrato ?? null, [...(scope.filtros ?? [])].sort()]); } reading(domain: Dominio, item: Indicador, applied: GlobalApplied): NumericSnapshot | undefined { const existing = this.numeric().get(snapshotKey(domain, item, applied)); if (existing) return existing; const data = this.payloads().get(this.transportKey(domain, item.id, applied.tipo, applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined, item.version)); return data && data.contrato === item.contrato && data.tipo_periodo === applied.tipo ? { status: 'ready', data, sourceKey: this.sourceKey(domain, item, applied, data['version']) } : undefined; } private sourceKey(domain: Dominio, item: Pick, applied: GlobalApplied, version: unknown) { return snapshotKey(domain, { ...item, version: item.version ?? (typeof version === 'string' ? version : undefined) }, applied); } datos(domain: Dominio, id: string, tipo: TipoPeriodo, periods?: string[], version?: string, scope: DatosScope = {}) { const key = this.transportKey(domain, id, tipo, periods, version, scope); let request = this.cache.get(key); if (!request) { request = this.queue.run(() => this.service.datos(domain, id, tipo, periods, scope)).pipe( map(data => { if (version && data['version'] !== undefined && data['version'] !== version) throw new Error('La versión recibida no corresponde al indicador.'); return data; }), tap(data => this.payloads.update(current => new Map(current).set(key, data))), // Ref counting cancels unfinished transport; errors never become cached values. shareReplay({ bufferSize: 1, refCount: true })); this.cache.set(key, request); } return request; } read(domain: Dominio, item: Indicador, applied: GlobalApplied) { const key = snapshotKey(domain, item, applied); const periods = applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined; return defer(() => this.datos(domain, item.id, applied.tipo, applied.selection.mode === 'explicit' ? applied.selection.periodos : undefined, item.version)).pipe( map(data => { if (data.contrato !== item.contrato || data.tipo_periodo !== applied.tipo || (item.version && data['version'] !== undefined && data['version'] !== item.version) || (periods && data.periodos.some(p => !periods.includes(p))) || data.filas.some(row => typeof row['periodo'] !== 'string' || !data.periodos.includes(row['periodo']))) { throw new Error('Los datos recibidos no corresponden a la selección aplicada.'); } return { status: 'ready', data, sourceKey: this.sourceKey(domain, item, applied, data['version']) } as NumericSnapshot; }), catchError(error => of({ status: 'error', message: httpMessage(error) })), startWith({ status: 'loading' } as NumericSnapshot), // The request key is an alias when the catalog omits version. A ready // snapshot also has its canonical identity using the published data version. tap(value => this.numeric.update(current => new Map(current).set(key, value).set(value.sourceKey ?? key, value)))); } publishKpi(domain: Dominio, item: Pick, applied: GlobalApplied, value: KpiSnapshot, version?: string) { const key = snapshotKey(domain, item, applied), sourceKey = this.sourceKey(domain, item, applied, version); const snapshot = { ...value, sourceKey }; this.kpis.update(current => new Map(current).set(key, snapshot).set(sourceKey, snapshot)); } }