feat(cama): «Análisis» tab with exploratory outcomes of the BI-RADS 4+ cohort
Breast cancer gets a tab between Histórico and Seguimiento that answers "how often, and how fast, does a BI-RADS 4+ patient reach the event", by a pre-specified stratum, with every number computed by the server and labelled as descriptive. How: - AnalisisService reads GET /<domain>/analisis (scenarios, estimators, strata, filters, blocked analyses with their reasons) and GET /<domain>/analisis/resultados (C9b curves, risk table, log-rank with Holm pairs, RMST, C12 hazard ratios, C13 validation report). - The guards accept demonstration data only, reject any key that only a patient row would carry (at any depth), a suppressed group with counts, and a published curve point with fewer at risk than the threshold. - curvasFigura draws each published group as a step line with its 95 % band; forestFigura draws the HRs on a log axis, with an open marker when the proportional-hazards check fails. Both are pure functions of the answer. - Clicking a curve keeps that group as a filter and stratifies by the other dimension (pedidoAlElegir); it only changes the request. - Too few events, a 404 catalog and blocked analyses (recurrence, survival by stage, subtype and St. Gallen strata) are shown with their reason instead of an empty chart. - CON_ANALISIS lists the domains with the tab: cama only. Implications: - The backend has neither endpoint yet: the tab shows "Funcionalidad pendiente de publicación" against the real WebApi. The contracts C9b, C12 and C13 are drafts and need grooming before the kit implements them. - No row-level data reaches the browser; suppression is the server's job and the client only double-checks it. - Death as a competing event needs a vital status the schema doesn't have.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { AnalisisResultados } from './indicadores-analisis.service';
|
||||
|
||||
const DIAS_POR_MES = 30.4375;
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
|
||||
function transparente(hex: string, alfa: number) {
|
||||
const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
|
||||
return m ? `rgba(${parseInt(m[1], 16)}, ${parseInt(m[2], 16)}, ${parseInt(m[3], 16)}, ${alfa})` : hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cumulative incidence per published group: a step line with its 95 % band. The curve ends where the
|
||||
* answer suppressed it (fewer at risk than the threshold); each line carries its group in `meta`, so a click
|
||||
* can only change the filters, never read rows.
|
||||
*/
|
||||
export function curvasFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), meses = r.horizonte_dias / DIAS_POR_MES;
|
||||
const data: Record<string, unknown>[] = [];
|
||||
let maximo = 1;
|
||||
for (const g of r.grupos.filter(x => !x.suprimido)) {
|
||||
const puntos = r.curvas.filter(c => c.grupo === g.grupo && c.suprimido === 0);
|
||||
if (!puntos.length) continue;
|
||||
const x = puntos.map(c => +(c.t / DIAS_POR_MES).toFixed(2));
|
||||
maximo = Math.max(maximo, ...puntos.map(c => c.ic_alto!));
|
||||
const comun = { type: 'scatter', mode: 'lines', x, legendgroup: g.grupo, line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false };
|
||||
data.push({ ...comun, y: puntos.map(c => c.ic_bajo) });
|
||||
data.push({ ...comun, y: puntos.map(c => c.ic_alto), fill: 'tonexty', fillcolor: transparente(g.color, tema === 'oscuro' ? .28 : .16) });
|
||||
data.push({
|
||||
type: 'scatter', mode: 'lines', x, y: puntos.map(c => c.valor), name: `${escapar(g.etiqueta)} (n = ${miles(g.n!)}, ${miles(g.eventos!)} eventos)`,
|
||||
legendgroup: g.grupo, meta: g.grupo, line: { shape: 'hv', width: 2.5, color: g.color },
|
||||
customdata: puntos.map(c => [pct(c.valor!), pct(c.ic_bajo!), pct(c.ic_alto!), miles(c.n_riesgo!), miles(c.n_eventos!)]),
|
||||
hovertemplate: `<b>${escapar(g.etiqueta)}</b><br>Mes %{x:.1f}: %{customdata[0]} % (IC 95 %: %{customdata[1]} a %{customdata[2]})<br>En riesgo: %{customdata[3]} · eventos acumulados: %{customdata[4]}<extra></extra>`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
data,
|
||||
layout: {
|
||||
autosize: true, height: 460, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 64, r: 16, b: 96 }, hovermode: 'closest',
|
||||
legend: { orientation: 'h', y: -0.22, itemclick: false, itemdoubleclick: false },
|
||||
xaxis: { title: { text: 'Meses desde el origen' }, range: [0, meses], dtick: 6, gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { title: { text: 'Incidencia acumulada (%)' }, range: [0, Math.min(100, maximo * 1.1)], gridcolor: p.grid, zeroline: false, fixedrange: true, ticksuffix: ' %' },
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
/** Hazard ratio of each group against the reference, on a log axis; an open marker flags a failed proportional-hazards check. */
|
||||
export function forestFigura(r: AnalisisResultados, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), e = r.efectos;
|
||||
if (e.estado !== 'listo' || !e.filas.length) return { data: [], layout: {} };
|
||||
const etiquetas = [`${escapar(e.etiqueta_referencia ?? e.referencia ?? '')} (referencia)`, ...e.filas.map(f => escapar(f.etiqueta))];
|
||||
const falla = (ph: number | null) => ph !== null && ph < .05;
|
||||
const minimo = Math.min(1, ...e.filas.map(f => f.ic_bajo)), maximo = Math.max(1, ...e.filas.map(f => f.ic_alto));
|
||||
return {
|
||||
data: [
|
||||
{ type: 'scatter', mode: 'markers', x: [1], y: [etiquetas[0]], marker: { symbol: 'diamond', size: 10, color: p.outline }, hoverinfo: 'skip', showlegend: false },
|
||||
{
|
||||
type: 'scatter', mode: 'markers', x: e.filas.map(f => f.hr), y: etiquetas.slice(1), showlegend: false,
|
||||
error_x: { type: 'data', symmetric: false, array: e.filas.map(f => f.ic_alto - f.hr), arrayminus: e.filas.map(f => f.hr - f.ic_bajo), color: p.text, thickness: 1.5, width: 6 },
|
||||
marker: { size: 11, color: e.filas.map(f => falla(f.ph_p) ? p.background : p.text), line: { color: p.text, width: 2 }, symbol: 'square' },
|
||||
customdata: e.filas.map(f => [f.ic_bajo.toLocaleString('es-MX'), f.ic_alto.toLocaleString('es-MX'), miles(f.n_eventos), falla(f.ph_p) ? '<br>Riesgos no proporcionales: el HR promedia un efecto que cambia.' : '']),
|
||||
hovertemplate: '%{y}<br>HR %{x:.2f} (IC 95 %: %{customdata[0]} a %{customdata[1]})<br>%{customdata[2]} eventos%{customdata[3]}<extra></extra>',
|
||||
},
|
||||
],
|
||||
layout: {
|
||||
autosize: true, height: Math.max(220, 70 + 44 * etiquetas.length), paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 16, l: 16, r: 24, b: 56 },
|
||||
xaxis: { type: 'log', title: { text: 'Razón de riesgos (HR), escala logarítmica' }, range: [Math.log10(minimo * .7), Math.log10(maximo * 1.4)], gridcolor: p.grid, zeroline: false, fixedrange: true },
|
||||
yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true },
|
||||
shapes: [{ type: 'line', xref: 'x', yref: 'paper', x0: 1, x1: 1, y0: 0, y1: 1, line: { color: p.outline, dash: 'dot', width: 1.5 } }],
|
||||
},
|
||||
config: { displayModeBar: false },
|
||||
};
|
||||
}
|
||||
|
||||
export const mesesDe = (dias: number) => Math.round(dias / DIAS_POR_MES);
|
||||
@@ -0,0 +1,103 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { Dominio, requireDominio } from './indicadores.models';
|
||||
|
||||
// Exploratory outcomes of a domain's cohort: what can be asked (`/analisis`) and its aggregate answer
|
||||
// (`/analisis/resultados`). The answer is curves (C9b), tests, effects (C12) and checks (C13), never patient rows.
|
||||
export interface AnalisisOpcion { clave: string; etiqueta: string; }
|
||||
export interface AnalisisEscenario extends AnalisisOpcion { evento: string; origen: string; poblacion: string; }
|
||||
export interface AnalisisEstimador extends AnalisisOpcion { nota: string; }
|
||||
export interface AnalisisEstrato extends AnalisisOpcion { disponible: boolean; motivo?: string; }
|
||||
export interface AnalisisFiltro { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
|
||||
export interface AnalisisBloqueado { clave: string; titulo: string; motivo: string; }
|
||||
export interface AnalisisCatalogo {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||
escenarios: AnalisisEscenario[]; estimadores: AnalisisEstimador[]; estratos: AnalisisEstrato[];
|
||||
filtros: AnalisisFiltro[]; bloqueados: AnalisisBloqueado[];
|
||||
}
|
||||
export interface AnalisisPedido { escenario: string; estimador: string; estrato: string; filtros: Record<string, string>; }
|
||||
|
||||
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.
|
||||
export interface PuntoCurva { grupo: string; t: number; estimador: 'KM' | 'CIF'; valor: number | null; ic_bajo: number | null; ic_alto: number | null; n_riesgo: number | null; n_eventos: number | null; suprimido: 0 | 1; }
|
||||
// C12
|
||||
export interface FilaEfecto { termino: string; etiqueta: string; hr: number; ic_bajo: number; ic_alto: number; n_eventos: number; metodo: 'cox' | 'bayes'; ph_p: number | null; }
|
||||
export interface Efectos { estado: 'listo' | 'insuficiente' | 'no_aplica'; motivo: string | null; metodo: string; referencia: string | null; etiqueta_referencia?: string; filas: FilaEfecto[]; }
|
||||
// C13
|
||||
export interface FilaValidacion { chequeo: string; escopo: string; estadistico: number | null; p: number | null; umbral: number | null; aprobado: boolean | null; nota: string | null; version_modelo: string; sql_sha: string | null; }
|
||||
export interface AnalisisResultados {
|
||||
simulado: true; corte: string; horizonte_dias: number; umbral_supresion: number;
|
||||
escenario: string; estimador: string; estrato: string; filtros: Record<string, string>;
|
||||
poblacion: { n: number | null; eventos: number | null; totales_ocultos: boolean; seguimiento_mediano_dias: number | null };
|
||||
grupos: GrupoAnalisis[]; curvas: PuntoCurva[];
|
||||
tabla_riesgo: { cortes_dias: number[]; filas: { grupo: string; cortes: (number | null)[] }[] };
|
||||
pruebas: {
|
||||
logrank: { chi2: number; gl: number; p: number } | null;
|
||||
pares: { a: string; b: string; p: number; p_holm: number }[];
|
||||
rmst: { grupo: string; rmst: number; dif: number | null; ic_bajo: number | null; ic_alto: number | null }[];
|
||||
rmst_referencia?: string; nota: string | null;
|
||||
};
|
||||
efectos: Efectos; validacion: FilaValidacion[]; avisos: string[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
|
||||
const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
|
||||
const numONulo = (v: unknown) => v === null || num(v);
|
||||
const lista = (v: unknown, f: (x: unknown) => boolean) => Array.isArray(v) && v.every(f);
|
||||
const opcion = (v: unknown) => record(v) && text(v['clave']) && text(v['etiqueta']);
|
||||
// Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth.
|
||||
const DE_PACIENTE = new Set(['id_seudonimo', 'pac_id', 'paciente', 'pacientes', 'items', 'fecha_nacimiento', 'curp', 'nss']);
|
||||
function sinFilasDePaciente(v: unknown): boolean {
|
||||
if (Array.isArray(v)) return v.every(sinFilasDePaciente);
|
||||
if (!record(v)) return true;
|
||||
return Object.entries(v).every(([k, x]) => !DE_PACIENTE.has(k) && sinFilasDePaciente(x));
|
||||
}
|
||||
const invalido = (): never => { throw new Error('Respuesta de análisis inválida'); };
|
||||
|
||||
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'])) || !(v['escenarios'] as unknown[]).length
|
||||
|| !lista(v['estimadores'], e => opcion(e) && record(e) && text(e['nota'])) || !(v['estimadores'] as unknown[]).length
|
||||
|| !lista(v['estratos'], e => opcion(e) && record(e) && typeof e['disponible'] === 'boolean')
|
||||
|| !lista(v['filtros'], f => record(f) && text(f['clave']) && text(f['etiqueta']) && lista(f['opciones'], o => record(o) && text(o['codigo']) && text(o['etiqueta'])))
|
||||
|| !lista(v['bloqueados'], b => record(b) && text(b['clave']) && text(b['titulo']) && text(b['motivo']))
|
||||
|| !sinFilasDePaciente(v)) invalido();
|
||||
return v as unknown as AnalisisCatalogo;
|
||||
}
|
||||
|
||||
export function analisisResultados(v: unknown): AnalisisResultados {
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
const pob = v['poblacion'], tabla = v['tabla_riesgo'], pruebas = v['pruebas'], efectos = v['efectos'];
|
||||
if (!sinFilasDePaciente(v) || !num(v['horizonte_dias']) || !num(v['umbral_supresion']) || !text(v['escenario']) || !text(v['estimador']) || !text(v['estrato'])
|
||||
|| !record(v['filtros']) || !record(pob) || !numONulo(pob['n']) || !numONulo(pob['eventos'])
|
||||
|| !lista(v['grupos'], g => record(g) && text(g['grupo']) && text(g['etiqueta']) && text(g['color']) && typeof g['suprimido'] === 'boolean'
|
||||
&& numONulo(g['n']) && numONulo(g['eventos']) && (!g['suprimido'] || g['n'] === null && g['eventos'] === null))
|
||||
|| !lista(v['curvas'], c => record(c) && text(c['grupo']) && num(c['t']) && (c['estimador'] === 'KM' || c['estimador'] === 'CIF')
|
||||
&& (c['suprimido'] === 1 ? c['valor'] === null && c['n_riesgo'] === null : num(c['valor']) && num(c['ic_bajo']) && num(c['ic_alto']) && num(c['n_riesgo'])))
|
||||
|| !record(tabla) || !lista(tabla['cortes_dias'], num) || !lista(tabla['filas'], f => record(f) && text(f['grupo']) && lista(f['cortes'], numONulo))
|
||||
|| !record(pruebas) || !lista(pruebas['pares'], record) || !lista(pruebas['rmst'], record)
|
||||
|| !record(efectos) || !['listo', 'insuficiente', 'no_aplica'].includes(efectos['estado'] as string)
|
||||
|| !lista(efectos['filas'], f => record(f) && text(f['termino']) && num(f['hr']) && num(f['ic_bajo']) && num(f['ic_alto']) && num(f['n_eventos']))
|
||||
|| !lista(v['validacion'], f => record(f) && text(f['chequeo']) && text(f['escopo']) && (f['aprobado'] === null || typeof f['aprobado'] === 'boolean'))
|
||||
|| !lista(v['avisos'], text)) invalido();
|
||||
// A published point must stay at or above the threshold of patients at risk.
|
||||
const umbral = v['umbral_supresion'] as number;
|
||||
if ((v['curvas'] as PuntoCurva[]).some(c => c.suprimido === 0 && c.n_riesgo! < umbral)) invalido();
|
||||
return v as unknown as AnalisisResultados;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AnalisisService {
|
||||
private readonly http = inject(HttpClient);
|
||||
catalogo(dominio: Dominio) {
|
||||
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis`).pipe(map(analisisCatalogo));
|
||||
}
|
||||
resultados(dominio: Dominio, pedido: AnalisisPedido) {
|
||||
let params = new HttpParams().set('escenario', pedido.escenario).set('estimador', pedido.estimador).set('estrato', pedido.estrato);
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { Component, output } from '@angular/core';
|
||||
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, grupoDelClic, pedidoAlElegir } from './indicadores-analisis';
|
||||
import { curvasFigura, forestFigura } from './indicadores-analisis-figuras';
|
||||
import { AnalisisCatalogo, AnalisisResultados, analisisCatalogo, analisisResultados } 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.
|
||||
// Fixtures: `catalogo` (two scenarios, two estimators, two available strata and one that isn't, one blocked
|
||||
// analysis) and `resultados` (two published BI-RADS groups, one suppressed, a ready Cox model), both built below.
|
||||
|
||||
const catalogo = (): AnalisisCatalogo => ({
|
||||
simulado: true, corte: '2026-10-20', horizonte_dias: 730, umbral_supresion: 5,
|
||||
escenarios: [
|
||||
{ clave: 'diagnostico', etiqueta: 'Cáncer confirmado', evento: 'Cáncer confirmado', origen: 'Mastografía índice', poblacion: 'BI-RADS 4 o más' },
|
||||
{ clave: 'incidencia', etiqueta: 'Cáncer posterior', evento: 'Cáncer posterior', origen: 'Biopsia benigna', poblacion: 'Biopsia benigna' },
|
||||
],
|
||||
estimadores: [{ clave: 'km', etiqueta: '1 − Kaplan-Meier', nota: 'Censura la muerte.' }, { clave: 'cif', etiqueta: 'Aalen-Johansen', nota: 'Muerte competitiva.' }],
|
||||
estratos: [{ clave: 'ninguno', etiqueta: 'Sin estratificar', disponible: true }, { clave: 'birads', etiqueta: 'Categoría BI-RADS', disponible: true },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', disponible: true }, { clave: 'subtipo', etiqueta: 'Subtipo molecular', disponible: false, motivo: 'Sin IHC.' }],
|
||||
filtros: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'B4A', etiqueta: 'BI-RADS 4A' }, { codigo: 'B5', etiqueta: 'BI-RADS 5' }] },
|
||||
{ clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: [{ codigo: '50-59', etiqueta: '50-59 años' }] }],
|
||||
bloqueados: [{ clave: 'sobrevida', titulo: 'Sobrevida por etapa clínica', motivo: 'No hay etapa clínica ni estado vital.' }],
|
||||
});
|
||||
const punto = (grupo: string, t: number, valor: number, n_riesgo: number, n_eventos: number) =>
|
||||
({ 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, escenario: 'diagnostico', estimador: 'cif', estrato: 'birads', filtros: {},
|
||||
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 },
|
||||
{ grupo: 'B5', etiqueta: 'BI-RADS 5', color: '#C26A2B', suprimido: false, motivo: null, n: 120, eventos: 100, competitivos: null },
|
||||
{ grupo: 'B6', etiqueta: 'BI-RADS 6', color: '#4E8A4B', suprimido: true, motivo: 'Menos de 5 eventos', n: null, eventos: null, competitivos: null },
|
||||
],
|
||||
curvas: [punto('B4A', 0, 0, 180, 0), punto('B4A', 90, 4, 150, 7), punto('B4A', 730, 6, 90, 11),
|
||||
punto('B5', 0, 0, 120, 0), punto('B5', 40, 70, 30, 85),
|
||||
{ grupo: 'B5', t: 300, estimador: 'CIF', valor: null, ic_bajo: null, ic_alto: null, n_riesgo: null, n_eventos: null, suprimido: 1 }],
|
||||
tabla_riesgo: { cortes_dias: [0, 365, 730], filas: [{ grupo: 'B4A', cortes: [180, 130, 90] }, { grupo: 'B5', cortes: [120, 6, null] }] },
|
||||
pruebas: { logrank: { chi2: 120.5, gl: 1, p: 1e-20 }, pares: [{ a: 'B4A', b: 'B5', p: 1e-20, p_holm: 1e-20 }],
|
||||
rmst: [{ grupo: 'B4A', rmst: 700, dif: null, ic_bajo: null, ic_alto: null }, { grupo: 'B5', rmst: 210, dif: -490, ic_bajo: -520, ic_alto: -460 }],
|
||||
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 }],
|
||||
avisos: ['Análisis descriptivo, no causal.', 'Horizonte de 2 años (730 días).', 'Requiere el estado vital.'],
|
||||
});
|
||||
|
||||
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.
|
||||
expect(analisisResultados(resultados()).grupos).toHaveLength(3);
|
||||
expect(analisisCatalogo(catalogo()).bloqueados).toHaveLength(1);
|
||||
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.
|
||||
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('Figuras del análisis', () => {
|
||||
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');
|
||||
});
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
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' });
|
||||
});
|
||||
});
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { readonly plotClick = output<unknown>(); }
|
||||
|
||||
describe('Pestaña Análisis', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
|
||||
});
|
||||
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(); };
|
||||
|
||||
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.
|
||||
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']);
|
||||
req.flush(resultados()); fixture.detectChanges();
|
||||
expect(text()).toContain('Totales ocultos para no revelar un grupo suprimido');
|
||||
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('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('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.
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
http.expectOne('/cama/analisis').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
|
||||
expect(text()).toContain('Funcionalidad pendiente de publicación');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, 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';
|
||||
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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { curvasFigura, forestFigura, mesesDe } from './indicadores-analisis-figuras';
|
||||
import { AnalisisCatalogo, AnalisisPedido, AnalisisResultados, AnalisisService } from './indicadores-analisis.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { Dominio, Tema } from './indicadores.models';
|
||||
|
||||
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' };
|
||||
|
||||
export const formatoP = (p: number | null) => p === null ? '—' : p < .001 ? '< 0.001' : p.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
|
||||
const DIMENSIONES = ['birads', 'grupo_edad'];
|
||||
|
||||
/** 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 {
|
||||
if (!DIMENSIONES.includes(pedido.estrato)) return pedido;
|
||||
const filtros = { ...pedido.filtros, [pedido.estrato]: grupo };
|
||||
const libre = catalogo.estratos.find(e => e.disponible && DIMENSIONES.includes(e.clave) && !filtros[e.clave]);
|
||||
return { ...pedido, filtros, estrato: libre?.clave ?? 'ninguno' };
|
||||
}
|
||||
|
||||
// Exploratory outcomes of the BI-RADS 4+ cohort: cumulative incidence by a pre-specified stratum, the tests that
|
||||
// compare the groups, hazard ratios when there are enough events, and the checks behind them. Nothing is requested
|
||||
// until the tab is first opened.
|
||||
@Component({
|
||||
selector: 'app-indicadores-analisis',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatIconModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
template: `
|
||||
@switch (catalogo().estado) {
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Cargando el análisis" /> }
|
||||
@case ('pendiente') { <p role="status" class="panel">Funcionalidad pendiente de publicación.</p> }
|
||||
@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) {
|
||||
<div class="controles">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Escenario</mat-label>
|
||||
<mat-select [value]="pedido()!.escenario" (selectionChange)="cambiar({ escenario: $event.value })">
|
||||
@for (e of c.escenarios; track e.clave) { <mat-option [value]="e.clave">{{ e.etiqueta }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
<span id="analisis-estimador" class="etiqueta">Estimador</span>
|
||||
<mat-button-toggle-group aria-labelledby="analisis-estimador" hideSingleSelectionIndicator [value]="pedido()!.estimador" (change)="cambiar({ estimador: $event.value })">
|
||||
@for (e of c.estimadores; 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>
|
||||
<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 c.estratos; track e.clave) {
|
||||
<mat-option [value]="e.clave" [disabled]="!e.disponible">{{ e.etiqueta }}@if (!e.disponible) { <span class="motivo"> · no disponible</span> }</mat-option>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@for (f of c.filtros; 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"><strong>{{ e.poblacion }}.</strong> Origen: {{ e.origen }}. Evento: {{ e.evento }}.
|
||||
@for (b of bloqueadosEstrato(); track b.clave) { <br><span class="motivo">{{ b.etiqueta }}: {{ b.motivo }}</span> }</p>
|
||||
}
|
||||
|
||||
@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> }
|
||||
}
|
||||
@if (res(); as r) {
|
||||
<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 (r.poblacion.seguimiento_mediano_dias) { seguimiento mediano {{ meses(r.poblacion.seguimiento_mediano_dias) }} meses · }
|
||||
horizonte {{ meses(r.horizonte_dias) }} meses · descriptivo, no causal
|
||||
</p>
|
||||
<div class="paneles">
|
||||
<article class="panel ancho">
|
||||
<h2>Incidencia acumulada 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>
|
||||
@if (figuraCurvas().data.length) {
|
||||
<app-plotly-chart [style.--plot-height]="'460px'" [showNotes]="false" [figure]="figuraCurvas()" (plotClick)="clicCurva($event)"
|
||||
[label]="'Incidencia acumulada por ' + (estratoElegido()?.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>
|
||||
<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>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
} @else { <p role="status">Ningún grupo tiene {{ r.umbral_supresion }} eventos o más con estos filtros.</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">
|
||||
<h2>Comparación entre grupos</h2>
|
||||
@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.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>
|
||||
}
|
||||
@if (r.pruebas.nota) { <p class="nota">{{ r.pruebas.nota }}</p> }
|
||||
</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, 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>
|
||||
|
||||
<article class="panel ancho">
|
||||
<h2>Reporte de validación</h2>
|
||||
<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) {
|
||||
<tr [class.falla]="v.aprobado === false">
|
||||
<td>{{ v.chequeo }}</td><td>{{ v.escopo }}</td>
|
||||
<td>{{ v.p !== null ? 'p ' + formatoP(v.p) : v.estadistico !== null ? v.estadistico.toLocaleString('es-MX') : '—' }}</td>
|
||||
<td>{{ v.umbral === null ? '—' : v.umbral.toLocaleString('es-MX') }}</td>
|
||||
<td>{{ v.aprobado === null ? 'No aplica' : v.aprobado ? 'Cumple' : 'No cumple' }}</td>
|
||||
<td>{{ v.nota ?? '' }}</td>
|
||||
</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
<p class="nota">Versión del modelo: {{ r.validacion[0]?.version_modelo }}.</p>
|
||||
</article>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (c.bloqueados.length) {
|
||||
<section class="pendientes" aria-labelledby="analisis-pendientes">
|
||||
<h2 id="analisis-pendientes">Análisis que aún no se pueden calcular</h2>
|
||||
<div class="tarjetas">
|
||||
@for (b of c.bloqueados; track b.clave) { <article class="bloqueado"><h3>{{ b.titulo }}</h3><p>{{ b.motivo }}</p></article> }
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
}
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.controles mat-form-field { min-width: 12rem; }
|
||||
.controles mat-form-field:first-child { min-width: 20rem; }
|
||||
.contexto, .resumen { margin: var(--issste-space-3) 0 0; font: var(--mat-sys-body-medium); color: var(--issste-text); }
|
||||
.resumen { margin-bottom: var(--issste-space-6); color: var(--issste-text-secondary); }
|
||||
.motivo, .nota, .etiqueta { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; }
|
||||
p { margin: var(--issste-space-3) 0 0; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
table { width: 100%; margin-top: var(--issste-space-4); border-collapse: collapse; font: var(--mat-sys-body-medium); }
|
||||
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
|
||||
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
|
||||
.riesgo td { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.validacion tr.falla td { font-weight: 600; }
|
||||
.estado-modelo { padding: var(--issste-space-4); border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.estado-modelo.insuficiente { border-style: solid; }
|
||||
.pendientes { margin-top: var(--issste-space-6); }
|
||||
.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); }
|
||||
@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);
|
||||
readonly formatoP = formatoP;
|
||||
readonly miles = (v: number) => v.toLocaleString('es-MX');
|
||||
readonly meses = mesesDe;
|
||||
private readonly service = inject(AnalisisService);
|
||||
readonly catalogo = signal<Carga<AnalisisCatalogo>>({ estado: 'cargando' });
|
||||
readonly resultados = signal<Carga<AnalisisResultados>>({ estado: 'cargando' });
|
||||
readonly pedido = signal<AnalisisPedido | undefined>(undefined);
|
||||
private readonly pedidos = new Subject<AnalisisPedido>();
|
||||
private readonly catalogos = new Subject<void>();
|
||||
private abierto = false;
|
||||
|
||||
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 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 estratoElegido = computed(() => this.cat()?.estratos.find(e => e.clave === this.pedido()?.estrato));
|
||||
readonly bloqueadosEstrato = computed(() => this.cat()?.estratos.filter(e => !e.disponible) ?? []);
|
||||
readonly hayFiltros = computed(() => Object.values(this.pedido()?.filtros ?? {}).some(Boolean));
|
||||
readonly puedeElegir = computed(() => DIMENSIONES.includes(this.pedido()?.estrato ?? '') && (this.res()?.grupos.filter(g => !g.suprimido).length ?? 0) > 1);
|
||||
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: {} }; });
|
||||
|
||||
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 => {
|
||||
this.catalogo.set(carga);
|
||||
if (carga.estado === 'listo' && !this.pedido()) {
|
||||
const c = carga.datos;
|
||||
this.cambiar({ escenario: c.escenarios[0].clave, estimador: c.estimadores.at(-1)!.clave,
|
||||
estrato: c.estratos.find(e => e.disponible && e.clave !== 'ninguno')?.clave ?? 'ninguno', filtros: {} });
|
||||
}
|
||||
});
|
||||
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));
|
||||
effect(() => {
|
||||
if (!this.active() || this.abierto) return;
|
||||
untracked(() => { this.abierto = true; this.catalogos.next(); });
|
||||
});
|
||||
}
|
||||
|
||||
cambiar(cambio: Partial<AnalisisPedido>) {
|
||||
const pedido = { escenario: '', estimador: '', estrato: 'ninguno', filtros: {}, ...this.pedido(), ...cambio };
|
||||
this.pedido.set(pedido);
|
||||
this.pedidos.next(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 });
|
||||
}
|
||||
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.cat()?.estratos.find(e => e.disponible && DIMENSIONES.includes(e.clave) && !filtros[e.clave])?.clave ?? 'ninguno'
|
||||
: this.pedido()?.estrato;
|
||||
this.cambiar({ filtros, estrato });
|
||||
}
|
||||
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);
|
||||
}
|
||||
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(); }
|
||||
}
|
||||
@@ -125,6 +125,12 @@
|
||||
</section>
|
||||
}
|
||||
|
||||
@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'" />
|
||||
</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'"
|
||||
(fichaPacienteAbierta)="setFichaPacienteAbierta($event)" />
|
||||
|
||||
@@ -30,8 +30,9 @@ 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';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos';
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
@@ -41,16 +42,20 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
|
||||
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)];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, IndicadoresAnalisis, TeaResumenPeriodo],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections() { return this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
|
||||
get sections() { return this.conAnalisis ? ANALISIS_SECTIONS : this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
|
||||
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
|
||||
get conAnalisis() { return CON_ANALISIS.includes(this.dominio); }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
setFichaPacienteAbierta(open: boolean) {
|
||||
|
||||
@@ -37,8 +37,9 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
|
||||
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
// 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']
|
||||
: 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)!;
|
||||
expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]);
|
||||
|
||||
Reference in New Issue
Block a user