127 lines
7.6 KiB
TypeScript
127 lines
7.6 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
|
import { map } from 'rxjs';
|
|
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models';
|
|
|
|
function record(value: unknown): value is Record<string, unknown> {
|
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
}
|
|
@Injectable({ providedIn: 'root' })
|
|
export class IndicadoresService {
|
|
private readonly http = inject(HttpClient);
|
|
catalogo(dominio: Dominio = 'tea') {
|
|
const domain = requireDominio(dominio);
|
|
return this.http.get<unknown>(`/${domain}/indicadores`).pipe(map(catalogoValido));
|
|
}
|
|
metadatos(dominio: Dominio, indicador: string) {
|
|
return this.http.get<unknown>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}/metadatos`).pipe(map(metadatosValidos));
|
|
}
|
|
datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
|
const domain = requireDominio(dominio);
|
|
const params = datosParams(tipo, periodos, scope);
|
|
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params })
|
|
.pipe(map(value => datosValidos(value, indicador, tipo, periodos, scope)));
|
|
}
|
|
figura(selection: FigureSelection) {
|
|
const dominio = requireDominio(selection.dominio ?? 'tea');
|
|
let params = new HttpParams().set('tema', selection.tema);
|
|
const periodos = figuraPeriodos(selection);
|
|
if (periodos) params = params.set('periodos', periodos.join(','));
|
|
const url = `/${dominio}/indicadores/${encodeURIComponent(selection.indicador)}/figuras/${encodeURIComponent(selection.figura)}`;
|
|
return this.http.get<unknown>(url, { params }).pipe(map(figuraValida));
|
|
}
|
|
}
|
|
|
|
export function catalogoValido(value: unknown): Indicador[] {
|
|
if (!Array.isArray(value) || !value.every(item => record(item)
|
|
&& typeof item['id'] === 'string' && item['id'].trim().length > 0 && typeof item['titulo'] === 'string'
|
|
&& typeof item['contrato'] === 'string' && Array.isArray(item['figuras'])
|
|
&& (item['version'] === undefined || typeof item['version'] === 'string')
|
|
&& item['figuras'].every((figure: unknown) => typeof figure === 'string' && figure.trim().length > 0)
|
|
&& new Set(item['figuras']).size === item['figuras'].length
|
|
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
|
|
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
|
|
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
|
|
throw new Error('Respuesta de catálogo inválida');
|
|
}
|
|
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
|
|
return value as Indicador[];
|
|
}
|
|
export function metadatosValidos(value: unknown): IndicadorMetadatos {
|
|
if (!record(value)) throw new Error('Metadatos inválidos');
|
|
const description = value['descripcion'];
|
|
if (description !== undefined && description !== null && typeof description !== 'string') throw new Error('Metadatos inválidos');
|
|
const ficha = value['ficha'];
|
|
if (ficha !== undefined && ficha !== null) {
|
|
if (!record(ficha)) throw new Error('Metadatos inválidos');
|
|
for (const field of ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota']) {
|
|
const content = ficha[field];
|
|
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
|
|
}
|
|
}
|
|
for (const field of ['referencias', 'poblaciones']) {
|
|
const list = value[field];
|
|
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
|
? typeof v['tipo'] === 'string' && typeof v['etiqueta'] === 'string' && (v['ref'] === null || typeof v['ref'] === 'string')
|
|
: typeof v['grupo'] === 'string' && typeof v['codigo'] === 'string' && typeof v['descripcion'] === 'string')))) throw new Error('Metadatos inválidos');
|
|
}
|
|
const figureDetails = value['figuras_detalle'];
|
|
if (figureDetails !== undefined && figureDetails !== null && (!Array.isArray(figureDetails) || !figureDetails.every(v => record(v)
|
|
&& typeof v['figura'] === 'string' && v['figura'].trim().length > 0
|
|
&& (v['descripcion'] === null || typeof v['descripcion'] === 'string')
|
|
&& (v['como_leer'] === null || Array.isArray(v['como_leer']) && v['como_leer'].every(line => typeof line === 'string'))))) {
|
|
throw new Error('Metadatos inválidos');
|
|
}
|
|
if (Array.isArray(figureDetails) && new Set(figureDetails.map(item => (item as Record<string, unknown>)['figura'])).size !== figureDetails.length) {
|
|
throw new Error('Metadatos inválidos');
|
|
}
|
|
return value as IndicadorMetadatos;
|
|
}
|
|
// The `/datos` query; throws on a period list or dimension the contract doesn't admit.
|
|
export function datosParams(tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
|
if (periodos && (!periodos.length || parsePeriodos(periodos.join(','), tipo) === null)) {
|
|
throw new Error('Periodos inválidos');
|
|
}
|
|
let params = new HttpParams();
|
|
if (scope.estrato) {
|
|
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
|
params = params.set('estrato', scope.estrato);
|
|
}
|
|
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
|
if (periodos) params = params.set('periodos', [...new Set(periodos)].join(','));
|
|
return params;
|
|
}
|
|
export function datosValidos(value: unknown, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}): IndicadorDatos {
|
|
if (!record(value) || value['id'] !== indicador || typeof value['contrato'] !== 'string'
|
|
|| value['tipo_periodo'] !== tipo
|
|
|| !Array.isArray(value['periodos']) || !value['periodos'].every(p => typeof p === 'string')
|
|
|| !Array.isArray(value['filas']) || !value['filas'].every(record)
|
|
|| (value['notas'] !== undefined && (!Array.isArray(value['notas']) || !value['notas'].every(n => typeof n === 'string')))) {
|
|
throw new Error('Respuesta de datos inválida');
|
|
}
|
|
const publishedPeriods = value['periodos'] as string[];
|
|
if ((value['estrato'] ?? undefined) !== scope.estrato) throw new Error('Dimensión recibida distinta de la solicitada');
|
|
if ((periodos && publishedPeriods.some(p => !periodos.includes(p)))
|
|
|| value['filas'].some(row => typeof row['periodo'] !== 'string' || !publishedPeriods.includes(row['periodo']))) {
|
|
throw new Error('Los datos recibidos no corresponden a los periodos solicitados');
|
|
}
|
|
return value as unknown as IndicadorDatos;
|
|
}
|
|
// The figure's explicit periods, trimmed and unique; throws on an empty list or mixed period types.
|
|
export function figuraPeriodos(selection: FigureSelection): string[] | undefined {
|
|
if (selection.periodos !== undefined) {
|
|
if (!selection.periodos.length) throw new Error('Selección explícita vacía');
|
|
const text = selection.periodos.join(',');
|
|
const tipos = selection.tipoPeriodo ? [selection.tipoPeriodo] : (['semestre', 'mes'] as const);
|
|
if (!tipos.some(tipo => parsePeriodos(text, tipo) !== null)) {
|
|
throw new Error('Periodos inválidos o de tipos mezclados');
|
|
}
|
|
}
|
|
return selection.periodos?.length ? [...new Set(selection.periodos.map(periodo => periodo.trim()))] : undefined;
|
|
}
|
|
export function figuraValida(value: unknown): PlotlyFigure {
|
|
if (!record(value) || !Array.isArray(value['data']) || !value['data'].every(record)
|
|
|| !record(value['layout'])) throw new Error('Respuesta de figura inválida');
|
|
return value as unknown as PlotlyFigure;
|
|
}
|