47a0ab5f1b
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
174 lines
13 KiB
TypeScript
174 lines
13 KiB
TypeScript
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 /<dominio>/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<string, unknown> => !!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<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
|
|
}
|
|
}
|
|
|
|
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
|
|
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
|
|
export interface AnalisisSeleccion {
|
|
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
|
|
ventana: { meses: number; desde: string; hasta: string };
|
|
filtros: Record<string, string | null>;
|
|
}
|
|
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
|
|
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
|
|
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
|
|
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
|
|
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
|
|
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
|
|
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
|
|
}
|
|
export interface TarjetaAnalisis {
|
|
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
|
|
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
|
|
}
|
|
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
|
|
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
|
|
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
|
|
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
|
|
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
|
|
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
|
|
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
|
|
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
|
|
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
|
|
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
|
|
export interface PeriodoTendencia {
|
|
periodo: string; inicio: string; fin: string; incompleto: boolean;
|
|
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
|
|
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
|
|
maligno: Proporcion;
|
|
}
|
|
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
|
|
export interface TendenciaAnalisis {
|
|
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
|
|
denominador: string; periodos: PeriodoTendencia[];
|
|
}
|
|
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
|
|
|
|
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
|
|
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
|
|
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
|
|
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
|
|
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
|
|
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
|
|
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
|
|
|
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
|
|
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|
|
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
|
|
return v as unknown as AnalisisCatalogoDescriptivo;
|
|
}
|
|
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
|
|
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
|
|
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
|
|
return v as unknown as ResumenAnalisis;
|
|
}
|
|
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
|
|
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|
|
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
|
|
&& record(i['seleccion']))) invalidoDescriptivo();
|
|
return v as unknown as DistribucionAnalisis;
|
|
}
|
|
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
|
|
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|
|
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
|
|
return v as unknown as ComparacionAnalisis;
|
|
}
|
|
export function mapaDescriptivo(v: unknown): MapaAnalisis {
|
|
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|
|
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
|
|
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
|
|
return v as unknown as MapaAnalisis;
|
|
}
|
|
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
|
|
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|
|
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
|
|
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
|
|
return v as unknown as TendenciaAnalisis;
|
|
}
|
|
|
|
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
|
|
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
|
|
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
|
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
|
|
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
|
|
return params;
|
|
}
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class AnalisisDescriptivoService {
|
|
private readonly http = inject(HttpClient);
|
|
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
|
|
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
|
|
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
|
|
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
|
|
}
|
|
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
|
|
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
|
|
}
|
|
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
|
|
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
|
|
}
|
|
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
|
|
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
|
|
}
|
|
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
|
|
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
|
|
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
|
|
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
|
|
}
|
|
}
|