import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate } from './cacu-seguimiento.models'; import { Dominio, requireDominio } from './indicadores.models'; // The epidemiological analysis of a domain's cohort. What the server publishes today is one aggregate: how many // patients of the cohort fall in each BI-RADS category at a cut-off (`GET //analisis/indicadores?corte=`). // It is a descriptive count, not an incidence or a survival estimate, and it never carries patient rows. The answer // names the cohort, the scenario and a `revision` of the cohort that the patients' list must quote back: a list asked // for with another revision is refused, so a group opened from this count is always the group that was counted. export interface GrupoAnalisis { codigo: string; n: number | null; suprimido: boolean; } export interface AnalisisAgregado { simulado: true; cohorte: string; revision: string; escenario: string; corte: string; umbral_supresion: number; unidad: string; denominador: string; grupos: GrupoAnalisis[]; } /** What a patients' list must quote back to open a group of the aggregate. */ export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; } /** Today as the date input writes it, in the user's own calendar day. */ export function hoyIso(ahora = new Date()) { const dos = (n: number) => String(n).padStart(2, '0'); return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`; } const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; // Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth. const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']); function sinFilasDePaciente(v: unknown): boolean { if (Array.isArray(v)) return v.every(sinFilasDePaciente); if (!record(v)) return true; return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x)); } /** Validates the aggregate before anything is drawn: aggregates only, and nothing published under the threshold. */ export function analisisAgregado(v: unknown): AnalisisAgregado { const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); }; if (!record(v) || v['simulado'] !== true) return invalido(); const umbral = v['umbral_supresion'], grupos = v['grupos']; if (!sinFilasDePaciente(v) || !text(v['cohorte']) || !text(v['escenario']) || !isoDate(v['corte']) || !text(v['unidad']) || !text(v['denominador']) || !text(v['revision']) || !/^[0-9a-f]{64}$/.test(v['revision']) || typeof umbral !== 'number' || !Number.isFinite(umbral) || umbral < 1 || !Array.isArray(grupos) || !grupos.length || !grupos.every(g => record(g) && text(g['codigo']) && typeof g['suprimido'] === 'boolean' && (g['suprimido'] ? g['n'] === null : typeof g['n'] === 'number' && Number.isInteger(g['n']) && g['n'] >= umbral)) || new Set(grupos.map(g => (g as GrupoAnalisis).codigo)).size !== grupos.length) return invalido(); return v as unknown as AnalisisAgregado; } @Injectable({ providedIn: 'root' }) export class AnalisisService { private readonly http = inject(HttpClient); agregado(dominio: Dominio, corte: string) { if (!isoDate(corte)) throw new Error('Fecha de corte inválida'); return this.http.get(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado)); } }