Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6465165e34 | |||
| a26df55214 | |||
| 72e5f9bf93 | |||
| 08f1d812ac | |||
| ce207a72a5 | |||
| 5094880622 | |||
| 093ceffa36 | |||
| 6a7c1d0cbd | |||
| fb5a4ed5cc | |||
| a3a552ad0e | |||
| fb54cfb188 | |||
| 4e9b25bd8f | |||
| 68e2930e65 | |||
| fa029d69b8 | |||
| 67ae7f482f | |||
| 304c563845 |
@@ -80,7 +80,8 @@ describe('Encabezado del marco', () => {
|
||||
await ir(url);
|
||||
expect(selector()).toBeNull();
|
||||
expect(root().querySelector('.platform-title')).toBeNull();
|
||||
expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información');
|
||||
expect(root().querySelector('.site-header__section')).toBeNull();
|
||||
expect(root().querySelector('.site-header__nav')?.textContent).not.toContain('Análisis de información');
|
||||
expect(root().querySelector('.app-shell--indicadores')).toBeNull();
|
||||
if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos');
|
||||
});
|
||||
|
||||
+1
-2
@@ -20,9 +20,8 @@
|
||||
}
|
||||
} @else {
|
||||
<nav class="site-header__nav" aria-label="Secciones">
|
||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||
@if (breadcrumb(); as crumb) {
|
||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
||||
<span class="site-header__crumb" aria-current="page">{{ crumb }}</span>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
|
||||
@@ -41,14 +41,6 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
text-decoration: none;
|
||||
color: var(--color-text);
|
||||
font-size: 15px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
@@ -89,11 +81,6 @@
|
||||
width: clamp(132px, 42vw, 170px);
|
||||
}
|
||||
|
||||
.site-header__section {
|
||||
font-size: 13px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.site-footer__content {
|
||||
min-height: 76px;
|
||||
padding: 0 20px;
|
||||
|
||||
@@ -60,6 +60,15 @@ describe('App', () => {
|
||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('home shows only the brand name as eyebrow and names the risk models action', async () => {
|
||||
// Fails if the eyebrow regains the section text or the action goes back to «Indicadores».
|
||||
const page = await render('/');
|
||||
expect(page.querySelector('.home__eyebrow')?.textContent?.trim()).toBe('ISSSTELEON');
|
||||
const acciones = Array.from(page.querySelectorAll('.home__action')).map(a => a.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(acciones.some(t => t?.endsWith('Modelos predictivos de riesgo'))).toBe(true);
|
||||
expect(acciones.some(t => t?.endsWith('Indicadores'))).toBe(false);
|
||||
});
|
||||
|
||||
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
|
||||
const page = await render('/conectar');
|
||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface Concept { coding?: Coding[]; text?: string }
|
||||
export interface Quantity { value?: number; unit?: string }
|
||||
export interface Extension {
|
||||
url: string;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number;
|
||||
valueCode?: string; valueString?: string; valueInteger?: number; valueDecimal?: number; valueBoolean?: boolean;
|
||||
valueDate?: string; valueDateTime?: string; valueCoding?: Coding; valueReference?: { reference?: string };
|
||||
extension?: Extension[];
|
||||
}
|
||||
|
||||
@@ -97,13 +97,13 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
|
||||
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||
<tbody>@for (i of d.items; track i.codigo) {
|
||||
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
|
||||
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
|
||||
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
|
||||
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
|
||||
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Análisis de riesgos'">Ver pacientes</button> }</td></tr>
|
||||
}</tbody></table>
|
||||
</div>
|
||||
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
|
||||
@@ -155,7 +155,7 @@ export function detalleTarjeta(t: TarjetaAnalisis): string {
|
||||
}
|
||||
@if (m(); as mm) {
|
||||
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
|
||||
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Análisis de riesgos.</p>
|
||||
<details><summary>Valores publicados</summary>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
|
||||
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
|
||||
|
||||
@@ -127,7 +127,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
||||
expect(tarjetas[0].textContent).not.toContain('6 pacientes');
|
||||
expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS');
|
||||
expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.');
|
||||
expect(text()).toContain('abrir la lista en Seguimiento');
|
||||
expect(text()).toContain('abrir la lista en Análisis de riesgos');
|
||||
});
|
||||
it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => {
|
||||
// Fails if the cards stay on screen without an answer with categories.
|
||||
@@ -177,7 +177,7 @@ describe('Pestaña Análisis epidemiológico', () => {
|
||||
const filas = Array.from(root().querySelectorAll('tbody tr')) as HTMLElement[];
|
||||
expect(filas.map(f => !!f.querySelector('button.ver'))).toEqual([false, false, false, false, true, false]);
|
||||
expect(filas[0].textContent).toContain(MOTIVO_GRUPO_SUPRIMIDO);
|
||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Seguimiento');
|
||||
expect(filas[4].querySelector('button')!.getAttribute('aria-label')).toBe('Ver pacientes de BI-RADS 5 en Análisis de riesgos');
|
||||
});
|
||||
it('el botón de la tabla y la barra emiten la misma selección; la barra suprimida no emite nada', () => {
|
||||
// Fails if a click stops reaching Seguimiento, sends another group, or a hidden bar emits.
|
||||
|
||||
@@ -93,18 +93,18 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
|
||||
<p class="aviso" role="status">{{ aviso() }}</p>
|
||||
<app-plotly-chart [style.--plot-height]="'360px'" [style.--plot-min-width]="'480px'" [showNotes]="false" [figure]="figura()" (plotClick)="clicGrupo($event)"
|
||||
label="Pacientes por categoría BI-RADS" />
|
||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||
<p class="nota">Haga clic en una barra o use «Ver pacientes» para abrir la lista en Análisis de riesgos. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.</p>
|
||||
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Pacientes por categoría BI-RADS, tabla">
|
||||
<table>
|
||||
<caption>Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col"><span class="visually-hidden">Análisis de riesgos</span></th></tr></thead>
|
||||
<tbody>
|
||||
@for (g of d.grupos; track g.codigo) {
|
||||
<tr [attr.data-grupo]="g.codigo">
|
||||
<th scope="row">{{ etiqueta(g.codigo) }}</th>
|
||||
<td>{{ g.suprimido ? 'No publicado' : miles(g.n!) }}</td>
|
||||
<td>@if (g.suprimido) { <span class="sin-lista">{{ motivo }}</span> }
|
||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Seguimiento'">Ver pacientes</button> }</td>
|
||||
@else { <button type="button" class="ver" (click)="verGrupo(g.codigo, $event.currentTarget)" [attr.aria-label]="'Ver pacientes de ' + etiqueta(g.codigo) + ' en Análisis de riesgos'">Ver pacientes</button> }</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
// technical sheet from `Measure`, the data rows from `MeasureReport`, the periods from two one-report searches, the
|
||||
// C3r box plot, and the follow-up list and patient summary from `EpisodeOfCare` and `$resumen-tea`; each mapped into
|
||||
// the shapes the page reads and passed through the same checks.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database.
|
||||
// Fixtures: `indicadores-fhir.fixtures.ts`, real responses of the WebApi over its TEA fixture database; `conModelo`
|
||||
// below adds to its patient summary the age at the EEG, a metric's age-norm curve and the ADOS-2 association model,
|
||||
// in the shape `webapi/fhir/tea.py` emits them.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Bundle, Resource, resources } from './fhir';
|
||||
import {
|
||||
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
|
||||
periodosDesde, Report,
|
||||
@@ -20,6 +22,49 @@ import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-f
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
const SD = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
const CURVA = `${SD}/curva-referencia`;
|
||||
const curva = {
|
||||
url: CURVA, extension: [
|
||||
{ url: `${CURVA}/fuente`, valueString: 'tea-ritmo_posterior/3' }, { url: `${CURVA}/estado`, valueString: 'validada' },
|
||||
...[12, 24, 36].map(v => ({ url: `${CURVA}/edad-meses`, valueDecimal: v })),
|
||||
...([['p5', [4, 4.5, 5]], ['p25', [5, 5.5, 6]], ['mediana', [5.5, 6, 6.5]], ['p75', [6, 6.5, 7]], ['p95', [6.5, 7, 7.5]]] as [string, number[]][])
|
||||
.flatMap(([p, vs]) => vs.map(v => ({ url: `${CURVA}/${p}`, valueDecimal: v }))),
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
],
|
||||
});
|
||||
// The fixture's patient summary with what the WebApi adds when the analysis and the association model have data.
|
||||
function conModelo(): Bundle {
|
||||
const bundle = structuredClone(fx.resumenPaciente) as Bundle;
|
||||
for (const r of resources(bundle)) {
|
||||
if (r.resourceType === 'DiagnosticReport') r.extension = [...(r.extension ?? []), { url: `${SD}/edad-meses`, valueDecimal: 23.6 }];
|
||||
const codigo = (r['code'] as { coding?: { code?: string }[] } | undefined)?.coding?.[0]?.code;
|
||||
if (r.resourceType === 'Observation' && codigo === 'ritmo_posterior' && !r.id?.startsWith('electrodos-'))
|
||||
r.extension = [...(r.extension ?? []), curva];
|
||||
}
|
||||
const riesgo: Resource = {
|
||||
resourceType: 'RiskAssessment', id: 'relacion-ados2-P-4A59E9D8B4', status: 'final',
|
||||
meta: { tag: resources(bundle)[0].meta?.tag },
|
||||
extension: [{ url: `${SD}/modelo-version`, valueString: '1.0.0' }, { url: `${SD}/modelo-validado`, valueBoolean: false },
|
||||
{ url: `${SD}/modelo-nivel`, valueString: 'item' }, { url: `${SD}/modelo-n-cohorte`, valueInteger: 40 }],
|
||||
prediction: [prediccion('occipital', -2.6), prediccion('parietal', null)],
|
||||
};
|
||||
bundle.entry = [...(bundle.entry ?? []), { resource: riesgo }];
|
||||
return bundle;
|
||||
}
|
||||
const reports = (bundle: Bundle) => resources(bundle, 'MeasureReport') as Report[];
|
||||
|
||||
describe('Indicadores sobre FHIR', () => {
|
||||
@@ -210,6 +255,49 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
|
||||
});
|
||||
|
||||
it('el resumen lleva la edad al EEG y la norma por edad de la métrica cuando la WebApi las manda', async () => {
|
||||
// Pins down: the report's `edad-meses` extension as the EEG's age and a metric observation's `curva-referencia`
|
||||
// sub-extensions read back in order as the age norm (ages, five percentiles, source and state), so the page's
|
||||
// checks accept it. Fails if the adapter stops reading either extension or scrambles the series.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect(detalle.eeg!.edad_meses).toBe(23.6);
|
||||
expect(detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!.curva_referencia).toEqual({
|
||||
fuente: 'tea-ritmo_posterior/3', estado: 'validada', edad_meses: [12, 24, 36],
|
||||
p5: [4, 4.5, 5], p25: [5, 5.5, 6], mediana: [5.5, 6, 6.5], p75: [6, 6.5, 7], p95: [6.5, 7, 7.5] });
|
||||
});
|
||||
|
||||
it('el resumen arma la relación con el ADOS-2 del RiskAssessment y deja fuera la fila incompleta', async () => {
|
||||
// Pins down: the model's version, validation, level and cohort from the resource's extensions, and each
|
||||
// prediction as a row with the metric's and zone's labels, the outcome, OR, interval, q, z, both probabilities
|
||||
// and the observed score; a prediction without its z is dropped instead of failing the page's checks. Fails if
|
||||
// the adapter stops reading the RiskAssessment or lets an incomplete row through.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(conModelo());
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const relacion = (await answer).relacion_ados2!;
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
it('sin edad, norma ni modelo el resumen no inventa esos campos', async () => {
|
||||
// Pins down: a summary without the new extensions or a RiskAssessment (the fixture as the WebApi served it before
|
||||
// the analysis wrote them) leaves `edad_meses`, `curva_referencia` and `relacion_ados2` out, so the page hides
|
||||
// the chart and the panel. Fails if the adapter fills them with defaults.
|
||||
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
|
||||
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
|
||||
const detalle = await answer;
|
||||
expect('edad_meses' in detalle.eeg!).toBe(false);
|
||||
expect(detalle.eeg!.alteraciones.some(a => 'curva_referencia' in a)).toBe(false);
|
||||
expect('relacion_ados2' in detalle).toBe(false);
|
||||
});
|
||||
|
||||
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
|
||||
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
|
||||
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
|
||||
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -42,13 +42,13 @@ describe('Pestaña Histórico', () => {
|
||||
// Fails if the history tab of TEA or CaMa leaks into CaCu.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => {
|
||||
|
||||
@@ -37,7 +37,7 @@ import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'seguimiento', label: 'Seguimiento' },
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
@@ -48,7 +48,7 @@ export const CAMA_ANALYSIS_ENABLED = false;
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
|
||||
@@ -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(
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -39,9 +39,9 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
|
||||
// TEA and CaMa also have Histórico; the follow-up tab is named Análisis de riesgos in every domain; CaCu keeps its three tabs.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', '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)!;
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
@let r = respuesta();
|
||||
<section aria-labelledby="analisis-recurrencia-titulo">
|
||||
<h5 id="analisis-recurrencia-titulo">Análisis de recurrencia</h5>
|
||||
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Cohorte
|
||||
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
|
||||
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="factores-recurrencia-titulo">
|
||||
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
|
||||
@if (r && r.escenarios.length) {
|
||||
<label class="selector horizons">Horizonte
|
||||
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
|
||||
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
|
||||
</select>
|
||||
</label>
|
||||
<app-cama-factores-riesgo [fila]="factores()" />
|
||||
} @else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
|
||||
</section>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
|
||||
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
|
||||
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
|
||||
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-recurrencia',
|
||||
imports: [PlotlyChart, CamaFactoresRiesgo],
|
||||
templateUrl: './cama-analisis-recurrencia.component.html',
|
||||
styleUrl: './cama-analisis.component.scss',
|
||||
})
|
||||
export class CamaAnalisisRecurrencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
readonly cohortes = COHORTES;
|
||||
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
private readonly cohorteElegida = signal<string | null>(null);
|
||||
private readonly escenarioElegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
|
||||
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
|
||||
/** The scenarios of the cohort chosen, from the list of that cohort only. */
|
||||
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
|
||||
readonly escenario = computed(() => {
|
||||
const lista = this.escenarios();
|
||||
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
|
||||
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
|
||||
});
|
||||
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
|
||||
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
|
||||
readonly factores = computed(() => {
|
||||
const f = this.escenario();
|
||||
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
|
||||
});
|
||||
|
||||
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
|
||||
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
<section aria-labelledby="analisis-supervivencia-titulo">
|
||||
<h5 id="analisis-supervivencia-titulo">Análisis de supervivencia</h5>
|
||||
@let m = menu();
|
||||
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
|
||||
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
|
||||
@if (m) {
|
||||
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@let l = lectura();
|
||||
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
|
||||
@if (l?.tipo === 'error') { <p role="alert">No se pudo calcular la supervivencia de este escenario.</p> }
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Supervivencia: ' + escenario()" /> }
|
||||
}
|
||||
}
|
||||
</section>
|
||||
<section aria-labelledby="factores-supervivencia-titulo">
|
||||
<h5 id="factores-supervivencia-titulo">Factores de riesgo</h5>
|
||||
@if (lectura()?.tipo === 'lista') { <app-cama-factores-riesgo [fila]="factores()" /> }
|
||||
@else { <p class="pending">Se muestran al elegir un escenario clínico.</p> }
|
||||
</section>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { Component, computed, inject, input, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, map, of, startWith, switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaCurvasService, EscenarioConFactores, SeleccionRechazada } from './cama-curvas.service';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
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.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-supervivencia',
|
||||
imports: [PlotlyChart, CamaFactoresRiesgo],
|
||||
templateUrl: './cama-analisis-supervivencia.component.html',
|
||||
styleUrl: './cama-analisis.component.scss',
|
||||
})
|
||||
export class CamaAnalisisSupervivencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaCurvasService);
|
||||
/** 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<string | null>(null);
|
||||
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
|
||||
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
|
||||
startWith<Lectura>({ tipo: 'cargando' })))), { initialValue: null as Lectura | null });
|
||||
readonly figura = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? figuraSupervivencia(l.datos.respuesta.curvas) : null; });
|
||||
readonly factores = computed(() => { const l = this.lectura(); return l?.tipo === 'lista' ? l.datos.factores : null; });
|
||||
|
||||
elegir(nombre: string): void { this.elegido.set(nombre); }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
:host { display: block; }
|
||||
.selector { display: inline-flex; flex-direction: column; gap: .25rem; margin: 0 1.5rem .75rem 0; font-size: .85rem; }
|
||||
.selector select { font: inherit; padding: .35rem .5rem; min-width: 16rem; max-width: 100%; }
|
||||
.horizons { margin: 0 0 .5rem; }
|
||||
.pending { color: var(--mat-sys-outline, #777); margin: 0; }
|
||||
@@ -0,0 +1,177 @@
|
||||
// Covers Luis's specification of CaMa's record: the risk-factor label built from a summary row (the factors present in at least 95 % and in
|
||||
// 50-95 % of the scenario, robust solid and suggestive outlined, grey "none" message), the survival analysis (one menu of scenarios; the
|
||||
// one chosen decides the curve and the label at once; it opens on the patient's) and the recurrence analysis (two chained menus, the
|
||||
// cohorts never mixed, a horizon for the label with 60 months by default). Fixtures: stubs of `CamaCurvasService` and
|
||||
// `CamaRecurrenciaService` with a record like the API answers.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
|
||||
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
||||
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
||||
import { CamaCurvasService, respuestaCurvas } from './cama-curvas.service';
|
||||
import { CamaFactoresRiesgo, entradasDe } from './cama-factores-riesgo.component';
|
||||
import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
|
||||
const meses = Array.from({ length: 25 }, (_, i) => i);
|
||||
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
|
||||
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
|
||||
const curvas = (escenario: string, n = 245) => ({ modelo: { nombre: 'cama-survival', version: '3' }, curvas: {
|
||||
version: 1, escenario, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
|
||||
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, km_adjusted: { months: meses, S: decreciente(0.72) },
|
||||
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
|
||||
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, etiquetas: {} } });
|
||||
const fila = (escenario: string, extra: object = {}) => ({ escenario, riesgo_definitorios: 'Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)', riesgo_mayoritarios: 'HER2=H3 (sugerente, 60%)',
|
||||
n_factores_riesgo_incluidos: 3, incluye_factor_riesgo: true, ...extra });
|
||||
|
||||
const texto = (f: { nativeElement: unknown }) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
function plotly() {
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
|
||||
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
|
||||
return { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) };
|
||||
}
|
||||
function elegir(f: { nativeElement: unknown; detectChanges(): void }, etiqueta: string, valor: string) {
|
||||
const select = [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!.querySelector('select')!;
|
||||
select.value = valor;
|
||||
select.dispatchEvent(new Event('change'));
|
||||
f.detectChanges();
|
||||
}
|
||||
|
||||
describe('Factores de riesgo: la etiqueta', () => {
|
||||
const montar = (f: object | null) => {
|
||||
const fx = TestBed.createComponent(CamaFactoresRiesgo);
|
||||
fx.componentRef.setInput('fila', f);
|
||||
fx.detectChanges();
|
||||
return fx;
|
||||
};
|
||||
|
||||
// Fails if an entry is cut at the wrong place or its strength is read from anything but its own parentheses.
|
||||
it('reads the entries of a cell and whether each is robust', () => {
|
||||
expect(entradasDe('Grado=G3 (robusto, 97%); Ki67=alto (sugerente, 96%)')).toEqual([
|
||||
{ texto: 'Grado=G3 (robusto, 97%)', robusto: true }, { texto: 'Ki67=alto (sugerente, 96%)', robusto: false }]);
|
||||
expect(entradasDe('')).toEqual([]);
|
||||
});
|
||||
|
||||
// Fails if the two groups lose their order or a robust factor is not told from a suggestive one.
|
||||
it('lists the defining factors, then the majority ones, a robust one solid and a suggestive one outlined', () => {
|
||||
const fx = montar(fila('< 45 años'));
|
||||
const items = [...(fx.nativeElement as HTMLElement).querySelectorAll('li')];
|
||||
|
||||
expect(texto(fx)).toContain('Factores de riesgo de este escenario');
|
||||
expect(items.map(i => i.textContent!.trim())).toEqual(['Grado=G3 (robusto, 97%)', 'Ki67=alto (sugerente, 96%)', 'HER2=H3 (sugerente, 60%)']);
|
||||
expect(items.map(i => i.classList.contains('robust'))).toEqual([true, false, false]);
|
||||
});
|
||||
|
||||
// Fails if a scenario with no factors is shown empty, or with a different message.
|
||||
it.each([[null], [fila('X', { incluye_factor_riesgo: false })], [fila('X', { n_factores_riesgo_incluidos: 0 })]])('says there are none (%#)', f => {
|
||||
const fx = montar(f);
|
||||
|
||||
expect(texto(fx)).toContain('Sin factores de riesgo identificados en este escenario.');
|
||||
expect((fx.nativeElement as HTMLElement).querySelector('li')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de supervivencia', () => {
|
||||
let consulta: ReturnType<typeof vi.fn>;
|
||||
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 } }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
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', () => {
|
||||
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(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
||||
});
|
||||
|
||||
// Fails if choosing a scenario changes only the curve or only the label: the selector decides both at once, one scenario at a time.
|
||||
it('changes the curve and the label together when another scenario is chosen, and never draws two', () => {
|
||||
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');
|
||||
|
||||
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
||||
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
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', () => {
|
||||
const largo = { ...figura('metabric', 'Largo'), observado_hasta: 300, months_max: 72,
|
||||
km: { months: Array.from({ length: 301 }, (_, i) => i), S: Array.from({ length: 301 }, (_, i) => 1 - i / 400), low: Array.from({ length: 301 }, (_, i) => (i <= 72 ? 0.85 : 0.2)), high: Array.from({ length: 301 }, () => 1) } };
|
||||
|
||||
expect((figuraRecurrencia(respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios: [largo], resumen: [], predeterminado: null }).escenarios[0]).layout as any).yaxis.range[0]).toBeGreaterThan(0.5);
|
||||
});
|
||||
|
||||
const figura = (cohorte: string, escenario: string) => ({ cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, n: 300, recaidas: 180,
|
||||
horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72,
|
||||
km: { months: Array.from({ length: 61 }, (_, i) => i), S: Array.from({ length: 61 }, (_, i) => 1 - i / 200), low: Array.from({ length: 61 }, (_, i) => 1 - i / 190), high: Array.from({ length: 61 }, () => 1) },
|
||||
weibull: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, weibull_fractional: { t: [0, 60, 72], S: [1, 0.7, 0.65] }, points: { COMB: { S: [0.9, 0.8, 0.7], low: [0.85, 0.75, 0.65], high: [0.95, 0.85, 0.75] } } });
|
||||
const resumen = (cohorte: string, escenario: string, h: number) => ({ cohorte, escenario, horizonte_meses: h, riesgo_definitorios: `Marca=${cohorte}-${h} (robusto, 99%)`, riesgo_mayoritarios: '',
|
||||
n_factores_riesgo_incluidos: 1, incluye_factor_riesgo: true });
|
||||
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
||||
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
||||
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaAnalisisRecurrencia);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
return f;
|
||||
};
|
||||
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
||||
.querySelectorAll('option');
|
||||
|
||||
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
||||
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
||||
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Cohorte', 'metabric');
|
||||
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('scanb');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
|
||||
// Fails if the label ignores the horizon, or does not open on 60 months.
|
||||
it('shows the label at the horizon chosen, 60 months by default', () => {
|
||||
const f = montar();
|
||||
expect((f.nativeElement as HTMLElement).querySelector<HTMLSelectElement>('.horizons select')!.value).toBe('60');
|
||||
|
||||
elegir(f, 'Horizonte', '12');
|
||||
|
||||
expect(texto(f)).toContain('Marca=scanb-12');
|
||||
expect(texto(f)).not.toContain('Marca=scanb-60');
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { catchError, map, Observable, of, throwError } from 'rxjs';
|
||||
// version they come from and says when the data are simulated. A 404 is "no model in production yet".
|
||||
export interface SerieDeSupervivencia { S: number[]; low: number[]; high: number[]; }
|
||||
export interface CurvasSupervivencia {
|
||||
escenario?: string;
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
@@ -59,6 +60,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
return {
|
||||
modelo: { nombre: m['nombre'] as string, version: m['version'] as string },
|
||||
curvas: {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
@@ -68,21 +70,52 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConsultaCurvas { filtros?: Record<string, string[]>; periodo?: { desde?: string; hasta?: string }; }
|
||||
/** The selection was refused with a reason (a 422): too few patients, or invalid. */
|
||||
/** The scenario summary's row of a scenario: its risk factors. `riesgo_*` are entries `Variable=Categoría (robusto|sugerente, porcentaje)`
|
||||
* separated by `;`; `horizonte_meses` and `cohorte` only in the recurrence analysis. */
|
||||
export interface FilaFactores {
|
||||
escenario: string; riesgo_definitorios: string; riesgo_mayoritarios: string;
|
||||
n_factores_riesgo_incluidos: number; incluye_factor_riesgo: boolean; horizonte_meses?: number; cohorte?: string;
|
||||
}
|
||||
export function filaFactores(v: unknown): FilaFactores {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string') invalid();
|
||||
const f = v as Record<string, any>;
|
||||
return { escenario: f['escenario'], riesgo_definitorios: typeof f['riesgo_definitorios'] === 'string' ? f['riesgo_definitorios'] : '',
|
||||
riesgo_mayoritarios: typeof f['riesgo_mayoritarios'] === 'string' ? f['riesgo_mayoritarios'] : '',
|
||||
n_factores_riesgo_incluidos: Number.isFinite(f['n_factores_riesgo_incluidos']) ? f['n_factores_riesgo_incluidos'] : 0,
|
||||
incluye_factor_riesgo: f['incluye_factor_riesgo'] === true || f['incluye_factor_riesgo'] === 'True',
|
||||
...(Number.isFinite(f['horizonte_meses']) ? { horizonte_meses: f['horizonte_meses'] } : {}), ...(typeof f['cohorte'] === 'string' ? { cohorte: f['cohorte'] } : {}) };
|
||||
}
|
||||
|
||||
/** The scenarios the menu offers, and the one the patient belongs to first. */
|
||||
export interface MenuEscenarios { escenarios: { 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. */
|
||||
export class SeleccionRechazada extends Error {}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaCurvasService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The figure's record for the selection, scored with the production version over the data ingested so far. A refused
|
||||
* selection fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
|
||||
consulta(consulta: ConsultaCurvas): Observable<RespuestaCurvas> {
|
||||
return this.http.post<unknown>('/cama/modelo/curvas/consulta', consulta).pipe(
|
||||
map(respuestaCurvas),
|
||||
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
|
||||
escenarios(pacId: string): Observable<MenuEscenarios | null> {
|
||||
return this.http.get<unknown>('/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 };
|
||||
}),
|
||||
catchError(() => of(null)),
|
||||
);
|
||||
}
|
||||
|
||||
/** The figure of one scenario scored with the production version over the data ingested so far, and its risk factors. A refused
|
||||
* scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */
|
||||
consulta(escenario: string): Observable<EscenarioConFactores> {
|
||||
return this.http.post<unknown>('/cama/modelo/curvas/consulta', { escenario }).pipe(
|
||||
map(r => ({ respuesta: respuestaCurvas(r), factores: record(r) && r['factores'] ? filaFactores(r['factores']) : null })),
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 422
|
||||
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'La selección no se puede calcular.')))
|
||||
? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'El escenario no se puede calcular.')))
|
||||
: throwError(() => error)),
|
||||
);
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@if (hay()) {
|
||||
<p class="title">Factores de riesgo de este escenario</p>
|
||||
@if (definitorios().length) {
|
||||
<div class="group"><span class="marker" aria-hidden="true">▲</span>
|
||||
<ul aria-label="Presentes en al menos 95 % del escenario">
|
||||
@for (e of definitorios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
|
||||
</ul></div>
|
||||
}
|
||||
@if (mayoritarios().length) {
|
||||
<div class="group"><span class="marker" aria-hidden="true">▲</span>
|
||||
<ul aria-label="Presentes en 50 a 95 % del escenario">
|
||||
@for (e of mayoritarios(); track e.texto) { <li [class.robust]="e.robusto" [class.suggestive]="!e.robusto">{{ e.texto }}</li> }
|
||||
</ul></div>
|
||||
}
|
||||
} @else {
|
||||
<p class="none">Sin factores de riesgo identificados en este escenario.</p>
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
:host { display: block; }
|
||||
.title { font-weight: 600; margin: 0 0 .5rem; }
|
||||
.group { display: flex; gap: .5rem; align-items: flex-start; margin: .25rem 0; }
|
||||
.marker { color: var(--mat-sys-error, #b3261e); line-height: 1.9; }
|
||||
ul { display: flex; flex-wrap: wrap; gap: .4rem; list-style: none; margin: 0; padding: 0; }
|
||||
li { border: 1px solid var(--mat-sys-error, #b3261e); border-radius: 1rem; padding: .15rem .7rem; font-size: .9rem; }
|
||||
li.robust { background: var(--mat-sys-error, #b3261e); color: var(--mat-sys-on-error, #fff); }
|
||||
li.suggestive { background: transparent; color: var(--mat-sys-error, #b3261e); }
|
||||
.none { color: var(--mat-sys-outline, #777); margin: 0; }
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { FilaFactores } from './cama-curvas.service';
|
||||
|
||||
export interface EntradaFactor { texto: string; robusto: boolean; }
|
||||
|
||||
/** The entries of a summary cell, `Variable=Categoría (robusto|sugerente, porcentaje)` separated by `;`. */
|
||||
export function entradasDe(celda: string): EntradaFactor[] {
|
||||
return celda.split(';').map(e => e.trim()).filter(Boolean).map(texto => ({ texto, robusto: /\(\s*robusto\b/i.test(texto) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The risk factors of one clinical scenario, from its row of the scenario summary: the factors present in at least 95 % of the scenario
|
||||
* and those in 50 to 95 %, a robust one solid and a suggestive one outlined. A scenario with none says so, in grey.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-factores-riesgo',
|
||||
templateUrl: './cama-factores-riesgo.component.html',
|
||||
styleUrl: './cama-factores-riesgo.component.scss',
|
||||
})
|
||||
export class CamaFactoresRiesgo {
|
||||
readonly fila = input<FilaFactores | null>(null);
|
||||
readonly definitorios = computed(() => entradasDe(this.fila()?.riesgo_definitorios ?? ''));
|
||||
readonly mayoritarios = computed(() => entradasDe(this.fila()?.riesgo_mayoritarios ?? ''));
|
||||
readonly hay = computed(() => (this.fila()?.incluye_factor_riesgo ?? false) && (this.fila()?.n_factores_riesgo_incluidos ?? 0) > 0
|
||||
&& this.definitorios().length + this.mayoritarios().length > 0);
|
||||
}
|
||||
@@ -34,21 +34,24 @@
|
||||
</ul>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
|
||||
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<app-paciente-riesgo-tabla [pacId]="p.idField === 'pac_id' ? p.patientId : null" dominio="cama" />
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="prognosis-card" appearance="outlined" aria-labelledby="pronostico-title">
|
||||
<mat-card-header><h3 id="pronostico-title">Pronóstico y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
<ul>
|
||||
@for (item of placeholders; track item.key) {
|
||||
<li [attr.data-pronostico]="item.key"><strong>{{ item.label }}</strong><span>{{ prognosisUnavailable }}</span></li>
|
||||
}
|
||||
</ul>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
@if (p.idField === 'pac_id' && p.clinicalScenario === postTreatment) { <app-cama-analisis-recurrencia [pacId]="p.patientId" /> }
|
||||
<section aria-labelledby="recomendaciones-pronostico-title">
|
||||
<h5 id="recomendaciones-pronostico-title">Recomendaciones</h5>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
</section>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
<mat-card class="risk-card" appearance="outlined" aria-labelledby="riesgo-individual-title">
|
||||
<mat-card-header><h3 id="riesgo-individual-title">Riesgo de muerte</h3></mat-card-header>
|
||||
<mat-card-content>
|
||||
@if (p.idField === 'pac_id') { <app-cama-analisis-supervivencia [pacId]="p.patientId" /> }
|
||||
<section aria-labelledby="recomendaciones-riesgo-title">
|
||||
<h5 id="recomendaciones-riesgo-title">Recomendaciones</h5>
|
||||
<p class="availability">{{ recommendationsUnavailable }}</p>
|
||||
</section>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
// Covers CaMa's individual record: how a follow-up row becomes its summary, what the card shows (only fields the list
|
||||
// carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus
|
||||
// carries, "No disponible" for the rest, the two analyses with their risk factors in the order Luis's specification gives), and its focus
|
||||
// and back behaviour. Fixture: fixtures/cama_seguimiento.json.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { EMPTY, of } from 'rxjs';
|
||||
import { CamaCurvasService } from './cama-curvas.service';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from '../paciente-riesgo.provider';
|
||||
import fixtureData from '../../fixtures/cama_seguimiento.json';
|
||||
import { seguimientoTablaResponse } from '../../seguimiento-tabla.service';
|
||||
import { CamaPatientCard } from './cama-patient-card';
|
||||
import { CamaPatientSummary, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
|
||||
import { CamaPatientSummary, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } from './cama-patient.models';
|
||||
|
||||
const rows = () => seguimientoTablaResponse(structuredClone(fixtureData)).items;
|
||||
const complete = () => rows().find(r => r['biopsia'] !== null && r['dias_mastografia_diagnostico'] !== null)!;
|
||||
const incomplete = () => rows().find(r => r['biopsia'] === null)!;
|
||||
const withPacId = (escenario: string | null = null) => ({ ...complete(), pac_id: '7', id_seudonimo: null, escenario_clinico: escenario });
|
||||
|
||||
describe('Ficha CaMa: resumen', () => {
|
||||
// Fails if a field of the row is mapped to another one or lost on the way to the card.
|
||||
@@ -41,8 +44,11 @@ describe('Ficha CaMa: resumen', () => {
|
||||
describe('Ficha CaMa: componente', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<CamaPatientCard>>;
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
// The record asks for the patient's risk; here she has none, so the card shows what the list carries.
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] }));
|
||||
// The record asks for the analyses; here there is no model in production, so the card shows what the list carries.
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } },
|
||||
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
|
||||
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] }));
|
||||
function montar(summary: CamaPatientSummary) {
|
||||
fixture = TestBed.createComponent(CamaPatientCard);
|
||||
fixture.componentRef.setInput('summary', summary);
|
||||
@@ -75,17 +81,28 @@ describe('Ficha CaMa: componente', () => {
|
||||
expect(text).toContain('Días de mastografía a diagnóstico');
|
||||
});
|
||||
|
||||
// Fails if a placeholder gains a figure or loses its explanation: no prognosis may be shown without a model.
|
||||
it('has placeholders, with no figures, for recurrence and prognostic factors', () => {
|
||||
montar(toCamaPatientSummary(complete(), '2026-10-20')!);
|
||||
const items = [...root().querySelectorAll('[data-pronostico]')];
|
||||
expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['recurrence', 'factors']);
|
||||
expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Factores pronóstico']);
|
||||
for (const item of items) {
|
||||
expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE);
|
||||
expect(item.textContent).not.toMatch(/\d/);
|
||||
}
|
||||
expect(root().textContent).toContain(RECOMMENDATIONS_UNAVAILABLE);
|
||||
// Fails if the cards or their subsections leave the order and the names of the specification: recurrence first, then death, each with
|
||||
// its risk factors, and the recommendations unchanged (not available) in both.
|
||||
it('has "Pronóstico y recomendaciones" (recurrence, risk factors, recommendations) before "Riesgo de muerte" (survival, risk factors, recommendations)', () => {
|
||||
montar(toCamaPatientSummary(withPacId('Post-tratamiento'), '2026-10-20')!);
|
||||
const card = (selector: string) => root().querySelector(selector) as HTMLElement;
|
||||
const subsections = (selector: string) => [...card(selector).querySelectorAll('h5')].map(h => h.textContent!.trim());
|
||||
|
||||
expect([...root().querySelectorAll('mat-card h3')].map(h => h.textContent!.trim()).slice(-2)).toEqual(['Pronóstico y recomendaciones', 'Riesgo de muerte']);
|
||||
expect(subsections('.prognosis-card')).toEqual(['Análisis de recurrencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(root().textContent!.split(RECOMMENDATIONS_UNAVAILABLE).length - 1).toBe(2);
|
||||
expect(root().textContent).not.toMatch(/Información simulada|Entorno DEV|Riesgo individual CaMa|Probabilidad de recurrencia|Factores pronóstico/);
|
||||
});
|
||||
|
||||
// Fails if a patient who has not been treated is shown the recurrence analysis (and its factors), which only makes sense after treatment.
|
||||
it('shows the recurrence analysis only to a patient after treatment', () => {
|
||||
montar(toCamaPatientSummary(withPacId('En observación'), '2026-10-20')!);
|
||||
const subsections = (selector: string) => [...(root().querySelector(selector) as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim());
|
||||
|
||||
expect(subsections('.prognosis-card')).toEqual(['Recomendaciones']);
|
||||
expect(subsections('.risk-card')).toEqual(['Análisis de supervivencia', 'Factores de riesgo', 'Recomendaciones']);
|
||||
expect(root().textContent).not.toContain('Análisis de recurrencia');
|
||||
});
|
||||
|
||||
// Fails if the record opens without moving focus to its title, which strands keyboard and screen-reader users.
|
||||
|
||||
@@ -3,18 +3,20 @@ 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 { PacienteRiesgoTabla } from '../paciente-riesgo-tabla';
|
||||
import { CamaAnalisisRecurrencia } from './cama-analisis-recurrencia.component';
|
||||
import { CamaAnalisisSupervivencia } from './cama-analisis-supervivencia.component';
|
||||
import {
|
||||
CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
CamaPatientSummary, NOT_AVAILABLE, RECOMMENDATIONS_UNAVAILABLE,
|
||||
} from './cama-patient.models';
|
||||
|
||||
/**
|
||||
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries and the patient's risk with her
|
||||
* survival figure; recurrence and prognostic factors are placeholders until a validated model supplies them.
|
||||
* Individual record of a CaMa follow-up patient. It shows what the follow-up list carries, the recurrence analysis with its risk
|
||||
* factors ("Pronóstico y recomendaciones") and the survival analysis with its risk factors ("Riesgo de muerte"), one clinical
|
||||
* scenario at a time (the recurrence analysis only for patients after treatment); the recommendations are not available yet.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-patient-card',
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla],
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia],
|
||||
templateUrl: './cama-patient-card.html',
|
||||
styleUrl: './cama-patient-card.scss',
|
||||
})
|
||||
@@ -22,8 +24,8 @@ export class CamaPatientCard implements AfterViewInit {
|
||||
readonly summary = input.required<CamaPatientSummary>();
|
||||
readonly back = output<void>();
|
||||
readonly notAvailable = NOT_AVAILABLE;
|
||||
readonly placeholders = PROGNOSIS_PLACEHOLDERS;
|
||||
readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE;
|
||||
/** The recurrence analysis is for patients who have been treated: it is shown only in this clinical scenario. */
|
||||
readonly postTreatment = 'Post-tratamiento';
|
||||
readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE;
|
||||
private readonly title = viewChild<ElementRef<HTMLElement>>('title');
|
||||
readonly generating = signal(false);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Covers the one-patient PDF: that it reuses the institutional frame of the follow-up report in portrait, prints only
|
||||
// the fields of the record, shows placeholders (no figures) for recurrence and prognostic factors (survival is drawn in the record from the risk evaluation), and
|
||||
// the fields of the record, shows placeholders (no figures) for recurrence, survival and prognostic factors, and
|
||||
// renders to a real PDF file. Fixture: fixtures/cama_seguimiento.json. The logo is left out of the render test
|
||||
// because the test browser has no `Worker` to decode a PNG; the image path is checked in a real browser.
|
||||
import fixtureData from '../../fixtures/cama_seguimiento.json';
|
||||
@@ -46,10 +46,10 @@ describe('Ficha CaMa: PDF individual', () => {
|
||||
});
|
||||
|
||||
// Fails if a placeholder gains a figure or an explanation other than "unavailable".
|
||||
it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => {
|
||||
it('has placeholders, with no figures, for recurrence, survival, prognostic factors and recommendations', () => {
|
||||
const found = texts(definition()['content']);
|
||||
for (const t of ['Probabilidad de recurrencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
|
||||
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(2);
|
||||
for (const t of ['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t);
|
||||
expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(3);
|
||||
});
|
||||
|
||||
// Fails if the document carries a platform identifier field.
|
||||
|
||||
@@ -27,10 +27,11 @@ export interface CamaPatientSummary {
|
||||
daysMammographyToDiagnosis: number | null;
|
||||
}
|
||||
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do (survival is drawn from
|
||||
* the patient's risk evaluation, not a placeholder). */
|
||||
/** Placeholders for results that exist only once a validated model and its clinical definition do: what the exported PDF of the
|
||||
* record says about them (on screen, the analyses and their risk factors are drawn from the models). */
|
||||
export const PROGNOSIS_PLACEHOLDERS = [
|
||||
{ key: 'recurrence', label: 'Probabilidad de recurrencia' },
|
||||
{ key: 'survival', label: 'Supervivencia' },
|
||||
{ key: 'factors', label: 'Factores pronóstico' },
|
||||
] as const;
|
||||
export const PROGNOSIS_UNAVAILABLE = 'No disponible: pendiente de definición clínica y de un modelo validado.';
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const ETIQUETAS_RECURRENCIA = {
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Libre de recaída S(t)', km: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull',
|
||||
weibull_fraccional: 'Weibull fraccional', puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
|
||||
} as const;
|
||||
export const COLORES_RECURRENCIA = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
|
||||
|
||||
/** A curve in two parts: solid up to the follow-up the cohort has, dotted after it (the extrapolation). */
|
||||
function curva(t: number[], S: number[], hasta: number, color: string, nombre: string, dash?: string): Record<string, unknown>[] {
|
||||
const dentro = t.map((x, i) => i).filter(i => t[i] <= hasta), fuera = t.map((x, i) => i).filter(i => t[i] >= hasta);
|
||||
return [
|
||||
{ type: 'scatter', mode: 'lines', x: dentro.map(i => t[i]), y: dentro.map(i => S[i]), line: { color, width: 3, ...(dash ? { dash } : {}) }, name: nombre, legendgroup: nombre,
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + nombre + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: fuera.map(i => t[i]), y: fuera.map(i => S[i]), line: { color, width: 1.8, dash: 'dot' }, showlegend: false, legendgroup: nombre, hoverinfo: 'skip' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The recurrence analysis' figure of one scenario of one cohort, as the pipeline draws it: the Kaplan-Meier curve of the scenario's
|
||||
* patients with its Greenwood band, the classic and the fractional Weibull (dotted past the follow-up), and the recurrence-free
|
||||
* probability at each horizon by the combination of the LR and the HBN, as diamonds with their bootstrap interval.
|
||||
*/
|
||||
export function figuraRecurrencia(f: FiguraRecurrencia, tema: Tema = 'claro'): PlotlyFigure {
|
||||
const L = ETIQUETAS_RECURRENCIA, d = f.points.COMB, km = f.km;
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const visibles = (t: number[], S: number[]) => S.filter((_, i) => t[i] <= f.months_max);
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...visibles(km.months, km.low), ...visibles(f.weibull.t, f.weibull.S), ...visibles(f.weibull_fractional.t, f.weibull_fractional.S), ...d.low) - 0.02) * 20) / 20);
|
||||
const data: Record<string, unknown>[] = [
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES_RECURRENCIA.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES_RECURRENCIA.km, width: 2, shape: 'hv' }, name: L.km, legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.km + '</extra>' },
|
||||
...curva(f.weibull.t, f.weibull.S, f.observado_hasta, COLORES_RECURRENCIA.weibull, L.weibull),
|
||||
...curva(f.weibull_fractional.t, f.weibull_fractional.S, f.observado_hasta, COLORES_RECURRENCIA.fraccional, L.weibull_fraccional, 'dash'),
|
||||
{ type: 'scatter', mode: 'markers', name: L.puntos, x: f.horizons_months, y: d.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES_RECURRENCIA.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES_RECURRENCIA.modelo, thickness: 2, width: 6,
|
||||
array: d.high.map((hi, i) => Math.max(0, hi - d.S[i])), arrayminus: d.S.map((s, i) => Math.max(0, s - d.low[i])) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + L.puntos + '</extra>' },
|
||||
];
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: `${f.escenario}<br>${f.cohorte_nombre} · n=${f.n.toLocaleString('es-MX')}, recaídas=${f.recaidas.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: L.eje_x }, range: [0, f.months_max + 0.8], dtick: 12 },
|
||||
yaxis: { ...eje, title: { text: L.eje_y }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { catchError, map, Observable, of } from 'rxjs';
|
||||
import { FilaFactores, filaFactores } from './cama-curvas.service';
|
||||
|
||||
// CaMa's recurrence figures of a patient, `GET /cama/modelo/recurrencia?paciente=`: the clinical scenarios her covariates meet,
|
||||
// each as the recurrence analysis of an external cohort (METABRIC or SCAN-B) drew it. They describe the scenario's patients in
|
||||
// that cohort, not her; the answer names the version that published them. A 404 or a failure is "none to show".
|
||||
export interface FiguraRecurrencia {
|
||||
cohorte: string; cohorte_nombre: string; escenario: string; n: number; recaidas: number;
|
||||
horizons_months: number[]; observado_hasta: number; months_max: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { COMB: { S: number[]; low: number[]; high: number[] } };
|
||||
}
|
||||
export interface RespuestaRecurrencia {
|
||||
modelo: { nombre: string; version: string }; horizontes: number[]; escenarios: FiguraRecurrencia[];
|
||||
/** The summary's rows, one per cohort, scenario and horizon: the risk-factor label. */
|
||||
resumen: FilaFactores[];
|
||||
/** The cohort and scenario the patient's own covariates place her in first, if any. */
|
||||
predeterminado: { cohorte: string; escenario: string } | null;
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(x => typeof x === 'number' && Number.isFinite(x)) && (length === undefined || v.length === length);
|
||||
const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1);
|
||||
|
||||
function invalid(): never { throw new Error('Respuesta de recurrencia inválida'); }
|
||||
|
||||
function figura(v: unknown, horizons: number): FiguraRecurrencia {
|
||||
if (!record(v) || typeof v['escenario'] !== 'string' || typeof v['cohorte_nombre'] !== 'string' || typeof v['cohorte'] !== 'string') invalid();
|
||||
const f = v as Record<string, any>;
|
||||
if (!numbers(f['horizons_months'], horizons) || !Number.isFinite(f['n']) || !Number.isFinite(f['recaidas']) || !Number.isFinite(f['observado_hasta']) || !Number.isFinite(f['months_max'])) invalid();
|
||||
const km = f['km'], w = f['weibull'], k = f['weibull_fractional'], p = f['points']?.['COMB'];
|
||||
const n = Array.isArray(km?.months) ? km.months.length : -1;
|
||||
if (!numbers(km?.months) || !probabilities(km?.S, n) || !probabilities(km?.low, n) || !probabilities(km?.high, n)) invalid();
|
||||
for (const c of [w, k]) if (!numbers(c?.t) || !probabilities(c?.S, c.t.length)) invalid();
|
||||
if (!probabilities(p?.S, horizons) || !probabilities(p?.low, horizons) || !probabilities(p?.high, horizons)) invalid();
|
||||
if ((p.low as number[]).some((l, i) => l > p.high[i])) invalid();
|
||||
return f as FiguraRecurrencia;
|
||||
}
|
||||
|
||||
/** Validate at the boundary: the shapes and ranges, so the chart never draws a partial or impossible curve. */
|
||||
export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (!record(v) || !record(v['modelo']) || !Array.isArray(v['escenarios']) || !numbers(v['horizontes'])) invalid();
|
||||
const m = v['modelo'] as Record<string, unknown>, h = (v['horizontes'] as number[]).length;
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
if (!Array.isArray(v['resumen'])) invalid();
|
||||
const d = v['predeterminado'];
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CamaRecurrenciaService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The recurrence analysis of both cohorts and the patient's default, or `null` when there is no recurrence model in production or it fails. */
|
||||
recurrencia(pacId: string): Observable<RespuestaRecurrencia | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe(
|
||||
map(respuestaRecurrencia), catchError(() => of(null)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { CurvasSupervivencia } from './cama-curvas.service';
|
||||
|
||||
/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any
|
||||
* of these (`[config.etiquetas]`), so the clinicians define it, not the code. */
|
||||
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
|
||||
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
|
||||
puntos: 'LR + HBN combinado (IC 95 % bootstrap)',
|
||||
};
|
||||
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a' } as const;
|
||||
|
||||
const etiqueta = (c: CurvasSupervivencia, clave: string) => c.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
|
||||
|
||||
/**
|
||||
* The SEER pipeline's survival figure of one clinical scenario: the Kaplan-Meier curve of its patients with its Greenwood band,
|
||||
* the classic and the fractional Weibull, and the model's survival at each horizon as diamonds with their bootstrap interval.
|
||||
* Titled with the scenario, its patients and its deaths.
|
||||
*/
|
||||
export function figuraSupervivencia(c: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure {
|
||||
const km = c.km, diamantes = c.points.COMB, t = (clave: string) => etiqueta(c, clave);
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...km.low, ...c.weibull_fractional.S, ...diamantes.low) - 0.02) * 20) / 20);
|
||||
const data: Record<string, unknown>[] = [
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('km_crudo') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: c.weibull.t, y: c.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: c.weibull_fractional.t, y: c.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull_fraccional') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'markers', name: t('puntos'), x: c.horizons_months, y: diamantes.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6,
|
||||
array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' },
|
||||
];
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: `${c.escenario ?? 'Toda la cohorte'}<br>n=${c.n.toLocaleString('es-MX')}, fallecidos=${c.events.toLocaleString('es-MX')}`, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, c.months_max + 0.8], dtick: 5 },
|
||||
yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
<section class="survival" aria-labelledby="supervivencia-paciente-titulo">
|
||||
<h5 id="supervivencia-paciente-titulo">Supervivencia de la paciente</h5>
|
||||
@let l = lectura();
|
||||
@if (l.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l.tipo === 'rechazada') { <p role="status">{{ l.motivo }}</p> }
|
||||
@if (l.tipo === 'error') { <p role="status">No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.</p> }
|
||||
@if (figura(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Supervivencia de la paciente" />
|
||||
}
|
||||
</section>
|
||||
-1
@@ -1 +0,0 @@
|
||||
:host { display: block; }
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
// Covers the patient's survival in her CaMa record: the cohort's curves are asked live (for everyone, then for the covariates
|
||||
// she is compared on), a refused selection says why, a failure leaves her own curve, and the figure has the SEER pipeline's
|
||||
// look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds) with hers over it. Fixtures: a stub of
|
||||
// `CamaCurvasService` that records each selection, and a cohort record like `POST /cama/modelo/curvas/consulta` answers.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of, throwError } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime';
|
||||
import { CamaCurvasService, respuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
|
||||
import { CamaSupervivenciaPaciente } from './cama-supervivencia-paciente.component';
|
||||
import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivenciaPaciente } from './cama-supervivencia-paciente';
|
||||
|
||||
const meses = Array.from({ length: 25 }, (_, i) => i);
|
||||
const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24));
|
||||
const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) });
|
||||
function cohorte(n = 245): any {
|
||||
return {
|
||||
modelo: { nombre: 'cama-survival', version: '3' },
|
||||
curvas: {
|
||||
version: 1, n, events: 67, median_follow_up_months: 9, horizons_months: [6, 12, 18], months_max: 24, bootstrap_replicas: 200,
|
||||
km: { months: meses, S: decreciente(0.7), low: decreciente(0.6), high: decreciente(0.8) }, km_adjusted: { months: meses, S: decreciente(0.72) },
|
||||
weibull: { t: [0, 12, 24], S: [1, 0.85, 0.72] }, weibull_fractional: { t: [0, 12, 24], S: [1, 0.84, 0.71] },
|
||||
points: { LR: serie([0.93, 0.85, 0.78]), HBN: serie([0.92, 0.84, 0.77]), COMB: serie([0.925, 0.845, 0.775]) }, etiquetas: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
const horizontes = [{ horizonte_anios: 0.5, probabilidad: 0.07 }, { horizonte_anios: 1, probabilidad: 0.18 }, { horizonte_anios: 1.5, probabilidad: 0.25 }];
|
||||
|
||||
describe('Figura de supervivencia de la paciente', () => {
|
||||
const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).curvas)!;
|
||||
const traza = (f: any, nombre: string) => f.data.find((t: any) => t.name === nombre) as any;
|
||||
|
||||
// Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the cohort's diamonds.
|
||||
it('has the cohort\'s Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => {
|
||||
const f = figura();
|
||||
|
||||
expect(f.data.some((t: any) => t.fill === 'tonexty')).toBe(true);
|
||||
expect(traza(f, ETIQUETAS_PREDETERMINADAS['km_crudo']).line).toMatchObject({ color: COLORES.km, shape: 'hv' });
|
||||
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull']).line.color).toBe(COLORES.weibull);
|
||||
expect(traza(f, ETIQUETAS_PREDETERMINADAS['weibull_fraccional']).line).toMatchObject({ color: COLORES.fraccional, dash: 'dash' });
|
||||
const rombos = traza(f, ETIQUETAS_PREDETERMINADAS['puntos']);
|
||||
expect(rombos.x).toEqual([6, 12, 18]);
|
||||
expect(rombos.marker).toMatchObject({ symbol: 'diamond', color: COLORES.modelo });
|
||||
expect(rombos.error_y.array.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]);
|
||||
});
|
||||
|
||||
// Fails if her curve is not on the figure, or sits at other horizons than her evaluation's.
|
||||
it('draws hers over the cohort\'s: a curve and her diamonds at her horizons', () => {
|
||||
const f = figura();
|
||||
const suya = f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'markers') as any;
|
||||
|
||||
expect(suya.x).toEqual([6, 12, 18]);
|
||||
expect(suya.y.map((v: number) => +v.toFixed(2))).toEqual([0.93, 0.82, 0.75]);
|
||||
expect(suya.error_y).toBeUndefined();
|
||||
expect((f.data.find((t: any) => t.legendgroup === 'paciente' && t.mode === 'lines') as any).line.color).toBe(COLORES.paciente);
|
||||
});
|
||||
|
||||
// Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, n and deaths.
|
||||
it('is labelled and scaled as the pipeline\'s figure', () => {
|
||||
const l = figura().layout as any;
|
||||
|
||||
expect(l.yaxis.title.text).toBe('Supervivencia S(t)');
|
||||
expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico');
|
||||
expect(l.yaxis.tickformat).toBe('.2f');
|
||||
expect(l.title.text).toContain('n=245, fallecidos=67');
|
||||
expect(l.legend.yanchor).toBe('bottom');
|
||||
});
|
||||
|
||||
// Fails if her curve and her diamonds take two legend entries, which says nothing the curve does not.
|
||||
it('has one legend entry for her curve and her diamonds', () => {
|
||||
const f = figura();
|
||||
const suyas = f.data.filter((t: any) => t.legendgroup === 'paciente') as any[];
|
||||
|
||||
expect(suyas).toHaveLength(2);
|
||||
expect(suyas.filter(t => t.showlegend !== false)).toHaveLength(1);
|
||||
expect(f.data.some((t: any) => t.name === 'Paciente: modelo en cada horizonte')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Supervivencia de la paciente: componente', () => {
|
||||
let consulta: ReturnType<typeof vi.fn>;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('ResizeObserver', class { observe = vi.fn(); unobserve = vi.fn(); disconnect = vi.fn(); });
|
||||
const runtime = { react: vi.fn(() => Promise.resolve()), purge: vi.fn(), Plots: { resize: vi.fn(() => Promise.resolve()) },
|
||||
addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) };
|
||||
consulta = vi.fn(() => of(respuestaCurvas(cohorte())));
|
||||
TestBed.configureTestingModule({ providers: [
|
||||
{ provide: CamaCurvasService, useValue: { consulta } },
|
||||
{ provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
const f = TestBed.createComponent(CamaSupervivenciaPaciente);
|
||||
f.componentRef.setInput('pacId', '7');
|
||||
f.componentRef.setInput('horizontes', horizontes);
|
||||
f.detectChanges();
|
||||
return f;
|
||||
};
|
||||
const texto = (f: ReturnType<typeof montar>) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
|
||||
// Fails if the cohort's curves are not asked live for everyone, or the record offers choices the reader did not ask for.
|
||||
it('asks the cohort live, for everyone, and offers no choices', () => {
|
||||
const f = montar();
|
||||
|
||||
expect(consulta).toHaveBeenCalledWith({ filtros: {} });
|
||||
expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelector('input, fieldset')).toBeNull();
|
||||
expect(texto(f)).not.toContain('Comparar con');
|
||||
});
|
||||
|
||||
// Fails if a refused selection draws a figure, or does not say why.
|
||||
it('says why when the selection is refused and draws nothing', () => {
|
||||
consulta.mockReturnValue(throwError(() => new SeleccionRechazada('La selección tiene 3 pacientes y 0 defunciones.')));
|
||||
const f = montar();
|
||||
|
||||
expect(texto(f)).toContain('La selección tiene 3 pacientes');
|
||||
expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull();
|
||||
});
|
||||
|
||||
// Fails if a failed cohort computation leaves her without a figure.
|
||||
it('draws only her own curve when the cohort\'s cannot be had', () => {
|
||||
consulta.mockReturnValue(throwError(() => new Error('boom')));
|
||||
const f = montar();
|
||||
|
||||
expect(texto(f)).toContain('se muestra solo la de la paciente');
|
||||
expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
import { Component, computed, inject, input } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, map, of, startWith } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
|
||||
import { CamaCurvasService, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service';
|
||||
import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente';
|
||||
|
||||
/** What the reader calls each covariate of the model. */
|
||||
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas };
|
||||
|
||||
/**
|
||||
* One patient's survival, on the SEER pipeline's figure of the cohort. The cohort's curves are computed when the record opens,
|
||||
* from the data ingested so far and the model in production; hers is her own prediction on top of them.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-supervivencia-paciente',
|
||||
imports: [PlotlyChart],
|
||||
templateUrl: './cama-supervivencia-paciente.component.html',
|
||||
styleUrl: './cama-supervivencia-paciente.component.scss',
|
||||
})
|
||||
export class CamaSupervivenciaPaciente {
|
||||
readonly pacId = input.required<string>();
|
||||
readonly horizontes = input.required<readonly HorizonteRiesgoCacu[]>();
|
||||
private readonly service = inject(CamaCurvasService);
|
||||
readonly lectura = toSignal(this.service.consulta({ filtros: {} }).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
catchError(error => of<Lectura>(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })),
|
||||
startWith<Lectura>({ tipo: 'cargando' })), { initialValue: { tipo: 'cargando' } as Lectura });
|
||||
/** The figure: hers over the cohort's, or hers alone when the cohort's cannot be had. */
|
||||
readonly figura = computed(() => {
|
||||
const l = this.lectura();
|
||||
if (l.tipo === 'cargando' || l.tipo === 'rechazada') return null;
|
||||
return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null);
|
||||
});
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import { PlotlyFigure, Tema } from '../../indicadores.models';
|
||||
import { HorizonteRiesgoCacu } from '../paciente-riesgo.models';
|
||||
import { tieneIntervalo } from '../paciente-riesgo.validation';
|
||||
import { CurvasSupervivencia } from './cama-curvas.service';
|
||||
|
||||
/** The wording of the chart, as the SEER pipeline's own figure has it. The model's run can publish another wording for any
|
||||
* of these (`[config.etiquetas]`), so the clinicians define it, not the code. */
|
||||
export const ETIQUETAS_PREDETERMINADAS: Readonly<Record<string, string>> = {
|
||||
titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor',
|
||||
eje_x: 'Meses desde el diagnóstico', eje_y: 'Supervivencia S(t)',
|
||||
km_crudo: 'Kaplan-Meier (IC 95 % Greenwood)', weibull: 'Weibull', weibull_fraccional: 'Weibull fraccional',
|
||||
puntos: 'LR + HBN combinado (IC 95 % bootstrap)', paciente: 'Paciente',
|
||||
};
|
||||
export const COLORES = { km: '#222222', banda: 'rgba(160,170,182,.32)', weibull: '#1f77b4', fraccional: '#d1495b', modelo: '#6a3d9a', paciente: '#e08a00' } as const;
|
||||
/** The curve runs to this many months, as the cohort's does. */
|
||||
export const MESES_MAXIMOS = 24;
|
||||
|
||||
export interface PuntoDeSupervivencia { meses: number; S: number; bajo: number | null; alto: number | null; }
|
||||
|
||||
/** The model's survival at each horizon: one minus the mortality of the `RiskAssessment`, its interval turned around. */
|
||||
export function puntosDeSupervivencia(horizontes: readonly HorizonteRiesgoCacu[]): PuntoDeSupervivencia[] {
|
||||
return horizontes.filter(h => h.horizonte_anios > 0).map(h => ({
|
||||
meses: Math.round(h.horizonte_anios * 12), S: 1 - h.probabilidad,
|
||||
bajo: tieneIntervalo(h) ? 1 - h.ic_alto! : null, alto: tieneIntervalo(h) ? 1 - h.ic_bajo! : null,
|
||||
})).sort((a, b) => a.meses - b.meses);
|
||||
}
|
||||
|
||||
/** The survival month by month: log-linear between 0 and the horizons (a constant hazard in each interval), and past the
|
||||
* last one at the last interval's rate. It passes through every point and never rises. */
|
||||
export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = MESES_MAXIMOS): { meses: number[]; S: number[] } {
|
||||
const bordes = [0, ...puntos.map(p => p.meses)], log = [0, ...puntos.map(p => Math.log(Math.max(p.S, 1e-12)))];
|
||||
const ultimo = bordes.length - 1, pendiente = ultimo > 0 ? (log[ultimo] - log[ultimo - 1]) / (bordes[ultimo] - bordes[ultimo - 1]) : 0;
|
||||
const meses = Array.from({ length: Math.max(hasta, bordes[ultimo]) + 1 }, (_, m) => m);
|
||||
const S = meses.map(m => {
|
||||
if (m >= bordes[ultimo]) return Math.exp(log[ultimo] + pendiente * (m - bordes[ultimo]));
|
||||
let i = 0;
|
||||
while (bordes[i + 1] < m) i++;
|
||||
return Math.exp(log[i] + (log[i + 1] - log[i]) * (m - bordes[i]) / (bordes[i + 1] - bordes[i]));
|
||||
});
|
||||
return { meses, S: S.reduce<number[]>((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) };
|
||||
}
|
||||
|
||||
const etiqueta = (cohorte: CurvasSupervivencia | null, clave: string) => cohorte?.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave;
|
||||
|
||||
/**
|
||||
* The SEER pipeline's survival figure, with the patient on it. The cohort's (when the model's run published it): the
|
||||
* Kaplan-Meier curve with its Greenwood band, the classic and the fractional Weibull, and the model's survival at each
|
||||
* horizon as diamonds with their bootstrap interval. The patient's: her survival by the model, a curve through her value at each
|
||||
* horizon (and its interval, when her evaluation has one).
|
||||
*/
|
||||
export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], cohorte: CurvasSupervivencia | null = null, tema: Tema = 'claro', descripcion: string | null = null): PlotlyFigure | null {
|
||||
const puntos = puntosDeSupervivencia(horizontes);
|
||||
if (puntos.length === 0) return null;
|
||||
const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null), t = (clave: string) => etiqueta(cohorte, clave);
|
||||
const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)';
|
||||
const data: Record<string, unknown>[] = [];
|
||||
const bajos: number[] = [...curva.S, ...puntos.map(p => p.bajo ?? p.S)];
|
||||
let hasta = curva.meses[curva.meses.length - 1];
|
||||
if (cohorte) {
|
||||
const km = cohorte.km, diamantes = cohorte.points.COMB;
|
||||
hasta = Math.max(hasta, km.months[km.months.length - 1]);
|
||||
bajos.push(...km.low, ...cohorte.weibull_fractional.S, ...diamantes.low);
|
||||
data.push(
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.high, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.low, fill: 'tonexty', fillcolor: COLORES.banda, line: { width: 0, shape: 'hv' }, showlegend: false, hoverinfo: 'skip', legendgroup: 'km' },
|
||||
{ type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km, width: 2, shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km',
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('km_crudo') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: cohorte.weibull.t, y: cohorte.weibull.S, line: { color: COLORES.weibull, width: 3 }, name: t('weibull'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'lines', x: cohorte.weibull_fractional.t, y: cohorte.weibull_fractional.S, line: { color: COLORES.fraccional, width: 3, dash: 'dash' }, name: t('weibull_fraccional'),
|
||||
hovertemplate: '%{x:.1f} meses: %{y:.3f}<extra>' + t('weibull_fraccional') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'markers', name: t('puntos'), x: cohorte.horizons_months, y: diamantes.S,
|
||||
marker: { symbol: 'diamond', size: 15, color: COLORES.modelo, line: { color: 'white', width: 1.5 } },
|
||||
error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.modelo, thickness: 2, width: 6,
|
||||
array: diamantes.high.map((hi, i) => hi - diamantes.S[i]), arrayminus: diamantes.S.map((s, i) => s - diamantes.low[i]) },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('puntos') + '</extra>' });
|
||||
}
|
||||
data.push(
|
||||
{ type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), legendgroup: 'paciente', line: { color: COLORES.paciente, width: 3 },
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente') + '</extra>' },
|
||||
{ type: 'scatter', mode: 'markers', name: t('paciente'), legendgroup: 'paciente', showlegend: false, x: puntos.map(p => p.meses), y: puntos.map(p => p.S),
|
||||
marker: { symbol: 'diamond', size: 14, color: COLORES.paciente, line: { color: 'white', width: 1.5 } },
|
||||
...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLORES.paciente, thickness: 2, width: 6,
|
||||
array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}),
|
||||
hovertemplate: '%{x} meses: %{y:.3f}<extra>' + t('paciente') + '</extra>' });
|
||||
const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20);
|
||||
const base = descripcion ?? t('titulo');
|
||||
const titulo = cohorte ? `${base}<br>n=${cohorte.n.toLocaleString('es-MX')}, fallecidos=${cohorte.events.toLocaleString('es-MX')}` : base;
|
||||
const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' };
|
||||
const layout: Record<string, unknown> = {
|
||||
title: { text: titulo, x: 0.5, xanchor: 'center', font: { size: 15, color: texto } },
|
||||
paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto },
|
||||
xaxis: { ...eje, title: { text: t('eje_x') }, range: [0, hasta + 0.6], dtick: 5 },
|
||||
yaxis: { ...eje, title: { text: t('eje_y') }, range: [minimo, 1.005], dtick: 0.05, tickformat: '.2f' },
|
||||
legend: { x: 0.01, y: 0.02, xanchor: 'left', yanchor: 'bottom', bgcolor: 'rgba(255,255,255,.85)', bordercolor: rejilla, borderwidth: 1, font: { size: 12 } },
|
||||
margin: { l: 70, r: 20, t: 70, b: 60 }, hovermode: 'closest',
|
||||
};
|
||||
return { data, layout, config: { responsive: true, displaylogo: false } };
|
||||
}
|
||||
@@ -13,7 +13,7 @@
|
||||
</header>
|
||||
@if (estado.tipo === 'cargando') { <p role="status">Cargando información…</p> }
|
||||
@if (estado.tipo === 'no-disponible') { <p class="availability" role="status">Información no disponible.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Seguimiento para intentar de nuevo.</p> }
|
||||
@if (estado.tipo === 'error') { <p class="availability" role="alert">No se pudo cargar la información de este paciente. Regresa a Análisis de riesgos para intentar de nuevo.</p> }
|
||||
@if (registrosTemporales.length) { <p class="pending-changes" role="status">Cambios sin guardar</p> }
|
||||
<div class="detail-grid">
|
||||
<mat-card class="history-card" appearance="outlined" aria-labelledby="historial-title">
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
// Covers the patient's risk in CaMa's record: the table asks the CaMa endpoint (and CaCu's calls stay as they were), says
|
||||
// whose model scored her, shows the mortality at the horizons the model gives (6, 12 and 18 months) and the model's
|
||||
// index date, and the CaMa card carries the panel. Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
|
||||
// index date; the CaMa record does not show it (its two analyses replace it). Fixtures: a Bundle like `GET /cama/fhir/RiskAssessment?subject=
|
||||
// Patient/7` answers it (`riesgoCamaEjemplo`), and a provider that returns it.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { of } from 'rxjs';
|
||||
import { CamaPatientCard } from './cama/cama-patient-card';
|
||||
import { CamaPatientSummary } from './cama/cama-patient.models';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
import { EMPTY } from 'rxjs';
|
||||
import { CamaCurvasService } from './cama/cama-curvas.service';
|
||||
import { CamaRecurrenciaService } from './cama/cama-recurrencia.service';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { INTERVALO, prediccion } from './paciente-riesgo.testing';
|
||||
import { curvaMensual, figuraSupervivenciaPaciente, puntosDeSupervivencia } from './cama/cama-supervivencia-paciente';
|
||||
|
||||
const CS = 'https://isssteleon.org/fhir/CodeSystem';
|
||||
|
||||
@@ -42,38 +44,13 @@ const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({
|
||||
daysMammographyToDiagnosis: null, clinicalScenario: null,
|
||||
});
|
||||
|
||||
describe('Supervivencia individual de la paciente CaMa', () => {
|
||||
// Fails if a point of the figure is not one minus the mortality of its horizon, or its interval is not turned around.
|
||||
it('turns each horizon of the evaluation into survival with its interval', () => {
|
||||
const puntos = puntosDeSupervivencia([
|
||||
{ horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 },
|
||||
{ horizonte_anios: 1.5, probabilidad: 0.25 }, { horizonte_anios: 1, probabilidad: 0.18 }]);
|
||||
|
||||
expect(puntos.map(p => p.meses)).toEqual([6, 12, 18]);
|
||||
expect(puntos.map(p => +p.S.toFixed(2))).toEqual([0.93, 0.82, 0.75]);
|
||||
expect(puntos[0].bajo).toBeCloseTo(0.9);
|
||||
expect(puntos[0].alto).toBeCloseTo(0.95);
|
||||
expect(puntos[1].bajo).toBeNull();
|
||||
});
|
||||
|
||||
// Fails if the curve misses a point, rises, or stops at the last horizon.
|
||||
it('draws a curve through every point that never rises and goes on to 24 months', () => {
|
||||
const puntos = puntosDeSupervivencia([{ horizonte_anios: 0.5, probabilidad: 0.1 }, { horizonte_anios: 1, probabilidad: 0.2 }, { horizonte_anios: 1.5, probabilidad: 0.4 }]);
|
||||
const { meses, S } = curvaMensual(puntos);
|
||||
|
||||
expect(S[0]).toBe(1);
|
||||
expect(S[6]).toBeCloseTo(0.9); expect(S[12]).toBeCloseTo(0.8); expect(S[18]).toBeCloseTo(0.6);
|
||||
expect(meses[meses.length - 1]).toBe(24);
|
||||
expect(S.every((v, i) => i === 0 || v <= S[i - 1] + 1e-12)).toBe(true);
|
||||
expect(S[24]).toBeLessThan(S[18]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Riesgo individual de la paciente CaMa', () => {
|
||||
const obtener = vi.fn();
|
||||
beforeEach(() => {
|
||||
obtener.mockReset().mockImplementation(() => of(riesgoCamaEjemplo()));
|
||||
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } }] });
|
||||
TestBed.configureTestingModule({ providers: [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener } },
|
||||
{ provide: CamaCurvasService, useValue: { escenarios: () => of(null), consulta: () => EMPTY } },
|
||||
{ provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(null) } }] });
|
||||
});
|
||||
|
||||
// Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only).
|
||||
@@ -100,7 +77,6 @@ describe('Riesgo individual de la paciente CaMa', () => {
|
||||
f.detectChanges();
|
||||
|
||||
const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
expect(f.nativeElement.querySelector('app-cama-supervivencia-paciente')).not.toBeNull();
|
||||
expect(text).toContain('cama-survival');
|
||||
expect(text).toContain('2025-06-19');
|
||||
expect(text).toContain('Muerte por cualquier causa');
|
||||
@@ -111,18 +87,14 @@ describe('Riesgo individual de la paciente CaMa', () => {
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']);
|
||||
});
|
||||
|
||||
// Fails if the record asks for a risk by a row that has no `pac_id` (a legacy pseudonym), or does not ask when it has one.
|
||||
it('is asked for by the patient\'s pac_id, and not by a pseudonym', () => {
|
||||
const conPacId = TestBed.createComponent(CamaPatientCard);
|
||||
conPacId.componentRef.setInput('summary', resumen('pac_id'));
|
||||
conPacId.detectChanges();
|
||||
const conSeudonimo = TestBed.createComponent(CamaPatientCard);
|
||||
conSeudonimo.componentRef.setInput('summary', resumen('id_seudonimo'));
|
||||
conSeudonimo.detectChanges();
|
||||
// Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace.
|
||||
it('is not in the CaMa record: its analyses and their risk factors are', () => {
|
||||
const f = TestBed.createComponent(CamaPatientCard);
|
||||
f.componentRef.setInput('summary', resumen('pac_id'));
|
||||
f.detectChanges();
|
||||
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('7', 'cama');
|
||||
expect(conPacId.nativeElement.querySelector('.risk-card')).not.toBeNull();
|
||||
expect(conSeudonimo.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(obtener).not.toHaveBeenCalled();
|
||||
expect(f.nativeElement.querySelector('app-paciente-riesgo-tabla')).toBeNull();
|
||||
expect(INTERVALO).toContain('intervalo-confianza');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -38,9 +38,6 @@
|
||||
</table>
|
||||
</div>
|
||||
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
|
||||
@if (dominio() === 'cama' && pacId(); as id) {
|
||||
<app-cama-supervivencia-paciente [pacId]="id" [horizontes]="riesgo.horizontes" />
|
||||
}
|
||||
}
|
||||
}
|
||||
<p class="recommendations">Recomendaciones no disponibles.</p>
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { Component, computed, effect, inject, input } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { CamaSupervivenciaPaciente } from './cama/cama-supervivencia-paciente.component';
|
||||
import { DominioRiesgo } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-riesgo-tabla',
|
||||
imports: [DecimalPipe, CamaSupervivenciaPaciente],
|
||||
imports: [DecimalPipe],
|
||||
providers: [PacienteRiesgoState],
|
||||
templateUrl: './paciente-riesgo-tabla.html',
|
||||
styleUrl: './paciente-riesgo-tabla.scss',
|
||||
|
||||
@@ -75,6 +75,8 @@ describe('Tabla de seguimiento con pac_id', () => {
|
||||
// Opening a CaMa record asks for the patient's risk; in these tests nobody has one.
|
||||
afterEach(() => {
|
||||
http.match(r => r.url === '/cama/fhir/RiskAssessment').forEach(r => { if (!r.cancelled) r.flush({ resourceType: 'Bundle', type: 'searchset', total: 0 }); });
|
||||
// The record asks for the two analyses of the patient (survival's menu and recurrence's); there is no model for them here.
|
||||
http.match(r => r.url.startsWith('/cama/modelo/')).forEach(r => { if (!r.cancelled) r.flush({ error: 'sin modelo' }, { status: 404, statusText: 'Not Found' }); });
|
||||
fixture.destroy(); http.verify();
|
||||
});
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
|
||||
@@ -98,7 +98,7 @@
|
||||
}
|
||||
@if (vista === 'norma' && normaActual(e); as m) {
|
||||
<h3>Norma por edad</h3>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}</p>
|
||||
<p class="meta">{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, referencia {{ m.curva_referencia!.estado }}</p>
|
||||
@if (figuraNorma) {
|
||||
<app-plotly-chart [figure]="figuraNorma" [showNotes]="false" [style.--plot-height]="'280px'"
|
||||
[label]="'Norma por edad de ' + m.etiqueta + ' con el paciente ' + d.id_seudonimo" />
|
||||
@@ -144,7 +144,7 @@
|
||||
<tbody>
|
||||
@for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) {
|
||||
<tr [class.alterada]="zonaAlterada(f)">
|
||||
<td><strong>{{ biomarcador[f.biomarcador] ?? f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td><strong>{{ f.biomarcador }}</strong><small>{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · <span class="marca">alterada</span>}</small></td>
|
||||
<td>{{ f.resultado_etiqueta }}<small>{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}</small></td>
|
||||
<td><span class="or">OR {{ f.or }}</span><small>IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}</small><small>{{ direccion(f) }}</small></td>
|
||||
<td>
|
||||
|
||||
@@ -7,9 +7,6 @@ import {
|
||||
TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
const BIOMARCADOR: Record<string, string> = {
|
||||
picos: 'Picos paroxísticos', husos: 'Husos de sueño', ritmo_posterior: 'Ritmo posterior', gradiente: 'Gradiente anteroposterior',
|
||||
};
|
||||
// A zone counts as altered from |z| ≥ 2, as the alteration cards do.
|
||||
const Z_ALTERADO = 2;
|
||||
|
||||
@@ -162,7 +159,6 @@ export class TeaPacienteResumen implements OnInit {
|
||||
pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; }
|
||||
|
||||
// Relation with the ADOS-2: only the patient's altered zones (|z| ≥ 2), clearest cohort association first.
|
||||
readonly biomarcador = BIOMARCADOR;
|
||||
zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; }
|
||||
filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); }
|
||||
direccion(f: TeaRelacionAdos2) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { forkJoin, map, Observable, of, shareReplay } from 'rxjs';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { Bundle, code, codeIn, Concept, display, extension, extensions, isSimulated, Quantity, referenceId, Resource, resources } from './fhir';
|
||||
import { estratoValor } from './indicadores-fhir';
|
||||
import { SeguimientoQuery } from './cacu-seguimiento.models';
|
||||
import { validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import {
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg,
|
||||
TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaSeguimientoPaciente, teaSeguimientoResponse,
|
||||
TeaSeguimientoService,
|
||||
CLASIFICACIONES_ADOS2, RANGOS_CSS, RANGOS_MCHAT, TeaAdos2, TeaAdosDominio, TeaAlteracionEstado, TeaCriterioCalidad,
|
||||
TeaCurvaReferencia, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaNivelCalidad, teaPacienteDetalle, TeaRelacionAdos2,
|
||||
TeaRelacionModelo, TeaSeguimientoPaciente, teaSeguimientoResponse, TeaSeguimientoService,
|
||||
} from './tea-seguimiento.service';
|
||||
|
||||
// TEA's follow-up list and patient summary over the WebApi's FHIR endpoint: each child's screening is an
|
||||
@@ -26,6 +26,7 @@ interface Report extends Resource {
|
||||
effectiveDateTime?: string; subject?: { reference?: string }; result?: { reference?: string }[]; conclusionCode?: Concept[];
|
||||
}
|
||||
interface Metric { code?: string; display?: string; property?: { code: string; valueString?: string }[] }
|
||||
interface Prediction { outcome?: Concept; probabilityDecimal?: number; extension?: Resource['extension'] }
|
||||
|
||||
const MAX_COUNT = 200;
|
||||
const METRICAS = 'tea-eeg-metrica';
|
||||
@@ -111,6 +112,18 @@ export function ados2DeObservacion(o: Observation | undefined): TeaAdos2 | null
|
||||
};
|
||||
}
|
||||
|
||||
// The age norm a metric observation carries: one sub-extension per point, read back in order, because a FHIR
|
||||
// extension holds scalars, not arrays.
|
||||
function curvaDe(o: Observation): TeaCurvaReferencia | null {
|
||||
const curva = extension(o, 'curva-referencia');
|
||||
if (!curva) return null;
|
||||
const serie = (nombre: string) => extensions(curva, nombre).map(e => e.valueDecimal).filter((v): v is number => typeof v === 'number');
|
||||
return {
|
||||
fuente: extension(curva, 'fuente')?.valueString ?? '', estado: extension(curva, 'estado')?.valueString ?? '',
|
||||
edad_meses: serie('edad-meses'), p5: serie('p5'), p25: serie('p25'), mediana: serie('mediana'), p75: serie('p75'), p95: serie('p95'),
|
||||
};
|
||||
}
|
||||
|
||||
// A metric against its age baseline. Without a value nothing was measured; with a value but no z, the baseline doesn't
|
||||
// cover the child's age (or none is in production yet).
|
||||
function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
@@ -123,6 +136,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
const low = o.referenceRange?.[0]?.low?.value, high = o.referenceRange?.[0]?.high?.value;
|
||||
const referencia = typeof low === 'number' && typeof high === 'number'
|
||||
? { min: low, max: high, mediana: component(o, 'mediana')?.valueQuantity?.value ?? null } : null;
|
||||
const curva = evaluable ? curvaDe(o) : null;
|
||||
return {
|
||||
codigo, etiqueta: display(o.code) ?? metrica?.display ?? codigo,
|
||||
unidad: o.valueQuantity?.unit ?? metrica?.property?.find(p => p.code === 'unidad')?.valueString ?? '',
|
||||
@@ -130,6 +144,7 @@ function alteracion(o: Observation, metricas: Metric[]): TeaEegAlteracion {
|
||||
valor, valor_z: evaluable && typeof z === 'number' ? z : null, estado,
|
||||
sin_evaluar: evaluable ? null : valor === null ? 'sin_valor' : 'sin_referencia',
|
||||
efectos: (metrica?.property ?? []).filter(p => p.code === `efecto-${estado}`).map(p => p.valueString!).filter(Boolean),
|
||||
...(curva ? { curva_referencia: curva } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -152,6 +167,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
const listed = observations.filter(o => ids.has(o.id));
|
||||
const calidad = (concept: Concept | undefined) => (code(concept) ?? 'SIN_ANALIZAR').toLowerCase() as TeaNivelCalidad;
|
||||
const duracion = extension(report, 'duracion-min')?.valueDecimal;
|
||||
const edad = extension(report, 'edad-meses')?.valueDecimal;
|
||||
// The report lists each metric's electrode map under the same code too; it feeds the maps, not the cards.
|
||||
const alteraciones = listed.filter(o => codeIn(o.code, METRICAS) && !o.id?.startsWith('electrodos-')).map(o => alteracion(o, metricas));
|
||||
// A metric's electrode values are `electrodos-<the metric observation's id>`.
|
||||
@@ -166,6 +182,7 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
fecha: report.effectiveDateTime.slice(0, 10),
|
||||
duracion_min: duracion === undefined ? null : Math.round(duracion),
|
||||
canales: extension(report, 'canales')?.valueInteger ?? null,
|
||||
...(typeof edad === 'number' ? { edad_meses: edad } : {}),
|
||||
calidad: calidad(report.conclusionCode?.[0]),
|
||||
criterios_calidad: listed.filter(o => codeIn(o.code, CRITERIOS)).map(criterio),
|
||||
alteraciones, mapas,
|
||||
@@ -173,6 +190,34 @@ export function eegDeReporte(report: Report | undefined, observations: Observati
|
||||
};
|
||||
}
|
||||
|
||||
// The ADOS-2 association model: one `RiskAssessment`, a prediction per association row with the patient's z and
|
||||
// probabilities. A row missing a number the panel needs is left out; without rows there is no panel.
|
||||
export function relacionDeRiesgo(riesgo: Resource | undefined): TeaRelacionModelo | null {
|
||||
if (!riesgo) return null;
|
||||
const nivel = extension(riesgo, 'modelo-nivel')?.valueString;
|
||||
const filas = ((riesgo['prediction'] ?? []) as Prediction[]).map((p): TeaRelacionAdos2 | null => {
|
||||
const numero = (nombre: string) => extension(p, nombre)?.valueDecimal;
|
||||
const biomarcador = extension(p, 'biomarcador')?.valueCoding, zona = extension(p, 'zona')?.valueCoding;
|
||||
const tipo = extension(p, 'tipo')?.valueString, evento = extension(p, 'evento')?.valueString;
|
||||
const valores = [numero('valor-z'), numero('odds-ratio'), numero('ic-inf'), numero('ic-sup'), numero('q'), p.probabilityDecimal,
|
||||
numero('probabilidad-referencia')];
|
||||
if (!biomarcador?.code || !zona?.code || (tipo !== 'item' && tipo !== 'dominio') || !evento || !code(p.outcome)
|
||||
|| !valores.every(v => typeof v === 'number')) return null;
|
||||
const [valor_z, or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia] = valores as number[];
|
||||
return {
|
||||
biomarcador: biomarcador.display ?? biomarcador.code, zona: zona.code, zona_etiqueta: zona.display ?? zona.code, valor_z,
|
||||
tipo, resultado: code(p.outcome)!, resultado_etiqueta: display(p.outcome) ?? code(p.outcome)!, evento,
|
||||
or, ic_inf, ic_sup, q, probabilidad, probabilidad_referencia, observado: extension(p, 'observado')?.valueInteger ?? null,
|
||||
};
|
||||
}).filter((f): f is TeaRelacionAdos2 => f !== null);
|
||||
if ((nivel !== 'item' && nivel !== 'dominio') || !filas.length) return null;
|
||||
return {
|
||||
validado: extension(riesgo, 'modelo-validado')?.valueBoolean === true, nivel,
|
||||
n_cohorte: extension(riesgo, 'modelo-n-cohorte')?.valueInteger ?? 0,
|
||||
version: extension(riesgo, 'modelo-version')?.valueString ?? '', filas,
|
||||
};
|
||||
}
|
||||
|
||||
function resultadoEeg(report: Report | undefined, observations: Observation[], validadas: boolean): 'normal' | 'anormal' | null {
|
||||
if (!validadas || !report || code(report.conclusionCode?.[0]) !== 'BUENO') return null;
|
||||
return alteracionesDe(report, observations).length ? 'anormal' : 'normal';
|
||||
@@ -288,12 +333,14 @@ export class FhirTeaSeguimientoService extends TeaSeguimientoService {
|
||||
const all = resources(bundle);
|
||||
const observations = all.filter(r => r.resourceType === 'Observation') as Observation[];
|
||||
const episode = resources(bundle, 'EpisodeOfCare')[0];
|
||||
const relacion = relacionDeRiesgo(resources(bundle, 'RiskAssessment')[0]);
|
||||
return teaPacienteDetalle({
|
||||
simulado: all.length > 0 && all.every(isSimulated),
|
||||
id_seudonimo: id,
|
||||
grupo_edad: grupoEdad(episode && extension(episode, 'grupo-edad')?.valueCoding?.code),
|
||||
ados2: ados2DeObservacion(byCode(observations, 'ados2')),
|
||||
eeg: eegDeReporte(resources(bundle, 'DiagnosticReport')[0] as Report | undefined, observations, metricas),
|
||||
...(relacion ? { relacion_ados2: relacion } : {}),
|
||||
}, id);
|
||||
}));
|
||||
}
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
<section class="home" aria-labelledby="home-title">
|
||||
<div class="home__content">
|
||||
<p class="home__eyebrow">ISSSTELEON · Análisis de información</p>
|
||||
<p class="home__eyebrow">ISSSTELEON</p>
|
||||
<h1 id="home-title">Analiza tu información</h1>
|
||||
<p class="home__description">
|
||||
Conecta archivos, bases de datos y documentos PDF, mapea sus columnas a la base del proyecto y carga datos validados.
|
||||
@@ -12,7 +12,7 @@
|
||||
</a>
|
||||
<a class="home__action" routerLink="/indicadores">
|
||||
<mat-icon aria-hidden="true">insights</mat-icon>
|
||||
<span>Indicadores</span>
|
||||
<span>Modelos predictivos de riesgo</span>
|
||||
</a>
|
||||
<a class="home__action" routerLink="/bitacora">
|
||||
<mat-icon aria-hidden="true">fact_check</mat-icon>
|
||||
|
||||
Reference in New Issue
Block a user