From 4c181af291b5ffa1931c6e20f0d663d529a57184 Mon Sep 17 00:00:00 2001 From: ulises Date: Sun, 22 Nov 2026 08:46:39 -0600 Subject: [PATCH 01/19] CaMa patient card: the recurrence figure of the scenarios the patient meets, and a menu of both cohorts' scenarios MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shown only for patients after treatment, in the recurrence slot of "Pronóstico y recomendaciones". Includes the survival figure this builds on. Co-Authored-By: Claude Sonnet 5.5 --- .../cama/cama-patient-card.html | 8 +- .../cama/cama-patient-card.ts | 8 +- .../cama/cama-recurrencia-figura.ts | 55 +++++++++++ .../cama/cama-recurrencia.html | 38 ++++++++ .../cama/cama-recurrencia.models.ts | 49 ++++++++++ .../cama/cama-recurrencia.scss | 4 + .../cama/cama-recurrencia.service.ts | 29 ++++++ .../paciente-detalle/cama/cama-recurrencia.ts | 95 +++++++++++++++++++ .../cama/cama-supervivencia-figura.ts | 45 +++++++++ .../cama/cama-supervivencia.html | 16 ++++ .../cama/cama-supervivencia.models.ts | 42 ++++++++ .../cama/cama-supervivencia.scss | 3 + .../cama/cama-supervivencia.service.ts | 20 ++++ .../cama/cama-supervivencia.ts | 63 ++++++++++++ 14 files changed, 471 insertions(+), 4 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 1fef561..28df1cf 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -38,7 +38,13 @@
    @for (item of placeholders; track item.key) { -
  • {{ item.label }}{{ prognosisUnavailable }}
  • + @if (item.key === 'recurrence' && p.idField === 'pac_id') { +
  • {{ item.label }}
  • + } @else if (item.key === 'survival' && p.idField === 'pac_id') { +
  • {{ item.label }}
  • + } @else { +
  • {{ item.label }}{{ prognosisUnavailable }}
  • + } }

{{ recommendationsUnavailable }}

diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index a59872c..d7117ef 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -3,17 +3,19 @@ import { downloadBlob, exportFilename } from '../../export/download-file'; import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; +import { CamaRecurrencia } from './cama-recurrencia'; +import { CamaSupervivencia } from './cama-supervivencia'; import { CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, } from './cama-patient.models'; /** - * Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence, - * survival and prognostic factors are placeholders until a validated model supplies them. + * Individual record of a CaMa follow-up patient: what the follow-up list carries and, in its prognosis card, the recurrence and + * survival figures of the clinical scenarios the patient belongs to. */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule], + imports: [CamaRecurrencia, CamaSupervivencia, MatButtonModule, MatCardModule, MatIconModule], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts new file mode 100644 index 0000000..aac3bd9 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts @@ -0,0 +1,55 @@ +import { PlotlyFigure } from '../../indicadores.models'; +import { RecurrenciaFigura } from './cama-recurrencia.models'; + +const decimales = new Intl.NumberFormat('es-MX'); +const finitos = (valores: (number | null)[]) => valores.filter((v): v is number => v !== null && Number.isFinite(v)); + +/** + * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull (dotted past the + * follow-up), and the combined estimate at each horizon with its bootstrap interval. + */ +export function figuraRecurrencia(figura: RecurrenciaFigura): PlotlyFigure { + const km = figura.km; + const seguimiento = km.months[km.months.length - 1]; + const combinado = figura.points.COMB; + const tiempos = figura.weibull.t; + const dentro = tiempos.map(t => t <= seguimiento); + const trazo = (S: (number | null)[], dentroDelSeguimiento: boolean) => + S.map((v, i) => (dentro[i] === dentroDelSeguimiento || (!dentroDelSeguimiento && tiempos[i] === seguimiento) ? v : null)); + const todos = [...finitos(km.low), ...finitos(km.high), ...finitos(combinado.low), ...finitos(combinado.high), + ...finitos(figura.weibull.S), ...finitos(figura.weibull_fractional.S)]; + const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; + const horizontes = figura.horizons_months; + const S = combinado.S.map(v => v ?? NaN); + return { + data: [ + { x: km.months, y: km.low, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, + { x: km.months, y: km.high, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', + fillcolor: 'rgba(154,165,177,0.3)', hoverinfo: 'skip', showlegend: false }, + { x: km.months, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, + name: 'Kaplan-Meier (IC 95 % Greenwood)' }, + { x: tiempos, y: trazo(figura.weibull.S, true), type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, + { x: tiempos, y: trazo(figura.weibull.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#1f77b4', dash: 'dot' }, + hoverinfo: 'skip', showlegend: false }, + { x: tiempos, y: trazo(figura.weibull_fractional.S, true), type: 'scatter', mode: 'lines', + line: { width: 3, color: '#d1495b', dash: 'dash' }, name: 'Weibull fraccional' }, + { x: tiempos, y: trazo(figura.weibull_fractional.S, false), type: 'scatter', mode: 'lines', line: { width: 2, color: '#d1495b', dash: 'dot' }, + hoverinfo: 'skip', showlegend: false }, + { x: horizontes, y: S, type: 'scatter', mode: 'markers', + marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, + error_y: { type: 'data', symmetric: false, array: combinado.high.map((v, i) => (v ?? NaN) - S[i]), + arrayminus: combinado.low.map((v, i) => S[i] - (v ?? NaN)), color: '#6a3d9a', thickness: 2, width: 5 }, + name: 'LR + HBN combinado (IC 95 % bootstrap)' }, + ], + layout: { + title: { text: `${figura.escenario}
${figura.cohorte_nombre} · n=${decimales.format(figura.n)}, recaídas=${decimales.format(figura.recaidas)}`, + font: { size: 15 } }, + xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, figura.months_max + 0.8], dtick: 12, zeroline: false }, + yaxis: { title: { text: 'Libre de recaída S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, + legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, + margin: { l: 70, r: 20, t: 70, b: 60 }, + hovermode: 'x unified', + }, + config: { responsive: true, displaylogo: false }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html new file mode 100644 index 0000000..b518b4e --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.html @@ -0,0 +1,38 @@ +@switch (estado()) { + @case ('cargando') { } + @case ('sin-modelo') {

No hay una cohorte armada para el análisis de recurrencia.

} + @case ('error') { } + @default { + @if (!postratamiento()) { +

El análisis de recurrencia es para pacientes que ya terminaron su tratamiento.

+ } @else { + @if (deLaPaciente().length) { + + @for (e of deLaPaciente(); track e.cohorte + e.escenario) { + {{ nombreCohorte(e.cohorte) }} · {{ e.escenario }} + } + + } @else { +

La paciente no pertenece a ninguno de los escenarios clínicos del modelo. Elige uno del menú.

+ } + + } + @if (calculando()) { } + @if (figura(); as f) { } + @if (mensaje(); as texto) {

{{ texto }}

} + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts new file mode 100644 index 0000000..659eee5 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.models.ts @@ -0,0 +1,49 @@ +/** The recurrence analysis as `/cama/recurrencia` gives it: the scenarios of each cohort, a scenario's figure and a patient's scenarios. */ +export interface RecurrenciaEscenario { nombre: string; condiciones: Record; n: number; recaidas: number; dibujable: boolean } +export interface RecurrenciaCohorte { id: string; nombre: string; estado: 'calculando' | 'listo' | 'error'; error: string | null; escenarios: RecurrenciaEscenario[] } +export interface RecurrenciaEscenarios { build: number; horizontes: number[]; cohortes: RecurrenciaCohorte[] } +export interface RecurrenciaDePaciente { build: number; pac_id: number; postratamiento: boolean; escenarios: { cohorte: string; escenario: string }[] } + +export interface RecurrenciaFigura { + cohorte: string; + cohorte_nombre: string; + escenario: string; + n: number; + recaidas: number; + horizons_months: number[]; + months_max: number; + bootstrap_replicas: number; + km: { months: number[]; S: number[]; low: number[]; high: number[] }; + weibull: { t: number[]; S: (number | null)[] }; + weibull_fractional: { t: number[]; S: (number | null)[] }; + points: { COMB: { S: (number | null)[]; low: (number | null)[]; high: (number | null)[] } }; +} +export type RecurrenciaRespuestaFigura = { estado: 'calculando' } | { estado: 'listo'; figura: RecurrenciaFigura }; + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); + +export function recurrenciaEscenarios(v: unknown): RecurrenciaEscenarios { + if (!record(v) || typeof v['build'] !== 'number' || !numbers(v['horizontes']) || !Array.isArray(v['cohortes']) + || !v['cohortes'].every(c => record(c) && typeof c['id'] === 'string' && typeof c['nombre'] === 'string' && Array.isArray(c['escenarios']))) { + throw new Error('Respuesta de escenarios de recurrencia inválida'); + } + return v as unknown as RecurrenciaEscenarios; +} + +export function recurrenciaDePaciente(v: unknown): RecurrenciaDePaciente { + if (!record(v) || typeof v['postratamiento'] !== 'boolean' || !Array.isArray(v['escenarios']) + || !v['escenarios'].every(e => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')) { + throw new Error('Respuesta de recurrencia de la paciente inválida'); + } + return v as unknown as RecurrenciaDePaciente; +} + +export function recurrenciaFigura(v: unknown): RecurrenciaFigura { + if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte'] !== 'string' || typeof v['n'] !== 'number' + || typeof v['recaidas'] !== 'number' || !numbers(v['horizons_months']) || !record(v['km']) || !numbers(v['km']['months']) + || !numbers(v['km']['S']) || !record(v['weibull']) || !record(v['weibull_fractional']) || !record(v['points'])) { + throw new Error('Respuesta de figura de recurrencia inválida'); + } + return v as unknown as RecurrenciaFigura; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss new file mode 100644 index 0000000..fbd6238 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.scss @@ -0,0 +1,4 @@ +:host { display: block; min-width: 0; --plot-height: 420px; } +.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } +.menu { display: flex; flex-wrap: wrap; gap: 0.75rem; margin: 0.75rem 0; } +.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts new file mode 100644 index 0000000..980c059 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts @@ -0,0 +1,29 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http'; +import { map } from 'rxjs'; +import { + recurrenciaDePaciente, recurrenciaEscenarios, recurrenciaFigura, RecurrenciaRespuestaFigura, +} from './cama-recurrencia.models'; + +@Injectable({ providedIn: 'root' }) +export class CamaRecurrenciaService { + private readonly http = inject(HttpClient); + + /** The scenarios of each cohort, with their size and whether they have enough recurrences to be drawn. */ + escenarios() { + return this.http.get('/cama/recurrencia/escenarios').pipe(map(recurrenciaEscenarios)); + } + + /** The scenarios a patient's covariates meet, in each cohort; empty for a patient who is not after treatment. */ + deLaPaciente(pacId: number) { + return this.http.get(`/cama/recurrencia/pacientes/${pacId}`).pipe(map(recurrenciaDePaciente)); + } + + /** The figure of one scenario; `calculando` while the cohort's models are being computed. */ + figura(cohorte: string, escenario: string) { + const params = new HttpParams().set('cohorte', cohorte).set('escenario', escenario); + return this.http.get('/cama/recurrencia/figura', { params, observe: 'response' }).pipe( + map((r: HttpResponse): RecurrenciaRespuestaFigura => + r.status === 202 ? { estado: 'calculando' } : { estado: 'listo', figura: recurrenciaFigura(r.body) })); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts new file mode 100644 index 0000000..48b5943 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.ts @@ -0,0 +1,95 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { MatSelectModule } from '@angular/material/select'; +import { forkJoin, Subscription, timer } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../../indicadores.models'; +import { figuraRecurrencia } from './cama-recurrencia-figura'; +import { RecurrenciaCohorte } from './cama-recurrencia.models'; +import { CamaRecurrenciaService } from './cama-recurrencia.service'; + +const ESPERA_CALCULO_MS = 5000; + +/** + * A patient's recurrence: the clinical scenarios her covariates meet and, from a menu, any scenario of either cohort, with the + * figure of the one chosen, computed over the live cohort. + */ +@Component({ + selector: 'app-cama-recurrencia', + imports: [MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + templateUrl: './cama-recurrencia.html', + styleUrl: './cama-recurrencia.scss', +}) +export class CamaRecurrencia { + readonly pacId = input.required(); + readonly estado = signal<'cargando' | 'listo' | 'sin-modelo' | 'error'>('cargando'); + readonly postratamiento = signal(false); + readonly cohortes = signal([]); + readonly deLaPaciente = signal<{ cohorte: string; escenario: string }[]>([]); + readonly elegido = signal<{ cohorte: string; escenario: string } | null>(null); + readonly figura = signal(null); + readonly calculando = signal(false); + readonly mensaje = signal(null); + private readonly menuCohorte = signal(null); + readonly cohorteDelMenu = computed(() => this.menuCohorte() ?? this.elegido()?.cohorte ?? this.cohortes()[0]?.id ?? ''); + readonly escenariosDelMenu = computed(() => + this.cohortes().find(c => c.id === this.cohorteDelMenu())?.escenarios.filter(e => e.dibujable) ?? []); + private readonly servicio = inject(CamaRecurrenciaService); + private readonly destroy = inject(DestroyRef); + private pedido?: Subscription; + + constructor() { + effect(() => this.cargar(this.pacId())); + } + + nombreCohorte(id: string) { return this.cohortes().find(c => c.id === id)?.nombre ?? id; } + + private cargar(pacId: number) { + this.estado.set('cargando'); this.limpiar(); this.elegido.set(null); this.menuCohorte.set(null); + forkJoin({ menu: this.servicio.escenarios(), paciente: this.servicio.deLaPaciente(pacId) }) + .pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: ({ menu, paciente }) => { + this.cohortes.set(menu.cohortes); + this.postratamiento.set(paciente.postratamiento); + this.deLaPaciente.set(paciente.escenarios); + this.estado.set('listo'); + if (paciente.postratamiento && paciente.escenarios.length) this.elegir(paciente.escenarios[0].cohorte, paciente.escenarios[0].escenario); + }, + error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), + }); + } + + private limpiar() { this.figura.set(null); this.mensaje.set(null); this.calculando.set(false); this.pedido?.unsubscribe(); } + + elegirDePaciente(clave: string) { const [cohorte, ...resto] = clave.split('|'); this.elegir(cohorte, resto.join('|')); } + + elegirCohorte(cohorte: string) { this.menuCohorte.set(cohorte); this.elegido.set(null); this.limpiar(); } + + elegir(cohorte: string, escenario: string) { + this.limpiar(); + this.elegido.set({ cohorte, escenario }); this.menuCohorte.set(cohorte); this.calculando.set(true); + const vigente = () => this.elegido()?.cohorte === cohorte && this.elegido()?.escenario === escenario; + const pedir = () => { + this.pedido = this.servicio.figura(cohorte, escenario).subscribe({ + next: r => { + if (!vigente()) return; + if (r.estado === 'calculando') { + this.mensaje.set('Calculando los modelos de la cohorte; la figura aparecerá en cuanto estén listos.'); + this.pedido = timer(ESPERA_CALCULO_MS).subscribe(() => { if (vigente()) pedir(); }); + return; + } + this.calculando.set(false); this.mensaje.set(null); this.figura.set(figuraRecurrencia(r.figura)); + }, + error: (e: { status?: number }) => { + if (!vigente()) return; + this.calculando.set(false); + this.mensaje.set(e?.status === 404 ? 'El escenario tiene pocas recaídas para dibujar su curva.' : 'No se pudo calcular la figura. Intenta nuevamente.'); + }, + }); + }; + pedir(); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts new file mode 100644 index 0000000..f914101 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts @@ -0,0 +1,45 @@ +import { PlotlyFigure } from '../../indicadores.models'; +import { SupervivenciaFigura } from './cama-supervivencia.models'; + +const decimales = new Intl.NumberFormat('es-MX'); + +/** + * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the + * LR + HBN combined survival at each horizon with its bootstrap interval. + */ +export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure { + const meses = figura.months ?? []; + const km = figura.km!; + const curvas = figura.curve_months ?? []; + const combinados = figura.points.filter(p => p.model === 'COMB'); + const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1]; + const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])] + .filter(v => Number.isFinite(v)); + const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; + return { + data: [ + { x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)', + hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, + name: 'Kaplan-Meier (IC 95 % Greenwood)' }, + { x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, + { x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' }, + name: 'Weibull fraccional' }, + { x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers', + marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, + error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low), + color: '#6a3d9a', thickness: 2, width: 5 }, + name: 'LR + HBN combinado (IC 95 % bootstrap)' }, + ], + layout: { + title: { text: `${figura.scenario}
n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } }, + xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false }, + yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, + legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, + margin: { l: 70, r: 20, t: 70, b: 60 }, + hovermode: 'x unified', + }, + config: { responsive: true, displaylogo: false }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html new file mode 100644 index 0000000..a516010 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html @@ -0,0 +1,16 @@ +@switch (estado()) { + @case ('cargando') { } + @case ('sin-modelo') {

No hay un modelo de supervivencia en producción.

} + @case ('error') { } + @case ('sin-escenarios') {

La paciente no pertenece a ninguno de los escenarios clínicos del modelo.

} + @default { + @if (escenarios().length > 1) { + + @for (nombre of escenarios(); track nombre) { {{ nombre }} } + + } + @if (cargandoFigura()) { } + @if (figura(); as f) { } + @if (sinDibujo(); as mensaje) {

{{ mensaje }}

} + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts new file mode 100644 index 0000000..00c744b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts @@ -0,0 +1,42 @@ +/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */ +export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number } + +export interface SupervivenciaFigura { + scenario: string; + members: number; + deaths: number; + drawable: boolean; + horizons: number[]; + months?: number[]; + km?: { S: number[]; lo: number[]; hi: number[] }; + curve_months?: number[]; + weibull?: { k: number; S: number[] }; + fractional?: { k: number; alpha: number; beta: number; S: number[] }; + points: SupervivenciaPunto[]; +} + +export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] } + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); + +export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios { + if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string') + || typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') { + throw new Error('Respuesta de escenarios de supervivencia inválida'); + } + return v as unknown as SupervivenciaEscenarios; +} + +export function supervivenciaFigura(v: unknown): SupervivenciaFigura { + if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number' + || typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) { + throw new Error('Respuesta de figura de supervivencia inválida'); + } + if (v['drawable']) { + const km = v['km'], w = v['weibull'], f = v['fractional']; + if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi']) + || !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta'); + } + return v as unknown as SupervivenciaFigura; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss new file mode 100644 index 0000000..d2249ae --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss @@ -0,0 +1,3 @@ +:host { display: block; min-width: 0; --plot-height: 420px; } +.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } +.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts new file mode 100644 index 0000000..a85c12b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts @@ -0,0 +1,20 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models'; + +@Injectable({ providedIn: 'root' }) +export class CamaSupervivenciaService { + private readonly http = inject(HttpClient); + + /** The scenarios a patient belongs to, from her variables over the timeline. */ + escenarios(pacId: number) { + return this.http.get(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios)); + } + + /** The figure of one scenario over the production model and the live cohort. */ + figura(escenario: string) { + const params = new HttpParams().set('escenario', escenario); + return this.http.get('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura)); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts new file mode 100644 index 0000000..b90f182 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts @@ -0,0 +1,63 @@ +import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Subscription } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../../indicadores.models'; +import { figuraSupervivencia } from './cama-supervivencia-figura'; +import { CamaSupervivenciaService } from './cama-supervivencia.service'; + +/** + * A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in + * production and the live cohort. + */ +@Component({ + selector: 'app-cama-supervivencia', + imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart], + templateUrl: './cama-supervivencia.html', + styleUrl: './cama-supervivencia.scss', +}) +export class CamaSupervivencia { + readonly pacId = input.required(); + readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando'); + readonly escenarios = signal([]); + readonly elegido = signal(null); + readonly figura = signal(null); + readonly cargandoFigura = signal(false); + readonly sinDibujo = signal(null); + private readonly servicio = inject(CamaSupervivenciaService); + private readonly destroy = inject(DestroyRef); + private pedido?: Subscription; + + constructor() { + effect(() => this.cargar(this.pacId())); + } + + private cargar(pacId: number) { + this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null); + this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: respuesta => { + this.escenarios.set(respuesta.scenarios); + if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; } + this.estado.set('listo'); + this.elegir(respuesta.scenarios[0]); + }, + error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), + }); + } + + elegir(escenario: string) { + this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true); + this.pedido?.unsubscribe(); + this.pedido = this.servicio.figura(escenario).subscribe({ + next: f => { + this.cargandoFigura.set(false); + if (this.elegido() !== escenario) return; + if (f.drawable) this.figura.set(figuraSupervivencia(f)); + else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`); + }, + error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); }, + }); + } +} From dd356efb6b04cfe630b7e1b79ca3aee96570d910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 22 Nov 2026 09:22:15 -0600 Subject: [PATCH 02/19] CaMa patient card: the SEER model's survival by clinical scenario beside the production model's --- .../cama/cama-patient-card.html | 6 ++ .../cama/cama-patient-card.ts | 3 +- .../cama/cama-supervivencia-seer-figura.ts | 45 +++++++++++++ .../cama/cama-supervivencia.html | 16 +++++ .../cama/cama-supervivencia.models.ts | 42 +++++++++++++ .../cama/cama-supervivencia.scss | 3 + .../cama/cama-supervivencia.service.ts | 20 ++++++ .../cama/cama-supervivencia.ts | 63 +++++++++++++++++++ 8 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index eb4fcfc..4d362d3 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -48,6 +48,12 @@

Riesgo de muerte

@if (p.idField === 'pac_id') { } + @if (p.idField === 'pac_id') { +
+
Supervivencia por escenario clínico (modelo SEER)
+ +
+ }
Recomendaciones

{{ recommendationsUnavailable }}

diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index 04c8d89..0e56235 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -5,6 +5,7 @@ import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component'; import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component'; +import { CamaSupervivencia } from './cama-supervivencia'; import { CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE, } from './cama-patient.models'; @@ -16,7 +17,7 @@ import { */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia], + imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia, CamaSupervivencia], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts new file mode 100644 index 0000000..f914101 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts @@ -0,0 +1,45 @@ +import { PlotlyFigure } from '../../indicadores.models'; +import { SupervivenciaFigura } from './cama-supervivencia.models'; + +const decimales = new Intl.NumberFormat('es-MX'); + +/** + * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the + * LR + HBN combined survival at each horizon with its bootstrap interval. + */ +export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure { + const meses = figura.months ?? []; + const km = figura.km!; + const curvas = figura.curve_months ?? []; + const combinados = figura.points.filter(p => p.model === 'COMB'); + const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1]; + const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])] + .filter(v => Number.isFinite(v)); + const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; + return { + data: [ + { x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)', + hoverinfo: 'skip', showlegend: false }, + { x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, + name: 'Kaplan-Meier (IC 95 % Greenwood)' }, + { x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, + { x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' }, + name: 'Weibull fraccional' }, + { x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers', + marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, + error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low), + color: '#6a3d9a', thickness: 2, width: 5 }, + name: 'LR + HBN combinado (IC 95 % bootstrap)' }, + ], + layout: { + title: { text: `${figura.scenario}
n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } }, + xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false }, + yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, + legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, + margin: { l: 70, r: 20, t: 70, b: 60 }, + hovermode: 'x unified', + }, + config: { responsive: true, displaylogo: false }, + }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html new file mode 100644 index 0000000..a516010 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html @@ -0,0 +1,16 @@ +@switch (estado()) { + @case ('cargando') { } + @case ('sin-modelo') {

No hay un modelo de supervivencia en producción.

} + @case ('error') { } + @case ('sin-escenarios') {

La paciente no pertenece a ninguno de los escenarios clínicos del modelo.

} + @default { + @if (escenarios().length > 1) { + + @for (nombre of escenarios(); track nombre) { {{ nombre }} } + + } + @if (cargandoFigura()) { } + @if (figura(); as f) { } + @if (sinDibujo(); as mensaje) {

{{ mensaje }}

} + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts new file mode 100644 index 0000000..00c744b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts @@ -0,0 +1,42 @@ +/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */ +export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number } + +export interface SupervivenciaFigura { + scenario: string; + members: number; + deaths: number; + drawable: boolean; + horizons: number[]; + months?: number[]; + km?: { S: number[]; lo: number[]; hi: number[] }; + curve_months?: number[]; + weibull?: { k: number; S: number[] }; + fractional?: { k: number; alpha: number; beta: number; S: number[] }; + points: SupervivenciaPunto[]; +} + +export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] } + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); + +export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios { + if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string') + || typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') { + throw new Error('Respuesta de escenarios de supervivencia inválida'); + } + return v as unknown as SupervivenciaEscenarios; +} + +export function supervivenciaFigura(v: unknown): SupervivenciaFigura { + if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number' + || typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) { + throw new Error('Respuesta de figura de supervivencia inválida'); + } + if (v['drawable']) { + const km = v['km'], w = v['weibull'], f = v['fractional']; + if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi']) + || !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta'); + } + return v as unknown as SupervivenciaFigura; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss new file mode 100644 index 0000000..d2249ae --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss @@ -0,0 +1,3 @@ +:host { display: block; min-width: 0; --plot-height: 420px; } +.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } +.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts new file mode 100644 index 0000000..a85c12b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts @@ -0,0 +1,20 @@ +import { inject, Injectable } from '@angular/core'; +import { HttpClient, HttpParams } from '@angular/common/http'; +import { map } from 'rxjs'; +import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models'; + +@Injectable({ providedIn: 'root' }) +export class CamaSupervivenciaService { + private readonly http = inject(HttpClient); + + /** The scenarios a patient belongs to, from her variables over the timeline. */ + escenarios(pacId: number) { + return this.http.get(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios)); + } + + /** The figure of one scenario over the production model and the live cohort. */ + figura(escenario: string) { + const params = new HttpParams().set('escenario', escenario); + return this.http.get('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura)); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts new file mode 100644 index 0000000..7de57ea --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts @@ -0,0 +1,63 @@ +import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { Subscription } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../../indicadores.models'; +import { figuraSupervivencia } from './cama-supervivencia-seer-figura'; +import { CamaSupervivenciaService } from './cama-supervivencia.service'; + +/** + * A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in + * production and the live cohort. + */ +@Component({ + selector: 'app-cama-supervivencia', + imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart], + templateUrl: './cama-supervivencia.html', + styleUrl: './cama-supervivencia.scss', +}) +export class CamaSupervivencia { + readonly pacId = input.required(); + readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando'); + readonly escenarios = signal([]); + readonly elegido = signal(null); + readonly figura = signal(null); + readonly cargandoFigura = signal(false); + readonly sinDibujo = signal(null); + private readonly servicio = inject(CamaSupervivenciaService); + private readonly destroy = inject(DestroyRef); + private pedido?: Subscription; + + constructor() { + effect(() => this.cargar(this.pacId())); + } + + private cargar(pacId: number) { + this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null); + this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: respuesta => { + this.escenarios.set(respuesta.scenarios); + if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; } + this.estado.set('listo'); + this.elegir(respuesta.scenarios[0]); + }, + error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), + }); + } + + elegir(escenario: string) { + this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true); + this.pedido?.unsubscribe(); + this.pedido = this.servicio.figura(escenario).subscribe({ + next: f => { + this.cargandoFigura.set(false); + if (this.elegido() !== escenario) return; + if (f.drawable) this.figura.set(figuraSupervivencia(f)); + else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`); + }, + error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); }, + }); + } +} From 990cab0e373ef8ad4496cec797576475121df65b Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:04:13 -0600 Subject: [PATCH 03/19] Patient risk: probabilities in percent, survival as such, covariates, and one row per model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The table says its probabilities are percentages (0 to 100 %) with their 95 % interval, and its covariates under it. A model whose estimand asks for its complement (survival from a probability of dying) shows 1 − p with its interval swapped. "Riesgo acumulado" reads "probabilidad". The models' details are a table of one row per model, without the version or the batch state. --- .../paciente-riesgo-cama.spec.ts | 2 +- .../paciente-riesgo-estimando.spec.ts | 50 ++++++++++++++----- .../paciente-riesgo-tabla.html | 48 ++++++++++-------- .../paciente-riesgo-tabla.scss | 2 + .../paciente-detalle/paciente-riesgo-tabla.ts | 3 +- .../paciente-riesgo.models.ts | 6 ++- .../paciente-riesgo.presentacion.ts | 16 ++++-- .../paciente-detalle/paciente-riesgo.spec.ts | 17 ++++--- .../paciente-riesgo.testing.ts | 5 +- .../paciente-riesgo.validation.ts | 14 +++++- 10 files changed, 112 insertions(+), 51 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 423dc9d..6e3f422 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -84,7 +84,7 @@ describe('Riesgo individual de la paciente CaMa', () => { expect(text).toContain('17.8 %'); expect(text).toContain('25.1 %'); expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/); - expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); + expect([...(f.nativeElement as HTMLElement).querySelectorAll('table.risk tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); }); // Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace. diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index cb6363f..a0d0257 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -5,7 +5,7 @@ import { of } from 'rxjs'; import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; -import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { conIntervalo, covariables, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; @@ -27,8 +27,8 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => { expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({ - quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.', - outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' }); + quantity: 'Probabilidad', description: 'Probabilidad de CIN2+ antes de cada horizonte.', + outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', covariates: 'VPH y citología índice' }); expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista()); }); @@ -40,7 +40,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => { const { root } = setup(riesgoCacuConEstimando()); - expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim())) .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo'); for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) { @@ -52,7 +52,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('dibuja la curva solo al abrir su sección', async () => { const { fixture, root } = setup(riesgoCacuConEstimando()); const details = root.querySelector('details.risk-curve') as HTMLDetailsElement; - expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado'); + expect(details.querySelector('summary')!.textContent).toContain('Curva de probabilidad'); expect(root.querySelector('app-plotly-chart')).toBeNull(); details.open = true; details.dispatchEvent(new Event('toggle')); @@ -66,7 +66,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { expect(banda.data).toHaveLength(3); expect(banda.data[2]['y']).toEqual([8, 21, 34]); expect(banda.data[1]['y']).toEqual([5, 15, 26]); - expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)'); + expect((banda.layout['yaxis'] as any).title.text).toBe('Probabilidad (%)'); const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) }; const barras = figuraRiesgoPaciente([parcial]); @@ -76,9 +76,9 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => { const { root } = setup(riesgoCacuDosDesenlaces()); - expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim())) .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); - const fila = [...root.querySelectorAll('tbody tr')][2]; + const fila = [...root.querySelectorAll('table.risk tbody tr')][2]; expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim())) .toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']); }); @@ -86,8 +86,8 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => { const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']); - expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo ' - + 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen una probabilidad ' + + 'a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + 'respectivamente.'); expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull(); }); @@ -113,19 +113,19 @@ describe('Riesgo individual: qué se estima y su curva', () => { const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' }; expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01'); expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) ' - + 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); + + 'tienen una probabilidad a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); }); it('sin modelo de un desenlace su columna dice No disponible', () => { const { root } = setup(riesgoCacuConEstimando()); - const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']); }); it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => { const data = riesgoCacuCancerSinEstimar(); const { root } = setup(data); - const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']); expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población'); const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!; @@ -134,4 +134,28 @@ describe('Riesgo individual: qué se estima y su curva', () => { expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers')) .toHaveLength(1); }); + + it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido', () => { + const data = riesgoCacuConEstimando(); + const r = data.entry[0].resource; + r.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' }); + r.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; }); + const lote = riesgoPacienteResponse(data, '42')!.riesgo; + expect(lote.horizontes[0]).toMatchObject({ horizonte_anios: 1 }); + expect(lote.horizontes[0].probabilidad).toBeCloseTo(0.92); + expect(lote.horizontes[0].ic_bajo).toBeCloseTo(0.88); + expect(lote.horizontes[0].ic_alto).toBeCloseTo(0.95); + expect(encabezado(lote)).toBe('Probabilidad de supervivencia'); + }); + + it('pone las covariables al pie de la tabla y el detalle en una fila por modelo, sin versión ni estado', () => { + const { root } = setup(riesgoCacuDosDesenlaces()); + expect(root.querySelector('.covariates-note')!.textContent).toBe('Covariables: VPH y citología índice.'); + expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(2); + expect(root.textContent).not.toMatch(/Versión del modelo|Estado del lote/); + expect(root.querySelector('caption')!.textContent).toContain('Probabilidad en porcentaje (0 a 100 %)'); + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + riesgos[1].estimando = { ...riesgos[1].estimando, covariates: 'otras' }; + expect(covariables(riesgos)).toBe('Covariables: Probabilidad a LIEAG+: VPH y citología índice; Probabilidad a cáncer: otras.'); + }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 6cbd5f0..5416dfd 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -14,9 +14,9 @@ @let filas = filasDe(lotesDe(columnas)); @if (filas.length) {
- - +
{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice - ({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis
+ @for (c of columnas; track c.encabezado) { } @@ -36,25 +36,31 @@ @for (c of columnas; track c.encabezado) { @if (c.lote?.sin_estimacion; as motivo) {

{{ c.encabezado }}: {{ motivo }}.

} } + @if (covariables(riesgos); as texto) {

{{ texto }}

}
Detalle del modelo - @for (r of riesgos; track r.id) { - @if (riesgos.length > 1) {
{{ encabezado(r) }}
} - - } +
+
Probabilidad en porcentaje (0 a 100 %) por horizonte desde la fecha índice + ({{ riesgo.fecha_indice }}), con su intervalo de confianza de 95 % entre paréntesis
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ c.encabezado }} (%)
+ + + + + + + @for (r of riesgos; track r.id) { + + + + + + + + + + } + +
ProbabilidadModeloQué se estimaDesenlaceDesdeFecha índiceEvaluado en
{{ encabezado(r) }}{{ r.modelo_nombre }}{{ r.estimando?.description ?? '—' }}{{ r.estimando?.outcome ?? r.desenlace_texto ?? r.desenlace }}{{ r.estimando?.index_date ?? '—' }}{{ r.fecha_indice }}
+
@if (filas.length > 1) {
@@ -62,7 +68,7 @@ @if (frase(riesgos); as texto) {

{{ texto }}

} @if (curvaAbierta()) { + [label]="'Curvas de probabilidad individual ' + rotulo() + ' por horizonte'" /> }
} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index 768e31a..5b1677d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -24,3 +24,5 @@ tbody tr:last-child > * { border-bottom: 0; } .risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; } .unavailable { color: var(--issste-text-secondary); } .unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; } +.covariates-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; } +table.models { min-width: 48rem; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 1cb53c2..0fa8ab7 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -3,7 +3,7 @@ import { LowerCasePipe } from '@angular/common'; import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; import { PlotlyFigure } from '../indicadores.models'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; -import { ColumnaRiesgo, columnasRiesgo, conRiesgo, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { ColumnaRiesgo, columnasRiesgo, conRiesgo, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -39,6 +39,7 @@ export class PacienteRiesgoTabla { readonly frase = fraseRiesgo; readonly filasDe = filasRiesgo; readonly conRiesgo = conRiesgo; + readonly covariables = covariables; columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); } lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); } private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 9da4a44..f2bf13e 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -16,13 +16,17 @@ export interface HorizonteRiesgoCacu { /** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */ export interface EstimandoRiesgo { - /** e.g. "Riesgo acumulado"; also `method.text`. */ + /** e.g. "Probabilidad"; also `method.text`. */ quantity?: string; description?: string; outcome?: string; index_date?: string; /** The unit the horizons are counted in, e.g. "años". */ horizons_unit?: string; + /** The variables the model uses, in words, as the record writes them under the table. */ + covariates?: string; + /** `supervivencia`: the model gives the probability of the outcome (dying) and the record shows its complement. */ + complement?: string; } /** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts index f31c557..da9a3ee 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -5,7 +5,7 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; export function etiquetaDesenlace(lote: LoteRiesgoCacu): string { if (lote.desenlace.startsWith('cin2')) return 'LIEAG+'; if (lote.desenlace === 'cancer') return 'cáncer'; - if (lote.desenlace === 'muerte') return 'muerte'; + if (lote.desenlace === 'muerte') return lote.estimando?.complement === 'supervivencia' ? 'supervivencia' : 'muerte'; return lote.desenlace_texto ?? lote.desenlace; } @@ -13,7 +13,8 @@ export function etiquetaDesenlace(lote: LoteRiesgoCacu): string { * `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */ export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string { const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : ''; - return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`; + const etiqueta = etiquetaDesenlace(lote); + return `${etiqueta === 'supervivencia' ? 'Probabilidad de supervivencia' : `Probabilidad a ${etiqueta}`}${desde}`; } /** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8", @@ -110,6 +111,15 @@ export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null { const desenlaces = junta(riesgos.map(etiquetaDesenlace)); const valores = junta(ultima.celdas.map(c => conIntervalo(c!))); const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`; - return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} ` + return `${inicio} (${fecha}) tienen una probabilidad a ${anios} de estar presente o de aparecer ${desenlaces} ` + `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`; } + +/** The covariates under the table: each model's, by its column, or once when every model uses the same ones. */ +export function covariables(riesgos: LoteRiesgoCacu[]): string | null { + const con = riesgos.filter(r => r.estimando?.covariates); + if (!con.length) return null; + const textos = [...new Set(con.map(r => r.estimando!.covariates!))]; + if (textos.length === 1) return `Covariables: ${textos[0]}.`; + return `Covariables: ${con.map(r => `${encabezado(r)}: ${r.estimando!.covariates}`).join('; ')}.`; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 684d4e0..f8cb645 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -45,13 +45,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); // horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval - expect(root.querySelectorAll('thead th')).toHaveLength(3); - expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); - expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); + expect(root.querySelectorAll('table.risk thead th')).toHaveLength(3); + expect([...root.querySelectorAll('table.risk thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); + expect(root.querySelectorAll('table.risk tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)'); - expect(root.textContent).toContain('Final (final)'); - for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { + // the record names the model, its index date and outcome, not its version nor the batch's state + expect(root.textContent).not.toMatch(/Final \(final\)|2\.1\.0/); + for (const value of ['modelo-cacu', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); } // The record no longer shows the cohort's internals (its definition, version or model variables). @@ -73,7 +74,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(getComputedStyle(scroll).overflow).toBe('auto'); expect(getComputedStyle(scroll).maxWidth).toBe('100%'); expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); - expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); + expect(getComputedStyle(root.querySelector('table.risk thead th')!).position).toBe('sticky'); }); it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { @@ -85,10 +86,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { prediccion(0.00123, '2026-06-01', '2038-09-01'), ]; const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; - expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); + expect([...root.querySelectorAll('table.risk tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']); - expect(root.textContent).toContain('Preliminar (preliminary)'); + expect(root.textContent).not.toContain('Preliminar (preliminary)'); }); it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index c3d0eea..e69b7b6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -57,9 +57,10 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { export function riesgoCacuConEstimando(): any { const data = riesgoCacuEjemplo(); const resource = data.entry[0].resource; - resource.method.text = 'Riesgo acumulado'; + resource.method.text = 'Probabilidad'; resource.extension = [{ url: ESTIMANDO, extension: [ - { url: 'quantity', valueString: 'Riesgo acumulado' }, + { url: 'quantity', valueString: 'Probabilidad' }, + { url: 'covariates', valueString: 'VPH y citología índice' }, { url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' }, { url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' }, { url: 'horizons_unit', valueString: 'años' }, diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index 932bf4b..46e826d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -13,7 +13,7 @@ const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph']; -const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit']; +const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'covariates', 'complement']; function utcTimestamp(v: unknown): v is string { return typeof v === 'string' @@ -138,6 +138,17 @@ function simulated(resource: Record): boolean { return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } +/** A model whose estimand asks for its complement (survival from a probability of dying): each horizon becomes + * 1 − p, and its interval 1 − high to 1 − low. */ +function complemento(lote: LoteRiesgoCacu): void { + if (lote.estimando?.complement !== 'supervivencia') return; + lote.horizontes = lote.horizontes.map(h => ({ + ...h, probabilidad: 1 - h.probabilidad, + ic_bajo: h.ic_alto == null ? h.ic_alto ?? null : 1 - h.ic_alto, + ic_alto: h.ic_bajo == null ? h.ic_bajo ?? null : 1 - h.ic_bajo, + })); +} + /** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ export function ordenDesenlace(desenlace: string): number { return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2; @@ -157,6 +168,7 @@ export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): if (!record(resource) || !simulated(resource)) invalid(); return riskAssessment(structuredClone(resource), pacId); }); + riesgos.forEach(complemento); riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace)); return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos }; } From 68b5e927e7833e159edea0fae4ff3503f3d773df Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:04:13 -0600 Subject: [PATCH 04/19] CaCu follow-up table: the latest biopsy, and the probabilities of the status filtered A column with each patient's latest biopsy. The probability columns follow the follow-up status chosen, its scenario's models: a case shows survival, pre-colposcopy LIEAG+ and cancer, post-colposcopy and post-treatment LIEAG+, every patient none. A horizon selector, and an order by the most recent study or one of the columns shown, which the API applies to the whole list. --- .../indicadores/cacu-seguimiento.models.ts | 25 +++++++++- .../indicadores/cacu-seguimiento.service.ts | 15 +++++- .../indicadores/cacu-seguimiento.spec.ts | 48 ++++++++++++++++++- .../indicadores/indicadores-tracking.html | 18 ++++++- .../indicadores/indicadores-tracking.ts | 34 +++++++++++-- 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 4fbd27f..40e7fad 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,4 +1,6 @@ -export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } +export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia'; +export type OrdenSeguimiento = 'reciente' | ProbabilidadClave; +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } // A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`. export interface SeguimientoPaciente { @@ -9,13 +11,20 @@ export interface SeguimientoPaciente { ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; dias_toma_diagnostico: number | null; + /** CaCu: her latest biopsy reported by the cut-off, with its grade. */ + ultima_biopsia?: { fecha: string; grado: string | null } | null; + /** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */ + probabilidades?: Partial> | null; prioridad: SeguimientoStatus | null; } +export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; } export interface SeguimientoResponse { simulado: boolean; corte: string; ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string }; - filtros: { estatus: string | null }; + filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number }; + /** The horizons the models give, in years, for ordering and showing the probabilities. */ + horizontes_disponibles?: number[]; estatus_disponibles: SeguimientoStatus[]; reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[]; paginacion: { page: number; page_size: number; total_items: number; total_pages: number }; @@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string { export function latestStudy(item: SeguimientoPaciente): string | null { return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null; } +/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */ +export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined { + return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte); +} +/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival). + * Every patient or an unknown status shows none: each scenario has its own models. */ +export const COLUMNAS_DE_PROBABILIDAD: Readonly> = { + CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'], +}; +export const ETIQUETA_PROBABILIDAD: Readonly> = { + lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia', +}; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index d073b33..a1e68fc 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -7,6 +7,14 @@ import { PAGE_SIZE_MAX } from './seguimiento-tabla.service'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; +const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia']; +const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0; +const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1; +// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates. +const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string'); +const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) => + ['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad']) + && (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto'])))); export function validSeguimientoQuery(q: SeguimientoQuery) { return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX; } @@ -17,6 +25,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const p = v['paginacion'], window = v['ventana'], filters = v['filtros']; if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta']) || !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string') + || (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string)) + || (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios))) || !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status) || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages']) @@ -25,7 +35,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const c = item['ultima_citologia'], h = item['ultimo_vph']; return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) - && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); + && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])) + && biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']); }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @@ -37,6 +48,8 @@ export class CacuSeguimientoService { let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size); if (query.corte) params = params.set('corte', query.corte); if (query.estatus) params = params.set('estatus', query.estatus); + if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden); + if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte); return this.http.get('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse)); } } diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 679d629..e9e24c6 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -42,7 +42,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(root.textContent).toContain('Insatisfactoria'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte'); - expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8); + expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9); expect(root.querySelector('form input[name="corte"]')).not.toBeNull(); expect(root.querySelector('form select[name="meses"]')).not.toBeNull(); expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull(); @@ -97,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => { for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); http.expectNone(()=>true); }); + // Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the + // horizon stop reaching the API (the list is paginated, so ordering happens there). + it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' }, + probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }], + cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] }, + } : item); + const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } }; + open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const fila = root.querySelector('tbody tr')!; + expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %'); + expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)'); + expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']); + + fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1'); + req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges(); + expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)'); + }); + + // Fails if the columns stop following the status filtered: each scenario has its own models. + it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' }, + probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item); + const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } }; + open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim()); + expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)'); + expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false); + expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)'); + expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']); + + fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia'; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.has('orden')).toBe(false); + req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges(); + expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false); + expect(root.querySelector('select[name="orden"]')).toBeNull(); + }); }); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 0ad6b25..0af754a 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -48,6 +48,18 @@ @for (t of tiposAlteracion; track t.codigo) { } } + @if (dominio === 'cacu') { + @if (columnasDelEstatus(draft.estatus).length) { + + } + @if (columnasDelEstatus(draft.estatus).length) { + + } + } @@ -107,16 +119,18 @@
- + @for (c of columnasProbabilidad(); track c) {} @for (item of response.items; track identidad(item).id) { + + @for (c of columnasProbabilidad(); track c) { } - } @empty { } + } @empty { }
Resultados disponibles por paciente
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHÚltima biopsia{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)Estudio más recienteDías de toma a diagnósticoPrioridad
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible }@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}Fecha: {{ b.fecha }} } @else { No disponible }{{ probabilidad(item, c) ?? 'No disponible' }}{{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
No hay registros para los filtros aplicados.
No hay registros para los filtros aplicados.
diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 3c6d847..d49291a 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -5,7 +5,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service'; -import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion'; import { MatButtonModule } from '@angular/material/button'; import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; @@ -64,6 +65,28 @@ export class IndicadoresTracking implements OnChanges { private metadataLoaded = false; categories: Record = {}; draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 }; + /** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */ + horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; } + horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; } + readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD; + /** The probability columns of a follow-up status (its scenario's models); none for every patient. */ + columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] { + return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : []; + } + /** The probability columns of the list shown: those of the status it was filtered by. */ + columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); } + /** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */ + ordenes(): { codigo: string; etiqueta: string }[] { + return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' }, + ...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))]; + } + /** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */ + probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null { + const h = probabilidadAl(item, clave, this.horizonteMostrado()); + if (!h) return null; + const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : ''; + return `${porcentaje(h.probabilidad)} %${ic}`; + } private applied: SeguimientoQuery = { ...this.draft }; readonly latestStudy = latestStudy; readonly gruposEdad = GRUPOS_EDAD_TEA; @@ -87,7 +110,7 @@ export class IndicadoresTracking implements OnChanges { if (result.data) { const data = result.data; this.statuses = data.estatus_disponibles; - this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; + this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size }; this.draft = { ...this.applied }; if (!this.metadataLoaded) { this.metadataLoaded = true; @@ -131,7 +154,12 @@ export class IndicadoresTracking implements OnChanges { this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q }; (this.dominio === 'tea' ? this.teaRequests : this.requests).next(q); } - apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); } + apply() { + this.draft.page_size = acotarTamano(this.draft.page_size); + // an order by a column the chosen status doesn't show goes back to the most recent study + if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente'; + this.load({ ...this.draft, page: 1 }); + } retry() { this.load(this.applied); } navigate(page: number) { if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return; From 396902541deda5d190b9e3d5e9eb4b8960b0d3f3 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:38:12 -0600 Subject: [PATCH 05/19] CaCu history: the screening-to-treatment time panel draws its measure `CACU-DIAS-TOMA-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it, and the panel specs count the active and reserved panels from their lists. --- .../fixtures/cacu_fhir_measures.json | 119 +++++++++++++++++- .../indicadores/indicadores-cacu-fhir.spec.ts | 4 +- .../indicadores-historico-cacu-fhir.spec.ts | 4 +- ...indicadores-historico-cacu-paneles.spec.ts | 31 ++--- .../indicadores-historico-config.ts | 5 +- 5 files changed, 140 insertions(+), 23 deletions(-) diff --git a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json index d4126ee..9684288 100644 --- a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json +++ b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json @@ -1,7 +1,7 @@ { "resourceType": "Bundle", "type": "searchset", - "total": 7, + "total": 8, "link": [ { "relation": "self", @@ -414,6 +414,123 @@ "mode": "match" } }, + { + "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO", + "resource": { + "resourceType": "Measure", + "id": "CACU-DIAS-TOMA-TRATAMIENTO", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/contrato", + "valueCode": "C3r" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo", + "valueCode": "semestre" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo", + "valueCode": "mes" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/figuras", + "valueString": "fig_c3r_caja" + } + ], + "url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO", + "version": "0.1.0", + "name": "cacu_dias_toma_tratamiento", + "title": "Tiempo de tamizaje a tratamiento", + "status": "active", + "subjectCodeableConcept": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/unidad", + "code": "examen" + } + ] + }, + "description": "Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del realizado.", + "scoring": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-scoring", + "code": "continuous-variable" + } + ] + }, + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + }, + "group": [ + { + "code": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida", + "code": "TOTAL" + } + ] + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "description": "Unidades del periodo", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "description": "Unidades con valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-population-exclusion" + } + ] + }, + "description": "Unidades sin valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + } + ] + } + ] + }, + "search": { + "mode": "match" + } + }, { "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-EU-TIEMPO-REPORTE", "resource": { diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index a4a773b..1a367e7 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -107,13 +107,13 @@ const reporteDe = (m: Measure, conteos: number[]): Report => ({ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => { it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => { - // Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none + // Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none // yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not // checked against the renderer. const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras])); expect(figuras).toEqual({ cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'], - cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], + cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], cacu_riesgo_banda: [], ind1: [], }); }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 7236108..9daec48 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -96,7 +96,8 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { // the page gives it, and with the contract the panel expects. const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); - expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']); + expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', + 'cacu_dias_toma_tratamiento']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); @@ -105,7 +106,6 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'], ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'], ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], ]); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index c4c80d1..0b5330e 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -19,8 +19,9 @@ const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStar const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1']; const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; -const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']; -const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', + 'cacu_dias_toma_tratamiento']; +const RESERVADOS = ['cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); @@ -95,21 +96,21 @@ describe('Histórico de CaCu', () => { expect([...vistos].sort()).toEqual([...ACTIVOS].sort()); for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false); }); - it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => { + it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo)); expect(paneles()).toHaveLength(9); - expect(graficas()).toHaveLength(6); - const reservados = paneles().slice(6); + expect(graficas()).toHaveLength(ACTIVOS.length); + const reservados = paneles().slice(ACTIVOS.length); expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true); expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual( - HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo'])); + HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo'])); }); it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => { // Pins down: the state of a reserved panel comes from the config alone. for (const catalogo of [ACTIVOS.map(item), CATALOGO]) { montar(catalogo, true); responder(); - expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo')); + expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo')); fixture.destroy(); TestBed.resetTestingModule(); } }); @@ -122,7 +123,7 @@ describe('Histórico de CaCu', () => { it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { // Pins down the first request: the page asks for the latest five months, not the twelve it could. montar(CATALOGO, true); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); }); @@ -130,7 +131,7 @@ describe('Histórico de CaCu', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)'); expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); @@ -176,7 +177,7 @@ describe('Histórico de CaCu', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5)); pedidos.length = 0; fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder(); @@ -188,7 +189,7 @@ describe('Histórico de CaCu', () => { const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo'); expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); }); it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => { montar(CATALOGO, true); @@ -196,17 +197,17 @@ describe('Histórico de CaCu', () => { const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.querySelector('[role="alert"]')).not.toBeNull(); expect(panel.textContent).not.toContain('private'); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); const reintentar = panel.querySelector('button') as HTMLButtonElement; reintentar.click(); fixture.detectChanges(); responder(); - expect(graficas()).toHaveLength(6); + expect(graficas()).toHaveLength(ACTIVOS.length); }); it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => { // Pins down the expected contract: the panel does not draw a C1 where it declared a composition. montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} }); const panel = panelDe(tituloDe('cacu_eu7')); expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1'); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); }); it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => { montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} }); @@ -226,7 +227,7 @@ describe('Histórico de CaCu', () => { } }); it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => { - montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true); + montar(RESERVADOS.map(item), true); expect(paneles()).toHaveLength(9); expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 6de8005..3025d8c 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -42,7 +42,7 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, ]; -// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. +// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask. export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' }, @@ -50,8 +50,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', - enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] }, + { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] }, { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', From eada50d2ff92aa7ba07329b62a25290b96313aa5 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:38:55 -0600 Subject: [PATCH 06/19] CaCu history: the diagnosis-to-treatment time panel draws its measure `CACU-DIAS-DIAGNOSTICO-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it. --- .../fixtures/cacu_fhir_measures.json | 119 +++++++++++++++++- .../indicadores/indicadores-cacu-fhir.spec.ts | 3 +- .../indicadores-historico-cacu-fhir.spec.ts | 3 +- ...indicadores-historico-cacu-paneles.spec.ts | 4 +- .../indicadores-historico-config.ts | 3 +- 5 files changed, 124 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json index 9684288..bb879ea 100644 --- a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json +++ b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json @@ -1,7 +1,7 @@ { "resourceType": "Bundle", "type": "searchset", - "total": 8, + "total": 9, "link": [ { "relation": "self", @@ -297,6 +297,123 @@ "mode": "match" } }, + { + "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "resource": { + "resourceType": "Measure", + "id": "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/contrato", + "valueCode": "C3r" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo", + "valueCode": "semestre" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo", + "valueCode": "mes" + }, + { + "url": "https://isssteleon.org/fhir/StructureDefinition/figuras", + "valueString": "fig_c3r_caja" + } + ], + "url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "version": "0.1.0", + "name": "cacu_dias_diagnostico_tratamiento", + "title": "Tiempo de diagnóstico a tratamiento", + "status": "active", + "subjectCodeableConcept": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/unidad", + "code": "examen" + } + ] + }, + "description": "Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.", + "scoring": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-scoring", + "code": "continuous-variable" + } + ] + }, + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + }, + "group": [ + { + "code": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida", + "code": "TOTAL" + } + ] + }, + "population": [ + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "initial-population" + } + ] + }, + "description": "Unidades del periodo", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "description": "Unidades con valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-population-exclusion" + } + ] + }, + "description": "Unidades sin valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + } + ] + } + ] + }, + "search": { + "mode": "match" + } + }, { "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-DIAGNOSTICO", "resource": { diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index 1a367e7..1e506b9 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -112,7 +112,8 @@ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas // checked against the renderer. const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras])); expect(figuras).toEqual({ - cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'], + cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'], + cacu_dias_toma_diagnostico: ['fig_c3r_caja'], cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], cacu_riesgo_banda: [], ind1: [], }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 9daec48..8d04acf 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -97,7 +97,7 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento']); + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); @@ -106,7 +106,6 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'], ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], ]); // The risk bands are in the catalog and stay reserved. diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 0b5330e..43d11fe 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -20,8 +20,8 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025- const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento']; -const RESERVADOS = ['cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']; +const RESERVADOS = ['cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 3025d8c..479f657 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -51,8 +51,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', - enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] }, + { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] }, ]; From 2a36397fac3574565bef5dff41a06a8597e22cbe Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:39:42 -0600 Subject: [PATCH 07/19] CaCu history: the CIN2+ risk-band panel draws its measure `CACU-RIESGO-BANDA` is published, so its panel reads it like the others; it counts the patients of the confirmed risk batches, and is empty until one is confirmed. No CaCu history panel stays reserved. --- .../indicadores-historico-cacu-fhir.spec.ts | 11 ++++------- .../indicadores-historico-cacu-paneles.spec.ts | 4 ++-- .../indicadores/indicadores-historico-config.ts | 3 +-- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 8d04acf..8ad15ca 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -97,18 +97,15 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']); + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); } }); - it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { - const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); - expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], - ]); - // The risk bands are in the catalog and stay reserved. + it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => { + // Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure. + expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]); expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda'); }); }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 43d11fe..40e88fc 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -20,8 +20,8 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025- const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']; -const RESERVADOS = ['cacu_riesgo_banda']; + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +const RESERVADOS: string[] = []; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 479f657..ffce074 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -52,8 +52,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', - enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] }, + { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' }, ]; const HISTORICOS: Readonly>> = { From ec5b8fde6b939c8fa7e62a4948ebb831e284266f Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:54:54 -0600 Subject: [PATCH 08/19] CaCu treatment time cards: no provisional notice under the value --- .../features/indicadores/indicadores-kpi-tratamiento.spec.ts | 3 ++- src/app/features/indicadores/indicadores-kpi.ts | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts b/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts index a2850a3..f40ff6c 100644 --- a/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts @@ -78,7 +78,8 @@ describe('KPI de tratamiento de CaCu', () => { expect(cards[0].querySelector('.value')).toBeNull(); expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75'); expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD); - expect(cards[1].textContent).toContain('El evento de tratamiento se infiere de notas clínicas'); + // the cards carry no provisional notice: what the measure is lives in its technical sheet + expect(cards[1].textContent).not.toContain('Indicador provisional'); expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento'); expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull(); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 86b0443..1278d29 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -22,7 +22,6 @@ const CACU_TRATAMIENTO_C3R = { unit: 'días (mediana)', requiresObservations: true, c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`, - note: 'Indicador provisional. El evento de tratamiento se infiere de notas clínicas, sin confirmación de que se realizó.', } satisfies Omit; export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [ From 5bf6af8ecfa108375a1cca8b44ee8daf498485ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 22 Nov 2026 16:12:44 -0600 Subject: [PATCH 09/19] Revert "CaMa patient card: the SEER model's survival by clinical scenario beside the production model's" This reverts commit dd356efb6b04cfe630b7e1b79ca3aee96570d910. --- .../cama/cama-patient-card.html | 6 -- .../cama/cama-patient-card.ts | 3 +- .../cama/cama-supervivencia-seer-figura.ts | 45 ------------- .../cama/cama-supervivencia.html | 16 ----- .../cama/cama-supervivencia.models.ts | 42 ------------- .../cama/cama-supervivencia.scss | 3 - .../cama/cama-supervivencia.service.ts | 20 ------ .../cama/cama-supervivencia.ts | 63 ------------------- 8 files changed, 1 insertion(+), 197 deletions(-) delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 4d362d3..eb4fcfc 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -48,12 +48,6 @@

Riesgo de muerte

@if (p.idField === 'pac_id') { } - @if (p.idField === 'pac_id') { -
-
Supervivencia por escenario clínico (modelo SEER)
- -
- }
Recomendaciones

{{ recommendationsUnavailable }}

diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index 0e56235..04c8d89 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -5,7 +5,6 @@ import { MatCardModule } from '@angular/material/card'; import { MatIconModule } from '@angular/material/icon'; import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component'; import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component'; -import { CamaSupervivencia } from './cama-supervivencia'; import { CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE, } from './cama-patient.models'; @@ -17,7 +16,7 @@ import { */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia, CamaSupervivencia], + imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts deleted file mode 100644 index f914101..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-seer-figura.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { PlotlyFigure } from '../../indicadores.models'; -import { SupervivenciaFigura } from './cama-supervivencia.models'; - -const decimales = new Intl.NumberFormat('es-MX'); - -/** - * The figure the doctors read: Kaplan-Meier with its Greenwood band, the classic and the fractional Weibull, and the - * LR + HBN combined survival at each horizon with its bootstrap interval. - */ -export function figuraSupervivencia(figura: SupervivenciaFigura): PlotlyFigure { - const meses = figura.months ?? []; - const km = figura.km!; - const curvas = figura.curve_months ?? []; - const combinados = figura.points.filter(p => p.model === 'COMB'); - const alcance = curvas.length ? curvas[curvas.length - 1] : meses[meses.length - 1]; - const todos = [...km.lo, ...km.hi, ...combinados.flatMap(p => [p.low, p.high]), ...(figura.weibull?.S ?? []), ...(figura.fractional?.S ?? [])] - .filter(v => Number.isFinite(v)); - const minimo = Math.min(...todos), maximo = Math.max(...todos), margen = (maximo - minimo) * 0.06; - return { - data: [ - { x: meses, y: km.lo, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, hoverinfo: 'skip', showlegend: false }, - { x: meses, y: km.hi, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 0 }, fill: 'tonexty', fillcolor: 'rgba(154,165,177,0.3)', - hoverinfo: 'skip', showlegend: false }, - { x: meses, y: km.S, type: 'scatter', mode: 'lines', line: { shape: 'hv', width: 2, color: '#222222' }, - name: 'Kaplan-Meier (IC 95 % Greenwood)' }, - { x: curvas, y: figura.weibull!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#1f77b4' }, name: 'Weibull' }, - { x: curvas, y: figura.fractional!.S, type: 'scatter', mode: 'lines', line: { width: 3, color: '#d1495b', dash: 'dash' }, - name: 'Weibull fraccional' }, - { x: combinados.map(p => p.months), y: combinados.map(p => p.S), type: 'scatter', mode: 'markers', - marker: { symbol: 'diamond', size: 12, color: '#6a3d9a', line: { color: '#ffffff', width: 1 } }, - error_y: { type: 'data', symmetric: false, array: combinados.map(p => p.high - p.S), arrayminus: combinados.map(p => p.S - p.low), - color: '#6a3d9a', thickness: 2, width: 5 }, - name: 'LR + HBN combinado (IC 95 % bootstrap)' }, - ], - layout: { - title: { text: `${figura.scenario}
n=${decimales.format(figura.members)}, fallecidos=${decimales.format(figura.deaths)}`, font: { size: 15 } }, - xaxis: { title: { text: 'Meses desde el diagnóstico' }, range: [0, alcance + 0.8], dtick: 3, zeroline: false }, - yaxis: { title: { text: 'Supervivencia S(t)' }, range: [Math.max(0, minimo - margen), Math.min(1.005, maximo + margen)] }, - legend: { x: 0.01, y: 0.01, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,0)' }, - margin: { l: 70, r: 20, t: 70, b: 60 }, - hovermode: 'x unified', - }, - config: { responsive: true, displaylogo: false }, - }; -} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html deleted file mode 100644 index a516010..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.html +++ /dev/null @@ -1,16 +0,0 @@ -@switch (estado()) { - @case ('cargando') { } - @case ('sin-modelo') {

No hay un modelo de supervivencia en producción.

} - @case ('error') { } - @case ('sin-escenarios') {

La paciente no pertenece a ninguno de los escenarios clínicos del modelo.

} - @default { - @if (escenarios().length > 1) { - - @for (nombre of escenarios(); track nombre) { {{ nombre }} } - - } - @if (cargandoFigura()) { } - @if (figura(); as f) { } - @if (sinDibujo(); as mensaje) {

{{ mensaje }}

} - } -} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts deleted file mode 100644 index 00c744b..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.models.ts +++ /dev/null @@ -1,42 +0,0 @@ -/** The survival figure of one clinical scenario, as `GET /cama/supervivencia/figura` gives it. */ -export interface SupervivenciaPunto { model: 'LR' | 'HBN' | 'COMB'; months: number; S: number; low: number; high: number } - -export interface SupervivenciaFigura { - scenario: string; - members: number; - deaths: number; - drawable: boolean; - horizons: number[]; - months?: number[]; - km?: { S: number[]; lo: number[]; hi: number[] }; - curve_months?: number[]; - weibull?: { k: number; S: number[] }; - fractional?: { k: number; alpha: number; beta: number; S: number[] }; - points: SupervivenciaPunto[]; -} - -export interface SupervivenciaEscenarios { model_version: string; build: number; pac_id: number; scenarios: string[] } - -const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); -const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number'); - -export function supervivenciaEscenarios(v: unknown): SupervivenciaEscenarios { - if (!record(v) || !Array.isArray(v['scenarios']) || !v['scenarios'].every(s => typeof s === 'string') - || typeof v['model_version'] !== 'string' || typeof v['pac_id'] !== 'number') { - throw new Error('Respuesta de escenarios de supervivencia inválida'); - } - return v as unknown as SupervivenciaEscenarios; -} - -export function supervivenciaFigura(v: unknown): SupervivenciaFigura { - if (!record(v) || typeof v['scenario'] !== 'string' || typeof v['members'] !== 'number' || typeof v['deaths'] !== 'number' - || typeof v['drawable'] !== 'boolean' || !numbers(v['horizons']) || !Array.isArray(v['points'])) { - throw new Error('Respuesta de figura de supervivencia inválida'); - } - if (v['drawable']) { - const km = v['km'], w = v['weibull'], f = v['fractional']; - if (!numbers(v['months']) || !numbers(v['curve_months']) || !record(km) || !numbers(km['S']) || !numbers(km['lo']) || !numbers(km['hi']) - || !record(w) || !numbers(w['S']) || !record(f) || !numbers(f['S'])) throw new Error('Figura de supervivencia incompleta'); - } - return v as unknown as SupervivenciaFigura; -} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss deleted file mode 100644 index d2249ae..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.scss +++ /dev/null @@ -1,3 +0,0 @@ -:host { display: block; min-width: 0; --plot-height: 420px; } -.scenarios { display: flex; flex-wrap: wrap; margin-bottom: 0.75rem; } -.availability { margin: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts deleted file mode 100644 index a85c12b..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.service.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { inject, Injectable } from '@angular/core'; -import { HttpClient, HttpParams } from '@angular/common/http'; -import { map } from 'rxjs'; -import { supervivenciaEscenarios, supervivenciaFigura } from './cama-supervivencia.models'; - -@Injectable({ providedIn: 'root' }) -export class CamaSupervivenciaService { - private readonly http = inject(HttpClient); - - /** The scenarios a patient belongs to, from her variables over the timeline. */ - escenarios(pacId: number) { - return this.http.get(`/cama/supervivencia/pacientes/${pacId}`).pipe(map(supervivenciaEscenarios)); - } - - /** The figure of one scenario over the production model and the live cohort. */ - figura(escenario: string) { - const params = new HttpParams().set('escenario', escenario); - return this.http.get('/cama/supervivencia/figura', { params }).pipe(map(supervivenciaFigura)); - } -} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts deleted file mode 100644 index 7de57ea..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { MatButtonToggleModule } from '@angular/material/button-toggle'; -import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { Subscription } from 'rxjs'; -import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; -import { PlotlyFigure } from '../../indicadores.models'; -import { figuraSupervivencia } from './cama-supervivencia-seer-figura'; -import { CamaSupervivenciaService } from './cama-supervivencia.service'; - -/** - * A patient's survival: the clinical scenarios she belongs to and the figure of the one chosen, computed over the model in - * production and the live cohort. - */ -@Component({ - selector: 'app-cama-supervivencia', - imports: [MatButtonToggleModule, MatProgressBarModule, PlotlyChart], - templateUrl: './cama-supervivencia.html', - styleUrl: './cama-supervivencia.scss', -}) -export class CamaSupervivencia { - readonly pacId = input.required(); - readonly estado = signal<'cargando' | 'listo' | 'sin-escenarios' | 'sin-modelo' | 'error'>('cargando'); - readonly escenarios = signal([]); - readonly elegido = signal(null); - readonly figura = signal(null); - readonly cargandoFigura = signal(false); - readonly sinDibujo = signal(null); - private readonly servicio = inject(CamaSupervivenciaService); - private readonly destroy = inject(DestroyRef); - private pedido?: Subscription; - - constructor() { - effect(() => this.cargar(this.pacId())); - } - - private cargar(pacId: number) { - this.estado.set('cargando'); this.figura.set(null); this.sinDibujo.set(null); this.elegido.set(null); - this.servicio.escenarios(pacId).pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: respuesta => { - this.escenarios.set(respuesta.scenarios); - if (!respuesta.scenarios.length) { this.estado.set('sin-escenarios'); return; } - this.estado.set('listo'); - this.elegir(respuesta.scenarios[0]); - }, - error: (e: { status?: number }) => this.estado.set(e?.status === 404 ? 'sin-modelo' : 'error'), - }); - } - - elegir(escenario: string) { - this.elegido.set(escenario); this.figura.set(null); this.sinDibujo.set(null); this.cargandoFigura.set(true); - this.pedido?.unsubscribe(); - this.pedido = this.servicio.figura(escenario).subscribe({ - next: f => { - this.cargandoFigura.set(false); - if (this.elegido() !== escenario) return; - if (f.drawable) this.figura.set(figuraSupervivencia(f)); - else this.sinDibujo.set(`El escenario tiene ${f.members} pacientes y ${f.deaths} fallecidos: son pocos para dibujar su curva.`); - }, - error: () => { this.cargandoFigura.set(false); this.sinDibujo.set('No se pudo calcular la figura. Intenta nuevamente.'); }, - }); - } -} From 7f1e43bdc5eff01d162cc41debe6a83522902ffe Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 16:26:55 -0600 Subject: [PATCH 10/19] =?UTF-8?q?CaCu=20indicators:=20no=20=C2=ABTiempo=20?= =?UTF-8?q?de=20tamizaje=20a=20diagn=C3=B3stico=C2=BB=20figures=20next=20t?= =?UTF-8?q?o=20the=20screening=20route=20chart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The route chart draws every time from the sample to each event, the cytology's result and the diagnosis included, so the separate time figures repeated it. They come back only when the chart isn't shown (the catalog lacks one of its measures). --- .../indicadores/indicadores-cacu-secciones.spec.ts | 11 ++++------- src/app/features/indicadores/indicadores-page.ts | 14 +++++++------- .../indicadores-screening-route-page.spec.ts | 10 +++++----- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 11845e3..56638f3 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -53,14 +53,11 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = 'catalog-card: Tiempo de toma de muestra a diagnóstico']); }); - it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => { - // Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route - // chart's own page spec forbids. + it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => { + // Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it. abrir([...CACU, ...RUTA]); - expect(titulos('.kpi-section .catalog-grid')).toEqual([ - 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', - 'catalog-card: Tiempo de toma de muestra a diagnóstico']); + expect(root().querySelector('.subsection-title')).toBeNull(); + expect(titulos('.kpi-section .catalog-grid')).toEqual([]); expect(root().querySelector('app-indicador-screening-route')).not.toBeNull(); expect(titulos('.graphic-section .catalog-grid')).toEqual([ 'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica', diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index ff07dc5..4c19360 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -400,8 +400,9 @@ export class IndicadoresPage { const selected = new Set(this.selectedIndicators()); return { items: this.catalogOrder().filter(item => selected.has(item.id)) }; }); - // The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's five times, each a - // pending slot while the catalog does not publish its indicator. The rest are the clinical ones. + // The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending + // slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The + // rest are the clinical ones. // The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for. readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => { const items = this.searchResults().items; @@ -416,11 +417,10 @@ export class IndicadoresPage { return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo }; }); } - if (this.dominio !== 'cacu' || !this.catalog().length) return []; - // The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while - // it is shown, so those slots are left to the chart instead of drawn twice or as pending. - const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : []; - return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => { + // With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to + // each event. Without it (the catalog lacks one of its measures) the times keep their figures. + if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return []; + return CACU_FIGURAS_OPORTUNIDAD.map(figura => { const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined; return item ? { item, titulo: item.titulo } : { titulo: figura.titulo }; }); diff --git a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts index c226da3..2ae7b88 100644 --- a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts +++ b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts @@ -33,14 +33,14 @@ describe('Ruta del tamizaje: página de CaCu', () => { const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route'); const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id); - it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => { - // Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis' - // keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card. + it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => { + // Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the + // «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as + // a card. abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]); expect(ruta()).not.toBeNull(); const ids = tarjetas(); - for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id); - expect(ids).toContain('cacu_eu_tiempo_reporte'); + for (const id of ROUTE_IDS) expect(ids).not.toContain(id); expect(ids).toContain('cacu_eu7'); }); it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => { From f058f1f476367d5778241ace99ccdde8a5a858a3 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 16:30:01 -0600 Subject: [PATCH 11/19] Screening route chart: it follows the page's period filter, with no filter of its own The chart takes the page's period type and shows the newest of the periods the filter applies that has published boxes (the newest with data when the filter applies every period), so it moves with the other indicators. Its own period selector is gone; the period shown is written over the chart. --- .../indicadores/indicador-screening-route.html | 7 +------ .../indicadores/indicador-screening-route.spec.ts | 4 +++- .../indicadores/indicador-screening-route.ts | 12 +++++------- src/app/features/indicadores/indicadores-page.html | 2 +- src/app/features/indicadores/indicadores-page.ts | 6 ++++++ src/app/features/indicadores/screening-route.spec.ts | 11 +++++++++++ src/app/features/indicadores/screening-route.ts | 10 +++++++--- 7 files changed, 34 insertions(+), 18 deletions(-) diff --git a/src/app/features/indicadores/indicador-screening-route.html b/src/app/features/indicadores/indicador-screening-route.html index fef2e09..72d1bec 100644 --- a/src/app/features/indicadores/indicador-screening-route.html +++ b/src/app/features/indicadores/indicador-screening-route.html @@ -8,12 +8,7 @@ } @if (model(); as m) {
- - Periodo - - @for (period of m.periods; track period) { {{ periodLabel(period) }} } - - + @if (m.period) {

Periodo: {{ periodLabel(m.period) }}

} Acumulado desde la toma Por pasos diff --git a/src/app/features/indicadores/indicador-screening-route.spec.ts b/src/app/features/indicadores/indicador-screening-route.spec.ts index 7a804b5..3b38cf7 100644 --- a/src/app/features/indicadores/indicador-screening-route.spec.ts +++ b/src/app/features/indicadores/indicador-screening-route.spec.ts @@ -64,8 +64,10 @@ describe('Ruta del tamizaje: componente', () => { expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeUndefined(); f.componentInstance.selectView('steps'); f.detectChanges(); expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeDefined(); - f.componentInstance.selectPeriod('2025-S1'); f.detectChanges(); + // the period follows the page's filter, with no request of its own + f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges(); expect(f.componentInstance.model()!.period).toBe('2025-S1'); + expect(f.nativeElement.querySelector('mat-select')).toBeNull(); f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicador-screening-route.ts b/src/app/features/indicadores/indicador-screening-route.ts index c1d66fe..e2752a2 100644 --- a/src/app/features/indicadores/indicador-screening-route.ts +++ b/src/app/features/indicadores/indicador-screening-route.ts @@ -3,9 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http'; import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; -import { MatFormFieldModule } from '@angular/material/form-field'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { MatSelectModule } from '@angular/material/select'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { etiquetaPeriodo } from './indicadores-historico-figures'; @@ -16,7 +14,7 @@ import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, ro /** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */ @Component({ selector: 'app-indicador-screening-route', - imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-screening-route.html', styleUrl: './indicador-screening-route.scss', }) @@ -24,17 +22,18 @@ export class IndicadorScreeningRoute { readonly dominio = input.required(); readonly tema = input.required(); readonly tipo = input('semestre'); + /** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */ + readonly periodos = input(undefined); /** The measures load once the region is visible. */ readonly visible = input(true); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); readonly message = signal(''); readonly view = signal('cumulative'); - readonly requestedPeriod = signal(undefined); private readonly payloads = signal | undefined>(undefined); readonly model = computed(() => { const data = this.payloads(); - return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined; + return data ? routeModel(data, this.tipo(), this.periodos()) : undefined; }); readonly figure = computed(() => { const model = this.model(); @@ -56,7 +55,6 @@ export class IndicadorScreeningRoute { } retry() { this.load(this.dominio(), this.tipo()); } - selectPeriod(period: string) { this.requestedPeriod.set(period); } selectView(view: RouteView) { this.view.set(view); } private load(dominio: Dominio, tipo: TipoPeriodo) { @@ -67,7 +65,7 @@ export class IndicadorScreeningRoute { this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({ next: data => { try { - const model = routeModel(data, tipo, this.requestedPeriod()); + const model = routeModel(data, tipo, this.periodos()); this.payloads.set(data); this.status.set(routeHasData(model) ? 'ready' : 'empty'); } catch (error) { this.failure(error); } diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index fed9daa..5b80202 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -126,7 +126,7 @@ Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.
} - @if (screeningRouteAvailable) { } + @if (screeningRouteAvailable) { }
@for (item of clinicosItems(); track cardIdentity(item)) { 0 && !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA); } + /** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening + * route); `undefined` when it applies every period. */ + periodosDelFiltro(): readonly string[] | undefined { + const seleccion = this.filters?.applied.selection; + return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined; + } // CaCu's screening route chart, once the catalog publishes every measure it reads. get screeningRouteAvailable() { return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id)); diff --git a/src/app/features/indicadores/screening-route.spec.ts b/src/app/features/indicadores/screening-route.spec.ts index bd397c0..69f781e 100644 --- a/src/app/features/indicadores/screening-route.spec.ts +++ b/src/app/features/indicadores/screening-route.spec.ts @@ -49,6 +49,17 @@ describe('Ruta del tamizaje: modelo', () => { expect(routeModel(data, 'semestre').period).toBe('2025-S2'); expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1'); }); + it('con los periodos del filtro de la página se usa el más reciente de ellos con cajas publicadas', () => { + // Fails if the chart, which has no period filter of its own, ignores the page's periods or opens on an empty one of + // them while an earlier one it was given has data. + const vacio = (id: string) => payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id]), + row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S1', '2025-S2', '2026-S1']); + const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)])); + expect(routeModel(data, 'semestre', ['2025-S1', '2026-S1', '2025-S2']).period).toBe('2025-S2'); + expect(routeModel(data, 'semestre', ['2025-S1']).period).toBe('2025-S1'); + expect(routeModel(data, 'semestre', ['2026-S1']).period).toBe('2026-S1'); + expect(routeModel(data, 'semestre', ['2023-S1']).period).toBe('2025-S2'); + }); it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => { // Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box // becomes a bar or leaves a gap in the chain. diff --git a/src/app/features/indicadores/screening-route.ts b/src/app/features/indicadores/screening-route.ts index 0f8f768..77fd39e 100644 --- a/src/app/features/indicadores/screening-route.ts +++ b/src/app/features/indicadores/screening-route.ts @@ -47,7 +47,8 @@ const fail = (message: string): never => { throw new RouteIncompatible(message); const NOT_AVAILABLE: Caja = { estado: 'No disponible' }; /** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */ -export function routeModel(data: Record, tipo: TipoPeriodo, requested?: string): RouteModel { +export function routeModel(data: Record, tipo: TipoPeriodo, + requested?: string | readonly string[]): RouteModel { const boxes: Record> = {}; for (const id of ROUTE_IDS) { const d = data[id]; @@ -66,9 +67,12 @@ export function routeModel(data: Record, tipo: TipoPerio } } const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse(); - // Without a valid request the newest period that has a published box: a semester that has just begun is empty. + // The newest of the requested periods (the page's filter) that has a published box, else the newest requested one; + // without a valid request, the newest period that has a published box: a semester that has just begun is empty. const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado'); - const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0]; + const pedidos = (typeof requested === 'string' ? [requested] : [...(requested ?? [])]) + .filter(p => periods.includes(p)).sort().reverse(); + const period = pedidos.length ? pedidos.find(hasData) ?? pedidos[0] : periods.find(hasData) ?? periods[0]; let cursor = 0; const rows = ROUTE_STEPS.map((step): RouteRow => { const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE; From 29c9e6853b3d6bb524818be17e02b7760b5b9afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Trevi=C3=B1o=20Cervantes?= Date: Sun, 22 Nov 2026 18:04:57 -0600 Subject: [PATCH 12/19] CaMa recurrence: the patient's own scenarios, without a cohort menu --- .../cama-analisis-recurrencia.component.html | 13 +++---- .../cama-analisis-recurrencia.component.ts | 34 +++++++++---------- .../cama/cama-analisis.component.spec.ts | 22 ++++++------ .../cama/cama-recurrencia.service.ts | 7 +++- 4 files changed, 37 insertions(+), 39 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html index 16b0a97..a72627d 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html @@ -4,16 +4,11 @@ @if (r === undefined) {

Buscando el análisis de recurrencia…

} @if (r === null) {

Todavía no hay un modelo de recurrencia en producción.

} @if (r) { - @if (r.escenarios.length === 0) {

Todavía no hay escenarios clínicos de recurrencia para mostrar.

} + @if (escenarios().length === 0) {

La paciente no cumple las condiciones de ningún escenario clínico de recurrencia.

} @else { - @if (figura(); as figure) { } @@ -22,7 +17,7 @@
Factores de riesgo
- @if (r && r.escenarios.length) { + @if (escenario()) { + @if (opciones().length === 1) {

Escenario clínico de la paciente: {{ escenario() }}

} + @else { + + } @let l = lectura(); @if (l?.tipo === 'cargando') {

Calculando con los datos más recientes…

} @if (l?.tipo === 'rechazada') {

{{ $any(l).motivo }}

} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts index 512bd71..e1dcc6a 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts @@ -9,9 +9,9 @@ import { figuraSupervivencia } from './cama-supervivencia-figura'; type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores }; /** - * «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label - * at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on - * the scenario the patient belongs to. + * «Análisis de supervivencia» and its «Factores de riesgo» of the clinical scenario the patient's own data place her in; when they place + * her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the + * model in production. */ @Component({ selector: 'app-cama-analisis-supervivencia', @@ -25,6 +25,8 @@ export class CamaAnalisisSupervivencia { /** The menu; `undefined` while it loads, `null` when there is no model in production. */ readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id)))); private readonly elegido = signal(null); + /** Her scenarios; every scenario only if the server could not place her. */ + readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; }); readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null); readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of(null) : this.service.consulta(nombre).pipe( map((datos): Lectura => ({ tipo: 'lista', datos })), diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts index ae2cdf2..622ba6e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts @@ -78,7 +78,8 @@ describe('Análisis de supervivencia', () => { beforeEach(() => { consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) })); TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: { - escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] }); + escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }, { nombre: 'Estadio IV', n: 30 }], + deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], predeterminado: 'Estadio I' }), consulta } }] }); }); afterEach(() => vi.unstubAllGlobals()); const montar = () => { @@ -89,12 +90,12 @@ describe('Análisis de supervivencia', () => { return f; }; - // Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed. - it('opens on the patient\'s scenario with the menu the API gave', () => { + // Fails if the menu does not open on the patient's scenario, or offers a scenario her data do not place her in. + it('opens on the patient\'s scenario and offers only hers', () => { const f = montar(); const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim()); - expect(opciones).toEqual(['< 45 años', 'Estadio I']); + expect(opciones).toEqual(['Estadio I', '< 45 años']); expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I'); expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']); }); @@ -104,7 +105,7 @@ describe('Análisis de supervivencia', () => { const f = montar(); expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row - elegir(f, 'Escenario clínico', '< 45 años'); + elegir(f, 'Escenarios clínicos de la paciente', '< 45 años'); expect(consulta).toHaveBeenLastCalledWith('< 45 años'); expect(texto(f)).toContain('Grado=G3 (robusto, 97%)'); @@ -112,6 +113,25 @@ describe('Análisis de supervivencia', () => { }); }); +describe('Análisis de supervivencia de una paciente con un solo escenario', () => { + // Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu. + it('names her one scenario and draws it without a menu', () => { + const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null })); + TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: { + escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], + deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] }); + const f = TestBed.createComponent(CamaAnalisisSupervivencia); + f.componentRef.setInput('pacId', '9'); + f.detectChanges(); + f.detectChanges(); + + expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull(); + expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte'); + expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte'); + vi.unstubAllGlobals(); + }); +}); + describe('Análisis de recurrencia', () => { // Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2. it('scales the y axis to the months it draws', () => { diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts index b3a4f0f..e9de7cb 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -87,7 +87,7 @@ export function filaFactores(v: unknown): FilaFactores { } /** The scenarios the menu offers, and the one the patient belongs to first. */ -export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; } +export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; deLaPaciente: { nombre: string; n: number }[]; predeterminado: string | null; } /** A scenario's figure with its risk factors (`null`: it has no summary row). */ export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; } /** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */ @@ -97,13 +97,13 @@ export class SeleccionRechazada extends Error {} export class CamaCurvasService { private readonly http = inject(HttpClient); - /** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */ + /** The scenarios the menu offers, the patient's own and her default, or `null` when there is no model in production or no cohort yet. */ escenarios(pacId: string): Observable { return this.http.get('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( map(r => { if (!record(r) || !Array.isArray(r['escenarios'])) invalid(); - const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; }); - return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null }; + const leer = (v: unknown) => (Array.isArray(v) ? v : []).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; }); + return { escenarios: leer(r['escenarios']), deLaPaciente: leer(r['de_la_paciente']), predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null }; }), catchError(() => of(null)), ); From ff1f6758ba67f0286b292b4321ea9f2169fa043f Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 22:27:49 -0600 Subject: [PATCH 19/19] fix(cacu): ajustar trazabilidad y figuras disponibles --- .../indicadores-cacu-secciones.spec.ts | 20 ++++++++++++++----- ...indicadores-historico-cacu-paneles.spec.ts | 2 +- .../indicadores-historico-pestana.spec.ts | 2 +- .../indicadores/indicadores-historico.ts | 4 ++-- .../features/indicadores/indicadores-kpi.ts | 7 +++---- .../features/indicadores/indicadores-page.ts | 15 +++++++------- .../indicadores-recorrido-analisis.spec.ts | 2 +- .../indicadores/indicadores-sections.spec.ts | 2 +- 8 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 521e7e6..145e33d 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -39,16 +39,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')] .map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim()); - it('las cinco figuras conservan su orden y las ausentes quedan como pendientes', () => { + it('las figuras disponibles conservan su orden sin reservas vacías', () => { // Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose // the names of the request. abrir(CACU); expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico'); expect(titulos('.kpi-section .catalog-grid')).toEqual([ 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', - 'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía', - 'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia', 'catalog-card: Tiempo de toma de muestra a diagnóstico']); }); @@ -68,7 +65,6 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(root().querySelector('app-indicador-screening-route')).toBeNull(); expect(titulos('.kpi-section .catalog-grid')).toEqual([ 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', 'catalog-card: Tiempo de toma de muestra a resultado de colposcopía', 'catalog-card: Tiempo de toma de muestra a resultado de biopsia', 'catalog-card: Tiempo de toma de muestra a diagnóstico']); @@ -91,6 +87,20 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull(); }); + it('agrega la gráfica publicada de diagnóstico a tratamiento al final', () => { + abrir([...CACU, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]); + expect(titulos('.kpi-section .catalog-grid')).toEqual([ + 'catalog-card: Tiempo de toma de muestra a resultado de citología', + 'catalog-card: Tiempo de toma de muestra a diagnóstico', + 'catalog-card: Tiempo de diagnóstico a tratamiento']); + }); + + it('conserva la ruta y muestra la gráfica publicada de diagnóstico a tratamiento', () => { + abrir([...CACU, ...RUTA, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]); + expect(root().querySelector('app-indicador-screening-route')).not.toBeNull(); + expect(titulos('.kpi-section .catalog-grid')).toEqual(['catalog-card: Tiempo de diagnóstico a tratamiento']); + }); + it('Datos y definiciones conserva todo el catálogo', () => { // Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab. abrir(CACU); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 40e88fc..04426a7 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -76,7 +76,7 @@ describe('Histórico de CaCu', () => { const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!; const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo; const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); - const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!; + const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!; it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => { // Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it. diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index fb6c8e5..f0ea485 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -42,7 +42,7 @@ describe('Pestaña Histórico', () => { // Fails if CaCu loses its history tab or gains CaMa's analysis tab. abrir('cama', []); abrir('cacu', [item('cacu_x', 'C2')]); - expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); expect(root().querySelector('#panel-analisis')).toBeNull(); }); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 4647bfa..fe1f47c 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -117,13 +117,13 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
@for (paso of pasos; track paso.titulo) {

{{ paso.titulo }}

- +
}
} @else { + [label]="(dominio() === 'cacu' ? 'Trazabilidad de ' : 'Histórico de ') + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" /> } @if (panel.figura.comoLeer) {

{{ panel.figura.comoLeer }}

} @if (panel.figura.suprimidos.length) { diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index d8a7bf3..f719d9a 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -66,17 +66,16 @@ export const KPI_RESUMEN_TEA: KpiDefinition[] = [ export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg']; -// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot -// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure. +// CaCu's available figures in display order; titles are assigned when the catalog publishes them. export interface FiguraOportunidad { id?: string; titulo: string; } export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' }, - { titulo: 'Tiempo de toma de muestra a resultado de VPH' }, { id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' }, { id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' }, + { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento' }, ]; -// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. Same rules as CaCu's: an entry +// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry // with no `id` has no published indicator yet and draws as pending. export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' }, diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 5d1db51..43c5468 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -47,6 +47,7 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ // TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's, // between its history and its follow-up list. const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]]; +const SECTIONS_CACU: typeof SECTIONS_WITH_HISTORY = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]]; // Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered. export const CAMA_ANALYSIS_ENABLED = false; // TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them. @@ -67,7 +68,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } + get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.dominio === 'cacu' ? SECTIONS_CACU : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; } get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; } readonly activeSection = signal('resumen'); @@ -423,12 +424,12 @@ export class IndicadoresPage { return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo }; }); } - // With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to - // each event. Without it (the catalog lacks one of its measures) the times keep their figures. - if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return []; - return CACU_FIGURAS_OPORTUNIDAD.map(figura => { - const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined; - return item ? { item, titulo: item.titulo } : { titulo: figura.titulo }; + // Preserve the route chart; individual figures require a published figure contract. + if (this.dominio !== 'cacu' || !this.catalog().length) return []; + return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => { + if (this.screeningRouteAvailable && figura.id !== 'cacu_dias_diagnostico_tratamiento') return []; + const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0); + return item ? [{ item, titulo: item.titulo }] : []; }); }); readonly clinicosItems = computed(() => { diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 2ad3912..2612c1c 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( - ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + ['Indicadores', dominio === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 7c45c3a..f35e0a3 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -40,7 +40,7 @@ describe('Secciones compartidas por dominio', () => { const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); // TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain. - const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + const esperadas = ['Indicadores', domain === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;