Files
WebApp/src/app/features/indicadores/seguimiento-tabla.service.ts
T
rockdrigo 710790b98e feat(cama): «Análisis epidemiológico»: epidemiological figures, chosen comparisons, and curves and cells that open their patients
How:
- The tab is now «Análisis epidemiológico». Its first section,
  «Indicadores epidemiológicos», shows the cohort's figures at 24 months
  (GET /<domain>/analisis/indicadores, guarded by analisisIndicadores):
  cumulative incidence of cancer and of recurrence, follow-up adherence and
  survival, each with its interval, counts and assumptions.
- Stages publish a list of variables (two or more) instead of a fixed pair.
  The curves have their own menus: one variable and two or more of its
  values (`grupos`; with all of them the request names none, with one the
  page asks for another and sends nothing). Cox sits beside them, on the
  same groups.
- The heatmap has its own menus for rows and columns, always two distinct
  variables (cruceDeEtapa keeps a pair the stage owns); its answer adds the
  log-rank of each variable, plain and stratified by the other.
- A curve click, its «Ver pacientes» button in the risk table, or a
  coloured cell emits verPacientes with the scenario's population
  (`filtro_seguimiento`) and the values (seleccionDeCurva,
  seleccionDeCelda). The page opens Seguimiento with that selection.
- IndicadoresSeguimientoTabla takes the selection as an input: it asks the
  whole cohort (`meses = 0`, «Toda la cohorte», now in MESES_VENTANA) with
  those filters and says where the list comes from; «Quitar selección»
  goes back to the 3-month window. A new id applies a repeated click.

Implications:
- Seguimiento's contract gains `meses = 0` (no time window); the backend
  must accept it, or answer 400 until it does.
- The list behind a curve is patient-level: the drill-down needs the same
  access rule as Seguimiento, and the figures it comes from stay suppressed.
- Two more endpoints for the backend (/analisis/indicadores, and the new
  parameters grupos, filas and columnas).
2026-11-12 18:38:12 -06:00

82 lines
5.5 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';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
// domain, or per source: the answer can be rebuilt from another source without changing this client.
export type SeguimientoValor = string | number | null;
export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
// `detalles` are shown under the value, each with its label (for example the date of a result).
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[]; }
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoOpcion[]; }
export interface SeguimientoTablaQuery {
corte?: string; meses: MesesVentana; page: number; page_size: number;
// The filters the list announces in `filtros_disponibles`, by key; an empty value is no filter.
filtros?: Record<string, string | undefined>;
}
export interface SeguimientoTablaResponse {
simulado: true;
corte: string;
ventana: { meses: MesesVentana; desde: string; hasta: string };
filtros: Record<string, string | null>;
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
export class SeguimientoInvalido extends Error {}
// 0 is the whole list, without a time window: what a curve or a heatmap cell of the analysis opens.
export const MESES_VENTANA = [1, 3, 6, 12, 0] as const;
export type MesesVentana = typeof MESES_VENTANA[number];
export const PAGE_SIZE_MAX = 200;
const RESERVADAS = ['meses', 'page', 'page_size', 'corte'];
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const valor = (v: unknown) => v === null || typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v));
// Keys travel as query parameters, so they are restricted to what cannot collide with the shared ones.
const clave = (v: unknown): v is string => text(v) && /^[a-z][a-z0-9_]*$/.test(v) && !RESERVADAS.includes(v);
const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiqueta']);
export function validQuery(q: SeguimientoTablaQuery) {
return (!q.corte || isoDate(q.corte)) && (MESES_VENTANA as readonly number[]).includes(q.meses) && integer(q.page, 1)
&& integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX && Object.keys(q.filtros ?? {}).every(clave);
}
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
// The current authorization covers demonstration records only: validated before any item reaches the view.
if (!record(v) || v['simulado'] !== true) throw new SeguimientoInvalido('El seguimiento no cumple el contrato esperado.');
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'], available = v['filtros_disponibles'], columns = v['columnas'];
const filtrosOk = Array.isArray(available) && available.every(f => record(f) && clave(f['clave']) && text(f['etiqueta'])
&& Array.isArray(f['opciones']) && f['opciones'].every(opcion)) && new Set(available.map(f => (f as Record<string, unknown>)['clave'])).size === available.length;
const columnasOk = Array.isArray(columns) && columns.length > 0 && columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
&& (c['detalles'] === undefined || (Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta'])))));
if (!isoDate(v['corte']) || !record(window) || !(MESES_VENTANA as readonly number[]).includes(window['meses'] as number)
|| !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || p['page_size'] > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|| !filtrosOk || !columnasOk
|| !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record<string, unknown>[]).some(a => a['clave'] === k))
|| !Array.isArray(v['items']) || v['items'].length > p['page_size']
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
return v as unknown as SeguimientoTablaResponse;
}
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
private readonly http = inject(HttpClient);
consultar(dominio: Dominio, query: SeguimientoTablaQuery) {
if (!validQuery(query)) throw new SeguimientoInvalido('Parámetros de seguimiento inválidos');
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
}
}