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).
This commit is contained in:
@@ -9,13 +9,15 @@ import { Dominio, requireDominio } from './indicadores.models';
|
||||
// and the two variables it is stratified and filtered by; each variable says its NOM numeral and whether the schema
|
||||
// records it or the answer assumes it.
|
||||
export interface AnalisisOpcion { clave: string; etiqueta: string; }
|
||||
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; }
|
||||
// `filtro_seguimiento`: the follow-up list's filters that list this scenario's population.
|
||||
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; etapa: string; filtro_seguimiento: Record<string, string>; }
|
||||
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
|
||||
export type EstadoVariable = 'registrado' | 'supuesto';
|
||||
export interface AnalisisVariable extends AnalisisOpcion { nom: string; estado: EstadoVariable; fuente: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||
export interface AnalisisEtapa extends AnalisisOpcion {
|
||||
pregunta: string; escenarios: string[]; estimadores: string[]; medida: 'incidencia' | 'supervivencia';
|
||||
estratos: [string, string]; evento_supuesto: string | null;
|
||||
// The variables the stage can be compared by: one at a time in the curves, two at a time in the grid.
|
||||
variables: string[]; evento_supuesto: string | null;
|
||||
// Every variable the NOM asks for at this stage, and whether the schema has it.
|
||||
requeridas: { variable: string; nom: string; estado: string }[];
|
||||
}
|
||||
@@ -25,7 +27,20 @@ export interface AnalisisCatalogo {
|
||||
etapas: AnalisisEtapa[]; escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[];
|
||||
variables: AnalisisVariable[]; bloqueados: AnalisisBloqueado[];
|
||||
}
|
||||
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; }
|
||||
// `grupos`: the values of the variable to compare, two or more; empty compares them all.
|
||||
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; grupos: string[]; filtros: Record<string, string>; }
|
||||
export interface PedidoSubgrupos { escenario: string; estimador: string; filas: string; columnas: string; }
|
||||
// The log-rank of one variable of the grid, plain and at equal value of the other one.
|
||||
export interface PruebaCruzada {
|
||||
variable: string; etiqueta: string; estratificada_por: string; etiqueta_estrato: string;
|
||||
logrank: { chi2: number; gl: number; p: number; grupos: number } | null; estratificado: { chi2: number; gl: number; p: number; grupos: number } | null;
|
||||
}
|
||||
// One epidemiological figure of the cohort at the horizon (incidence, recurrence, adherence or survival).
|
||||
export interface IndicadorEpidemiologico {
|
||||
clave: string; titulo: string; etapa: string; unidad: string; descripcion: string; supuesto: string | null; suprimido: boolean;
|
||||
n: number | null; eventos: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; t_dias: number | null;
|
||||
}
|
||||
export interface AnalisisIndicadores { simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; indicadores: IndicadorEpidemiologico[]; }
|
||||
|
||||
export interface GrupoAnalisis { grupo: string; etiqueta: string; color: string; suprimido: boolean; motivo: string | null; n: number | null; eventos: number | null; competitivos: number | null; }
|
||||
// C9b: one row per group and event time; a suppressed row ends the published curve.
|
||||
@@ -38,7 +53,7 @@ export interface FilaValidacion { chequeo: string; escopo: string; estadistico:
|
||||
export interface AnalisisResultados {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||
etapa: string; medida: 'incidencia' | 'supervivencia';
|
||||
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>;
|
||||
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; grupos_elegidos: string[] | null;
|
||||
// What of this answer rests on data the schema does not record.
|
||||
supuestos: string[];
|
||||
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
|
||||
@@ -61,7 +76,7 @@ export interface CeldaSubgrupo {
|
||||
export interface AnalisisSubgrupos {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number; escenario: string; estimador: string;
|
||||
etapa: string; medida: 'incidencia' | 'supervivencia'; supuestos: string[];
|
||||
dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion;
|
||||
dimension_filas: AnalisisOpcion; dimension_columnas: AnalisisOpcion; pruebas: PruebaCruzada[];
|
||||
filas: { codigo: string; etiqueta: string }[]; columnas: { codigo: string; etiqueta: string }[]; celdas: CeldaSubgrupo[];
|
||||
}
|
||||
|
||||
@@ -83,13 +98,14 @@ const invalido = (): never => { throw new Error('Respuesta de análisis inválid
|
||||
export function analisisCatalogo(v: unknown): AnalisisCatalogo {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!text(v['corte']) || !num(v['horizonte_dias']) || !num(v['umbral_supresion'])
|
||||
|| !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])) || !(v['escenarios'] as unknown[]).length
|
||||
|| !lista(v['escenarios'], e => opcion(e) && record(e) && text(e['evento']) && text(e['origen']) && text(e['poblacion']) && text(e['etapa'])
|
||||
&& record(e['filtro_seguimiento']) && Object.values(e['filtro_seguimiento']).every(text)) || !(v['escenarios'] as unknown[]).length
|
||||
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
|
||||
|| !lista(v['variables'], x => opcion(x) && record(x) && text(x['nom']) && ['registrado', 'supuesto'].includes(x['estado'] as string)
|
||||
&& text(x['fuente']) && lista(x['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|
||||
|| !lista(v['etapas'], e => opcion(e) && record(e) && text(e['pregunta']) && ['incidencia', 'supervivencia'].includes(e['medida'] as string)
|
||||
&& lista(e['escenarios'], text) && (e['escenarios'] as unknown[]).length > 0 && lista(e['estimadores'], text) && (e['estimadores'] as unknown[]).length > 0
|
||||
&& lista(e['estratos'], text) && (e['estratos'] as unknown[]).length === 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|
||||
&& lista(e['variables'], text) && (e['variables'] as unknown[]).length >= 2 && lista(e['requeridas'], record)) || !(v['etapas'] as unknown[]).length
|
||||
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|
||||
|| !sinFilasDePaciente(v)) invalido();
|
||||
return v as unknown as AnalisisCatalogo;
|
||||
@@ -122,6 +138,7 @@ export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
|
||||
const eje = (x: unknown) => lista(x, o => record(o) && text(o['codigo']) && text(o['etiqueta']));
|
||||
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador'])
|
||||
|| !eje(v['filas']) || !eje(v['columnas']) || !opcion(v['dimension_filas']) || !opcion(v['dimension_columnas']) || !lista(v['supuestos'], text)
|
||||
|| !lista(v['pruebas'], x => record(x) && text(x['variable']) && text(x['estratificada_por']) && (x['logrank'] === null || record(x['logrank'])) && (x['estratificado'] === null || record(x['estratificado'])))
|
||||
|| !lista(v['celdas'], c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean'
|
||||
&& (c['suprimido'] ? c['n'] === null && c['eventos'] === null && c['valor'] === null
|
||||
: num(c['n']) && num(c['eventos']) && num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['t_dias'])))) invalido();
|
||||
@@ -131,6 +148,16 @@ export function analisisSubgrupos(v: unknown): AnalisisSubgrupos {
|
||||
return v as unknown as AnalisisSubgrupos;
|
||||
}
|
||||
|
||||
export function analisisIndicadores(v: unknown): AnalisisIndicadores {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!sinFilasDePaciente(v) || !num(v['umbral_supresion']) || !lista(v['indicadores'], x => record(x) && text(x['clave']) && text(x['titulo'])
|
||||
&& text(x['descripcion']) && typeof x['suprimido'] === 'boolean'
|
||||
&& (x['suprimido'] ? x['valor'] === null && x['eventos'] === null : num(x['valor']) && num(x['n']) && num(x['eventos'])))) invalido();
|
||||
// A published figure never stands on fewer patients than the threshold.
|
||||
if ((v['indicadores'] as IndicadorEpidemiologico[]).some(x => !x.suprimido && x.n! < (v['umbral_supresion'] as number))) invalido();
|
||||
return v as unknown as AnalisisIndicadores;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisService {
|
||||
private readonly http = inject(HttpClient);
|
||||
@@ -139,11 +166,15 @@ export class AnalisisService {
|
||||
}
|
||||
resultados(dominio: Dominio, pedido: AnalisisPedido) {
|
||||
let params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('estrato', pedido.estrato);
|
||||
if (pedido.grupos.length) params = params.set('grupos', pedido.grupos.join(','));
|
||||
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/resultados`, { params }).pipe(map(analisisResultados));
|
||||
}
|
||||
subgrupos(dominio: Dominio, escenario: string, estimador: string) {
|
||||
const params = new HttpParams().set('escenario', escenario).set('estimador', estimador);
|
||||
subgrupos(dominio: Dominio, pedido: PedidoSubgrupos) {
|
||||
const params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('filas', pedido.filas).set('columnas', pedido.columnas);
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/subgrupos`, { params }).pipe(map(analisisSubgrupos));
|
||||
}
|
||||
indicadores(dominio: Dominio) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`).pipe(map(analisisIndicadores));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,39 +3,48 @@ import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresAnalisis, celdaDelClic, grupoDelClic, pedidoAlElegir } from './indicadores-analisis';
|
||||
import {
|
||||
IndicadoresAnalisis, SeleccionPacientes, celdaDelClic, cruceDeEtapa, grupoDelClic, pedidoDeEtapa, seleccionDeCelda, seleccionDeCurva,
|
||||
} from './indicadores-analisis';
|
||||
import { curvasFigura, forestFigura, subgruposFigura } from './indicadores-analisis-figuras';
|
||||
import { AnalisisCatalogo, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisResultados, analisisSubgrupos } from './indicadores-analisis.service';
|
||||
import {
|
||||
AnalisisCatalogo, AnalisisIndicadores, AnalisisResultados, AnalisisSubgrupos, analisisCatalogo, analisisIndicadores, analisisResultados, analisisSubgrupos,
|
||||
} from './indicadores-analisis.service';
|
||||
|
||||
// Covers the «Análisis» tab of breast cancer: the answer's guard (aggregates only, nothing under the threshold),
|
||||
// the figures built from it, the click that only changes the request, and the tab's requests and states.
|
||||
// The tab has three parts (survival, subgroup explorer, cohort diagnostics) under one set of controls.
|
||||
// Fixtures: `catalogo` (two stages, development and survival, with their scenarios, estimators and two variables
|
||||
// each, one of them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a
|
||||
// ready Cox model) and `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell), all built below.
|
||||
// Covers the «Análisis epidemiológico» tab of breast cancer: the guards of its answers (aggregates only, nothing
|
||||
// under the threshold), the figures built from them, the selections a curve or a cell sends to Seguimiento, and the
|
||||
// tab's requests: the epidemiological figures, the curves of two or more values of one variable, and the heatmap of
|
||||
// two distinct variables.
|
||||
// Fixtures, all built below: `catalogo` (two stages, development with three variables and survival with two, one of
|
||||
// them assumed; one blocked analysis), `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model),
|
||||
// `subgrupos` (a two-by-two BI-RADS and age grid with one suppressed cell and its crossed tests) and `indicadores`
|
||||
// (one published figure and one suppressed).
|
||||
|
||||
const catalogo = (): AnalisisCatalogo => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
|
||||
etapas: [
|
||||
{ clave: 'desarrollo', etiqueta: 'Desarrollo', pregunta: '¿Quién llega a cáncer?', escenarios: ['diagnostico', 'incidencia'], estimadores: ['cif', 'km'],
|
||||
medida: 'incidencia', estratos: ['birads', 'grupo_edad'], evento_supuesto: null, requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
|
||||
medida: 'incidencia', variables: ['birads', 'grupo_edad', 'brca'], evento_supuesto: null,
|
||||
requeridas: [{ variable: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado' }] },
|
||||
{ clave: 'supervivencia', etiqueta: 'Supervivencia', pregunta: '¿Quién sigue viva?', escenarios: ['supervivencia'], estimadores: ['km'],
|
||||
medida: 'supervivencia', estratos: ['etapa_clinica', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
|
||||
medida: 'supervivencia', variables: ['estadio', 'grupo_edad'], evento_supuesto: 'Estado vital supuesto.',
|
||||
requeridas: [{ variable: 'Estado vital y causa de muerte', nom: '16.8', estado: 'supuesto' }] },
|
||||
],
|
||||
escenarios: [
|
||||
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo' },
|
||||
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo' },
|
||||
{ clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia' },
|
||||
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más', etapa: 'desarrollo', filtro_seguimiento: {} },
|
||||
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna', etapa: 'desarrollo', filtro_seguimiento: { resultado: 'BENIGNO' } },
|
||||
{ clave: 'supervivencia', etiqueta: 'Supervivencia', evento: 'Muerte', origen: 'Diagnóstico', poblacion: 'Cáncer invasor', etapa: 'supervivencia', filtro_seguimiento: { resultado: 'INVASOR' } },
|
||||
],
|
||||
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
|
||||
variables: [
|
||||
{ clave: 'birads', etiqueta: 'Categoría BI-RADS', nom: 'Apéndice B', estado: 'registrado', fuente: 'mastografia.birads',
|
||||
opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }] },
|
||||
opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }, { codigo: 'B6', etiqueta: 'BI-RADS 6' }] },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', nom: '16.5', estado: 'registrado', fuente: 'paciente.fecha_nacimiento',
|
||||
opciones: [{ codigo: '50-59', etiqueta: '50-59 años' }] },
|
||||
{ clave: 'etapa_clinica', etiqueta: 'Etapa clínica', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
|
||||
opciones: [{ codigo: 'I', etiqueta: 'Etapa I' }, { codigo: 'IV', etiqueta: 'Etapa IV' }] },
|
||||
opciones: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }] },
|
||||
{ clave: 'brca', etiqueta: 'BRCA1/2', nom: 'Factores de riesgo', estado: 'supuesto', fuente: 'Prueba genética.',
|
||||
opciones: [{ codigo: 'BRCA1', etiqueta: 'Mutación BRCA1' }, { codigo: 'NEGATIVO', etiqueta: 'Sin mutación' }] },
|
||||
{ clave: 'estadio', etiqueta: 'Estadio clínico', nom: '10.3.2', estado: 'supuesto', fuente: 'Nota de oncología.',
|
||||
opciones: [{ codigo: 'I', etiqueta: 'Estadio I' }, { codigo: 'IV', etiqueta: 'Estadio IV' }] },
|
||||
],
|
||||
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
|
||||
});
|
||||
@@ -43,7 +52,7 @@ const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_even
|
||||
({ grupo, t, estimador: 'CIF' as const, valor, ic_bajo: valor * .8, ic_alto: valor * 1.2, n_riesgo, n_eventos, suprimido: 0 as const });
|
||||
const resultados = (): AnalisisResultados => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||
escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {},
|
||||
escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {}, grupos_elegidos: null,
|
||||
poblacion: { n: null, eventos: null, totales_ocultos: true, seguimiento_mediano_dias: 700 },
|
||||
grupos: [
|
||||
{ grupo: 'B4A', etiqueta: 'BI-RADS 4A', color: '#1F5F8B', suprimido: false, motivo: null, n: 180, eventos: 11, competitivos: null },
|
||||
@@ -59,15 +68,16 @@ const resultados = (): AnalisisResultados => ({
|
||||
rmst_referencia: 'B4A', nota: 'Prueba de Gray pendiente.' },
|
||||
efectos: { estado: 'listo', motivo: null, metodo: 'cox', referencia: 'B4A', etiqueta_referencia: 'BI-RADS 4A',
|
||||
filas: [{ termino: 'B5', etiqueta: 'BI-RADS 5', hr: 30, ic_bajo: 16, ic_alto: 59, n_eventos: 100, metodo: 'cox', ph_p: .01 }] },
|
||||
validacion: [{ chequeo: 'Eventos por grupo', escopo: 'BI-RADS 6', estadistico: null, p: null, umbral: 5, aprobado: false, nota: 'Menos de 5 eventos', version_modelo: 'mock-0.1', sql_sha: null },
|
||||
{ chequeo: 'Balance de covariables (SMD < 0.1)', escopo: 'Comparación causal', estadistico: null, p: null, umbral: .1, aprobado: null, nota: 'No aplica.', version_modelo: 'mock-0.1', sql_sha: null }],
|
||||
validacion: [{ chequeo: 'Eventos por grupo', escopo: 'BI-RADS 6', estadistico: null, p: null, umbral: 5, aprobado: false, nota: 'Menos de 5 eventos', version_modelo: 'mock-0.1', sql_sha: null }],
|
||||
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
|
||||
});
|
||||
|
||||
const subgrupos = (): AnalisisSubgrupos => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, escenario: 'diagnostico', estimador: 'cif',
|
||||
etapa: 'desarrollo', medida: 'incidencia', supuestos: [],
|
||||
dimension_filas: { clave: 'birads', etiqueta: 'Categoría BI-RADS' }, dimension_columnas: { clave: 'grupo_edad', etiqueta: 'Grupo de edad' },
|
||||
pruebas: [{ variable: 'birads', etiqueta: 'Categoría BI-RADS', estratificada_por: 'grupo_edad', etiqueta_estrato: 'Grupo de edad',
|
||||
logrank: { chi2: 90, gl: 1, p: 1e-10, grupos: 2 }, estratificado: { chi2: 85, gl: 1, p: 1e-9, grupos: 2 } },
|
||||
{ variable: 'grupo_edad', etiqueta: 'Grupo de edad', estratificada_por: 'birads', etiqueta_estrato: 'Categoría BI-RADS', logrank: null, estratificado: null }],
|
||||
filas: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }],
|
||||
columnas: [{ codigo: '40-49', etiqueta: '40-49 años' }, { codigo: '50-59', etiqueta: '50-59 años' }],
|
||||
celdas: [
|
||||
@@ -77,87 +87,101 @@ const subgrupos = (): AnalisisSubgrupos => ({
|
||||
{ fila: 'B5', columna: '50-59', suprimido: false, motivo: null, n: 50, eventos: 45, t_dias: 730, valor: 92, ic_bajo: 81, ic_alto: 97 },
|
||||
],
|
||||
});
|
||||
const indicadores = (): AnalisisIndicadores => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5, indicadores: [
|
||||
{ clave: 'desarrollo', titulo: 'Incidencia de cáncer a 24 meses', etapa: 'desarrollo', unidad: '%', descripcion: 'Llegan a cáncer.', supuesto: null,
|
||||
suprimido: false, n: 600, eventos: 274, valor: 45.7, ic_bajo: 41.6, ic_alto: 49.6, t_dias: 730 },
|
||||
{ clave: 'recaida', titulo: 'Recaída a 24 meses', etapa: 'recaida', unidad: '%', descripcion: 'Recaen.', supuesto: 'Recaída supuesta.',
|
||||
suprimido: true, n: null, eventos: null, valor: null, ic_bajo: null, ic_alto: null, t_dias: null },
|
||||
],
|
||||
});
|
||||
|
||||
describe('Respuesta del análisis', () => {
|
||||
it('admite solo agregados de demostración', () => {
|
||||
// Fails if the guard stops rejecting real records or anything shaped like a patient row, at any depth.
|
||||
describe('Respuestas del análisis', () => {
|
||||
it('admiten solo agregados de demostración', () => {
|
||||
// Fails if the guards stop rejecting real records or anything shaped like a patient row, at any depth.
|
||||
expect(analisisResultados(resultados()).grupos).toHaveLength(3);
|
||||
expect(analisisCatalogo(catalogo()).bloqueados).toHaveLength(1);
|
||||
expect(analisisCatalogo(catalogo()).etapas).toHaveLength(2);
|
||||
expect(analisisIndicadores(indicadores()).indicadores).toHaveLength(2);
|
||||
expect(() => analisisResultados({ ...resultados(), simulado: false })).toThrow();
|
||||
expect(() => analisisResultados({ ...resultados(), pruebas: { ...resultados().pruebas, items: [{ id_seudonimo: 'M-1' }] } })).toThrow();
|
||||
expect(() => analisisCatalogo({ ...catalogo(), pacientes: [] })).toThrow();
|
||||
});
|
||||
it('rechaza un punto publicado con menos pacientes en riesgo que el umbral, y un grupo suprimido con conteos', () => {
|
||||
// Fails if a curve's tail or a suppressed group can carry counts below the threshold to the browser.
|
||||
it('rechazan cifras bajo el umbral: un punto de curva, un grupo suprimido con conteos, una celda o un indicador', () => {
|
||||
// Fails if a curve's tail, a suppressed group, a heatmap cell or an epidemiological figure can carry counts under the threshold.
|
||||
const r = resultados();
|
||||
expect(() => analisisResultados({ ...r, curvas: [...r.curvas, punto('B4A', 740, 7, 3, 12)] })).toThrow();
|
||||
expect(() => analisisResultados({ ...r, grupos: r.grupos.map(g => g.suprimido ? { ...g, n: 4 } : g) })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Explorador de subgrupos', () => {
|
||||
it('admite celdas publicadas solo desde el umbral y dibuja gris lo suprimido', () => {
|
||||
// Fails if a cell under the threshold reaches the grid, or a suppressed cell is drawn as a colour.
|
||||
expect(analisisSubgrupos(subgrupos()).celdas).toHaveLength(4);
|
||||
expect(() => analisisSubgrupos({ ...subgrupos(), celdas: subgrupos().celdas.map(c => c.suprimido ? c : { ...c, eventos: 3 }) })).toThrow();
|
||||
const fig = subgruposFigura(subgrupos(), 'claro');
|
||||
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
|
||||
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
|
||||
const textos = (fig.layout['annotations'] as { text: string }[]).map(a => a.text);
|
||||
expect(textos[0]).toContain('Suprimido');
|
||||
expect(textos[2]).toContain('a 4 meses');
|
||||
expect(() => analisisIndicadores({ ...indicadores(), indicadores: [{ ...indicadores().indicadores[0], n: 3 }] })).toThrow();
|
||||
});
|
||||
it('un clic en una celda con color da su BI-RADS y edad; en una gris, nada', () => {
|
||||
// Fails if a click on a suppressed cell could open a subgroup the answer hid.
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
|
||||
expect(celdaDelClic({ points: [{ z: 1 }] })).toBeUndefined();
|
||||
it('una etapa necesita al menos dos variables para comparar', () => {
|
||||
// Fails if a stage with a single variable reaches the curves or the heatmap, which compare two or more.
|
||||
expect(() => analisisCatalogo({ ...catalogo(), etapas: [{ ...catalogo().etapas[0], variables: ['birads'] }] })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Figuras del análisis', () => {
|
||||
it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
|
||||
// Fails if the survival stage is drawn on the incidence axis.
|
||||
const r = resultados();
|
||||
const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
|
||||
expect(((fig.layout['yaxis'] as { title: { text: string } }).title.text)).toBe('Supervivencia (%)');
|
||||
expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
|
||||
});
|
||||
it('dibuja una curva con su banda por grupo publicado y la corta donde la respuesta la suprime', () => {
|
||||
// Fails if a suppressed group gets a trace, the curve runs past its suppressed tail, or a line loses its group.
|
||||
const fig = curvasFigura(resultados(), 'claro');
|
||||
const lineas = fig.data.filter(t => t['meta']);
|
||||
expect(lineas.map(t => t['meta'])).toEqual(['B4A', 'B5']);
|
||||
expect(fig.data).toHaveLength(6);
|
||||
expect((lineas[1]['y'] as number[])).toEqual([0, 70]);
|
||||
expect(lineas[0]['name']).toContain('n = 180');
|
||||
expect(lineas[1]['y'] as number[]).toEqual([0, 70]);
|
||||
});
|
||||
it('en la etapa de supervivencia la curva baja desde 100 % y el eje dice Supervivencia', () => {
|
||||
// Fails if the survival stage is drawn on the incidence axis.
|
||||
const r = resultados();
|
||||
const fig = curvasFigura({ ...r, medida: 'supervivencia', curvas: r.curvas.map(c => c.valor === null ? c : { ...c, valor: 100 - c.valor, ic_bajo: 100 - c.ic_alto!, ic_alto: 100 - c.ic_bajo! }) }, 'claro');
|
||||
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Supervivencia (%)');
|
||||
expect((fig.data.find(t => t['meta'] === 'B4A')!['y'] as number[])[0]).toBe(100);
|
||||
});
|
||||
it('marca vacío el HR con riesgos no proporcionales y no dibuja nada sin modelo', () => {
|
||||
// Fails if the forest plot hides the PH warning or draws an effect the answer did not publish.
|
||||
const fig = forestFigura(resultados(), 'claro');
|
||||
expect((fig.data[1]['marker'] as { color: string[] }).color[0]).toBe('#FFFFFF');
|
||||
expect(fig.data[0]['y']).toEqual(['BI-RADS 4A (referencia)']);
|
||||
expect(forestFigura({ ...resultados(), efectos: { ...resultados().efectos, estado: 'insuficiente', filas: [] } }, 'claro').data).toEqual([]);
|
||||
});
|
||||
it('el mapa de calor dibuja gris lo suprimido y nombra sus dos variables', () => {
|
||||
// Fails if a suppressed cell is drawn as a colour, or the axes stop naming the variables chosen.
|
||||
const fig = subgruposFigura(subgrupos(), 'claro');
|
||||
expect((fig.data[1]['z'] as (number | null)[][])[0]).toEqual([null, 10]);
|
||||
expect((fig.data[0]['z'] as (number | null)[][])[0]).toEqual([1, null]);
|
||||
expect((fig.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Categoría BI-RADS');
|
||||
expect((fig.layout['annotations'] as { text: string }[])[2].text).toContain('a 4 meses');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Clic en una curva', () => {
|
||||
const pedido = { escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {} };
|
||||
it('deja solo ese grupo y estratifica por la otra dimensión', () => {
|
||||
// Fails if the click reads anything but the line's group, or keeps stratifying by the filtered dimension.
|
||||
expect(grupoDelClic({ points: [{ data: { meta: 'B5' } }] })).toBe('B5');
|
||||
describe('Selecciones que van a Seguimiento', () => {
|
||||
it('una curva lleva la población del escenario y el valor del grupo', () => {
|
||||
// Fails if a curve opens a list wider than its own patients, or names another group.
|
||||
const pedido = { escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} };
|
||||
expect(grupoDelClic({ points: [{ data: { meta: 'IV' } }] })).toBe('IV');
|
||||
expect(grupoDelClic({ points: [{ data: {} }] })).toBeUndefined();
|
||||
expect(pedidoAlElegir(pedido, 'B5', catalogo())).toEqual({ ...pedido, estrato: 'grupo_edad', filtros: { birads: 'B5' } });
|
||||
const ambos = pedidoAlElegir({ ...pedido, estrato: 'grupo_edad', filtros: { birads: 'B5' } }, '50-59', catalogo());
|
||||
expect(ambos).toEqual({ ...pedido, estrato: 'ninguno', filtros: { birads: 'B5', grupo_edad: '50-59' } });
|
||||
expect(pedidoAlElegir({ ...pedido, estrato: 'ninguno' }, 'TOTAL', catalogo())).toEqual({ ...pedido, estrato: 'ninguno' });
|
||||
expect(seleccionDeCurva(catalogo(), pedido, 'IV')).toEqual({ filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio clínico, Estadio IV' });
|
||||
expect(seleccionDeCurva(catalogo(), pedido, 'XX')).toBeUndefined();
|
||||
});
|
||||
it('una celda lleva sus dos valores, y una celda gris nada', () => {
|
||||
// Fails if a click on a suppressed cell could open the patients the answer hid.
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B5', '40-49'], z: 90 }] })).toEqual({ fila: 'B5', columna: '40-49' });
|
||||
expect(celdaDelClic({ points: [{ customdata: ['B4A', '40-49'], z: null }] })).toBeUndefined();
|
||||
expect(seleccionDeCelda(catalogo(), subgrupos(), { fila: 'B5', columna: '40-49' }))
|
||||
.toEqual({ filtros: { birads: 'B5', grupo_edad: '40-49' }, etiqueta: 'Cáncer confirmado: BI-RADS 5 y 40-49 años' });
|
||||
});
|
||||
it('cada etapa abre con su primera variable y su primer cruce, y conserva un cruce que le pertenece', () => {
|
||||
// Fails if a stage keeps another stage's variable or an estimator it does not admit.
|
||||
expect(pedidoDeEtapa(catalogo(), 'supervivencia', { escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', grupos: ['B5', 'B6'], filtros: {} }))
|
||||
.toEqual({ escenario: 'supervivencia', estimador: 'km', estrato: 'estadio', grupos: [], filtros: {} });
|
||||
const [desarrollo, supervivencia] = catalogo().etapas;
|
||||
expect(cruceDeEtapa(desarrollo, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'brca', columnas: 'birads' });
|
||||
expect(cruceDeEtapa(supervivencia, { filas: 'brca', columnas: 'birads' })).toEqual({ filas: 'estadio', columnas: 'grupo_edad' });
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { readonly plotClick = output<unknown>(); }
|
||||
|
||||
describe('Pestaña Análisis', () => {
|
||||
describe('Pestaña Análisis epidemiológico', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
@@ -167,94 +191,100 @@ describe('Pestaña Análisis', () => {
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const text = () => fixture.nativeElement.textContent as string;
|
||||
const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); http.expectOne('/cama/analisis').flush(catalogo()); fixture.detectChanges(); };
|
||||
const curvas = () => http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
const abrir = () => {
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis').flush(catalogo()); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis/indicadores').flush(indicadores());
|
||||
};
|
||||
|
||||
it('no pide nada hasta abrirse y luego pide el primer escenario con Aalen-Johansen y BI-RADS', () => {
|
||||
// Fails if the tab loads while hidden, or its first request stops being the cohort's main question.
|
||||
it('no pide nada hasta abrirse; luego los indicadores y la primera variable con todos sus valores', () => {
|
||||
// Fails if the tab loads while hidden, or its first request stops being the stage's first variable.
|
||||
fixture.detectChanges();
|
||||
http.expectNone('/cama/analisis');
|
||||
abrir();
|
||||
const req = http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
expect(['escenario', 'estimador', 'estrato'].map(k => req.request.params.get(k))).toEqual(['diagnostico', 'cif', 'birads']);
|
||||
const req = curvas();
|
||||
expect(['escenario', 'estimador', 'estrato', 'grupos'].map(k => req.request.params.get(k))).toEqual(['diagnostico', 'cif', 'birads', null]);
|
||||
req.flush(resultados()); fixture.detectChanges();
|
||||
expect(text()).toContain('Totales ocultos para no revelar un grupo suprimido');
|
||||
expect(text()).toContain('Indicadores epidemiológicos');
|
||||
expect(text()).toContain('IC 95 %: 41.6 a 49.6 %');
|
||||
expect(text()).toContain('Dato oculto por tamaño');
|
||||
expect(text()).toContain('Grupos suprimidos: BI-RADS 6');
|
||||
expect(text()).toContain('< 5');
|
||||
expect(text()).toContain('Sobrevida por etapa clínica');
|
||||
expect(fixture.nativeElement.querySelector('tr.falla')?.textContent).toContain('No cumple');
|
||||
});
|
||||
it('filtrar la dimensión estratificada mueve el estrato y nunca envía un filtro vacío', () => {
|
||||
// Fails if a filter reaches the query empty, or the request stratifies by a dimension filtered to one value.
|
||||
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
|
||||
fixture.componentInstance.filtrar('birads', 'B5');
|
||||
let req = http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
expect([req.request.params.get('birads'), req.request.params.get('estrato')]).toEqual(['B5', 'grupo_edad']);
|
||||
req.flush(resultados());
|
||||
fixture.componentInstance.filtrar('birads', '');
|
||||
req = http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
expect(req.request.params.has('birads')).toBe(false);
|
||||
req.flush(resultados());
|
||||
it('compara dos o más grupos: con uno avisa y no consulta; con todos no los nombra', () => {
|
||||
// Fails if a single group is sent for a log-rank, or a full selection is sent as a list.
|
||||
abrir(); curvas().flush(resultados());
|
||||
const tab = fixture.componentInstance;
|
||||
tab.elegirGrupos(['B5']); fixture.detectChanges();
|
||||
http.expectNone(r => r.url === '/cama/analisis/resultados');
|
||||
expect(text()).toContain('Elija al menos dos grupos para comparar.');
|
||||
tab.elegirGrupos(['B4A', 'B5']);
|
||||
let req = curvas(); expect(req.request.params.get('grupos')).toBe('B4A,B5'); req.flush(resultados());
|
||||
tab.elegirGrupos(['B4A', 'B5', 'B6']);
|
||||
req = curvas(); expect(req.request.params.has('grupos')).toBe(false); req.flush(resultados());
|
||||
tab.estratificar('brca');
|
||||
req = curvas(); expect([req.request.params.get('estrato'), req.request.params.get('grupos')]).toEqual(['brca', null]); req.flush(resultados());
|
||||
});
|
||||
it('sin eventos suficientes explica por qué no hay razones de riesgos', () => {
|
||||
// Fails if the tab draws or hides the Cox panel silently when the answer says there are too few events.
|
||||
abrir();
|
||||
http.expectOne(r => r.url === '/cama/analisis/resultados').flush({ ...resultados(),
|
||||
efectos: { estado: 'insuficiente', motivo: '12 eventos para 4 parámetros.', metodo: 'cox', referencia: null, filas: [] } });
|
||||
fixture.detectChanges();
|
||||
expect(text()).toContain('Eventos insuficientes. 12 eventos para 4 parámetros.');
|
||||
});
|
||||
it('el explorador pide su cuadrícula solo al abrirse, y una celda abre sus curvas', () => {
|
||||
// Fails if the grid loads with the tab, is asked for again without a change of scenario, or a cell keeps a stratum.
|
||||
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
|
||||
it('el mapa de calor se pide al abrir su parte, con filas y columnas distintas que se eligen por separado', () => {
|
||||
// Fails if the grid loads with the tab, repeats a request without a change, or accepts the same variable twice.
|
||||
abrir(); curvas().flush(resultados());
|
||||
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
const req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||
expect([req.request.params.get('escenario'), req.request.params.get('estimador')]).toEqual(['diagnostico', 'cif']);
|
||||
const tab = fixture.componentInstance;
|
||||
tab.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
let req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'grupo_edad']);
|
||||
req.flush(subgrupos()); fixture.detectChanges();
|
||||
fixture.componentInstance.elegirVista('diagnostico'); fixture.detectChanges();
|
||||
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
expect(text()).toContain('Estratificado por la otra');
|
||||
tab.cruzar({ columnas: 'birads' }); fixture.detectChanges();
|
||||
http.expectNone(r => r.url === '/cama/analisis/subgrupos');
|
||||
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] }); fixture.detectChanges();
|
||||
const curvas = http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
expect(['estrato', 'birads', 'grupo_edad'].map(k => curvas.request.params.get(k))).toEqual(['ninguno', 'B5', '50-59']);
|
||||
curvas.flush(resultados()); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('curvas');
|
||||
expect(text()).toContain('BI-RADS 5, 50-59 años');
|
||||
tab.cruzar({ columnas: 'brca' }); fixture.detectChanges();
|
||||
req = http.expectOne(r => r.url === '/cama/analisis/subgrupos');
|
||||
expect(['filas', 'columnas'].map(k => req.request.params.get(k))).toEqual(['birads', 'brca']);
|
||||
req.flush(subgrupos());
|
||||
});
|
||||
it('el diagnóstico muestra el estado de la cohorte, la validación y lo bloqueado', () => {
|
||||
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
|
||||
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados()); fixture.detectChanges();
|
||||
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
|
||||
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
||||
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
|
||||
// The NOM variables of the stage, and whether the schema records them.
|
||||
expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
|
||||
expect(diagnostico.textContent).toContain('Sobrevida por etapa clínica');
|
||||
it('una curva, su botón de la tabla o una celda emiten la selección para Seguimiento', () => {
|
||||
// Fails if a click stops reaching Seguimiento, or sends a selection without the scenario's population.
|
||||
const emitidas: SeleccionPacientes[] = [];
|
||||
fixture.componentInstance.verPacientes.subscribe(s => emitidas.push(s));
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
fixture.componentInstance.clicCurva({ points: [{ data: { meta: 'B5' } }] });
|
||||
(fixture.nativeElement.querySelector('.riesgo .ver') as HTMLButtonElement).click();
|
||||
fixture.componentInstance.elegirVista('subgrupos'); fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cama/analisis/subgrupos').flush(subgrupos()); fixture.detectChanges();
|
||||
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B5', '50-59'], z: 92 }] });
|
||||
fixture.componentInstance.clicCelda({ points: [{ customdata: ['B4A', '40-49'], z: null }] });
|
||||
expect(emitidas.map(e => e.filtros)).toEqual([{ birads: 'B5' }, { birads: 'B4A' }, { birads: 'B5', grupo_edad: '50-59' }]);
|
||||
});
|
||||
it('las flechas mueven entre las tres partes', () => {
|
||||
// Fails if the parts stop behaving as a keyboard tab list.
|
||||
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados()); fixture.detectChanges();
|
||||
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('curvas');
|
||||
});
|
||||
it('cambiar de etapa pide su primer escenario, estimador y variable, y anuncia lo supuesto', () => {
|
||||
// Fails if a stage keeps another stage's stratum or an estimator it does not admit, or hides its assumptions.
|
||||
abrir(); http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
|
||||
fixture.componentInstance.filtrar('birads', 'B5');
|
||||
http.expectOne(r => r.url === '/cama/analisis/resultados').flush(resultados());
|
||||
it('cambiar de etapa pide su primera variable y anuncia lo supuesto', () => {
|
||||
// Fails if a stage keeps another stage's variable or an estimator it does not admit, or hides its assumptions.
|
||||
abrir(); curvas().flush(resultados());
|
||||
fixture.componentInstance.elegirEtapa('supervivencia'); fixture.detectChanges();
|
||||
const req = http.expectOne(r => r.url === '/cama/analisis/resultados');
|
||||
expect(['escenario', 'estimador', 'estrato', 'birads'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'etapa_clinica', null]);
|
||||
req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'etapa_clinica',
|
||||
const req = curvas();
|
||||
expect(['escenario', 'estimador', 'estrato'].map(k => req.request.params.get(k))).toEqual(['supervivencia', 'km', 'estadio']);
|
||||
req.flush({ ...resultados(), etapa: 'supervivencia', medida: 'supervivencia', escenario: 'supervivencia', estimador: 'km', estrato: 'estadio',
|
||||
supuestos: ['Estado vital supuesto.'] });
|
||||
fixture.detectChanges();
|
||||
expect(text()).toContain('¿Quién sigue viva?');
|
||||
expect(fixture.nativeElement.querySelector('.supuestos')?.textContent).toContain('Estado vital supuesto.');
|
||||
expect(fixture.nativeElement.querySelector('#analisis-curvas h2')?.textContent).toContain('Supervivencia a 24 meses');
|
||||
expect(fixture.componentInstance.estratosEtapa().map(e => e.estado)).toEqual([null, 'supuesto', 'registrado']);
|
||||
});
|
||||
it('el diagnóstico muestra el estado de la cohorte, la validación y las variables de la NOM', () => {
|
||||
// Fails if the cohort's status loses a figure, or a hidden total is shown as a number.
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
const diagnostico = fixture.nativeElement.querySelector('#analisis-diagnostico') as HTMLElement;
|
||||
expect(diagnostico.querySelectorAll('.dato')).toHaveLength(5);
|
||||
expect(diagnostico.querySelector('.dato .cifra')?.textContent).toBe('Oculto');
|
||||
expect(diagnostico.querySelector('.requeridas')?.textContent).toContain('Categoría BI-RADS');
|
||||
expect(diagnostico.querySelector('tr.falla')?.textContent).toContain('No cumple');
|
||||
});
|
||||
it('las flechas mueven entre las tres partes', () => {
|
||||
// Fails if the parts stop behaving as a keyboard tab list.
|
||||
abrir(); curvas().flush(resultados()); fixture.detectChanges();
|
||||
const lista = fixture.nativeElement.querySelector('.subsecciones') as HTMLElement;
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'End' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('diagnostico');
|
||||
lista.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' })); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.vista()).toBe('curvas');
|
||||
});
|
||||
it('sin análisis publicado queda pendiente', () => {
|
||||
// Fails if a 404 on the catalog is shown as an error instead of a feature not yet published.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core';
|
||||
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -6,10 +6,14 @@ import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { catchError, map, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { curvasFigura, forestFigura, mesesDe, nombreMedida, subgruposFigura } from './indicadores-analisis-figuras';
|
||||
import { AnalisisCatalogo, AnalisisEtapa, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable } from './indicadores-analisis.service';
|
||||
import {
|
||||
AnalisisCatalogo, AnalisisEtapa, AnalisisIndicadores, AnalisisPedido, AnalisisResultados, AnalisisService, AnalisisSubgrupos, AnalisisVariable,
|
||||
IndicadorEpidemiologico, PedidoSubgrupos,
|
||||
} from './indicadores-analisis.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Dominio, Tema } from './indicadores.models';
|
||||
|
||||
@@ -19,53 +23,68 @@ export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '<
|
||||
export type VistaAnalisis = 'curvas' | 'subgrupos' | 'diagnostico';
|
||||
export const VISTAS: readonly { id: VistaAnalisis; etiqueta: string }[] = [
|
||||
{ id: 'curvas', etiqueta: 'Curvas (Kaplan-Meier)' },
|
||||
{ id: 'subgrupos', etiqueta: 'Explorador de subgrupos' },
|
||||
{ id: 'subgrupos', etiqueta: 'Mapa de calor entre variables' },
|
||||
{ id: 'diagnostico', etiqueta: 'Diagnóstico de la cohorte' },
|
||||
];
|
||||
// The patients behind a curve or a heatmap cell: the follow-up list's filters and how to name the selection.
|
||||
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; }
|
||||
|
||||
/** The cell of the subgroup grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
|
||||
/** The cell of the grid: its row and column codes, from the coloured layer only (grey cells are suppressed). */
|
||||
export function celdaDelClic(evento: unknown): { fila: string; columna: string } | undefined {
|
||||
const punto = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
|
||||
const c = punto?.customdata;
|
||||
return Array.isArray(c) && typeof c[0] === 'string' && typeof c[1] === 'string' && typeof punto?.z === 'number' ? { fila: c[0], columna: c[1] } : undefined;
|
||||
}
|
||||
|
||||
/** The stage a scenario belongs to. */
|
||||
export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
|
||||
catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
|
||||
|
||||
/** The request a stage opens with: its first scenario and variable, the current estimator if the stage admits it, no filters. */
|
||||
export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
|
||||
const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
|
||||
const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
|
||||
return { escenario: etapa.escenarios[0], estimador, estrato: etapa.estratos[0], filtros: {} };
|
||||
}
|
||||
|
||||
/** The group of the clicked curve, from the line's `meta`; bands and empty clicks give nothing. */
|
||||
export function grupoDelClic(evento: unknown): string | undefined {
|
||||
const punto = (evento as { points?: { data?: { meta?: unknown } }[] } | undefined)?.points?.[0];
|
||||
return typeof punto?.data?.meta === 'string' ? punto.data.meta : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicking a group's curve keeps only that group and stratifies by the other dimension, like the donut's drill-down.
|
||||
* It only changes the request: the server answers with new aggregates.
|
||||
*/
|
||||
export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo: AnalisisCatalogo): AnalisisPedido {
|
||||
const dimensiones: readonly string[] = etapaDe(catalogo, pedido.escenario)?.estratos ?? [];
|
||||
if (!dimensiones.includes(pedido.estrato)) return pedido;
|
||||
const filtros = { ...pedido.filtros, [pedido.estrato]: grupo };
|
||||
return { ...pedido, filtros, estrato: dimensiones.find(d => !filtros[d]) ?? 'ninguno' };
|
||||
/** The stage a scenario belongs to. */
|
||||
export const etapaDe = (catalogo: AnalisisCatalogo, escenario: string | undefined): AnalisisEtapa | undefined =>
|
||||
catalogo.etapas.find(e => e.escenarios.includes(escenario ?? ''));
|
||||
|
||||
/** The request a stage opens with: its first scenario and variable, all its values, the estimator if the stage admits it. */
|
||||
export function pedidoDeEtapa(catalogo: AnalisisCatalogo, clave: string, actual?: AnalisisPedido): AnalisisPedido {
|
||||
const etapa = catalogo.etapas.find(e => e.clave === clave) ?? catalogo.etapas[0];
|
||||
const estimador = actual && etapa.estimadores.includes(actual.estimador) ? actual.estimador : etapa.estimadores[0];
|
||||
return { escenario: etapa.escenarios[0], estimador, estrato: etapa.variables[0], grupos: [], filtros: {} };
|
||||
}
|
||||
|
||||
// Exploratory outcomes of the BI-RADS 4+ cohort by stage (development, recurrence, survival), in three parts under
|
||||
// one set of controls: the curves (the stage's measure by one of its two variables and the tests that compare the
|
||||
// groups), a subgroup explorer (the grid of the stage's two variables and the hazard ratios) and the cohort's
|
||||
// diagnostics (its statistical status, the checks behind every figure and the NOM variables the stage needs).
|
||||
/** The grid a stage opens with: its first two variables, or the current ones while they belong to it. */
|
||||
export function cruceDeEtapa(etapa: AnalisisEtapa, actual?: { filas: string; columnas: string }) {
|
||||
const valido = actual && actual.filas !== actual.columnas && etapa.variables.includes(actual.filas) && etapa.variables.includes(actual.columnas);
|
||||
return valido ? { filas: actual.filas, columnas: actual.columnas } : { filas: etapa.variables[0], columnas: etapa.variables[1] };
|
||||
}
|
||||
|
||||
/** The follow-up filters of a curve: the scenario's population and the group's value of the compared variable. */
|
||||
export function seleccionDeCurva(catalogo: AnalisisCatalogo, pedido: AnalisisPedido, grupo: string): SeleccionPacientes | undefined {
|
||||
const escenario = catalogo.escenarios.find(e => e.clave === pedido.escenario), variable = catalogo.variables.find(v => v.clave === pedido.estrato);
|
||||
if (!escenario || !variable) return undefined;
|
||||
const valor = variable.opciones.find(o => o.codigo === grupo);
|
||||
if (!valor) return undefined;
|
||||
return { filtros: { ...escenario.filtro_seguimiento, [variable.clave]: grupo }, etiqueta: `${escenario.etiqueta}: ${variable.etiqueta}, ${valor.etiqueta}` };
|
||||
}
|
||||
|
||||
/** The follow-up filters of a grid cell: the scenario's population and both values. */
|
||||
export function seleccionDeCelda(catalogo: AnalisisCatalogo, sub: AnalisisSubgrupos, celda: { fila: string; columna: string }): SeleccionPacientes | undefined {
|
||||
const escenario = catalogo.escenarios.find(e => e.clave === sub.escenario);
|
||||
const fila = sub.filas.find(f => f.codigo === celda.fila), columna = sub.columnas.find(c => c.codigo === celda.columna);
|
||||
if (!escenario || !fila || !columna) return undefined;
|
||||
return { filtros: { ...escenario.filtro_seguimiento, [sub.dimension_filas.clave]: celda.fila, [sub.dimension_columnas.clave]: celda.columna },
|
||||
etiqueta: `${escenario.etiqueta}: ${fila.etiqueta} y ${columna.etiqueta}` };
|
||||
}
|
||||
|
||||
// Epidemiological analysis of the BI-RADS 4+ cohort. On top, the cohort's figures (incidence of cancer and of
|
||||
// recurrence, follow-up adherence and survival). Then, by stage (development, recurrence, survival), three parts:
|
||||
// the Kaplan-Meier curves of two or more values of one variable, the heatmap of two distinct variables, and the
|
||||
// cohort's diagnostics. A curve or a cell opens its patients in Seguimiento; nothing else leaves the aggregates.
|
||||
// Nothing is requested until the tab is first opened, and the grid only once its part is.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorKpiCard],
|
||||
template: `
|
||||
@switch (catalogo().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando el análisis" /> }
|
||||
@@ -73,6 +92,23 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
@case ('error') { <div role="alert" class="panel"><p>{{ $any(catalogo()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentarCatalogo()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (cat(); as c) {
|
||||
<section class="epidemiologicos" aria-labelledby="indicadores-epidemiologicos">
|
||||
<h2 id="indicadores-epidemiologicos">Indicadores epidemiológicos</h2>
|
||||
<p class="nota">De toda la cohorte, a {{ meses(c.horizonte_dias) }} meses. Descriptivos, no causales.</p>
|
||||
@switch (indicadores().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores epidemiológicos" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(indicadores()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarIndicadores()">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (ind(); as i) {
|
||||
<div class="kpis">
|
||||
@for (x of i.indicadores; track x.clave) {
|
||||
<app-indicador-kpi-card [title]="x.titulo" [value]="x.valor === null ? null : x.valor.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 })"
|
||||
[unit]="x.unidad" [state]="x.suprimido ? 'Dato oculto por tamaño' : 'Disponible'" [quietWhenAvailable]="true" [additionalInfo]="infoIndicador(x)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<div class="controles">
|
||||
<span id="analisis-etapa" class="etiqueta">Etapa</span>
|
||||
<mat-button-toggle-group class="etapas" aria-labelledby="analisis-etapa" hideSingleSelectionIndicator [value]="etapa()?.clave" (change)="elegirEtapa($event.value)">
|
||||
@@ -92,26 +128,6 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
@for (e of estimadoresEtapa(); track e.clave) { <mat-button-toggle [value]="e.clave" [attr.title]="e.nota">{{ e.clave === 'cif' ? 'Aalen-Johansen' : '1 − Kaplan-Meier' }}</mat-button-toggle> }
|
||||
</mat-button-toggle-group>
|
||||
} @else { <span class="etiqueta">Kaplan-Meier</span> }
|
||||
@if (vista() !== 'subgrupos') {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Estratificar por</mat-label>
|
||||
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
||||
@for (e of estratosEtapa(); track e.clave) {
|
||||
<mat-option [value]="e.clave">{{ e.etiqueta }}@if (e.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@for (f of variablesEtapa(); track f.clave) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>{{ f.etiqueta }}</mat-label>
|
||||
<mat-select [value]="pedido()!.filtros[f.clave] ?? ''" (selectionChange)="filtrar(f.clave, $event.value)">
|
||||
<mat-option value="">Todos</mat-option>
|
||||
@for (o of f.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (hayFiltros()) { <button type="button" mat-stroked-button (click)="limpiar()">Quitar filtros</button> }
|
||||
}
|
||||
</div>
|
||||
@if (escenario(); as e) {
|
||||
<p class="contexto">@if (etapa(); as et) { <strong>{{ et.pregunta }}</strong><br> }{{ e.poblacion }}. Origen: {{ e.origen }}. Evento: {{ e.evento }}. Horizonte de {{ meses(c.horizonte_dias) }} meses; descriptivo, no causal.</p>
|
||||
@@ -124,8 +140,27 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
}
|
||||
</div>
|
||||
|
||||
<!-- Curves: the stage's measure for each group, how the groups compare, and who is still at risk. -->
|
||||
<!-- Curves: two or more values of one variable, compared by log-rank and Cox. -->
|
||||
<section id="analisis-curvas" role="tabpanel" aria-labelledby="analisis-tab-curvas" [hidden]="vista() !== 'curvas'">
|
||||
<div class="controles-panel">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Comparar por</mat-label>
|
||||
<mat-select [value]="pedido()!.estrato" (selectionChange)="estratificar($event.value)">
|
||||
@for (v of variablesEtapa(); track v.clave) {
|
||||
<mat-option [value]="v.clave">{{ v.etiqueta }}@if (v.estado === 'supuesto') { <span class="motivo"> · supuesto</span> }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (variableCurvas(); as v) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Grupos a comparar</mat-label>
|
||||
<mat-select multiple [value]="gruposMostrados()" (selectionChange)="elegirGrupos($event.value)">
|
||||
@for (o of v.opciones; track o.codigo) { <mat-option [value]="o.codigo">{{ o.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
}
|
||||
@if (pocosGrupos()) { <span class="aviso-grupos" role="alert">Elija al menos dos grupos para comparar.</span> }
|
||||
</div>
|
||||
@switch (resultados().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el análisis" /> }
|
||||
@case ('error') { <div role="alert" class="panel"><p>{{ $any(resultados()).mensaje }}</p><button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div> }
|
||||
@@ -134,7 +169,6 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
<p class="resumen" role="status">
|
||||
@if (r.poblacion.n !== null) { {{ miles(r.poblacion.n) }} pacientes · {{ miles(r.poblacion.eventos ?? 0) }} eventos }
|
||||
@else if (r.poblacion.totales_ocultos) { Totales ocultos para no revelar un grupo suprimido }
|
||||
@if (hayFiltros()) { · {{ textoFiltros() }} }
|
||||
</p>
|
||||
@if (r.supuestos.length) {
|
||||
<div class="supuestos" role="note"><strong>Datos supuestos en el mock.</strong>
|
||||
@@ -142,84 +176,105 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
}
|
||||
<div class="paneles">
|
||||
<article class="panel ancho">
|
||||
<h2>{{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses</h2>
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. @if (puedeElegir()) { Haga clic en una curva para analizar solo ese grupo. }</p>
|
||||
<h2>{{ nombreMedida() }} a {{ meses(r.horizonte_dias) }} meses por {{ variableCurvas()?.etiqueta?.toLowerCase() }}</h2>
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una curva para ver sus pacientes en Seguimiento.</p>
|
||||
@if (figuraCurvas().data.length) {
|
||||
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
||||
[label]="nombreMedida() + ' por ' + (estratoElegido()?.etiqueta ?? 'grupo')" />
|
||||
[label]="nombreMedida() + ' por ' + (variableCurvas()?.etiqueta ?? 'grupo')" />
|
||||
<table class="riesgo">
|
||||
<caption>Pacientes en riesgo</caption>
|
||||
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }</tr></thead>
|
||||
<thead><tr><th scope="col">Grupo</th>@for (d of r.tabla_riesgo.cortes_dias; track d) { <th scope="col">Mes {{ meses(d) }}</th> }<th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<tbody>
|
||||
@for (f of r.tabla_riesgo.filas; track f.grupo) {
|
||||
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }</tr>
|
||||
<tr><th scope="row">{{ etiqueta(f.grupo) }}</th>@for (v of f.cortes; track $index) { <td>{{ v === null ? '< ' + r.umbral_supresion : miles(v) }}</td> }
|
||||
<td><button type="button" class="ver" (click)="verGrupo(f.grupo)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(f.grupo) + ' en Seguimiento'">Ver pacientes</button></td></tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.</p> }
|
||||
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con esta selección.</p> }
|
||||
@if (suprimidos().length) { <p class="nota">Grupos suprimidos: {{ textoSuprimidos() }}.</p> }
|
||||
<p class="nota">La curva termina donde quedan menos de {{ r.umbral_supresion }} pacientes en riesgo. La banda es el intervalo de confianza al 95 %.</p>
|
||||
@for (a of r.avisos.slice(2); track a) { <p class="nota">{{ a }}</p> }
|
||||
</article>
|
||||
|
||||
<article class="panel ancho">
|
||||
<article class="panel">
|
||||
<h2>Comparación entre grupos</h2>
|
||||
<div class="comparacion">
|
||||
<div>
|
||||
@if (r.pruebas.logrank; as lr) {
|
||||
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
|
||||
@if (r.pruebas.pares.length > 1) {
|
||||
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
|
||||
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
|
||||
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
}
|
||||
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
|
||||
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
|
||||
</div>
|
||||
@if (r.pruebas.rmst.length) {
|
||||
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
|
||||
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
|
||||
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
|
||||
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
|
||||
}</tbody>
|
||||
@if (r.pruebas.logrank; as lr) {
|
||||
<p>Log-rank: χ² = {{ lr.chi2.toLocaleString('es-MX') }}, {{ lr.gl }} gl, p {{ formatoP(lr.p) }}.</p>
|
||||
@if (r.pruebas.pares.length > 1) {
|
||||
<table><caption>Comparaciones por pares (corrección de Holm)</caption>
|
||||
<thead><tr><th scope="col">Grupos</th><th scope="col">p</th><th scope="col">p ajustada</th></tr></thead>
|
||||
<tbody>@for (par of r.pruebas.pares; track par.a + par.b) { <tr><td>{{ etiqueta(par.a) }} y {{ etiqueta(par.b) }}</td><td>{{ formatoP(par.p) }}</td><td>{{ formatoP(par.p_holm) }}</td></tr> }</tbody>
|
||||
</table>
|
||||
}
|
||||
</div>
|
||||
} @else { <p role="status">Se necesitan al menos dos grupos publicados para comparar.</p> }
|
||||
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
|
||||
@if (r.pruebas.rmst.length) {
|
||||
<table><caption>Tiempo medio libre de evento a {{ meses(r.horizonte_dias) }} meses (RMST)</caption>
|
||||
<thead><tr><th scope="col">Grupo</th><th scope="col">Días</th><th scope="col">Diferencia (IC 95 %)</th></tr></thead>
|
||||
<tbody>@for (f of r.pruebas.rmst; track f.grupo) {
|
||||
<tr><td>{{ etiqueta(f.grupo) }}</td><td>{{ f.rmst.toLocaleString('es-MX') }}</td>
|
||||
<td>{{ f.dif === null ? 'referencia' : f.dif.toLocaleString('es-MX') + ' (' + f.ic_bajo!.toLocaleString('es-MX') + ' a ' + f.ic_alto!.toLocaleString('es-MX') + ')' }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
}
|
||||
</article>
|
||||
|
||||
<article class="panel">
|
||||
<h2>Razón de riesgos (Cox)</h2>
|
||||
@if (r.efectos.estado === 'listo') {
|
||||
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
|
||||
<p class="nota">Modelo de Cox de una variable ({{ variableCurvas()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
|
||||
} @else {
|
||||
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
||||
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
<!-- Subgroups: every BI-RADS and age-group cell at once, and the hazard ratios of the chosen stratum. -->
|
||||
<!-- Heatmap: two distinct variables of the stage, each tested plain and at equal value of the other. -->
|
||||
<section id="analisis-subgrupos" role="tabpanel" aria-labelledby="analisis-tab-subgrupos" [hidden]="vista() !== 'subgrupos'">
|
||||
@if (cruce(); as x) {
|
||||
<div class="controles-panel">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Filas</mat-label>
|
||||
<mat-select [value]="x.filas" (selectionChange)="cruzar({ filas: $event.value })">
|
||||
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.columnas">{{ v.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Columnas</mat-label>
|
||||
<mat-select [value]="x.columnas" (selectionChange)="cruzar({ columnas: $event.value })">
|
||||
@for (v of variablesEtapa(); track v.clave) { <mat-option [value]="v.clave" [disabled]="v.clave === x.filas">{{ v.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
}
|
||||
<div class="paneles">
|
||||
<article class="panel ancho">
|
||||
<h2>{{ nombreMedida() }} a {{ meses(c.horizonte_dias) }} meses@if (sub(); as s) { por {{ s.dimension_filas.etiqueta.toLowerCase() }} y {{ s.dimension_columnas.etiqueta.toLowerCase() }} }</h2>
|
||||
@switch (subgrupos().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los subgrupos" /> }
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa de calor" /> }
|
||||
@case ('error') { <div role="alert"><p>{{ $any(subgrupos()).mensaje }}</p><button type="button" mat-stroked-button (click)="cargarSubgrupos(true)">Reintentar consulta</button></div> }
|
||||
}
|
||||
@if (sub(); as s) {
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus curvas.</p>
|
||||
<p class="nota">{{ estimadorElegido()?.etiqueta }}. Haga clic en una celda para ver sus pacientes en Seguimiento.</p>
|
||||
@if (s.supuestos.length) { <p class="nota">Supuesto en el mock: {{ s.supuestos.join(' ') }}</p> }
|
||||
<app-plotly-chart [style.--plot-height]="figuraSubgrupos().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraSubgrupos()" (plotClick)="clicCelda($event)"
|
||||
[label]="nombreMedida() + ' por ' + s.dimension_filas.etiqueta + ' y ' + s.dimension_columnas.etiqueta" />
|
||||
<p class="nota">Cada celda dice el porcentaje, los eventos y las pacientes. Una celda gris tiene menos de {{ s.umbral_supresion }} pacientes o eventos. «A N meses» marca una celda cuya curva termina antes del horizonte.</p>
|
||||
}
|
||||
</article>
|
||||
<article class="panel ancho">
|
||||
<h2>Razón de riesgos (Cox)</h2>
|
||||
@if (res(); as r) {
|
||||
@if (r.efectos.estado === 'listo') {
|
||||
<app-plotly-chart [style.--plot-height]="figuraForest().layout['height'] + 'px'" [showNotes]="false" [figure]="figuraForest()" label="Razones de riesgos con intervalo al 95 %" />
|
||||
<p class="nota">Modelo de Cox de una variable ({{ estratoElegido()?.etiqueta?.toLowerCase() }}), contra {{ r.efectos.etiqueta_referencia }}. Un cuadro vacío marca riesgos no proporcionales. Describe diferencias; no estima un efecto causal.</p>
|
||||
} @else {
|
||||
<p role="status" class="estado-modelo" [class.insuficiente]="r.efectos.estado === 'insuficiente'">
|
||||
{{ r.efectos.estado === 'insuficiente' ? 'Eventos insuficientes.' : 'No aplica.' }} {{ r.efectos.motivo }}</p>
|
||||
}
|
||||
<p class="nota">El estrato y los filtros se eligen en Curvas.</p>
|
||||
<table>
|
||||
<caption>Log-rank de cada variable</caption>
|
||||
<thead><tr><th scope="col">Variable</th><th scope="col">Log-rank</th><th scope="col">Estratificado por la otra</th></tr></thead>
|
||||
<tbody>@for (pr of s.pruebas; track pr.variable) {
|
||||
<tr><td>{{ pr.etiqueta }}</td>
|
||||
<td>{{ pr.logrank ? 'χ² ' + pr.logrank.chi2.toLocaleString('es-MX') + ', ' + pr.logrank.gl + ' gl, p ' + formatoP(pr.logrank.p) : 'Menos de dos grupos con eventos suficientes' }}</td>
|
||||
<td>{{ pr.estratificado ? 'p ' + formatoP(pr.estratificado.p) + ' (por ' + pr.etiqueta_estrato.toLowerCase() + ')' : '—' }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
<p class="nota">El log-rank estratificado compara los grupos de una variable dentro de cada valor de la otra: si la diferencia desaparece, la explicaba la otra variable.</p>
|
||||
}
|
||||
</article>
|
||||
</div>
|
||||
@@ -238,7 +293,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
@if (r.poblacion.totales_ocultos) { <p class="nota">Los totales se ocultan porque un grupo está suprimido y se podría deducir.</p> }
|
||||
<article class="panel">
|
||||
<h2>Reporte de validación</h2>
|
||||
<p class="nota">De {{ escenario()?.etiqueta?.toLowerCase() }}, {{ estratoElegido()?.etiqueta?.toLowerCase() }}@if (hayFiltros()) {, {{ textoFiltros() }}}.</p>
|
||||
<p class="nota">De las curvas: {{ escenario()?.etiqueta?.toLowerCase() }}, por {{ variableCurvas()?.etiqueta?.toLowerCase() }}.</p>
|
||||
<table class="validacion">
|
||||
<thead><tr><th scope="col">Chequeo</th><th scope="col">Alcance</th><th scope="col">Valor</th><th scope="col">Umbral</th><th scope="col">Resultado</th><th scope="col">Nota</th></tr></thead>
|
||||
<tbody>@for (v of r.validacion; track $index) {
|
||||
@@ -257,7 +312,7 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
@if (etapa(); as et) {
|
||||
<article class="panel requeridas">
|
||||
<h2>Variables de la NOM para la etapa de {{ et.etiqueta.toLowerCase() }}</h2>
|
||||
<p class="nota">Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las dos en uso:
|
||||
<p class="nota">Lo que hay que registrar para estratificar estas curvas, ajustar Cox y aplicar el log-rank. Las de esta etapa:
|
||||
@for (v of variablesEtapa(); track v.clave) { {{ v.etiqueta }} ({{ v.estado === 'registrado' ? 'registrada' : 'supuesta' }}){{ $last ? '.' : ';' }} }</p>
|
||||
<table>
|
||||
<thead><tr><th scope="col">Variable</th><th scope="col">NOM</th><th scope="col">En el esquema</th></tr></thead>
|
||||
@@ -304,6 +359,14 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
.tarjetas { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.bloqueado { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); background: transparent; }
|
||||
.bloqueado h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||
.epidemiologicos { margin-bottom: var(--issste-space-6); }
|
||||
.epidemiologicos .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); grid-auto-rows: 1fr; gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
.controles-panel { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
|
||||
.controles-panel mat-form-field { min-width: 14rem; }
|
||||
.ver { padding: 0; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
|
||||
.ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||
.aviso-grupos { color: var(--issste-text); font-weight: 600; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
.subsecciones { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin: var(--issste-space-4) 0; border-bottom: 1px solid var(--issste-border); }
|
||||
.subsecciones button { padding: var(--issste-space-2) var(--issste-space-4); border: 0; border-bottom: 3px solid transparent; background: none; color: var(--issste-text-secondary);
|
||||
font: var(--mat-sys-title-small); cursor: pointer; min-height: 44px; }
|
||||
@@ -322,80 +385,79 @@ export function pedidoAlElegir(pedido: AnalisisPedido, grupo: string, catalogo:
|
||||
.dato .cifra { color: var(--issste-text); font-size: 1.5rem; font-weight: 500; line-height: 1.2; }
|
||||
@media (max-width: 600px) { .controles { padding: var(--issste-space-3); } .controles mat-form-field, .controles mat-form-field:first-child { min-width: 100%; } }
|
||||
`,
|
||||
|
||||
})
|
||||
export class IndicadoresAnalisis {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The patients of a curve or a heatmap cell, for the page to open them in Seguimiento.
|
||||
readonly verPacientes = output<SeleccionPacientes>();
|
||||
readonly formatoP = formatoP;
|
||||
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
||||
readonly meses = mesesDe;
|
||||
readonly VISTAS = VISTAS;
|
||||
private readonly service = inject(AnalisisService);
|
||||
readonly catalogo = signal<Carga<AnalisisCatalogo>>({ estado: 'cargando' });
|
||||
readonly resultados = signal<Carga<AnalisisResultados>>({ estado: 'cargando' });
|
||||
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
||||
readonly indicadores = signal<Carga<AnalisisIndicadores>>({ estado: 'cargando' });
|
||||
readonly pedido = signal<AnalisisPedido | undefined>(undefined);
|
||||
readonly cruce = signal<{ filas: string; columnas: string } | undefined>(undefined);
|
||||
readonly vista = signal<VistaAnalisis>('curvas');
|
||||
readonly pocosGrupos = signal(false);
|
||||
private readonly pedidos = new Subject<AnalisisPedido>();
|
||||
private readonly pedidosSubgrupos = new Subject<PedidoSubgrupos>();
|
||||
private readonly catalogos = new Subject<void>();
|
||||
private readonly pedidosIndicadores = new Subject<void>();
|
||||
private abierto = false;
|
||||
private subgruposDe?: string;
|
||||
|
||||
readonly cat = computed(() => { const c = this.catalogo(); return c.estado === 'listo' ? c.datos : undefined; });
|
||||
readonly res = computed(() => { const r = this.resultados(); return r.estado === 'listo' ? r.datos : undefined; });
|
||||
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
|
||||
readonly ind = computed(() => { const i = this.indicadores(); return i.estado === 'listo' ? i.datos : undefined; });
|
||||
readonly escenario = computed(() => this.cat()?.escenarios.find(e => e.clave === this.pedido()?.escenario));
|
||||
readonly estimadorElegido = computed(() => this.cat()?.estimadores.find(e => e.clave === this.pedido()?.estimador));
|
||||
readonly etapa = computed(() => { const c = this.cat(); return c ? etapaDe(c, this.pedido()?.escenario) : undefined; });
|
||||
readonly nombreMedida = computed(() => nombreMedida(this.etapa()?.medida ?? 'incidencia'));
|
||||
private variable(clave: string): AnalisisVariable | undefined { return this.cat()?.variables.find(v => v.clave === clave); }
|
||||
// The stage's two variables, each with its source; the stratum adds «Sin estratificar».
|
||||
readonly variablesEtapa = computed(() => (this.etapa()?.estratos ?? [] as readonly string[]).map(k => this.variable(k)).filter((v): v is AnalisisVariable => !!v));
|
||||
readonly estratosEtapa = computed(() => [{ clave: 'ninguno', etiqueta: 'Sin estratificar', estado: null as string | null },
|
||||
...this.variablesEtapa().map(v => ({ clave: v.clave, etiqueta: v.etiqueta, estado: v.estado as string | null }))]);
|
||||
readonly variablesEtapa = computed(() => (this.etapa()?.variables ?? [] as readonly string[])
|
||||
.map(k => this.cat()?.variables.find(v => v.clave === k)).filter((v): v is AnalisisVariable => !!v));
|
||||
readonly escenariosEtapa = computed(() => this.cat()?.escenarios.filter(e => this.etapa()?.escenarios.includes(e.clave)) ?? []);
|
||||
readonly estimadoresEtapa = computed(() => this.cat()?.estimadores.filter(e => this.etapa()?.estimadores.includes(e.clave)) ?? []);
|
||||
readonly estratoElegido = computed(() => this.estratosEtapa().find(e => e.clave === this.pedido()?.estrato));
|
||||
readonly hayFiltros = computed(() => Object.values(this.pedido()?.filtros ?? {}).some(Boolean));
|
||||
readonly puedeElegir = computed(() => (this.etapa()?.estratos ?? [] as readonly string[]).includes(this.pedido()?.estrato ?? '') && (this.res()?.grupos.filter(g => !g.suprimido).length ?? 0) > 1);
|
||||
readonly variableCurvas = computed(() => this.variablesEtapa().find(v => v.clave === this.pedido()?.estrato));
|
||||
// Every value when none was picked; the selector shows them checked.
|
||||
readonly gruposMostrados = computed(() => { const p = this.pedido(); return p?.grupos.length ? p.grupos : this.variableCurvas()?.opciones.map(o => o.codigo) ?? []; });
|
||||
readonly suprimidos = computed(() => this.res()?.grupos.filter(g => g.suprimido) ?? []);
|
||||
readonly textoSuprimidos = computed(() => this.suprimidos().map(g => `${g.etiqueta} (${(g.motivo ?? 'suprimido').toLowerCase()})`).join('; '));
|
||||
readonly figuraCurvas = computed(() => { const r = this.res(); return r ? curvasFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly figuraForest = computed(() => { const r = this.res(); return r ? forestFigura(r, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly VISTAS = VISTAS;
|
||||
readonly vista = signal<VistaAnalisis>('curvas');
|
||||
readonly subgrupos = signal<Carga<AnalisisSubgrupos>>({ estado: 'cargando' });
|
||||
readonly sub = computed(() => { const s = this.subgrupos(); return s.estado === 'listo' ? s.datos : undefined; });
|
||||
readonly figuraSubgrupos = computed(() => { const s = this.sub(); return s ? subgruposFigura(s, this.tema()) : { data: [], layout: {} }; });
|
||||
readonly eventosPorParametro = computed(() => {
|
||||
const fila = this.res()?.validacion.find(v => v.chequeo === 'Eventos por parámetro');
|
||||
return fila?.estadistico == null ? null : fila.estadistico.toLocaleString('es-MX');
|
||||
});
|
||||
readonly textoFiltros = computed(() => {
|
||||
const cat = this.cat(), filtros = this.pedido()?.filtros ?? {};
|
||||
return Object.entries(filtros).filter(([, v]) => v)
|
||||
.map(([k, v]) => cat?.variables.find(f => f.clave === k)?.opciones.find(o => o.codigo === v)?.etiqueta ?? v).join(', ');
|
||||
});
|
||||
private readonly pedidosSubgrupos = new Subject<{ escenario: string; estimador: string }>();
|
||||
private subgruposDe?: string;
|
||||
|
||||
constructor() {
|
||||
const destroy = inject(DestroyRef);
|
||||
this.catalogos.pipe(switchMap(() => this.service.catalogo(this.dominio()).pipe(
|
||||
map((datos): Carga<AnalisisCatalogo> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of<Carga<AnalisisCatalogo>>(error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
||||
startWith<Carga<AnalisisCatalogo>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => {
|
||||
const cargar = <T>(fuente: () => Observable<T>, pendiente = false) => fuente().pipe(
|
||||
map((datos): Carga<T> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of<Carga<T>>(pendiente && error?.status === 404 ? { estado: 'pendiente' } : { estado: 'error', mensaje: httpMessage(error) })),
|
||||
startWith<Carga<T>>({ estado: 'cargando' }));
|
||||
this.catalogos.pipe(switchMap(() => cargar(() => this.service.catalogo(this.dominio()), true)), takeUntilDestroyed(destroy)).subscribe(carga => {
|
||||
this.catalogo.set(carga);
|
||||
if (carga.estado === 'listo' && !this.pedido()) this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
|
||||
if (carga.estado === 'listo' && !this.pedido()) {
|
||||
this.cambiar(pedidoDeEtapa(carga.datos, carga.datos.etapas[0].clave));
|
||||
this.cargarIndicadores();
|
||||
}
|
||||
});
|
||||
this.pedidos.pipe(switchMap(pedido => this.service.resultados(this.dominio(), pedido).pipe(
|
||||
map((datos): Carga<AnalisisResultados> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of<Carga<AnalisisResultados>>({ estado: 'error', mensaje: httpMessage(error) })),
|
||||
startWith<Carga<AnalisisResultados>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => this.resultados.set(carga));
|
||||
this.pedidosSubgrupos.pipe(switchMap(({ escenario, estimador }) => this.service.subgrupos(this.dominio(), escenario, estimador).pipe(
|
||||
map((datos): Carga<AnalisisSubgrupos> => ({ estado: 'listo', datos })),
|
||||
catchError(error => of<Carga<AnalisisSubgrupos>>({ estado: 'error', mensaje: httpMessage(error) })),
|
||||
startWith<Carga<AnalisisSubgrupos>>({ estado: 'cargando' }))), takeUntilDestroyed(destroy)).subscribe(carga => this.subgrupos.set(carga));
|
||||
// The grid depends only on the scenario and the estimator; it is asked for when its part is open.
|
||||
this.pedidos.pipe(switchMap(p => cargar(() => this.service.resultados(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.resultados.set(c));
|
||||
this.pedidosSubgrupos.pipe(switchMap(p => cargar(() => this.service.subgrupos(this.dominio(), p))), takeUntilDestroyed(destroy)).subscribe(c => this.subgrupos.set(c));
|
||||
this.pedidosIndicadores.pipe(switchMap(() => cargar(() => this.service.indicadores(this.dominio()))), takeUntilDestroyed(destroy)).subscribe(c => this.indicadores.set(c));
|
||||
// The grid follows the stage, the scenario, the estimator and its two variables; it is asked for when its part is open.
|
||||
effect(() => {
|
||||
const vista = this.vista(), pedido = this.pedido();
|
||||
if (vista === 'subgrupos' && pedido) untracked(() => this.cargarSubgrupos());
|
||||
const vista = this.vista(), pedido = this.pedido(), cruce = this.cruce();
|
||||
if (vista === 'subgrupos' && pedido && cruce) untracked(() => this.cargarSubgrupos());
|
||||
});
|
||||
effect(() => {
|
||||
if (!this.active() || this.abierto) return;
|
||||
@@ -404,8 +466,11 @@ export class IndicadoresAnalisis {
|
||||
}
|
||||
|
||||
cambiar(cambio: Partial<AnalisisPedido>) {
|
||||
const pedido = { escenario: '', estimador: '', estrato: 'ninguno', filtros: {}, ...this.pedido(), ...cambio };
|
||||
const pedido: AnalisisPedido = { escenario: '', estimador: '', estrato: '', grupos: [], filtros: {}, ...this.pedido(), ...cambio };
|
||||
this.pedido.set(pedido);
|
||||
this.pocosGrupos.set(false);
|
||||
const etapa = this.cat() && etapaDe(this.cat()!, pedido.escenario);
|
||||
if (etapa) this.cruce.set(cruceDeEtapa(etapa, this.cruce()));
|
||||
this.pedidos.next(pedido);
|
||||
}
|
||||
// A stage keeps the estimator when it admits it, and starts from its first scenario and variable.
|
||||
@@ -413,26 +478,37 @@ export class IndicadoresAnalisis {
|
||||
const c = this.cat();
|
||||
if (c && clave !== this.etapa()?.clave) this.cambiar(pedidoDeEtapa(c, clave, this.pedido()));
|
||||
}
|
||||
estratificar(estrato: string) {
|
||||
// A stratum can't also be a single-value filter: choosing it lifts that filter.
|
||||
const { [estrato]: _, ...filtros } = this.pedido()?.filtros ?? {};
|
||||
this.cambiar({ estrato, filtros });
|
||||
estratificar(estrato: string) { this.cambiar({ estrato, grupos: [] }); }
|
||||
// Two or more values are compared; with all of them checked, the request names none.
|
||||
elegirGrupos(grupos: string[]) {
|
||||
if (grupos.length < 2) { this.pocosGrupos.set(true); return; }
|
||||
const todos = this.variableCurvas()?.opciones.length ?? 0;
|
||||
this.cambiar({ grupos: grupos.length === todos ? [] : grupos });
|
||||
}
|
||||
filtrar(clave: string, valor: string) {
|
||||
const { [clave]: _, ...resto } = this.pedido()?.filtros ?? {};
|
||||
const filtros = valor ? { ...resto, [clave]: valor } : resto;
|
||||
// Filtering the stratified dimension to one value moves the stratification to another one.
|
||||
const estrato = valor && this.pedido()?.estrato === clave
|
||||
? (this.etapa()?.estratos ?? [] as readonly string[]).find(d => !filtros[d]) ?? 'ninguno'
|
||||
: this.pedido()?.estrato;
|
||||
this.cambiar({ filtros, estrato });
|
||||
cruzar(cambio: Partial<{ filas: string; columnas: string }>) {
|
||||
const actual = this.cruce();
|
||||
if (!actual) return;
|
||||
const siguiente = { ...actual, ...cambio };
|
||||
if (siguiente.filas !== siguiente.columnas) this.cruce.set(siguiente);
|
||||
}
|
||||
infoIndicador(x: IndicadorEpidemiologico) {
|
||||
if (x.suprimido) return x.descripcion;
|
||||
const intervalo = x.ic_bajo !== null && x.ic_alto !== null ? `IC 95 %: ${x.ic_bajo.toLocaleString('es-MX')} a ${x.ic_alto.toLocaleString('es-MX')} %. ` : '';
|
||||
const conteo = x.clave === 'adherencia' ? `${this.miles(x.eventos!)} de ${this.miles(x.n!)} pacientes. ` : `${this.miles(x.eventos!)} eventos en ${this.miles(x.n!)} pacientes. `;
|
||||
return intervalo + conteo + x.descripcion + (x.supuesto ? ' ' + x.supuesto : '');
|
||||
}
|
||||
limpiar() { this.cambiar({ filtros: {} }); }
|
||||
clicCurva(evento: unknown) {
|
||||
const grupo = grupoDelClic(evento), cat = this.cat(), pedido = this.pedido();
|
||||
if (!grupo || !cat || !pedido || !this.puedeElegir()) return;
|
||||
const siguiente = pedidoAlElegir(pedido, grupo, cat);
|
||||
if (siguiente !== pedido) this.cambiar(siguiente);
|
||||
const grupo = grupoDelClic(evento);
|
||||
if (grupo) this.verGrupo(grupo);
|
||||
}
|
||||
verGrupo(grupo: string) {
|
||||
const c = this.cat(), p = this.pedido(), seleccion = c && p ? seleccionDeCurva(c, p, grupo) : undefined;
|
||||
if (seleccion) this.verPacientes.emit(seleccion);
|
||||
}
|
||||
clicCelda(evento: unknown) {
|
||||
const celda = celdaDelClic(evento), c = this.cat(), s = this.sub();
|
||||
const seleccion = celda && c && s ? seleccionDeCelda(c, s, celda) : undefined;
|
||||
if (seleccion) this.verPacientes.emit(seleccion);
|
||||
}
|
||||
elegirVista(vista: VistaAnalisis) { this.vista.set(vista); }
|
||||
teclaVista(event: KeyboardEvent) {
|
||||
@@ -444,20 +520,15 @@ export class IndicadoresAnalisis {
|
||||
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>('[role="tab"]')[j]?.focus();
|
||||
}
|
||||
cargarSubgrupos(forzar = false) {
|
||||
const p = this.pedido();
|
||||
if (!p) return;
|
||||
const clave = p.escenario + '|' + p.estimador;
|
||||
const p = this.pedido(), x = this.cruce();
|
||||
if (!p || !x) return;
|
||||
const pedido = { escenario: p.escenario, estimador: p.estimador, ...x };
|
||||
const clave = JSON.stringify(pedido);
|
||||
if (!forzar && clave === this.subgruposDe) return;
|
||||
this.subgruposDe = clave;
|
||||
this.pedidosSubgrupos.next({ escenario: p.escenario, estimador: p.estimador });
|
||||
}
|
||||
// A cell opens its curves: both dimensions filtered, nothing left to stratify.
|
||||
clicCelda(evento: unknown) {
|
||||
const celda = celdaDelClic(evento), s = this.sub();
|
||||
if (!celda || !s) return;
|
||||
this.cambiar({ filtros: { [s.dimension_filas.clave]: celda.fila, [s.dimension_columnas.clave]: celda.columna }, estrato: 'ninguno' });
|
||||
this.vista.set('curvas');
|
||||
this.pedidosSubgrupos.next(pedido);
|
||||
}
|
||||
cargarIndicadores() { this.pedidosIndicadores.next(); }
|
||||
etiqueta(grupo: string) { return this.res()?.grupos.find(g => g.grupo === grupo)?.etiqueta ?? grupo; }
|
||||
reintentar() { const p = this.pedido(); if (p) this.pedidos.next(p); }
|
||||
reintentarCatalogo() { this.catalogos.next(); }
|
||||
|
||||
@@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => {
|
||||
http.match(() => true);
|
||||
}
|
||||
|
||||
it('CaMa: Resumen, Histórico, Análisis, Seguimiento y Datos y definiciones, en ese orden', () => {
|
||||
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
});
|
||||
it.each(['cacu'] as const)('%s no tiene la pestaña Histórico', domain => {
|
||||
|
||||
@@ -133,12 +133,12 @@
|
||||
|
||||
@if (conAnalisis) {
|
||||
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
|
||||
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" />
|
||||
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
|
||||
</section>
|
||||
}
|
||||
|
||||
<section id="panel-seguimiento" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" [attr.aria-labelledby]="fichaPacienteAbierta() ? 'dashboard-title' : 'tab-seguimiento'" tabindex="0" [hidden]="activeSection() !== 'seguimiento'">
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'"
|
||||
<app-indicadores-tracking [domainLabel]="domainLabels[dominio]" [dominio]="dominio" [active]="activeSection() === 'seguimiento'" [seleccion]="seleccionSeguimiento()"
|
||||
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
||||
</section>
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ import { IndicadoresInitialPeriod } from './indicadores-initial-period';
|
||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { IndicadoresAnalisis } from './indicadores-analisis';
|
||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
@@ -45,7 +46,7 @@ const MIN_BUSQUEDA = 5;
|
||||
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Domains whose cohort has an exploratory outcomes analysis.
|
||||
const CON_ANALISIS: readonly Dominio[] = ['cama'];
|
||||
const ANALISIS_SECTIONS: readonly { id: DashboardSection; label: string }[] = [...HISTORICO_SECTIONS.slice(0, 2), { id: 'analisis', label: 'Análisis' }, ...HISTORICO_SECTIONS.slice(2)];
|
||||
const ANALISIS_SECTIONS: readonly { id: DashboardSection; label: string }[] = [...HISTORICO_SECTIONS.slice(0, 2), { id: 'analisis', label: 'Análisis epidemiológico' }, ...HISTORICO_SECTIONS.slice(2)];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
@@ -59,6 +60,12 @@ export class IndicadoresPage {
|
||||
get conAnalisis() { return CON_ANALISIS.includes(this.dominio); }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
// The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again.
|
||||
readonly seleccionSeguimiento = signal<SeleccionSeguimiento | undefined>(undefined);
|
||||
verPacientes(seleccion: SeleccionPacientes) {
|
||||
this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 });
|
||||
this.changeSection('seguimiento');
|
||||
}
|
||||
setFichaPacienteAbierta(open: boolean) {
|
||||
this.fichaPacienteAbierta.set(open);
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ describe('Secciones compartidas por dominio', () => {
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// Breast cancer adds the exploratory analysis of its BI-RADS 4+ cohort after its history.
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis', 'Seguimiento', 'Datos y definiciones']
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Covers CaMa's follow-up table: when it asks, what it sends, how it draws the answer and each state (loading,
|
||||
// empty, pending, error, retry). The answers are fixtures (fixtures/cama_seguimiento.json and variations of it):
|
||||
// synthetic records, used by tests only; the view never reads them in normal use.
|
||||
// synthetic records, used by tests only; the view never reads them in normal use. It also covers the selection that
|
||||
// the epidemiological analysis sends (a curve or a heatmap cell): the whole cohort with that selection's filters.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -76,11 +77,28 @@ describe('Seguimiento de CaMa (tabla)', () => {
|
||||
expect(conBiopsia[4]).toMatch(/^Carcinoma invasor Fecha de biopsia: 20\d\d-\d\d-\d\d$/);
|
||||
expect(conBiopsia[5]).toMatch(/^[0-9]+$/);
|
||||
});
|
||||
it('una selección del análisis pide toda la cohorte con sus filtros, lo anuncia, y Quitar selección vuelve a la ventana de 3 meses', async () => {
|
||||
// Fails if a curve or a cell opens a list cut by a time window, without its filters, or that cannot be undone.
|
||||
fixture.componentRef.setInput('seleccion', { filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio IV', id: 1 });
|
||||
abrir();
|
||||
let r = solicitud();
|
||||
expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', resultado: 'INVASOR', estadio: 'IV' });
|
||||
r.flush(pagina(1, 50, { ventana: { meses: 0, desde: '2023-01-02', hasta: '2026-10-20' } })); await asentar();
|
||||
expect(root().querySelector('.seleccion')?.textContent).toContain('Supervivencia: Estadio IV');
|
||||
boton('Quitar selección').click(); fixture.detectChanges();
|
||||
r = solicitud();
|
||||
expect(parametros(r)).toEqual({ corte: '2026-10-20', meses: '3', page: '1', page_size: '50' });
|
||||
r.flush(pagina(1, 50)); await asentar();
|
||||
expect(root().querySelector('.seleccion')).toBeNull();
|
||||
// The same selection again (a new click) applies again.
|
||||
fixture.componentRef.setInput('seleccion', { filtros: { resultado: 'INVASOR', estadio: 'IV' }, etiqueta: 'Supervivencia: Estadio IV', id: 2 }); fixture.detectChanges();
|
||||
solicitud().flush(pagina(1, 50, { ventana: { meses: 0, desde: '2023-01-02', hasta: '2026-10-20' } }));
|
||||
});
|
||||
it('el formulario muestra el corte que devolvió el servidor, la ventana, los cuatro filtros anunciados y el tamaño', async () => {
|
||||
await cargado();
|
||||
expect((campo('Fecha de corte').querySelector('input') as HTMLInputElement).value).toBe('2026-10-20');
|
||||
expect((campo('Ventana de meses').querySelector('select') as HTMLSelectElement).selectedOptions[0].text.trim()).toBe('3 meses');
|
||||
expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']);
|
||||
expect([...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']);
|
||||
const etiquetas = [...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim());
|
||||
expect(etiquetas).toEqual(['Fecha de corte', 'Ventana de meses', 'Estatus de seguimiento', 'Categoría BI-RADS', 'Grupo de edad', 'Prioridad', 'Registros por página']);
|
||||
expect([...campo('Estatus de seguimiento').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
|
||||
|
||||
@@ -5,13 +5,16 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import {
|
||||
MESES_VENTANA, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
|
||||
MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse,
|
||||
SeguimientoTablaService, SeguimientoValor,
|
||||
} from './seguimiento-tabla.service';
|
||||
|
||||
type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error';
|
||||
type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string };
|
||||
interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; filtros: Record<string, string | undefined>; }
|
||||
// What the analysis sends: the list's filters, how to name them, and an id that changes with each click.
|
||||
export interface SeleccionSeguimiento { filtros: Record<string, string>; etiqueta: string; id: number; }
|
||||
|
||||
interface Borrador { corte?: string; meses: MesesVentana; page_size: number; filtros: Record<string, string | undefined>; }
|
||||
|
||||
/**
|
||||
* Follow-up list of a domain, drawn from what `GET /<dominio>/seguimiento` announces: the filters, the columns
|
||||
@@ -21,10 +24,16 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
|
||||
selector: 'app-seguimiento-tabla',
|
||||
imports: [FormsModule],
|
||||
template: `
|
||||
@if (seleccionMostrada(); as sel) {
|
||||
<div class="seleccion" role="status">
|
||||
<span>Pacientes de la selección del análisis epidemiológico: <strong>{{ sel }}</strong>. Toda la cohorte, sin ventana de tiempo.</span>
|
||||
<button type="button" (click)="quitarSeleccion()">Quitar selección</button>
|
||||
</div>
|
||||
}
|
||||
<form (ngSubmit)="aplicar()">
|
||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of ventanas; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
@for (m of ventanas; track m) { <option [ngValue]="m">{{ m === 0 ? 'Toda la cohorte' : m + (m === 1 ? ' mes' : ' meses') }}</option> }
|
||||
</select></label>
|
||||
@for (filtro of filtros(); track filtro.clave) {
|
||||
<label>{{ filtro.etiqueta }} <select [name]="'filtro-' + filtro.clave" [(ngModel)]="draft.filtros[filtro.clave]">
|
||||
@@ -86,11 +95,17 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f
|
||||
th { background: var(--issste-background); font-weight: 600; }
|
||||
small { display: block; margin-top: .35rem; }
|
||||
nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top: 1rem; }
|
||||
.seleccion { display: flex; flex-wrap: wrap; align-items: center; gap: .75rem; margin-bottom: 1rem; padding: .5rem .75rem;
|
||||
border-left: 4px solid var(--issste-accent); background: var(--issste-surface); }
|
||||
`,
|
||||
})
|
||||
export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input() active = false;
|
||||
// The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again.
|
||||
@Input() seleccion?: SeleccionSeguimiento;
|
||||
readonly seleccionMostrada = signal<string | undefined>(undefined);
|
||||
private seleccionAplicada?: number;
|
||||
private readonly service = inject(SeguimientoTablaService);
|
||||
private readonly consultas = new Subject<SeguimientoTablaQuery | null>();
|
||||
readonly ventanas = MESES_VENTANA;
|
||||
@@ -131,8 +146,19 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
this.previo = this.dominio; this.iniciado = false; this.consultas.next(null);
|
||||
this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 };
|
||||
}
|
||||
const sel = this.seleccion;
|
||||
if (this.active && sel && sel.id !== this.seleccionAplicada) {
|
||||
this.seleccionAplicada = sel.id; this.iniciado = true;
|
||||
this.draft = { ...this.draft, meses: 0, filtros: { ...sel.filtros } };
|
||||
this.aplicar(sel.etiqueta);
|
||||
return;
|
||||
}
|
||||
if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next(this.applied); }
|
||||
}
|
||||
quitarSeleccion() {
|
||||
this.draft = { ...this.draft, meses: 3, filtros: {} };
|
||||
this.aplicar();
|
||||
}
|
||||
|
||||
private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado {
|
||||
// A first page that does not exist yet is the list's own pending state; a later page that fails is an error.
|
||||
@@ -150,7 +176,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) };
|
||||
this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size;
|
||||
}
|
||||
aplicar() {
|
||||
// From the form the banner goes away: the list is no longer the analysis' selection.
|
||||
aplicar(seleccion?: string) {
|
||||
this.seleccionMostrada.set(seleccion);
|
||||
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros };
|
||||
this.applied = q;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [active]="active" />
|
||||
<app-seguimiento-tabla [dominio]="dominio" [active]="active" [seleccion]="seleccion" />
|
||||
} @else {
|
||||
<form (ngSubmit)="apply()">
|
||||
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
|
||||
|
||||
@@ -12,7 +12,7 @@ import { Dominio } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
@@ -25,6 +25,8 @@ export class IndicadoresTracking implements OnChanges {
|
||||
@Input({ required: true }) domainLabel = '';
|
||||
@Input() dominio: Dominio = 'tea';
|
||||
@Input() active = false;
|
||||
// CaMa: the patients of a curve or a heatmap cell of the analysis, for its follow-up list.
|
||||
@Input() seleccion?: SeleccionSeguimiento;
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
|
||||
@@ -12,14 +12,14 @@ export interface SeguimientoOpcion { codigo: string; etiqueta: string; }
|
||||
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: 1 | 3 | 6 | 12; page: number; page_size: number;
|
||||
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: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
ventana: { meses: MesesVentana; desde: string; hasta: string };
|
||||
filtros: Record<string, string | null>;
|
||||
filtros_disponibles: SeguimientoFiltro[];
|
||||
columnas: SeguimientoColumna[];
|
||||
@@ -29,7 +29,9 @@ export interface SeguimientoTablaResponse {
|
||||
}
|
||||
export class SeguimientoInvalido extends Error {}
|
||||
|
||||
export const MESES_VENTANA = [1, 3, 6, 12] as const;
|
||||
// 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'];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user