From 7aa3d2c6e63f76c7358be5f1c0c8abee442d7fdd Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Wed, 18 Nov 2026 19:59:03 -0600 Subject: [PATCH 01/21] Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum --- .../indicadores/indicador-figure-panel.ts | 126 ++++++++++++++++-- .../indicadores-stratified-panel.spec.ts | 47 ++++++- .../indicadores-stratified.spec.ts | 51 ++++++- .../indicadores/indicadores-stratified.ts | 67 ++++++++-- .../indicadores/indicadores.models.ts | 10 +- 5 files changed, 276 insertions(+), 25 deletions(-) diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index a6bb41f..0213b44 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -16,7 +16,7 @@ import { c2Capability, c2Figure } from './indicadores-c2-adapter'; import { c2BarsHighlight, teaC2Donut } from './indicadores-tea-c2'; import { C1_AGE_BARS, C1_DONUT_ESTRATO, c1DonutCapability, c1DonutFigure } from './indicadores-c1-donut'; import { c1AlterationCapability, c1AlterationFigure } from './indicadores-c1-alteraciones'; -import { stratifiedBars, stratifiedCapabilities, StratifiedCell } from './indicadores-stratified'; +import { etiquetaDimension, MedidaEstrato, stratifiedBars, stratifiedCapabilities, StratifiedCell, StratumOption, stratumOptions } from './indicadores-stratified'; import { donutPeriodFigures, periodDatos } from './indicadores-donut-periods'; import { c2GeneralSelection } from './indicadores-c2-general-selection'; import { MatTooltipModule } from '@angular/material/tooltip'; @@ -25,8 +25,48 @@ import { MatTooltipModule } from '@angular/material/tooltip'; selector: 'app-indicador-figure-panel', imports: [IndicadorFigureCard, MatTooltipModule], template: ` -
+

{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}

+ @if (sidebar) { + + }

{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}

@if (!dimension && figuraId === 'fig_c2_barras' && indicador.figuras.includes('fig_c2_donas')) { @@ -36,7 +76,7 @@ import { MatTooltipModule } from '@angular/material/tooltip'; {{ generalSelectionContext ? 'Selección activa' : 'Distribución completa' }} } - @if (figuraId === 'fig_c2_barras' && capabilities.length) { + @if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
Distribución
@@ -49,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@for (d of capabilities; track d) { + (click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }} }
} + @if (dimension) { +
+ + +
+ }
@if (!singlePeriod) {

Selecciona un periodo para consultar la distribución estratificada.

} } @@ -71,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip'; @if (hasSuppressedCells) {

Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.

} @if (hasMissingCells) {

Hay datos no disponibles; los espacios sin barra no representan un cero observado.

}
Valores publicados -
- @for (cell of cells; track $index) { } +
CategoríaEstratoConteo
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}
+ @for (cell of cells; track $index) { }
CategoríaEstratoConteoPorcentaje del estrato
{{ cell.category }}{{ cell.stratum }}{{ cell.status === 'Publicado' ? cell.value : cell.status }}{{ cell.percent === null ? '—' : cell.percent + ' %' }}
@if (!cells.length) {

No hay categorías publicadas para esta selección.

} @@ -117,6 +163,30 @@ import { MatTooltipModule } from '@angular/material/tooltip'; .donut-periods button { min-width: 44px; min-height: 44px; font-size: 1.5rem; background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: 4px; } .donut-periods button:disabled { opacity: .45; } .donut-periods button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + /* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay + shared with the neighbouring panel, so the bars line up with the donut. */ + :host { container-type: inline-size; } + .figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); } + .with-sidebar > :not(.strata-sidebar) { grid-column: 2; } + .strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0); + display: grid; gap: var(--issste-space-3); padding-block: var(--issste-space-3); min-width: 0; } + .sidebar-group { margin: 0; padding: 0; border: 0; min-width: 0; } + .sidebar-group legend { padding: 0; margin-bottom: .5rem; font-weight: 600; } + .sidebar-list { display: grid; gap: .25rem; } + .sidebar-list button, .sidebar-reset { min-height: 44px; width: 100%; padding: .5rem .75rem; text-align: start; + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); + color: var(--issste-text); font: inherit; overflow-wrap: anywhere; cursor: pointer; } + .sidebar-list button.active { border-color: var(--issste-accent); background: var(--issste-accent); color: var(--issste-on-accent, #fff); font-weight: 600; } + .sidebar-list .stratum-toggle:not(.active) { color: var(--issste-text-secondary); text-decoration: line-through; } + .sidebar-list button:disabled, .sidebar-reset:disabled { opacity: .5; cursor: not-allowed; } + .sidebar-list button:focus-visible, .sidebar-reset:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + .sidebar-reset { margin-top: .5rem; } + .sidebar-status { margin: 0 0 .5rem; color: var(--issste-text-secondary); font: var(--mat-sys-body-small); } + @container (max-width: 559px) { + .figure-panel.with-sidebar { display: flex; flex-direction: column; } + .strata-sidebar { position: static; } + .sidebar-list { grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr)); } + } .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; @@ -165,7 +235,39 @@ export class IndicadorFigurePanel implements OnChanges { return this.donutPages.find(p => p.period === this.activeDonutPeriod)!.state; } dimension: DimensionEstrato | '' = ''; + readonly etiquetaDimension = etiquetaDimension; + // Counts or each category's share of its stratum; an indicator can ask to open with the share. + private medidaElegida?: MedidaEstrato; + get medida(): MedidaEstrato { return this.medidaElegida ?? this.indicador.medida_estrato ?? 'conteo'; } + changeMedida(medida: MedidaEstrato) { + if (medida === this.medida) return; + this.medidaElegida = medida; + this.representStratified(); + } cells: StratifiedCell[] = []; + /** More stratifiers than a row of buttons holds comfortably: they go in a list beside the bars. */ + get sidebar() { return this.figuraId === 'fig_c2_barras' && this.capabilities.length > 2; } + estratos: StratumOption[] = []; + ocultos = new Set(); + toggleEstrato(valor: string) { + const ocultos = new Set(this.ocultos); + if (ocultos.has(valor)) ocultos.delete(valor); + else if (ocultos.size < this.estratos.length - 1) ocultos.add(valor); + else return; + this.ocultos = ocultos; + this.representStratified(); + } + mostrarTodos() { + if (!this.ocultos.size) return; + this.ocultos = new Set(); + this.representStratified(); + } + private representStratified() { + if (this.dimension && this.stratifiedData && this.result().status === 'ready') { + try { this.result.set(this.presentStratified(this.stratifiedData)); } + catch { this.result.set({ status: 'error', message: 'No se pudo representar la distribución.' }); } + } + } get hasSuppressedCells() { return this.cells.some(c => c.status === 'Suprimido'); } get hasMissingCells() { return this.cells.some(c => c.status === 'No disponible'); } private stratifiedData?: IndicadorDatos; @@ -177,14 +279,18 @@ export class IndicadorFigurePanel implements OnChanges { changeDimension(value: DimensionEstrato | '') { if (value && (!this.capabilities.includes(value) || !this.singlePeriod)) return; if (this.dimension === value) return; - this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.requestFigure(); + this.dimension = value; this.stratifiedData = undefined; this.cells = []; this.estratos = []; this.ocultos = new Set(); + this.requestFigure(); } chooseStratified() { if (this.singlePeriod && this.capabilities.length) this.changeDimension(this.dimension || this.capabilities[0]); } private presentStratified(data: IndicadorDatos): FigureState { const local = !this.localSelection.period || this.localSelection.period === data.periodos[0] ? this.localSelection : {}; - const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local); + this.estratos = stratumOptions(data); + const publicados = new Set(this.estratos.map(e => e.valor)); + if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v))); + const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos); this.cells = adapted.cells; return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id, tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }), @@ -349,7 +455,9 @@ export class IndicadorFigurePanel implements OnChanges { } } ngOnChanges(changes: SimpleChanges) { - if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) this.dimension = ''; + if (this.dimension && (!this.capabilities.includes(this.dimension) || !this.singlePeriod)) { + this.dimension = ''; this.estratos = []; this.ocultos = new Set(); + } const identity = figureIdentity(this.dominio, this.indicador.id, this.figuraId); if (identity !== this.donutIdentity) { this.activeDonutPeriod = undefined; this.donutIdentity = identity; } this.titleId = identityElementId(identity) + '-title'; diff --git a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts index 39f831c..3b8432d 100644 --- a/src/app/features/indicadores/indicadores-stratified-panel.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified-panel.spec.ts @@ -48,7 +48,9 @@ describe('Barras estratificadas: activación y caché',()=>{ toggle[1].click(); const stratified = request(); stratified.flush(age); fixture.detectChanges(); expect(fixture.componentInstance.dimension).toBe('grupo_edad'); expect(toggle[1].getAttribute('aria-checked')).toBe('true'); - expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions [role="radio"]')).toHaveLength(2); + // The dimensions, apart from the counts or percentage toggle that follows them. + expect(fixture.nativeElement.querySelectorAll('.distribution-dimensions:not(.distribution-medida) [role="radio"]')).toHaveLength(2); + expect(fixture.nativeElement.querySelectorAll('.distribution-medida [role="radio"]')).toHaveLength(2); for(const button of toggle) { expect(button.tagName).toBe('BUTTON'); expect(button.type).toBe('button'); } }); it('deshabilita estratificación en multiperiodo y conserva el mensaje contextual',()=>{ @@ -93,3 +95,46 @@ describe('Barras estratificadas: activación y caché',()=>{ expect(TestBed.inject(IndicadoresSnapshots).reading('cacu',item,applied)?.data).toEqual(general()); }); }); + +describe('Barra lateral de estratificación', () => { + // Fija: con más de dos estratificadores, la elección de dimensión, los valores visibles y la medida van en una + // barra lateral; ocultar y volver a mostrar valores redibuja sin pedir datos. Falla si la barra no aparece, si un + // valor oculto sigue en la figura, si se puede ocultar el último o si un cambio local vuelve a consultar. + let fixture:ReturnType>, http:HttpTestingController; + const tres:Indicador={...item,filtros:[...item.filtros!,{estrato:'estadio',etiqueta:'Estadio clínico',valores:[{valor:'I',etiqueta:'I'}]}]}; + const general=()=>({...c2Fixture(),id:item.id,version:item.version}); + beforeEach(()=>{ + TestBed.configureTestingModule({providers:[provideHttpClient(),provideHttpClientTesting()]}); + TestBed.overrideComponent(IndicadorFigureCard,{remove:{imports:[PlotlyChart]},add:{imports:[ChartStub]}}); + fixture=TestBed.createComponent(IndicadorFigurePanel); http=TestBed.inject(HttpTestingController); + for(const [k,v] of Object.entries({dominio:'cama',indicador:tres,figuraId:'fig_c2_barras',tema:'claro',applied})) fixture.componentRef.setInput(k,v); + }); + afterEach(()=>{fixture.destroy();http.verify();}); + const request=()=>http.expectOne(r=>r.url.endsWith('/datos')); + const aside=()=>fixture.nativeElement.querySelector('.strata-sidebar') as HTMLElement; + it('lista los estratificadores y oculta o muestra valores sin consultar',()=>{ + fixture.detectChanges(); request().flush(general()); fixture.detectChanges(); + expect(aside()).not.toBeNull(); expect(fixture.nativeElement.querySelector('.distribution-toggle')).toBeNull(); + const opciones=[...aside().querySelectorAll('[role="radiogroup"] [role="radio"]')] as HTMLButtonElement[]; + expect(opciones.map(b=>b.textContent!.trim())).toEqual(['Sin estratificar','Por grupo de edad','Por estatus de seguimiento','Por estadio clínico']); + opciones[1].click(); request().flush(age); fixture.detectChanges(); + const valores=()=>[...aside().querySelectorAll('.stratum-toggle')] as HTMLButtonElement[]; + expect(valores()).toHaveLength(age.valores_estrato.length); + valores()[0].click(); fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.data.map(t=>t['name'])).not.toContain('<25'); + expect(valores()[0].getAttribute('aria-pressed')).toBe('false'); + for(const b of valores().slice(1,-1)) b.click(); fixture.detectChanges(); + expect(valores().at(-1)!.disabled).toBe(true); expect(fixture.componentInstance.result().figure?.data).toHaveLength(1); + (aside().querySelector('.sidebar-reset') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(fixture.componentInstance.result().figure?.data).toHaveLength(age.valores_estrato.length); + http.expectNone(()=>true); + }); + it('cambiar de estratificador muestra de nuevo todos los valores',()=>{ + fixture.detectChanges(); request().flush(general()); + fixture.componentInstance.changeDimension('grupo_edad'); request().flush(age); + fixture.componentInstance.toggleEstrato('<25'); expect(fixture.componentInstance.ocultos.size).toBe(1); + fixture.componentInstance.changeDimension('estatus_seguimiento'); request().flush(status); + expect(fixture.componentInstance.ocultos.size).toBe(0); + expect(fixture.componentInstance.estratos.map(e=>e.valor)).toEqual(status.valores_estrato); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.spec.ts b/src/app/features/indicadores/indicadores-stratified.spec.ts index 9a1b389..3104625 100644 --- a/src/app/features/indicadores/indicadores-stratified.spec.ts +++ b/src/app/features/indicadores/indicadores-stratified.spec.ts @@ -1,6 +1,6 @@ import ageJson from './fixtures/cacu_eu7_datos_estrato_grupo_edad.json'; import statusJson from './fixtures/cacu_eu7_datos_estrato_estatus_seguimiento.json'; -import { stratifiedBars, stratifiedCapabilities } from './indicadores-stratified'; +import { etiquetaDimension, stratifiedBars, stratifiedCapabilities, stratumOptions } from './indicadores-stratified'; import { DimensionEstrato, Indicador } from './indicadores.models'; const age = { ...ageJson, tipo_periodo: 'semestre' as const }; @@ -61,3 +61,52 @@ describe('Contratos simulados de estratificación de los analistas', () => { expect(()=>stratifiedBars(data,'grupo_edad','2025-S2','claro')).toThrow(); }); }); + +// A CaMa quantity of interest broken down by a stratifier: two strata of different size, one with a suppressed total. +const porEtapa = () => ({ + id: 'cama_birads_cancer_invasor', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], estrato: 'etapa', + valores_estrato: ['TEMPRANA', 'AVANZADA', 'SIN'], etiquetas_estrato: { TEMPRANA: 'Temprana', AVANZADA: 'Avanzada', SIN: 'Sin dato' }, + grupos: { TOTAL: 'Total' }, grupos_de_categoria: {}, categorias: { B4A: { etiqueta: 'BI-RADS 4A' }, B5: { etiqueta: 'BI-RADS 5' } }, + totales_estrato: [{ periodo: '2025-S1', grupo: 'TOTAL', estrato: 'TEMPRANA', n: 40, suprimido: 0 }, { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'AVANZADA', n: 10, suprimido: 0 }, + { periodo: '2025-S1', grupo: 'TOTAL', estrato: 'SIN', n: null, suprimido: 1 }], + filas: [['TEMPRANA', 'B4A', 10], ['TEMPRANA', 'B5', 30], ['AVANZADA', 'B4A', 1], ['AVANZADA', 'B5', 9], ['SIN', 'B4A', null], ['SIN', 'B5', null]] + .map(([estrato, categoria, n], i) => ({ periodo: '2025-S1', grupo: 'TOTAL', estrato, categoria, n, orden: i % 2, suprimido: n === null ? 1 : 0 })), +}); +describe('Porcentaje en cada estrato', () => { + it('cada categoría es la parte de su estrato, y un estrato con total suprimido no tiene porcentaje', () => { + // Fails if the share is taken over the whole period instead of the stratum, or drawn over an unknown total. + const { figure, cells } = stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro', {}, 'porcentaje'); + expect(cells.filter(c => c.stratum !== 'Sin dato').map(c => c.percent)).toEqual([25, 75, 10, 90]); + expect(cells.filter(c => c.stratum === 'Sin dato').map(c => c.percent)).toEqual([null, null]); + expect((figure.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje del estrato'); + expect(stratifiedBars(porEtapa() as never, 'etapa', '2025-S1', 'claro').figure.data[0]['x']).toEqual([10, 30]); + }); + it('las dimensiones de CaMa toman su etiqueta del catálogo, y CaCu conserva la suya', () => { + // Fails if a new stratifier is offered without its published label, or CaCu's wording changes. + const item = { id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'] as ['semestre'], + filtros: [{ estrato: 'etapa', etiqueta: 'Etapa (temprana o avanzada)', valores: [{ valor: 'TEMPRANA', etiqueta: 'Temprana' }] }, + { estrato: 'grupo_edad', etiqueta: 'Grupo de edad', valores: [{ valor: '40-49', etiqueta: '40-49' }] }] }; + expect(stratifiedCapabilities(item)).toEqual(['grupo_edad', 'etapa']); + expect(etiquetaDimension(item, 'etapa')).toBe('Por etapa (temprana o avanzada)'); + expect(etiquetaDimension(item, 'grupo_edad')).toBe('Por grupo de edad'); + }); +}); + +describe('Estratos ocultos', () => { + // Fija: ocultar valores de un estrato quita sus series y sus celdas, cada estrato conserva su trama y nunca se + // quedan todas fuera. Falla si el filtro deja de aplicarse, si las tramas se recorren o si se puede vaciar la figura. + it('quita las series ocultas, conserva la trama de cada estrato y no deja la figura vacía', () => { + const todos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro'); + const patron = (f: typeof todos.figure, nombre: string) => (f.data.find(t => t['name'] === nombre)!['marker'] as Record>)['pattern']['shape']; + const algunos = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(['<25', '35-44'])); + expect(algunos.figure.data.map(t => t['name'])).toEqual(['25-34', '45-54', '55-64', '65+', 'Sin dato']); + expect(new Set(algunos.cells.map(c => c.stratum))).toEqual(new Set(['25-34', '45-54', '55-64', '65+', 'Sin dato'])); + for (const nombre of ['25-34', '65+', 'Sin dato']) expect(patron(algunos.figure, nombre)).toEqual(patron(todos.figure, nombre)); + const ninguno = stratifiedBars(age, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(age.valores_estrato)); + expect(ninguno.figure.data).toHaveLength(todos.figure.data.length); + }); + it('lista los valores del estrato con su etiqueta, en el orden publicado', () => { + expect(stratumOptions(age).map(e => e.etiqueta)).toEqual(['<25', '25-34', '35-44', '45-54', '55-64', '65+', 'Sin dato']); + expect(stratumOptions(age).at(-1)).toEqual({ valor: 'sin_dato', etiqueta: 'Sin dato' }); + }); +}); diff --git a/src/app/features/indicadores/indicadores-stratified.ts b/src/app/features/indicadores/indicadores-stratified.ts index 76404a8..9339969 100644 --- a/src/app/features/indicadores/indicadores-stratified.ts +++ b/src/app/features/indicadores/indicadores-stratified.ts @@ -4,30 +4,53 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +// The dimensions a C2's bars can be broken down by, in this order; `citologia_alto_grado` belongs to CaCu's C1 donut. +const ESTRATIFICABLES: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'birads', 'brca', 'estadio', 'tamano', 'etapa']; +/** The button of a dimension: CaCu's two keep their wording; the rest take the label the catalog publishes. */ +export function etiquetaDimension(item: Indicador, d: DimensionEstrato): string { + if (d === 'grupo_edad') return 'Por grupo de edad'; + if (d === 'estatus_seguimiento') return 'Por estatus de seguimiento'; + const etiqueta = item.filtros?.find(f => f.estrato === d)?.etiqueta; + return 'Por ' + (etiqueta ? etiqueta.charAt(0).toLowerCase() + etiqueta.slice(1) : d); +} +export type MedidaEstrato = 'conteo' | 'porcentaje'; export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] { return item.contrato === 'C2' && Array.isArray(item.filtros) - ? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d + ? ESTRATIFICABLES.filter(d => item.filtros!.some(f => f?.estrato === d && typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0 && f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : []; } -export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } -export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } { +/** A stratum a reader can show or hide: its published value and label, in the published order. */ +export interface StratumOption { valor: string; etiqueta: string; } +export function stratumOptions(data: IndicadorDatos): StratumOption[] { + const valores = Array.isArray(data['valores_estrato']) ? data['valores_estrato'] as unknown[] : []; + const etiquetas = record(data['etiquetas_estrato']) ? data['etiquetas_estrato'] : {}; + return valores.filter((v): v is string => typeof v === 'string') + .map(valor => ({ valor, etiqueta: typeof etiquetas[valor] === 'string' ? etiquetas[valor] as string : valor })); +} +// `percent`: the cell's share of its stratum, when the stratum's total is known. +export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; } +/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells, + * unless that would leave none. */ +export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } { if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period || !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos']) || Object.keys(data['grupos']).length !== 1 || !Array.isArray(data['valores_estrato']) || !data['valores_estrato'].length || !data['valores_estrato'].every(v => typeof v === 'string') || new Set(data['valores_estrato']).size !== data['valores_estrato'].length || !record(data['etiquetas_estrato'])) throw new Error('Distribución estratificada inválida'); - const strata = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; + const published = data['valores_estrato'] as string[], labels = data['etiquetas_estrato']; + const shown = published.filter(s => !hidden.has(s)); + const strata = shown.length ? shown : published; const statisticalGroup = Object.keys(data['grupos'])[0]; - if (strata.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); + if (published.some(s => typeof labels[s] !== 'string')) throw new Error('Etiquetas de estrato incompletas'); const catalog = data['categorias'], groups = data['grupos_de_categoria']; const entries = new Map(); const rows = new Map>(); for (const row of data.filas) { const id = row['categoria'], stratum = row['estrato'], n = row['n']; if (row['periodo'] !== period || row['grupo'] !== statisticalGroup || typeof id !== 'string' || !id - || typeof stratum !== 'string' || !strata.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) + || typeof stratum !== 'string' || !published.includes(stratum) || typeof row['orden'] !== 'number' || !Number.isFinite(row['orden']) || ![0, 1].includes(row['suprimido'] as number) || (row['suprimido'] === 1 ? n !== null : n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) throw new Error('Fila estratificada inválida'); const key = JSON.stringify([id, stratum]); if (rows.has(key) || (entries.has(id) && entries.get(id)!.order !== row['orden'])) throw new Error('Filas ambiguas'); @@ -44,21 +67,39 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato const cells: StratifiedCell[] = []; const theme = c2Theme(tema); const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id)); - const figure: PlotlyFigure = { data: strata.map((s, series) => { + // The stratum's total: the one published, or else the sum of its cells when every one is published. A share is + // only drawn over a known total; a suppressed or missing total leaves the stratum without percentages. + const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record[] : []; + const totalDe = (s: string): number | null => { + const publicado = totales.find(t => t['periodo'] === period && t['estrato'] === s && t['grupo'] === statisticalGroup); + if (publicado) return publicado['suprimido'] === 0 && typeof publicado['n'] === 'number' && publicado['n'] > 0 ? publicado['n'] : null; + const propias = [...entries.keys()].map(id => rows.get(JSON.stringify([id, s]))); + if (propias.some(r => !r || r['suprimido'] !== 0 || typeof r['n'] !== 'number')) return null; + const suma = propias.reduce((a, r) => a + (r!['n'] as number), 0); + return suma > 0 ? suma : null; + }; + const porcentaje = medida === 'porcentaje'; + const figure: PlotlyFigure = { data: strata.map(s => { + const series = published.indexOf(s); // a stratum keeps its pattern when others are hidden const selected = categories.map(([id, c]) => { const row = rows.get(JSON.stringify([id, s])); const status = row?.['suprimido'] === 1 ? 'Suprimido' : typeof row?.['n'] === 'number' ? 'Publicado' : 'No disponible'; const value = status === 'Publicado' ? row!['n'] as number : null; - cells.push({ category: c.label, stratum: labels[s] as string, value, status }); - return value; + const total = totalDe(s); + const percent = value !== null && total ? Math.round(1000 * value / total) / 10 : null; + cells.push({ category: c.label, stratum: labels[s] as string, value, percent, status }); + return { value, percent, total }; }); - return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)), + const x = selected.map(v => porcentaje ? v.percent : v.value); + return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)), + customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']), marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } }, - hovertemplate: '%{y}
%{x}%{fullData.name}' }; - }), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true, + hovertemplate: porcentaje ? '%{y}
%{x:.1f} % (%{customdata[0]} de %{customdata[1]})%{fullData.name}' : '%{y}
%{x}%{fullData.name}' }; + }), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true, height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, margin: { l: 100, r: 24, t: 40, b: 100 }, - xaxis: { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, + xaxis: porcentaje ? { range: [0, 100], title: { text: 'Porcentaje del estrato' }, ticksuffix: ' %', gridcolor: theme.grid } + : { rangemode: 'tozero', title: { text: 'Conteo publicado' }, gridcolor: theme.grid }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: categories.map(([, c]) => escape(c.label)).reverse(), automargin: true }, legend: { orientation: 'h', y: -0.12, itemclick: false, itemdoubleclick: false } } }; return { figure, cells }; diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index 70071b4..44d15a2 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -18,8 +18,16 @@ export interface Indicador { filtros?: IndicadorFiltro[]; // Tabs that show it; without this field, all of them. vistas?: string[]; + // Interactive donut and bars by one stratum, like CaCu's EU7. + escenario?: VistaEscenario; + // How the breakdown by stratum opens: counts, or each category's share of its stratum. + medida_estrato?: 'conteo' | 'porcentaje'; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads'; +// CaMa's stratifiers (brca, estadio, tamano, etapa) break down its quantities of interest. +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads' | 'brca' | 'estadio' | 'tamano' | 'etapa'; +export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads', 'brca', 'estadio', 'tamano', 'etapa']; +// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico». +export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; } export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } From 680cc0adc60394c639993f101d5ce7dcc0217de7 Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Fri, 20 Nov 2026 20:06:15 -0600 Subject: [PATCH 02/21] =?UTF-8?q?TEA:=20panel=20=C2=ABRelaci=C3=B3n=20con?= =?UTF-8?q?=20el=20ADOS-2=C2=BB=20en=20la=20ficha=20del=20paciente=20(prot?= =?UTF-8?q?otipo)=20y=20modo=20simulado=20local?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El panel muestra, por cada asociación clara de la cohorte (modelo de OR), la zona del EEG con el z del paciente, el aspecto del ADOS-2, el OR con su intervalo, la probabilidad para el paciente y lo observado. El campo relacion_ados2 es opcional. El modo simulado (servidor de prueba en Python y configuración «simulado» de Angular) es solo para trabajar en local. Co-Authored-By: Claude Opus 5.5 --- angular.json | 15 +++ simulado/README.md | 38 ++++++ simulado/proxy.simulado.json | 47 ++++++++ simulado/servidor.py | 110 ++++++++++++++++++ src/app/app.config.simulado.ts | 21 ++++ .../indicadores/tea-paciente-resumen.html | 45 +++++++ .../indicadores/tea-paciente-resumen.scss | 15 +++ .../indicadores/tea-paciente-resumen.ts | 32 ++++- .../indicadores/tea-seguimiento.service.ts | 29 ++++- .../indicadores/tea-seguimiento.spec.ts | 24 ++++ 10 files changed, 373 insertions(+), 3 deletions(-) create mode 100644 simulado/README.md create mode 100644 simulado/proxy.simulado.json create mode 100644 simulado/servidor.py create mode 100644 src/app/app.config.simulado.ts diff --git a/angular.json b/angular.json index e5cb6a7..aabfce8 100644 --- a/angular.json +++ b/angular.json @@ -62,6 +62,17 @@ "optimization": false, "extractLicenses": false, "sourceMap": true + }, + "simulado": { + "optimization": false, + "extractLicenses": false, + "sourceMap": true, + "fileReplacements": [ + { + "replace": "src/app/app.config.ts", + "with": "src/app/app.config.simulado.ts" + } + ] } }, "defaultConfiguration": "production" @@ -77,6 +88,10 @@ }, "development": { "buildTarget": "WebApp:build:development" + }, + "simulado": { + "buildTarget": "WebApp:build:simulado", + "proxyConfig": "simulado/proxy.simulado.json" } }, "defaultConfiguration": "development" diff --git a/simulado/README.md b/simulado/README.md new file mode 100644 index 0000000..61bb005 --- /dev/null +++ b/simulado/README.md @@ -0,0 +1,38 @@ +# Modo simulado (solo nuestra copia local, rama `ulises/tea-seguimiento`) + +Para ver y modificar la página de seguimiento de TEA sin la plataforma completa ni su preproceso. +Todo es **inventado**. No forma parte de la WebApp que se entrega. + +| Archivo | Qué es | +|---|---| +| `datos_tea.json` | 120 niños inventados: lista, ficha y la relación con el ADOS-2 (modelo de OR de E27). Se genera; no se versiona | +| `servidor.py` | Servidor de prueba (Python, sin instalar nada) en `localhost:5051` | +| `proxy.simulado.json` | Las rutas de la API, al servidor de prueba | +| `../src/app/app.config.simulado.ts` | Igual que `app.config.ts`, pero el seguimiento de TEA lee el contrato JSON (`/tea/seguimiento`) | + +## Cómo se usa + +1. Generar los datos (una vez, o cuando cambie el modelo), desde `biomarcadores-tea/`: + ``` + python experimentos/E27_modelo_or/simulado_plataforma.py + ``` +2. Levantar el servidor de prueba, desde `webapp-tea/`: + ``` + python simulado/servidor.py + ``` +3. En otra terminal, la página, desde `webapp-tea/`: + ``` + npx ng serve --configuration simulado --port 4300 + ``` +4. Abrir `http://localhost:4300/indicadores/tea`, entrar a **Seguimiento** y abrir un paciente. + +## El panel nuevo: «Relación con el ADOS-2» + +En la ficha del paciente (`tea-paciente-resumen.*`) muestra, por cada asociación clara de la cohorte (q < 0.05): +- la zona del EEG y el z del paciente, marcada si está alterada (|z| ≥ 2); +- el aspecto del ADOS-2 (reactivo o dominio); +- el OR de la cohorte con su intervalo y su q; +- la probabilidad que el modelo da a este paciente (con su edad y módulo) frente a la de un niño con z = 0; +- lo que muestra su ADOS-2. + +El campo `relacion_ados2` es opcional: sin él (la plataforma real hoy), el panel no aparece. diff --git a/simulado/proxy.simulado.json b/simulado/proxy.simulado.json new file mode 100644 index 0000000..ea18ef7 --- /dev/null +++ b/simulado/proxy.simulado.json @@ -0,0 +1,47 @@ +{ + "/api": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/imports": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/data": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/health": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/cacu": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/cama": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/tea": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/governance": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + }, + "/reportes": { + "target": "http://localhost:5051", + "secure": false, + "changeOrigin": true + } +} diff --git a/simulado/servidor.py b/simulado/servidor.py new file mode 100644 index 0000000..53b96a8 --- /dev/null +++ b/simulado/servidor.py @@ -0,0 +1,110 @@ +""" +servidor.py — Servidor de prueba con datos SIMULADOS para ver la página de TEA sin la plataforma completa. + +Solo para nuestra copia local (rama ulises/tea-seguimiento): no forma parte de la WebApp que se entrega. +Responde lo que pide la sección de seguimiento de TEA en su contrato JSON: +- `/tea/seguimiento`: la lista, con filtros y páginas; +- `/tea/seguimiento/`: la ficha, incluido el campo nuevo `relacion_ados2`. + +A lo demás de `/tea/...` contesta vacío, para que la página cargue. + +Los datos los escribe `biomarcadores-tea/experimentos/E27_modelo_or/simulado_plataforma.py` en `datos_tea.json`. + + python simulado/servidor.py # http://localhost:5051 + npx ng serve --configuration simulado --port 4300 +""" + +from __future__ import annotations + +import json +import math +import sys +from datetime import date, timedelta +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import parse_qs, unquote, urlparse + +PUERTO = 5051 +DATOS = json.loads((Path(__file__).with_name("datos_tea.json")).read_text(encoding="utf-8")) +VACIO_FHIR = {"resourceType": "Bundle", "type": "searchset", "total": 0, "entry": []} + + +def _num(q, k): + v = q.get(k, [None])[0] + try: + return float(v) if v is not None else None + except ValueError: + return None + + +def lista(q: dict) -> dict: + meses = int(q.get("meses", ["12"])[0]) if q.get("meses", ["12"])[0] in ("1", "3", "6", "12") else 12 + corte = q.get("corte", [date.today().isoformat()])[0] + page = max(1, int(q.get("page", ["1"])[0])) + size = min(200, max(1, int(q.get("page_size", ["25"])[0]))) + filtro = q.get("alteraciones_eeg", [None])[0] + ps = DATOS["pacientes"] + if filtro in ("normal", "anormal"): + ps = [p for p in ps if p["alteraciones_eeg"] == filtro] + elif filtro == "sin_eeg_valido": + ps = [p for p in ps if p["ultimo_eeg"] is None] + if q.get("grupo_edad"): + ps = [p for p in ps if p["grupo_edad"].startswith(q["grupo_edad"][0].replace("_", "-"))] + for campo, lo, hi in (("mchat", "mchat_min", "mchat_max"), ("css_ados2", "css_min", "css_max")): + a, b = _num(q, lo), _num(q, hi) + if a is not None: + ps = [p for p in ps if p[campo] is not None and a <= p[campo] <= (b if b is not None else 99)] + if q.get("estado_caso"): + ps = [p for p in ps if p["estado_caso"] == q["estado_caso"][0]] + if q.get("alteracion"): + ps = [p for p in ps if q["alteracion"][0] in p["alteraciones"]] + total = len(ps) + por_alt = [{"codigo": t["codigo"], "etiqueta": t["etiqueta"], "n": sum(t["codigo"] in p["alteraciones"] for p in ps)} + for t in DATOS["tipos_alteracion"]] + hasta = date.fromisoformat(corte) + return { + "simulado": True, "corte": corte, + "ventana": {"meses": meses, "desde": (hasta - timedelta(days=30 * meses)).isoformat(), "hasta": corte}, + "filtros": {"alteraciones_eeg": filtro}, + "paginacion": {"page": page, "page_size": size, "total_items": total, "total_pages": max(1, math.ceil(total / size))}, + "items": ps[(page - 1) * size: page * size], + "tipos_alteracion": DATOS["tipos_alteracion"], + "resumen_eeg": {"validadas": True, "con_eeg_valido": total, + "normales": sum(p["alteraciones_eeg"] == "normal" for p in ps), + "anormales": sum(p["alteraciones_eeg"] == "anormal" for p in ps), "sin_eeg": 0, + "por_alteracion": por_alt}, + } + + +class Manejador(BaseHTTPRequestHandler): + def _json(self, cuerpo, codigo=200): + datos = json.dumps(cuerpo, ensure_ascii=False).encode("utf-8") + self.send_response(codigo) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(datos))) + self.end_headers() + self.wfile.write(datos) + + def do_GET(self): # noqa: N802 + u = urlparse(self.path) + ruta, q = u.path.rstrip("/"), parse_qs(u.query) + if ruta == "/tea/seguimiento": + return self._json(lista(q)) + if ruta.startswith("/tea/seguimiento/"): + d = DATOS["detalles"].get(unquote(ruta.rsplit("/", 1)[1])) + return self._json(d) if d else self._json({"error": "no encontrado"}, 404) + if "/fhir/" in ruta: + return self._json(VACIO_FHIR) + if ruta.endswith("/indicadores"): + return self._json([]) + if ruta == "/health": + return self._json({"status": "ok", "simulado": True}) + return self._json({"error": "sin datos simulados para esta ruta"}, 404) + + def log_message(self, fmt, *args): + sys.stderr.write(" " + fmt % args + "\n") + + +if __name__ == "__main__": + print(f"Servidor simulado en http://localhost:{PUERTO} ({len(DATOS['pacientes'])} niños inventados)") + ThreadingHTTPServer(("127.0.0.1", PUERTO), Manejador).serve_forever() diff --git a/src/app/app.config.simulado.ts b/src/app/app.config.simulado.ts new file mode 100644 index 0000000..31b9c77 --- /dev/null +++ b/src/app/app.config.simulado.ts @@ -0,0 +1,21 @@ +import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'; +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter } from '@angular/router'; +import { routes } from './app.routes'; +import { IndicadoresService } from './features/indicadores/indicadores.service'; +import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; +import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; + +// SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento +// de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`). +export const appConfig: ApplicationConfig = { + providers: [ + provideBrowserGlobalErrorListeners(), + provideRouter(routes), + provideHttpClient(), + // The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract + // (`//indicadores//datos`, `/tea/seguimiento`). + { provide: IndicadoresService, useClass: FhirIndicadoresService }, + { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, + ] +}; diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index 2c77e3e..e827e9d 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -106,5 +106,50 @@ } } + + @if (d.relacion_ados2; as rel) { +
+

Relación con el ADOS-2 Datos de ejemplo

+

Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se + asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2. + No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}

+ @if (!rel.filas.length) { +

La cohorte no muestra asociaciones claras para las zonas de este paciente.

+ } @else { + @if (!conZonaAlterada(rel)) {

Ninguna zona de este paciente está alterada (|z| ≥ 2); se muestran las asociaciones de la cohorte como referencia.

} +
+ + + + + + + + + @for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) { + + + + + + + + } + +
Zona del EEGAspecto del ADOS-2Asociación en la cohorteProbabilidad para este pacienteLo que muestra su ADOS-2
{{ biomarcador[f.biomarcador] ?? f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · alterada}{{ f.resultado_etiqueta }}{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }}OR {{ f.or }}IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}{{ direccion(f) }} + {{ porcentaje(f.probabilidad) }} % + + {{ f.evento }} · con z = 0: {{ porcentaje(f.probabilidad_referencia) }} % + {{ observado(f) }}@if (coincide(f) !== null) { {{ coincide(f) ? 'Coincide con lo que el modelo esperaba' : 'No coincide con lo que el modelo esperaba' }} }
+
+

OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La + probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0. + Solo se muestran las asociaciones claras en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

+ } +
+ } } diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 886fdbf..5c88782 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -73,3 +73,18 @@ li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; } .canales-malos { margin: .25rem 0 0; padding-inline-start: 1.1rem; font-size: .85rem; } + +// Relation with the ADOS-2 (association model): full width, a scrollable table on narrow screens. +.relacion { grid-column: 1 / -1; } +.tabla-relacion { overflow-x: auto; } +.tabla-relacion table { width: 100%; min-width: 44rem; border-collapse: collapse; font-size: .85rem; } +.tabla-relacion th, .tabla-relacion td { padding: .45rem .5rem; border-top: 1px solid var(--issste-border); text-align: start; vertical-align: top; } +.tabla-relacion thead th { font-size: .8rem; color: var(--issste-text-secondary); font-weight: 600; } +.tabla-relacion small { display: block; margin-top: .1rem; color: var(--issste-text-secondary); font-size: .75rem; } +.tabla-relacion tr.alterada td:first-child { box-shadow: inset 4px 0 0 #B3261E; } +.tabla-relacion .marca { color: #B3261E; font-weight: 600; } +.or, .prob { font-weight: 700; font-variant-numeric: tabular-nums; } +.barra { position: relative; display: block; height: .45rem; margin-top: .25rem; border-radius: 999px; background: var(--issste-border); } +.barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } +.barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } +.nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 3abc899..223d026 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -4,9 +4,15 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; import { CLASIFICACIONES_ADOS2, TeaAlteracionEstado, TeaCriterioCalidad, TeaEeg, TeaEegAlteracion, TeaEegMapa, TeaPacienteDetalle, - TeaSeguimientoService, TeaAdos2, + TeaRelacionAdos2, TeaRelacionModelo, TeaSeguimientoService, TeaAdos2, } from './tea-seguimiento.service'; +const BIOMARCADOR: Record = { + 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; + // ADOS-2 calibrated severity score ranges. const NIVEL_CSS: Record = { minimo: 'Evidencia mínima o nula', bajo: 'Nivel bajo', moderado: 'Nivel moderado', alto: 'Nivel alto' }; const CALIDAD: Record = { bueno: 'Válido', malo: 'No válido', sin_analizar: 'Sin analizar' }; @@ -106,4 +112,28 @@ export class TeaPacienteResumen implements OnInit { clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; } alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } + + // Relation with the ADOS-2: the patient's altered zones first, then the clearest cohort associations. + readonly biomarcador = BIOMARCADOR; + zonaAlterada(f: TeaRelacionAdos2) { return Math.abs(f.valor_z) >= Z_ALTERADO; } + filasRelacion(rel: TeaRelacionModelo) { + return [...rel.filas].sort((a, b) => Number(this.zonaAlterada(b)) - Number(this.zonaAlterada(a)) || a.q - b.q); + } + conZonaAlterada(rel: TeaRelacionModelo) { return rel.filas.some(f => this.zonaAlterada(f)); } + direccion(f: TeaRelacionAdos2) { + return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad'; + } + porcentaje(p: number) { return Math.round(100 * p); } + qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; } + observado(f: TeaRelacionAdos2) { + if (f.observado === null) return 'Sin dato'; + if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)'; + return `CSS ${f.observado}`; + } + // Whether what the patient shows matches what the model leans to (above or below one half). + coincide(f: TeaRelacionAdos2) { + if (f.observado === null) return null; + const presente = f.tipo === 'item' ? f.observado >= 1 : f.observado >= 8; + return presente === (f.probabilidad >= .5); + } } diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 06534c3..83ad8fd 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -67,7 +67,20 @@ export interface TeaEeg { mapas: TeaEegMapa[]; ejes_mapa: { x: number[]; y: number[]; electrodos: { nombre: string; x: number; y: number }[] }; } -export interface TeaPacienteDetalle { simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null } +// The association model (OR) of each EEG alteration by zone with an ADOS-2 item or domain, fitted on the cohort; for +// this patient, their z, the probability the model gives them and what their ADOS-2 shows. Pending medical validation. +export interface TeaRelacionAdos2 { + biomarcador: string; zona: string; zona_etiqueta: string; valor_z: number; + tipo: 'item' | 'dominio'; resultado: string; resultado_etiqueta: string; evento: string; + or: number; ic_inf: number; ic_sup: number; q: number; + probabilidad: number; probabilidad_referencia: number; observado: number | null; +} +export interface TeaRelacionModelo { validado: boolean; nivel: 'item' | 'dominio'; n_cohorte: number; version: string; filas: TeaRelacionAdos2[] } +export interface TeaPacienteDetalle { + simulado: true; id_seudonimo: string; grupo_edad: string; ados2: TeaAdos2 | null; eeg: TeaEeg | null; + // Absent until the WebApi serves the model. + relacion_ados2?: TeaRelacionModelo | null; +} // TEA has no follow-up status; its third filter is the EEG result, using the CaCu status shape. export const CLASIFICACIONES_ADOS2: Record = { autismo: 'Autismo', espectro_autista: 'Espectro autista', no_espectro: 'No espectro', @@ -172,9 +185,21 @@ function validEeg(e: unknown): boolean { && m['z'].every(row => Array.isArray(row) && row.length === x.length && row.every(v => v === null || finite(v))) && Array.isArray(m['regiones']) && m['regiones'].every(r => record(r) && text(r['codigo']) && text(r['etiqueta']) && finite(r['valor_z']))); } +const probability = (v: unknown) => finite(v) && (v as number) >= 0 && (v as number) <= 1; +function validRelacion(r: unknown): boolean { + if (r === undefined || r === null) return true; + return record(r) && typeof r['validado'] === 'boolean' && ['item', 'dominio'].includes(r['nivel'] as string) + && integer(r['n_cohorte'], 1) && text(r['version']) && Array.isArray(r['filas']) + && r['filas'].every(f => record(f) && text(f['biomarcador']) && text(f['zona_etiqueta']) && finite(f['valor_z']) + && ['item', 'dominio'].includes(f['tipo'] as string) && text(f['resultado_etiqueta']) && text(f['evento']) + && finite(f['or']) && finite(f['ic_inf']) && finite(f['ic_sup']) && (f['ic_inf'] as number) <= (f['ic_sup'] as number) + && probability(f['q']) && probability(f['probabilidad']) && probability(f['probabilidad_referencia']) + && (f['observado'] === null || finite(f['observado']))); +} export function teaPacienteDetalle(v: unknown, id: string): TeaPacienteDetalle { if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.'); - if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg'])) + if (v['id_seudonimo'] !== id || typeof v['grupo_edad'] !== 'string' || !validAdos(v['ados2']) || !validEeg(v['eeg']) + || !validRelacion(v['relacion_ados2'])) throw new Error('Resumen del paciente inválido'); return v as unknown as TeaPacienteDetalle; } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 1fd9156..507244c 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -342,4 +342,28 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle(con({ ...alteraciones[0], efectos: [''] }), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow(); }); + // The association model's panel (prototype, simulated data): the field is optional and checked when present. + it('valida la relación con el ADOS-2 y la muestra con la zona alterada primero', () => { + const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa', + resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, + probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 }; + const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 }; + const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } }); + expect(() => teaPacienteDetalle(detalle, 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle({ ...detalle, relacion_ados2: null }, 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle(rel([fila]), 'T-0001')).not.toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow(); + expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow(); + const fixture = open(); + request().flush(tres); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges(); + const filas = Array.from(root.querySelectorAll('section.relacion tbody tr')); + expect(filas.map(f => f.classList.contains('alterada'))).toEqual([true, false]); + expect(filas[0].textContent).toContain('q < 0.001'); + expect(filas[0].textContent).toContain('93 %'); + http.verify(); + }); }); From 54b3e50ca59e0ccab228c89fb2ed0647e8ab5eac Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Fri, 20 Nov 2026 20:35:24 -0600 Subject: [PATCH 03/21] =?UTF-8?q?TEA:=20el=20panel=20de=20relaci=C3=B3n=20?= =?UTF-8?q?con=20el=20ADOS-2=20muestra=20solo=20las=20zonas=20alteradas=20?= =?UTF-8?q?del=20paciente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- src/app/features/indicadores/tea-paciente-resumen.html | 7 +++---- src/app/features/indicadores/tea-paciente-resumen.ts | 7 ++----- src/app/features/indicadores/tea-seguimiento.spec.ts | 5 +++-- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index e827e9d..e960920 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -113,10 +113,9 @@

Modelo de asociación ajustado en la cohorte ({{ rel.n_cohorte }} niños, por edad y módulo del ADOS-2): qué tanto se asocia cada alteración del EEG por zona con {{ rel.nivel === 'item' ? 'un reactivo' : 'la severidad de un dominio' }} del ADOS-2. No es un diagnóstico ni indica qué causa qué.@if (!rel.validado) { Pendiente de validación médica.}

- @if (!rel.filas.length) { -

La cohorte no muestra asociaciones claras para las zonas de este paciente.

+ @if (!filasRelacion(rel).length) { +

Ninguna zona alterada de este paciente (|z| ≥ 2) tiene una asociación clara con el ADOS-2 en la cohorte.

} @else { - @if (!conZonaAlterada(rel)) {

Ninguna zona de este paciente está alterada (|z| ≥ 2); se muestran las asociaciones de la cohorte como referencia.

}
@@ -147,7 +146,7 @@

OR mayor que 1: a mayor z en esa zona, más probable que el aspecto salga alterado; menor que 1, al revés. La probabilidad es la que da el modelo a un niño de su edad y módulo con su z; la marca gris de la barra es la de un niño con z = 0. - Solo se muestran las asociaciones claras en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

+ Solo se muestran las zonas alteradas del paciente (|z| ≥ 2) con una asociación clara en la cohorte (q < 0.05). Versión del modelo: {{ rel.version }}.

} } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 223d026..c3c960a 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -113,13 +113,10 @@ export class TeaPacienteResumen implements OnInit { alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } - // Relation with the ADOS-2: the patient's altered zones first, then the clearest cohort associations. + // 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].sort((a, b) => Number(this.zonaAlterada(b)) - Number(this.zonaAlterada(a)) || a.q - b.q); - } - conZonaAlterada(rel: TeaRelacionModelo) { return rel.filas.some(f => this.zonaAlterada(f)); } + filasRelacion(rel: TeaRelacionModelo) { return rel.filas.filter(f => this.zonaAlterada(f)).sort((a, b) => a.q - b.q); } direccion(f: TeaRelacionAdos2) { return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad'; } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 507244c..a58e589 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -343,7 +343,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle(con(alteraciones[3]), 'T-0001')).not.toThrow(); }); // The association model's panel (prototype, simulated data): the field is optional and checked when present. - it('valida la relación con el ADOS-2 y la muestra con la zona alterada primero', () => { + it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => { const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa', resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 }; @@ -361,7 +361,8 @@ describe('Seguimiento TEA', () => { root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges(); const filas = Array.from(root.querySelectorAll('section.relacion tbody tr')); - expect(filas.map(f => f.classList.contains('alterada'))).toEqual([true, false]); + expect(filas.length).toBe(1); + expect(filas[0].classList.contains('alterada')).toBe(true); expect(filas[0].textContent).toContain('q < 0.001'); expect(filas[0].textContent).toContain('93 %'); http.verify(); From 3bb1c8dd841513bd7931b883f1f3b33c05f6b5e3 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 23:02:48 -0600 Subject: [PATCH 04/21] CaCu patient record shows the risk's index date The record's index date is riesgo.fecha_indice (the model's decision point the horizons count from), not the cohort member's; the field is optional in the contract and validated as an ISO date. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- .../indicadores/paciente-detalle/paciente-riesgo-tabla.html | 2 +- .../indicadores/paciente-detalle/paciente-riesgo.models.ts | 2 ++ .../indicadores/paciente-detalle/paciente-riesgo.spec.ts | 4 +++- .../indicadores/paciente-detalle/paciente-riesgo.testing.ts | 2 +- .../paciente-detalle/paciente-riesgo.validation.spec.ts | 2 ++ .../paciente-detalle/paciente-riesgo.validation.ts | 1 + 6 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index faa62eb..a2c33dc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -13,7 +13,6 @@
Variables del modelo PIMM @@ -35,6 +34,7 @@ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index b7ff381..f1eb19d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -28,6 +28,8 @@ export interface LoteRiesgoCacu { lote_id: number; modelo_nombre: string; modelo_version: string; + /** The model's index date for this patient (ISO date): the horizons count from it. Absent from older APIs. */ + fecha_indice?: string | null; evaluado_en: string; estado_lote: EstadoEvaluacionCacu; horizontes: HorizonteRiesgoCacu[]; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 4eea34d..56d0b02 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -46,9 +46,11 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); expect(root.textContent).toContain('Final (final)'); expect(root.textContent).toContain('Preliminar (preliminary)'); - for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2023-04-15', 'incidente', 'ASC-US', 'POSITIVO']) { + for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2026-06-01', 'incidente', 'ASC-US', 'POSITIVO']) { expect(root.textContent).toContain(value); } + // The index date shown is the risk's (the model's decision point), not the cohort member's. + expect(root.textContent).not.toContain('2023-04-15'); expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index 511c042..ecf05cf 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -9,7 +9,7 @@ export function riesgoCacuEjemplo(): RiesgoPacienteCacu { tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO', }, riesgo: { - lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', + lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', horizontes: [ { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' }, diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts index 7716d4a..fbc8b28 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts @@ -90,6 +90,8 @@ describe('RIESGO-CACU-02: frontera del contrato DEV', () => { ['lote string', v => v.riesgo.lote_id = '12'], ['modelo omitido', v => delete v.riesgo.modelo_nombre], ['versión no textual', v => v.riesgo.modelo_version = 2], + ['fecha índice del riesgo inválida', v => v.riesgo.fecha_indice = '2026-02-30'], + ['fecha índice del riesgo no textual', v => v.riesgo.fecha_indice = 20260601], ['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'], ['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'], ['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'], diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index e26ba5a..a920048 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -38,6 +38,7 @@ function riesgoValido(v: unknown) { if (v === null) return true; if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version']) || !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false; + if (Object.hasOwn(v, 'fecha_indice') && v['fecha_indice'] !== null && !isoDate(v['fecha_indice'])) return false; const horizontes = v['horizontes']; return horizontes.every(horizonteValido) && horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']); From 00f773dd75396699c4a93d8c9525801d2db37ac5 Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 20 Nov 2026 23:11:56 -0600 Subject: [PATCH 05/21] CaCu patient record reads the patient's FHIR RiskAssessment The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/ and validates the searchset Bundle at the boundary (simulado tag, the patient asked for, one index date, probabilities and intervals); it shows the model, the risk's index date, the outcome, the evaluation and one row per horizon from each prediction's whenPeriod. The cohort's definition and the PIMM variables are no longer shown; an empty Bundle is a patient without a confirmed risk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7 --- .../paciente-riesgo-tabla.html | 29 +--- .../paciente-riesgo.models.ts | 33 ++-- .../paciente-riesgo.provider.ts | 9 +- .../paciente-detalle/paciente-riesgo.spec.ts | 74 +++------ .../paciente-detalle/paciente-riesgo.state.ts | 6 +- .../paciente-riesgo.testing.ts | 53 ++++-- .../paciente-riesgo.validation.spec.ts | 156 +++++++----------- .../paciente-riesgo.validation.ts | 117 +++++++++---- 8 files changed, 238 insertions(+), 239 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index a2c33dc..0cf617b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -8,33 +8,13 @@ @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') {

Información simulada · Entorno DEV · Sin evaluación clínica

- @if (lectura.datos.cohorte; as cohorte) { -
Cohorte
- -
- Variables del modelo PIMM -

Códigos técnicos del modelo; no constituyen un diagnóstico.

- -
- } @else { -

Sin membresía en la cohorte vigente.

- } - @if (lectura.datos.riesgo; as riesgo) { + @let riesgo = lectura.datos.riesgo;
Modelo y evaluación
@@ -46,7 +26,6 @@
- @for (h of riesgo.horizontes; track h.horizonte_anios) { @@ -54,14 +33,12 @@ - }
Horizonte (años) Probabilidad (%) Intervalo de confianza (%)Estado de evaluación
{{ h.horizonte_anios }} {{ h.probabilidad * 100 | number:'1.0-4' }} % @if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}
} @else {

Sin horizontes evaluados en el lote vigente.

} - } @else {

Sin riesgo disponible: no hay lote vigente.

} } }

Recomendaciones no disponibles.

diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index f1eb19d..dd56a2c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -1,48 +1,39 @@ import { Observable } from 'rxjs'; export type EstadoEvaluacionCacu = 'preliminary' | 'final'; -export type TipoCensuraCacu = 'prevalente' | 'incidente' | 'izquierda' | 'derecha' | 'derechaBasal' | 'no_informativo'; - -export interface CohorteRiesgoCacu { - url: string; - version: string; - fecha_indice: string; - tipo_censura: TipoCensuraCacu | null; - c: number | null; - l: number | null; - r: number | null; - pap_0: string | null; - hpv_0: string | null; -} export interface HorizonteRiesgoCacu { + /** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */ horizonte_anios: number; /** Transport values remain probabilities in [0, 1], never percentages. */ probabilidad: number; ic_bajo?: number | null; ic_alto?: number | null; - estado: EstadoEvaluacionCacu; } +/** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/`). */ export interface LoteRiesgoCacu { - lote_id: number; + /** The resource's id, `-`. */ + id: string; modelo_nombre: string; modelo_version: string; - /** The model's index date for this patient (ISO date): the horizons count from it. Absent from older APIs. */ - fecha_indice?: string | null; + /** The model's index date for this patient (the predictions' `whenPeriod.start`): the horizons count from it. */ + fecha_indice: string; evaluado_en: string; estado_lote: EstadoEvaluacionCacu; + /** The prediction's outcome code (e.g. `cin2_mas`) and its display. */ + desenlace: string; + desenlace_texto: string | null; horizontes: HorizonteRiesgoCacu[]; } -/** DEV-only contract from cacu_riesgo_paciente.md, 2026-10-28. */ +/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */ export interface RiesgoPacienteCacu { simulado: true; - cohorte: CohorteRiesgoCacu | null; - riesgo: LoteRiesgoCacu | null; + riesgo: LoteRiesgoCacu; } -/** `null` when the patient has no risk data. */ +/** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */ export interface PacienteRiesgoProvider { obtener(pacId: string): Observable; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 0749c29..5b4cf95 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -1,14 +1,17 @@ -import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'; import { inject, InjectionToken } from '@angular/core'; import { catchError, of, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; -// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data. +// The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/`, the identifier a follow-up row +// carries as `pac_id`; an empty Bundle (or a 404) is a patient without risk data. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { providedIn: 'root', factory: () => { const http = inject(HttpClient); return { - obtener: (pacId: string) => http.get(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe( + obtener: (pacId: string) => http.get('/cacu/fhir/RiskAssessment', { + params: new HttpParams().set('subject', `Patient/${pacId}`), + }).pipe( catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), ), }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 56d0b02..76caafc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -4,7 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common import { of, Subject, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; -import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; +import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; describe('RIESGO-CACU-02: presentación y aislamiento', () => { @@ -22,10 +22,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { TestBed.inject(HttpTestingController).verify(); }); - it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => { + it('pide el RiskAssessment FHIR de la paciente por su pac_id y trata un 404 como no disponible', () => { const f = setup(), root: HTMLElement = f.nativeElement; - TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo') - .flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' }); + TestBed.inject(HttpTestingController).expectOne('/cacu/fhir/RiskAssessment?subject=Patient/42') + .flush({ resourceType: 'OperationOutcome' }, { status: 404, statusText: 'Not Found' }); f.detectChanges(); expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); expect(root.textContent).toContain('Recomendaciones no disponibles'); @@ -33,29 +33,33 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); }); - it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => { + it('un Bundle vacío es una paciente sin riesgo confirmado', () => { + const f = setup({ obtener: () => of({ resourceType: 'Bundle', type: 'searchset', total: 0 }) }); + expect(f.nativeElement.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(f.nativeElement.querySelector('table')).toBeNull(); + }); + + it('renderiza el ejemplo contractual, metadatos y porcentajes sin alterar los datos', () => { const data = riesgoCacuEjemplo(), obtener = vi.fn(() => of(data)); - data.riesgo!.horizontes[1].estado = 'preliminary'; const baseline = structuredClone(data); const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); - expect(root.querySelectorAll('thead th')).toHaveLength(4); + expect(root.querySelectorAll('thead th')).toHaveLength(3); expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); expect(root.textContent).toContain('Final (final)'); - expect(root.textContent).toContain('Preliminar (preliminary)'); - for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', 'cacu/cohorte_vigilancia', '0.2.0', '2026-06-01', 'incidente', 'ASC-US', 'POSITIVO']) { + for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); } - // The index date shown is the risk's (the model's decision point), not the cohort member's. - expect(root.textContent).not.toContain('2023-04-15'); + // The record no longer shows the cohort's internals (its definition, version or model variables). + expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/); expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); - // Internal batch key stays in the contract, never in a UI label. - expect(root.textContent).not.toContain('lote_id'); + // The resource id (batch and patient) stays in the contract, never in a UI label. + expect(root.textContent).not.toMatch(/lote_id|12-42/); expect(data).toEqual(baseline); }); @@ -69,17 +73,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(getComputedStyle(scroll).maxWidth).toBe('100%'); expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); - expect(root.querySelector('details summary')!.textContent).toBe('Variables del modelo PIMM'); - expect(root.textContent).toContain('no constituyen un diagnóstico'); }); it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { const data = riesgoCacuEjemplo(); - data.riesgo!.estado_lote = 'preliminary'; - data.riesgo!.horizontes = [ - { horizonte_anios: 0.5, probabilidad: 0, ic_bajo: 0, ic_alto: 0, estado: 'preliminary' }, - { horizonte_anios: 8, probabilidad: 1, ic_bajo: null, ic_alto: 1, estado: 'final' }, - { horizonte_anios: 12.25, probabilidad: 0.00123, estado: 'final' }, + data.entry[0].resource.status = 'preliminary'; + data.entry[0].resource.prediction = [ + prediccion(0, '2026-06-01', '2026-12-01', [0, 0]), + prediccion(1, '2026-06-01', '2034-06-01'), + prediccion(0.00123, '2026-06-01', '2038-09-01'), ]; const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); @@ -88,31 +90,9 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(root.textContent).toContain('Preliminar (preliminary)'); }); - it('preserva variables nulas y el cero basal sin convertirlos en hallazgos', () => { + it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => { const data = riesgoCacuEjemplo(); - data.cohorte = { ...data.cohorte!, c: 0, l: null, r: null, pap_0: null, hpv_0: null, tipo_censura: null }; - const f = setup({ obtener: () => of(data) }); - const valores = [...f.nativeElement.querySelectorAll('details dd')].map((d: any) => d.textContent); - expect(valores).toEqual(['No disponible', '0', 'No disponible', 'No disponible', 'No disponible', 'No disponible']); - expect(f.nativeElement.textContent).not.toMatch(/undefined|null/); - }); - - it.each(['cohorte', 'riesgo', 'horizontes', 'ambos'])('distingue ausencia de %s', caso => { - const data = riesgoCacuEjemplo(); - if (caso === 'cohorte' || caso === 'ambos') data.cohorte = null; - if (caso === 'riesgo' || caso === 'ambos') data.riesgo = null; - if (caso === 'horizontes') data.riesgo!.horizontes = []; - const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; - if (!data.cohorte) expect(root.textContent).toContain('Sin membresía en la cohorte vigente'); - if (!data.riesgo) expect(root.textContent).toContain('Sin riesgo disponible: no hay lote vigente'); - if (caso === 'horizontes') expect(root.textContent).toContain('Sin horizontes evaluados'); - if (caso !== 'cohorte') expect(root.querySelector('table')).toBeNull(); - expect(root.textContent).toContain('Información simulada'); - expect(root.textContent).toContain('Recomendaciones no disponibles'); - }); - - it.each([false, 'true', undefined])('no expone una respuesta no simulada (%s)', simulado => { - const data = { ...riesgoCacuEjemplo(), simulado }; + if (tag === undefined) delete data.entry[0].resource.meta; else data.entry[0].resource.meta.tag = tag; const f = setup({ obtener: () => of(data) }); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.textContent).not.toContain('modelo-cacu'); @@ -120,7 +100,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { }); it('rechaza probabilidades inválidas sin presentar parcialmente la cohorte', () => { - const data = riesgoCacuEjemplo(); data.riesgo!.horizontes[0].probabilidad = 12; + const data = riesgoCacuEjemplo(); data.entry[0].resource.prediction[0].probabilityDecimal = 12; const f = setup({ obtener: () => of(data) }); expect(f.nativeElement.querySelector('[role="alert"]')).not.toBeNull(); expect(f.nativeElement.querySelectorAll('table, dl')).toHaveLength(0); @@ -136,14 +116,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { it('aísla estado y fixture entre instancias sin reutilizar información', () => { const source = new Subject(), f = setup({ obtener: () => source }); const data = riesgoCacuEjemplo(); source.next(data); f.detectChanges(); - data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges(); + data.entry[0].resource.prediction[0].probabilityDecimal = 1; f.detectChanges(); expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); f.destroy(); const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.componentRef.setInput('pacId', '43'); otra.detectChanges(); expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(otra.nativeElement.querySelector('table')).toBeNull(); - expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08); + expect(riesgoCacuEjemplo().entry[0].resource.prediction[0].probabilityDecimal).toBe(0.08); otra.destroy(); expect(source.observed).toBe(false); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index b5a08d5..3a5ed61 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -14,8 +14,10 @@ export class PacienteRiesgoState { readonly pacId = signal(undefined); readonly estado = toSignal(toObservable(this.pacId).pipe( switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe( - map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } - : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), + map((respuesta): PacienteRiesgoEstado => { + const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id); + return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos }; + }), catchError(() => of({ tipo: 'error' })), startWith(CARGANDO), )), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index ecf05cf..2344b80 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -1,20 +1,51 @@ import { RiesgoPacienteCacu } from './paciente-riesgo.models'; -/** TEST ONLY. Exact external contract example; never belongs to the selected patient. */ -export function riesgoCacuEjemplo(): RiesgoPacienteCacu { +const CS = 'https://isssteleon.org/fhir/CodeSystem'; +export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; + +/** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */ +export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any { + return { + outcome: { coding: [{ system: `${CS}/desenlace`, code: 'cin2_mas', display: 'CIN2+ por biopsia' }] }, + probabilityDecimal: p, whenPeriod: { start: inicio, end: fin }, + ...(ic ? { extension: [{ url: INTERVALO, valueRange: { low: { value: ic[0] }, high: { value: ic[1] } } }] } : {}), + }; +} + +/** TEST ONLY. The external contract example: a `searchset` Bundle with patient 42's current `RiskAssessment`, as + * `GET /cacu/fhir/RiskAssessment?subject=Patient/42` answers it; never belongs to the selected patient. */ +export function riesgoCacuEjemplo(): any { + return { + resourceType: 'Bundle', type: 'searchset', total: 1, + entry: [{ + fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/12-42', + resource: { + resourceType: 'RiskAssessment', id: '12-42', status: 'final', + meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] }, + subject: { reference: 'Patient/42' }, occurrenceDateTime: '2026-10-01T00:00:00Z', + method: { coding: [{ system: `${CS}/modelo`, code: 'modelo-cacu', version: '2.1.0' }] }, + prediction: [ + prediccion(0.08, '2026-06-01', '2027-06-01', [0.05, 0.12]), + prediccion(0.21, '2026-06-01', '2029-06-01', [0.15, 0.28]), + prediccion(0.34, '2026-06-01', '2031-06-01', [0.26, 0.44]), + ], + }, + search: { mode: 'match' }, + }], + }; +} + +/** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */ +export function riesgoCacuVista(): RiesgoPacienteCacu { return { simulado: true, - cohorte: { - url: 'cacu/cohorte_vigilancia', version: '0.2.0', fecha_indice: '2023-04-15', - tipo_censura: 'incidente', c: 0, l: 0.164, r: 0.548, pap_0: 'ASC-US', hpv_0: 'POSITIVO', - }, riesgo: { - lote_id: 12, modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', - evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', + id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', + evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia', horizontes: [ - { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12, estado: 'final' }, - { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28, estado: 'final' }, - { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44, estado: 'final' }, + { horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 }, + { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }, ], }, }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts index fbc8b28..238a9ec 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.spec.ts @@ -1,123 +1,89 @@ -import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; +import { prediccion, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; import { riesgoPacienteResponse, tieneIntervalo } from './paciente-riesgo.validation'; -import { TipoCensuraCacu } from './paciente-riesgo.models'; -describe('RIESGO-CACU-02: frontera del contrato DEV', () => { - it('conserva todos los campos del ejemplo externo y copia los objetos', () => { +const recurso = (v: any) => v.entry[0].resource; + +describe('RIESGO-CACU-02: frontera del contrato FHIR RiskAssessment (DEV)', () => { + it('lee el Bundle searchset en la vista de la ficha y no comparte objetos con la entrada', () => { const entrada = riesgoCacuEjemplo(); - const salida = riesgoPacienteResponse(entrada); - expect(salida).toEqual(entrada); - salida.riesgo!.horizontes[0].probabilidad = 0; - salida.cohorte!.c = -999; + const salida = riesgoPacienteResponse(entrada, '42')!; + expect(salida).toEqual(riesgoCacuVista()); + salida.riesgo.horizontes[0].probabilidad = 0; expect(entrada).toEqual(riesgoCacuEjemplo()); }); - it('admite campos aditivos sin eliminarlos ni renombrarlos', () => { - const entrada = { ...riesgoCacuEjemplo(), futuro: { estado: null } }; - expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + it('un Bundle vacío es una paciente sin riesgo confirmado, con o sin `entry`', () => { + expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0 })).toBeNull(); + expect(riesgoPacienteResponse({ resourceType: 'Bundle', type: 'searchset', total: 0, entry: [] })).toBeNull(); }); - it.each(['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo', null])( - 'preserva tipo_censura %s sin inferir etiquetas clínicas', tipo => { - const entrada = riesgoCacuEjemplo(); - entrada.cohorte!.tipo_censura = tipo as TipoCensuraCacu | null; - expect(riesgoPacienteResponse(entrada).cohorte!.tipo_censura).toBe(tipo); - }, - ); - - it('preserva los nulos independientes y el sentinel basal del contrato', () => { + it('el horizonte sale del whenPeriod; el inmediato es un periodo de un día', () => { const entrada = riesgoCacuEjemplo(); - entrada.cohorte = { ...entrada.cohorte!, tipo_censura: null, c: -999, l: null, r: null, pap_0: null, hpv_0: null }; - expect(riesgoPacienteResponse(entrada)).toEqual(entrada); - entrada.riesgo = null; - entrada.cohorte.c = null; - expect(riesgoPacienteResponse(entrada)).toEqual(entrada); - entrada.cohorte = null; - expect(riesgoPacienteResponse(entrada)).toEqual({ simulado: true, cohorte: null, riesgo: null }); + recurso(entrada).prediction = [prediccion(0.02, '2026-06-01', '2026-06-01'), prediccion(0.4, '2026-06-01', '2034-06-01')]; + expect(riesgoPacienteResponse(entrada)!.riesgo.horizontes.map(h => h.horizonte_anios)).toEqual([0, 8]); }); - it('no impone dependencia entre cohorte nullable y riesgo nullable', () => { + it('ordena las predicciones por horizonte y admite campos aditivos de FHIR', () => { const entrada = riesgoCacuEjemplo(); - entrada.cohorte = null; - expect(riesgoPacienteResponse(entrada)).toEqual(entrada); + recurso(entrada).prediction.reverse(); + recurso(entrada).note = [{ text: 'simulado' }]; + expect(riesgoPacienteResponse(entrada)).toEqual(riesgoCacuVista()); }); - it.each([[], [2.5], [0, 0.5, 7, 12]])('acepta horizontes dinámicos/parciales/vacíos %j', (...anios: number[]) => { + it.each([[undefined], [[]], [[{ url: 'otra', valueString: 'x' }]]])('sin extensión de intervalo no fabrica límites (%j)', ext => { const entrada = riesgoCacuEjemplo(); - entrada.riesgo!.horizontes = anios.map((horizonte_anios, i) => ({ - horizonte_anios, probabilidad: i % 2, estado: i % 2 ? 'preliminary' : 'final', - })); - expect(riesgoPacienteResponse(entrada)).toEqual(entrada); - }); - - it.each([ - {}, { ic_bajo: null, ic_alto: null }, { ic_bajo: 0, ic_alto: null }, - { ic_bajo: null, ic_alto: 1 }, { ic_bajo: 0 }, { ic_alto: 1 }, - ])('conserva IC incompletos sin generar límites: %j', limites => { - const entrada = riesgoCacuEjemplo(); - entrada.riesgo!.horizontes = [{ horizonte_anios: 2, probabilidad: 0.5, estado: 'preliminary', ...limites }]; - const salida = riesgoPacienteResponse(entrada); - expect(salida).toEqual(entrada); - expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(false); + const p = recurso(entrada).prediction[0]; + if (ext === undefined) delete p.extension; else p.extension = ext; + const h = riesgoPacienteResponse(entrada)!.riesgo.horizontes[0]; + expect([h.ic_bajo, h.ic_alto]).toEqual([null, null]); + expect(tieneIntervalo(h)).toBe(false); }); it.each([0, 1])('acepta probabilidad y límites extremos %s sin convertir el transporte a porcentaje', p => { const entrada = riesgoCacuEjemplo(); - entrada.riesgo!.estado_lote = 'preliminary'; - entrada.riesgo!.horizontes = [{ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p, estado: 'preliminary' }]; - const salida = riesgoPacienteResponse(entrada); - expect(salida).toEqual(entrada); - expect(tieneIntervalo(salida.riesgo!.horizontes[0])).toBe(true); + recurso(entrada).status = 'preliminary'; + recurso(entrada).prediction = [prediccion(p, '2026-06-01', '2030-06-01', [p, p])]; + const salida = riesgoPacienteResponse(entrada)!; + expect(salida.riesgo.estado_lote).toBe('preliminary'); + expect(salida.riesgo.horizontes[0]).toEqual({ horizonte_anios: 4, probabilidad: p, ic_bajo: p, ic_alto: p }); + expect(tieneIntervalo(salida.riesgo.horizontes[0])).toBe(true); }); const invalidos: [string, (v: any) => void][] = [ - ['no simulado', v => v.simulado = false], - ['simulado string', v => v.simulado = 'true'], - ['sin simulado', v => delete v.simulado], - ['sin cohorte', v => delete v.cohorte], - ['sin riesgo', v => delete v.riesgo], - ['cohorte lista', v => v.cohorte = []], - ['URL ajena', v => v.cohorte.url = 'otra'], - ['versión ausente', v => delete v.cohorte.version], - ['fecha inválida', v => v.cohorte.fecha_indice = '2026-02-30'], - ['enum PIMM desconocido', v => v.cohorte.tipo_censura = 'diagnostico'], - ['basal string', v => v.cohorte.c = '0'], - ['variable no finita', v => v.cohorte.l = Infinity], - ['variable omitida', v => delete v.cohorte.r], - ['pap no textual', v => v.cohorte.pap_0 = 5], - ['hpv no textual', v => v.cohorte.hpv_0 = false], - ['lote fraccionario', v => v.riesgo.lote_id = 1.5], - ['lote string', v => v.riesgo.lote_id = '12'], - ['modelo omitido', v => delete v.riesgo.modelo_nombre], - ['versión no textual', v => v.riesgo.modelo_version = 2], - ['fecha índice del riesgo inválida', v => v.riesgo.fecha_indice = '2026-02-30'], - ['fecha índice del riesgo no textual', v => v.riesgo.fecha_indice = 20260601], - ['evaluación fecha imposible', v => v.riesgo.evaluado_en = '2026-02-30T00:00:00Z'], - ['evaluación sin UTC', v => v.riesgo.evaluado_en = '2026-10-01T00:00:00-06:00'], - ['hora inválida', v => v.riesgo.evaluado_en = '2026-10-01T25:00:00Z'], - ['estado lote desconocido', v => v.riesgo.estado_lote = 'confirmado'], - ['sin horizontes', v => delete v.riesgo.horizontes], - ['horizontes nulos', v => v.riesgo.horizontes = null], - ['horizonte nulo', v => v.riesgo.horizontes[0] = null], - ['horizonte string', v => v.riesgo.horizontes[0].horizonte_anios = '1'], - ['horizonte no finito', v => v.riesgo.horizontes[0].horizonte_anios = NaN], - ['horizontes desordenados', v => v.riesgo.horizontes.reverse()], - ['horizontes repetidos', v => v.riesgo.horizontes[1].horizonte_anios = 1], - ['probabilidad negativa', v => v.riesgo.horizontes[0].probabilidad = -0.01], - ['probabilidad mayor a uno', v => v.riesgo.horizontes[0].probabilidad = 1.01], - ['probabilidad string', v => v.riesgo.horizontes[0].probabilidad = '0.08'], - ['probabilidad nula', v => v.riesgo.horizontes[0].probabilidad = null], - ['probabilidad no finita', v => v.riesgo.horizontes[0].probabilidad = NaN], - ['estado horizonte inválido', v => v.riesgo.horizontes[0].estado = 'FINAL'], - ['IC bajo inválido', v => v.riesgo.horizontes[0].ic_bajo = -0.01], - ['IC alto inválido', v => v.riesgo.horizontes[0].ic_alto = 1.01], - ['IC string', v => v.riesgo.horizontes[0].ic_alto = '0.12'], - ['IC invertido', v => Object.assign(v.riesgo.horizontes[0], { ic_bajo: 0.12, ic_alto: 0.05 })], - ['IC fuera de probabilidad', v => v.riesgo.horizontes[0].ic_alto = 0.07], + ['no es Bundle', v => v.resourceType = 'RiskAssessment'], + ['Bundle no searchset', v => v.type = 'collection'], + ['sin total', v => delete v.total], + ['entry no lista', v => v.entry = {}], + ['recurso ajeno', v => recurso(v).resourceType = 'Observation'], + ['no simulado', v => delete recurso(v).meta], + ['etiqueta ajena', v => recurso(v).meta.tag[0].code = 'real'], + ['sin id', v => delete recurso(v).id], + ['estado desconocido', v => recurso(v).status = 'amended'], + ['estado anulado', v => recurso(v).status = 'entered-in-error'], + ['otra paciente', v => recurso(v).subject.reference = 'Patient/43'], + ['sujeto no paciente', v => recurso(v).subject.reference = 'Group/42'], + ['evaluación sin UTC', v => recurso(v).occurrenceDateTime = '2026-10-01T00:00:00-06:00'], + ['evaluación fecha imposible', v => recurso(v).occurrenceDateTime = '2026-02-30T00:00:00Z'], + ['sin modelo', v => delete recurso(v).method], + ['modelo sin versión', v => delete recurso(v).method.coding[0].version], + ['sin predicciones', v => recurso(v).prediction = []], + ['predicción nula', v => recurso(v).prediction[0] = null], + ['sin desenlace', v => delete recurso(v).prediction[0].outcome], + ['probabilidad string', v => recurso(v).prediction[0].probabilityDecimal = '0.08'], + ['probabilidad mayor a uno', v => recurso(v).prediction[0].probabilityDecimal = 1.01], + ['probabilidad negativa', v => recurso(v).prediction[0].probabilityDecimal = -0.01], + ['sin periodo', v => delete recurso(v).prediction[0].whenPeriod], + ['periodo con fecha imposible', v => recurso(v).prediction[0].whenPeriod.end = '2027-02-30'], + ['periodo invertido', v => recurso(v).prediction[0].whenPeriod.end = '2025-06-01'], + ['dos fechas índice', v => recurso(v).prediction[1].whenPeriod.start = '2026-07-01'], + ['horizontes repetidos', v => recurso(v).prediction[1].whenPeriod.end = '2027-06-01'], + ['IC invertido', v => recurso(v).prediction[0].extension[0].valueRange = { low: { value: 0.12 }, high: { value: 0.05 } }], + ['IC fuera de probabilidad', v => recurso(v).prediction[0].extension[0].valueRange.high.value = 0.07], + ['IC string', v => recurso(v).prediction[0].extension[0].valueRange.high.value = '0.12'], ]; it.each(invalidos)('rechaza %s sin coerción ni datos parciales', (_, mutar) => { const entrada = riesgoCacuEjemplo(); mutar(entrada); - expect(() => riesgoPacienteResponse(entrada)).toThrow('Respuesta de riesgo individual DEV inválida'); + expect(() => riesgoPacienteResponse(entrada, '42')).toThrow('Respuesta de riesgo individual DEV inválida'); }); it.each([null, undefined, [], 0, 'respuesta'])('rechaza cuerpo inválido %j', entrada => { expect(() => riesgoPacienteResponse(entrada)).toThrow(); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index a920048..dbbade0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -1,55 +1,104 @@ import { isoDate } from '../cacu-seguimiento.models'; -import { HorizonteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); -const nullableNumber = (v: unknown) => v === null || finite(v); -const nullableText = (v: unknown) => v === null || typeof v === 'string'; -const text = (v: unknown) => typeof v === 'string'; -const estado = (v: unknown) => v === 'preliminary' || v === 'final'; +const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; +const estado = (v: unknown): v is 'preliminary' | 'final' => v === 'preliminary' || v === 'final'; const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; -const censuras = ['prevalente', 'incidente', 'izquierda', 'derecha', 'derechaBasal', 'no_informativo']; +const DAYS_PER_YEAR = 365.25; +const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; +const SIMULATED = 'simulado'; -function utcTimestamp(v: unknown) { +function utcTimestamp(v: unknown): v is string { return typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|\+00:00)$/.test(v) && isoDate(v.slice(0, 10)) && Number.isFinite(Date.parse(v)); } -function cohorteValida(v: unknown) { - return v === null || record(v) - && v['url'] === 'cacu/cohorte_vigilancia' && text(v['version']) && isoDate(v['fecha_indice']) - && (v['tipo_censura'] === null || censuras.includes(v['tipo_censura'] as string)) - && nullableNumber(v['c']) && nullableNumber(v['l']) && nullableNumber(v['r']) - && nullableText(v['pap_0']) && nullableText(v['hpv_0']); +function invalid(): never { + throw new Error('Respuesta de riesgo individual DEV inválida'); } -function horizonteValido(v: unknown) { - if (!record(v) || !finite(v['horizonte_anios']) || !probability(v['probabilidad']) || !estado(v['estado'])) return false; - for (const key of ['ic_bajo', 'ic_alto']) { - if (Object.hasOwn(v, key) && v[key] !== null && !probability(v[key])) return false; +/** Years between two ISO dates, to two decimals: a prediction's horizon from its `whenPeriod`. */ +function years(start: string, end: string): number { + const days = (Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86_400_000; + return Math.round(days / DAYS_PER_YEAR * 100) / 100; +} + +function interval(prediction: Record): { ic_bajo: number | null; ic_alto: number | null } { + const extensions = prediction['extension']; + if (extensions === undefined) return { ic_bajo: null, ic_alto: null }; + if (!Array.isArray(extensions)) invalid(); + const found = extensions.find(e => record(e) && e['url'] === INTERVAL); + if (found === undefined) return { ic_bajo: null, ic_alto: null }; + const range = found['valueRange']; + const low = record(range) && record(range['low']) ? range['low']['value'] : undefined; + const high = record(range) && record(range['high']) ? range['high']['value'] : undefined; + if (!probability(low) || !probability(high) || low > high) invalid(); + return { ic_bajo: low, ic_alto: high }; +} + +function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } { + if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid(); + const period = prediction['whenPeriod']; + if (!record(period) || !isoDate(period['start']) || !isoDate(period['end'])) invalid(); + const from = period['start'] as string, to = period['end'] as string; + if (start !== undefined && from !== start) invalid(); // one index date per patient + const h = years(from, to); + if (h < 0) invalid(); + const ic = interval(prediction); + const p = prediction['probabilityDecimal']; + if (ic.ic_bajo !== null && ic.ic_alto !== null && !(ic.ic_bajo <= p && p <= ic.ic_alto)) invalid(); + return { horizonte: { horizonte_anios: h, probabilidad: p, ...ic }, start: from }; +} + +function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { + if (!record(v) || v['resourceType'] !== 'RiskAssessment' || !text(v['id']) || !estado(v['status']) + || !utcTimestamp(v['occurrenceDateTime'])) invalid(); + const subject = v['subject']; + if (!record(subject) || !text(subject['reference']) || !subject['reference'].startsWith('Patient/') + || (pacId !== null && subject['reference'] !== `Patient/${pacId}`)) invalid(); + const method = v['method']; + const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined; + if (!record(model) || !text(model['code']) || !text(model['version'])) invalid(); + const predictions = v['prediction']; + if (!Array.isArray(predictions) || predictions.length === 0) invalid(); + let start: string | undefined; + const horizontes: HorizonteRiesgoCacu[] = []; + for (const prediction of predictions) { + const found = horizon(prediction, start); + start = found.start; + horizontes.push(found.horizonte); } - // Missing/null endpoints are preserved. A complete interval must contain the probability. - return !(probability(v['ic_bajo']) && probability(v['ic_alto'])) - || v['ic_bajo'] <= v['probabilidad'] && v['probabilidad'] <= v['ic_alto']; + horizontes.sort((a, b) => a.horizonte_anios - b.horizonte_anios); + if (horizontes.some((h, i) => i > 0 && horizontes[i - 1].horizonte_anios === h.horizonte_anios)) invalid(); + const outcome = record(predictions[0]) && record(predictions[0]['outcome']) && Array.isArray(predictions[0]['outcome']['coding']) + ? predictions[0]['outcome']['coding'][0] : undefined; + if (!record(outcome) || !text(outcome['code'])) invalid(); + return { + id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, + fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', + desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null, + horizontes, + }; } -function riesgoValido(v: unknown) { - if (v === null) return true; - if (!record(v) || !Number.isSafeInteger(v['lote_id']) || !text(v['modelo_nombre']) || !text(v['modelo_version']) - || !utcTimestamp(v['evaluado_en']) || !estado(v['estado_lote']) || !Array.isArray(v['horizontes'])) return false; - if (Object.hasOwn(v, 'fecha_indice') && v['fecha_indice'] !== null && !isoDate(v['fecha_indice'])) return false; - const horizontes = v['horizontes']; - return horizontes.every(horizonteValido) - && horizontes.every((h, i) => i === 0 || horizontes[i - 1]['horizonte_anios'] < h['horizonte_anios']); +function simulated(resource: Record): boolean { + const meta = resource['meta']; + return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } -/** Validate at the boundary. Reject real data, coercions and malformed fields; retain additive fields. */ -export function riesgoPacienteResponse(v: unknown): RiesgoPacienteCacu { - if (!record(v) || v['simulado'] !== true || !cohorteValida(v['cohorte']) || !riesgoValido(v['riesgo'])) { - throw new Error('Respuesta de riesgo individual DEV inválida'); - } - return structuredClone(v) as unknown as RiesgoPacienteCacu; +/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only). + * `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */ +export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null { + if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid(); + const entries = v['entry'] ?? []; + if (!Array.isArray(entries)) invalid(); + if (entries.length === 0) return null; + const resource = record(entries[0]) ? entries[0]['resource'] : undefined; + if (!record(resource) || !simulated(resource)) invalid(); + return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) }; } /** Presentation helper: an incomplete interval must never become a fabricated range. */ From efe4404c4eb10d39a3d6c503f53b34f273d16818 Mon Sep 17 00:00:00 2001 From: UlisesPG Date: Sat, 21 Nov 2026 00:27:16 -0600 Subject: [PATCH 06/21] =?UTF-8?q?Seguimiento=20TEA:=20gr=C3=A1fica=20de=20?= =?UTF-8?q?la=20norma=20por=20edad=20con=20el=20paciente?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El panel de la derecha muestra el mapa de zonas o la norma por edad (bandas 5-95 y 25-75 %, mediana y el punto del paciente). Datos de ejemplo. Co-Authored-By: Claude Opus 5.5 --- .../indicadores/tea-paciente-resumen.html | 27 ++++++-- .../indicadores/tea-paciente-resumen.scss | 6 ++ .../indicadores/tea-paciente-resumen.ts | 68 ++++++++++++++++--- .../indicadores/tea-seguimiento.service.ts | 22 +++++- .../indicadores/tea-seguimiento.spec.ts | 35 ++++++++++ 5 files changed, 142 insertions(+), 16 deletions(-) diff --git a/src/app/features/indicadores/tea-paciente-resumen.html b/src/app/features/indicadores/tea-paciente-resumen.html index e960920..3d8c515 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.html +++ b/src/app/features/indicadores/tea-paciente-resumen.html @@ -59,16 +59,16 @@
@if (d.eeg; as e) { -
+

Alteraciones del EEG Datos de ejemplo

-

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.

+

Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas o dónde queda el paciente en la norma por edad.

@if (!alteradas(e).length) {

Sin alteraciones en las métricas evaluadas.

}
    @for (m of e.alteraciones; track m.codigo) {
  • - {{ estado[m.estado] }}
    @@ -88,8 +88,24 @@
- @if (mapaActual(e); as mapa) { -
+ @if (abierto(e)) { +
+ @if (mapaActual(e) && normaActual(e)) { +
+ + +
+ } + @if (vista === 'norma' && normaActual(e); as m) { +

Norma por edad

+

{{ m.etiqueta }} · {{ m.curva_referencia!.fuente }}, en {{ m.curva_referencia!.estado }}

+ @if (figuraNorma) { + + } +

La línea es la mediana de la norma y las sombras, del 5 al 95 % (clara) y del 25 al 75 % (oscura). + El punto es este paciente: {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} a los {{ e.edad_meses }} meses (z = {{ m.valor_z }}).

+ } @else if (mapaActual(e); as mapa) {

Zonas más afectadas

{{ mapa.metrica }} · mapa ilustrativo

Azul: menos actividad Rojo: más actividad

@@ -102,6 +118,7 @@
  • {{ r.etiqueta }}z = {{ r.valor_z }}
  • } + }
    }
    diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index 5c88782..c75b477 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -88,3 +88,9 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border .barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } .barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } .nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } +// The switch between the head map and the age norm, when the metric has both. +.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; } +.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; } +.vistas button + button { border-inline-start: 1px solid var(--issste-border); } +.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; } +.leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index c3c960a..2f073cd 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -51,6 +51,36 @@ export function mapaFigure(eeg: TeaEeg, mapa: TeaEegMapa, fondo = '#FFFFFF'): Pl }; } +// The age norm around the patient: the 5–95 and 25–75 percentile bands, the median line and the patient as a point. +const BANDA_EXTERIOR = 'rgba(49,130,189,.16)', BANDA_INTERIOR = 'rgba(49,130,189,.32)', MEDIANA = '#2C6FA6', ALTERADO = '#B3261E'; +export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure { + const c = m.curva_referencia!, x = c.edad_meses, atras = [...x].reverse(); + const banda = (bajo: number[], alto: number[], color: string, nombre: string) => ({ + type: 'scatter', mode: 'lines', x: [...x, ...atras], y: [...alto, ...[...bajo].reverse()], fill: 'toself', fillcolor: color, + line: { width: 0 }, name: nombre, hoverinfo: 'skip', + }); + const unidad = m.unidad ? ` ${m.unidad}` : ''; + const alterado = m.estado === 'aumentado' || m.estado === 'disminuido'; + return { + data: [ + banda(c.p5, c.p95, BANDA_EXTERIOR, 'Del 5 al 95 %'), + banda(c.p25, c.p75, BANDA_INTERIOR, 'Del 25 al 75 %'), + { type: 'scatter', mode: 'lines', x, y: c.mediana, name: 'Mediana', line: { color: MEDIANA, width: 2 }, + hovertemplate: `%{x} meses: mediana %{y:.2f}${unidad}` }, + { type: 'scatter', mode: 'markers', x: [edad], y: [m.valor], name: 'Este paciente', + marker: { size: 11, color: alterado ? ALTERADO : INK, line: { color: '#FFFFFF', width: 2 } }, + hovertemplate: `Este paciente: %{y:.2f}${unidad} a los %{x:.1f} meses (z = ${m.valor_z})` }, + ], + layout: { + margin: { l: 52, r: 12, t: 8, b: 44 }, paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', + showlegend: true, legend: { orientation: 'h', y: -0.28, font: { size: 11 } }, font: { color: INK }, + xaxis: { title: { text: 'Edad (meses)' }, range: [x[0], x[x.length - 1]], dtick: 6, gridcolor: 'rgba(8,24,57,.08)', fixedrange: true }, + yaxis: { title: { text: m.unidad || m.etiqueta }, gridcolor: 'rgba(8,24,57,.08)', zeroline: false, fixedrange: true }, + }, + config: { displayModeBar: false }, + }; +} + @Component({ selector: 'app-tea-paciente-resumen', imports: [PlotlyChart], @@ -64,7 +94,7 @@ export class TeaPacienteResumen implements OnInit { readonly status = signal<'loading' | 'ready' | 'error'>('loading'); readonly detalle = signal(undefined); figura?: PlotlyFigure; - private mapaElegido?: string; + mapaElegido?: string; private readonly elemento = inject>(ElementRef); // The first solid background around this component: the map has no box of its own. private fondo() { @@ -74,13 +104,29 @@ export class TeaPacienteResumen implements OnInit { } return '#FFFFFF'; } + // The side panel shows the chosen metric's head map, its age norm, or both with a switch between them. + vista: 'zonas' | 'norma' = 'zonas'; + figuraNorma?: PlotlyFigure; mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } - elegirMapa(eeg: TeaEeg, codigo: string) { - // The chosen card closes the map again, and the cards take the whole space back. - const mapa = codigo === this.mapaElegido ? undefined : eeg.mapas.find(m => m.codigo === codigo); - this.mapaElegido = mapa?.codigo; - this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + // The age norm can only be drawn with the curve, the patient's value and their age. + private conNorma(eeg: TeaEeg, codigo?: string) { + const m = eeg.alteraciones.find(a => a.codigo === codigo); + return m && m.curva_referencia && m.valor !== null && typeof eeg.edad_meses === 'number' ? m : undefined; } + normaActual(eeg: TeaEeg) { return this.conNorma(eeg, this.mapaElegido); } + abierto(eeg: TeaEeg) { return !!this.mapaActual(eeg) || !!this.normaActual(eeg); } + private mostrar(eeg: TeaEeg, codigo: string | undefined) { + const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo); + this.mapaElegido = mapa || norma ? codigo : undefined; + this.vista = mapa ? 'zonas' : 'norma'; + this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); + this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number); + } + elegirMapa(eeg: TeaEeg, codigo: string) { + // The chosen card closes the panel again, and the cards take the whole space back. + this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo); + } + verVista(vista: 'zonas' | 'norma') { this.vista = vista; } readonly clasificacion = CLASIFICACIONES_ADOS2; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -90,10 +136,12 @@ export class TeaPacienteResumen implements OnInit { this.status.set('loading'); this.service.detalle(this.id).pipe(takeUntilDestroyed(this.destroy)).subscribe({ next: d => { - // Opens on the first altered metric, or on the first one if none is altered. - const e = d.eeg, inicial = e?.mapas.find(m => e.alteraciones.some(a => a.codigo === m.codigo && a.estado !== 'normal')) ?? e?.mapas[0]; - this.mapaElegido = inicial?.codigo; - this.figura = e && inicial ? mapaFigure(e, inicial, this.fondo()) : undefined; + // Opens on the first altered metric that has a map or a norm, or on the first one with either if none is altered. + const e = d.eeg; + if (e) { + const conPanel = e.alteraciones.filter(a => e.mapas.some(m => m.codigo === a.codigo) || this.conNorma(e, a.codigo)); + this.mostrar(e, (conPanel.find(a => a.estado === 'aumentado' || a.estado === 'disminuido') ?? conPanel[0])?.codigo); + } else { this.mapaElegido = undefined; this.figura = this.figuraNorma = undefined; } this.detalle.set(d); this.status.set('ready'); }, error: () => this.status.set('error'), diff --git a/src/app/features/indicadores/tea-seguimiento.service.ts b/src/app/features/indicadores/tea-seguimiento.service.ts index 83ad8fd..74ed6f4 100644 --- a/src/app/features/indicadores/tea-seguimiento.service.ts +++ b/src/app/features/indicadores/tea-seguimiento.service.ts @@ -56,10 +56,17 @@ export interface TeaEegAlteracion { valor: number | null; valor_z: number | null; estado: TeaAlteracionEstado; efectos: string[]; // Why it could not be evaluated: nothing measured (spindles without sleep), or no reference for the child's age. sin_evaluar: 'sin_valor' | 'sin_referencia' | null; + // The age norm the reference comes from (percentiles by month), when the analysis sends it. + curva_referencia?: TeaCurvaReferencia | null; +} +export interface TeaCurvaReferencia { + fuente: string; estado: string; edad_meses: number[]; p5: number[]; p25: number[]; mediana: number[]; p75: number[]; p95: number[]; } export interface TeaEegMapa { codigo: string; metrica: string; z: (number | null)[][]; regiones: TeaEegRegion[] } export interface TeaEeg { fecha: string; duracion_min: number | null; canales: number | null; + // Age at the EEG, to place the patient on the age norms. + edad_meses?: number | null; // The overall rating is the EEG analysis's verdict; its checks say why. calidad: TeaNivelCalidad; criterios_calidad: TeaCriterioCalidad[]; alteraciones: TeaEegAlteracion[]; @@ -154,13 +161,24 @@ function validAdos(a: unknown): boolean { return ok && a['total'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.puntaje, 0) && a['total_maximo'] === (dominios as TeaAdosDominio[]).reduce((t, d) => t + d.maximo, 0); } +// An age norm: ages in increasing order and, at each one, percentiles that never cross. +const PERCENTILES = ['p5', 'p25', 'mediana', 'p75', 'p95'] as const; +function validCurva(c: unknown): boolean { + if (c === undefined || c === null) return true; + if (!record(c) || !text(c['fuente']) || !text(c['estado']) || !Array.isArray(c['edad_meses'])) return false; + const edades = c['edad_meses'] as unknown[], n = edades.length; + if (n < 2 || !edades.every((e, i) => finite(e) && (i === 0 || (e as number) > (edades[i - 1] as number)))) return false; + const series = PERCENTILES.map(k => c[k]); + return series.every(s => Array.isArray(s) && s.length === n && s.every(finite)) + && edades.every((_, i) => series.every((s, k) => k === 0 || (s as number[])[i] >= (series[k - 1] as number[])[i])); +} // A metric that can't be evaluated says why and has no z; one that can has its value, z and reference. function validAlteracion(a: unknown): boolean { const ref = a !== null && record(a) ? a['referencia'] : undefined; if (!record(a) || !text(a['codigo']) || !text(a['etiqueta']) || typeof a['unidad'] !== 'string' || !(ref === null || record(ref) && finite(ref['min']) && finite(ref['max']) && (ref['min'] as number) <= (ref['max'] as number) && (ref['mediana'] === null || finite(ref['mediana']))) - || !Array.isArray(a['efectos']) || !a['efectos'].every(text)) return false; + || !Array.isArray(a['efectos']) || !a['efectos'].every(text) || !validCurva(a['curva_referencia'])) return false; const estado = a['estado']; if (estado === 'no_evaluable') return a['valor_z'] === null && ['sin_valor', 'sin_referencia'].includes(a['sin_evaluar'] as string) && (a['sin_evaluar'] === 'sin_valor') === (a['valor'] === null); @@ -170,7 +188,9 @@ function validAlteracion(a: unknown): boolean { function validEeg(e: unknown): boolean { if (e === null) return true; const optional = (v: unknown) => v === null || integer(v); + const edad = record(e) ? e['edad_meses'] : undefined; if (!record(e) || !isoDate(e['fecha']) || !optional(e['duracion_min']) || !optional(e['canales']) + || !(edad === undefined || edad === null || finite(edad) && (edad as number) >= 0) || !['bueno', 'malo', 'sin_analizar'].includes(e['calidad'] as string) || !Array.isArray(e['criterios_calidad']) || !e['criterios_calidad'].every(c => record(c) && text(c['codigo']) && text(c['etiqueta']) && ['bueno', 'malo'].includes(c['nivel'] as string) && typeof c['unidad'] === 'string' && typeof c['decisivo'] === 'boolean' diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index a58e589..9e91ad6 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -172,6 +172,41 @@ describe('Seguimiento TEA', () => { expect(root.querySelector('section.mapa')).not.toBeNull(); http.verify(); }); + it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => { + const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48], + p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] }; + const conCurva = detalle.eeg.alteraciones.map(m => + m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m); + const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } }; + const fixture = open(); + request().flush(data); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges(); + const panel = () => root.querySelector('section.mapa')!; + const vistas = () => panel().querySelectorAll('.vistas button'); + // Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age. + expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']); + expect(panel().textContent).toContain('Zonas más afectadas'); + vistas()[1].click(); fixture.detectChanges(); + expect(vistas()[1].getAttribute('aria-pressed')).toBe('true'); + expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad'); + expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)'); + expect(panel().querySelector('.regiones')).toBeNull(); + // Gradiente has no map: its card opens the norm alone, without the switch. + const tarjetas = root.querySelectorAll('button.nombre'); + tarjetas[4].click(); fixture.detectChanges(); + expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true'); + expect(vistas().length).toBe(0); + expect(panel().textContent).toContain('Gradiente anteroposterior'); + const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance; + const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[]; + expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']); + expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]); + const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m); + expect(() => teaPacienteDetalle({ ...conNorma, eeg: { ...conNorma.eeg, alteraciones: cruzada } }, 'T-0001')).toThrow(); + http.verify(); + }); it('el mapa oculta lo que queda fuera de la cabeza con el color que tiene detrás', () => { const figura = (fondo?: string) => mapaFigure(detalle.eeg as unknown as TeaEeg, detalle.eeg.mapas[0] as unknown as TeaEegMapa, fondo); const marco = (fondo?: string) => (figura(fondo).layout['shapes'] as { fillcolor: string }[])[0].fillcolor; From dae8bc517ed9308a5a7b0577f458a6a8f52b3267 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 01:55:05 -0600 Subject: [PATCH 07/21] =?UTF-8?q?CaMa=20follow-up:=20the=20clinical=20scen?= =?UTF-8?q?ario=20as=20Post-tratamiento=20or=20En=20observaci=C3=B3n=20in?= =?UTF-8?q?=20the=20list,=20the=20record=20and=20its=20PDF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/features/indicadores/etiquetas-cohorte.ts | 7 ++++++- .../indicadores-cohorte-etiquetas.spec.ts | 13 ++++++++++++- .../paciente-detalle/cama/cama-patient-card.html | 1 + .../paciente-detalle/cama/cama-patient-card.spec.ts | 2 +- .../paciente-detalle/cama/cama-patient-pdf.ts | 1 + .../paciente-detalle/cama/cama-patient.models.ts | 3 +++ .../indicadores/seguimiento-tabla.service.ts | 2 +- 7 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts index 21af265..e95eaf4 100644 --- a/src/app/features/indicadores/etiquetas-cohorte.ts +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly> = { BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido', }; +const ESCENARIOS: Readonly> = { POST_TRATAMIENTO: 'Post-tratamiento', EN_OBSERVACION: 'En observación' }; /** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; /** «50-59» as «50 a 59 años». Any other text is returned as it came. */ export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo; +/** The patient's clinical scenario at the cut-off: «Post-tratamiento» or «En observación». */ +export const etiquetaEscenario = (codigo: string) => ESCENARIOS[codigo] ?? codigo; -const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia }; +const POR_CLAVE: Readonly string>> = { + birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia, escenario_clinico: etiquetaEscenario, +}; /** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts index 82fba5a..f69ef7e 100644 --- a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts +++ b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts @@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf'; import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; -import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte'; +import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaEscenario, etiquetaHistologia } from './etiquetas-cohorte'; import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; @@ -33,6 +33,17 @@ describe('Etiquetas de la cohorte', () => { expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA'); expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia)) .toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']); + expect(['POST_TRATAMIENTO', 'EN_OBSERVACION', 'CONTROL'].map(etiquetaEscenario)).toEqual(['Post-tratamiento', 'En observación', 'CONTROL']); + }); + it('el escenario clínico de una fila se lee «Post-tratamiento» o «En observación» en la lista y en la ficha, con su código guardado', () => { + // Fails if the list or the record show the scenario's code, or the code the filter sends is lost. + const cruda = listaCohorte(); + const items = cruda['items'] as Record[]; + items[0]['escenario_clinico'] = 'POST_TRATAMIENTO'; items[1]['escenario_clinico'] = 'EN_OBSERVACION'; + const r = seguimientoTablaResponse(cruda); + expect(r.items[0]).toMatchObject({ escenario_clinico: 'Post-tratamiento', escenario_clinico_codigo: 'POST_TRATAMIENTO' }); + expect(r.items[1]).toMatchObject({ escenario_clinico: 'En observación', escenario_clinico_codigo: 'EN_OBSERVACION' }); + expect(toCamaPatientSummary(r.items[0], '2026-01-01')?.clinicalScenario).toBe('Post-tratamiento'); }); it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => { // Fails if the table, the record and the files can still show the code, or the code is lost for the requests. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 1fef561..9e1d3a7 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -11,6 +11,7 @@
    {{ p.idLabel }}
    {{ p.patientId }}
    Grupo de edad
    {{ p.ageGroup ?? notAvailable }}
    +
    Escenario clínico
    {{ p.clinicalScenario ?? notAvailable }}
    Estatus de seguimiento
    {{ p.status ?? notAvailable }}
    Prioridad
    {{ p.priority ?? notAvailable }}
    Días de mastografía a diagnóstico
    {{ p.daysMammographyToDiagnosis ?? notAvailable }}
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 4b413d7..d8aa33e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -16,7 +16,7 @@ describe('Ficha CaMa: resumen', () => { it('reads every field the follow-up row carries', () => { const row = complete(); expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({ - patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'], + patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], clinicalScenario: null, status: row['estatus'], priority: row['prioridad'], birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'], daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'], }); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts index bb7c405..d368548 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts @@ -21,6 +21,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo ...section('Resumen', [ [patient.idLabel, patient.patientId], ['Grupo de edad', patient.ageGroup], + ['Escenario clínico', patient.clinicalScenario], ['Estatus de seguimiento', patient.status], ['Prioridad', patient.priority], ['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis], diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index 311f9b6..192bef5 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -14,6 +14,8 @@ export interface CamaPatientSummary { idLabel: string; cutoff: string; ageGroup: string | null; + /** «Post-tratamiento» or «En observación» at the cut-off. */ + clinicalScenario: string | null; status: string | null; priority: string | null; birads: string | null; @@ -51,6 +53,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: idLabel: ETIQUETA_IDENTIDAD[identity.campo], cutoff, ageGroup: text(row['grupo_edad']), + clinicalScenario: text(row['escenario_clinico']), status: text(row['estatus']), priority: text(row['prioridad']), birads: text(row['birads']), diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index 028e4e9..239797c 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -147,7 +147,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR }), }; } -const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true }; +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true }; @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService { From e74e3d8fd455f223f26f7ea9fbdf1726a6ddce69 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 02:07:34 -0600 Subject: [PATCH 08/21] CaMa: a patient's risk in her record and a Supervivencia tab with the model's curves The risk table takes a domain (CaCu by default); the CaMa record shows the mortality at 6, 12 and 18 months from the model's index date. The Supervivencia tab draws the cohort's Kaplan-Meier with its band, the adjusted curve, the fractional Weibull and the model's survival with its bootstrap interval; its wording comes from the model's settings. --- .../cama-supervivencia-figura.ts | 60 +++++++ .../cama-supervivencia.html | 39 +++++ .../cama-supervivencia.scss | 11 ++ .../cama-supervivencia.service.ts | 84 ++++++++++ .../cama-supervivencia.spec.ts | 157 ++++++++++++++++++ .../cama-supervivencia/cama-supervivencia.ts | 51 ++++++ .../indicadores-historico-pestana.spec.ts | 4 +- .../indicadores/indicadores-page.html | 6 + .../features/indicadores/indicadores-page.ts | 7 +- .../indicadores/indicadores-sections.spec.ts | 4 +- .../cama/cama-patient-card.html | 6 + .../cama/cama-patient-card.spec.ts | 4 + .../cama/cama-patient-card.ts | 3 +- .../paciente-riesgo-cama.spec.ts | 98 +++++++++++ .../paciente-riesgo-tabla.html | 2 +- .../paciente-detalle/paciente-riesgo-tabla.ts | 8 +- .../paciente-riesgo.models.ts | 5 +- .../paciente-riesgo.provider.ts | 5 +- .../paciente-detalle/paciente-riesgo.state.ts | 11 +- .../indicadores/paciente-identidad.spec.ts | 6 +- 20 files changed, 553 insertions(+), 18 deletions(-) create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts create mode 100644 src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts new file mode 100644 index 0000000..e9f088d --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts @@ -0,0 +1,60 @@ +import { PlotlyFigure, Tema } from '../indicadores.models'; +import { CurvasSupervivencia, SerieDeSupervivencia } from './cama-supervivencia.service'; + +/** The clinicians' wording of the chart: what the model's run published (`[config.etiquetas]`), and these defaults for + * a label it leaves out. The labels are settings, not code, so they can be defined with the clinicians. */ +export const ETIQUETAS_PREDETERMINADAS: Readonly> = { + titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor', + eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', + km_crudo: 'Kaplan-Meier (observada)', km_ajustada: 'Kaplan-Meier ajustada por covariables', + weibull: 'Weibull ajustada', weibull_fraccional: 'Weibull fraccional ajustada', + puntos: 'Modelo (LR + red bayesiana) con IC 95 %', LR: 'Regresión logística', HBN: 'Red bayesiana', COMB: 'Modelo combinado', +}; + +export const COLORES = { km_crudo: '#9aa5b1', km_ajustada: '#3d4852', weibull: '#e0a060', fraccional: '#d1495b', modelo: '#6a3d9a', lr: '#1f77b4', hbn: '#2a9d8f' } as const; + +export const etiquetaDe = (curvas: CurvasSupervivencia, clave: string) => curvas.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave; + +function puntos(curvas: CurvasSupervivencia, serie: SerieDeSupervivencia, nombre: string, color: string, visible: true | 'legendonly', tamano: number): Record { + const h = curvas.horizons_months; + return { + type: 'scatter', mode: 'markers', name: nombre, x: h, y: serie.S, visible, legendgroup: nombre, + marker: { symbol: 'diamond', size: tamano, color, line: { color: 'white', width: 1 } }, + error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 1.8, width: 5, + array: serie.high.map((hi, i) => hi - serie.S[i]), arrayminus: serie.S.map((s, i) => s - serie.low[i]) }, + customdata: serie.low.map((lo, i) => [lo, serie.high[i]]), + hovertemplate: `${nombre}
    %{x} meses: %{y:.1%}
    IC 95 %: %{customdata[0]:.1%} a %{customdata[1]:.1%}`, + }; +} + +/** The figure of the model's results: the cohort's Kaplan-Meier with its band, the covariate-adjusted curve, the fitted + * Weibull curves, and the model's survival at each horizon as diamonds with their bootstrap interval. */ +export function figuraSupervivencia(curvas: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure { + const km = curvas.km, ajustada = curvas.km_adjusted, t = (clave: string) => etiquetaDe(curvas, clave); + const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)'; + const todos = [...km.low, ...ajustada.S, ...curvas.weibull_fractional.S, ...curvas.points.COMB.low]; + const minimo = Math.max(0, Math.min(...todos) - 0.03); + const data: Record[] = [ + { 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: 'rgba(154,165,177,.35)', line: { width: 0, shape: 'hv' }, + name: `${t('km_crudo')}, IC 95 %`, hoverinfo: 'skip', legendgroup: 'km' }, + { type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km_crudo, width: 1.4, dash: 'dot', shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km', + hovertemplate: '%{x} meses: %{y:.1%}' + t('km_crudo') + '' }, + { type: 'scatter', mode: 'lines', x: ajustada.months, y: ajustada.S, line: { color: COLORES.km_ajustada, width: 2, shape: 'hv' }, name: t('km_ajustada'), + hovertemplate: '%{x} meses: %{y:.1%}' + t('km_ajustada') + '' }, + { type: 'scatter', mode: 'lines', x: curvas.weibull.t, y: curvas.weibull.S, line: { color: COLORES.weibull, width: 2, dash: 'dash' }, name: t('weibull'), visible: 'legendonly' }, + { type: 'scatter', mode: 'lines', x: curvas.weibull_fractional.t, y: curvas.weibull_fractional.S, line: { color: COLORES.fraccional, width: 2.6 }, name: t('weibull_fraccional'), + hovertemplate: '%{x:.1f} meses: %{y:.1%}' + t('weibull_fraccional') + '' }, + puntos(curvas, curvas.points.LR, t('LR'), COLORES.lr, 'legendonly', 9), + puntos(curvas, curvas.points.HBN, t('HBN'), COLORES.hbn, 'legendonly', 9), + puntos(curvas, curvas.points.COMB, t('puntos'), COLORES.modelo, true, 12), + ]; + const layout: Record = { + title: { text: `${t('titulo')} (n = ${curvas.n.toLocaleString('es-MX')})`, x: 0, xanchor: 'left', font: { size: 16, color: texto } }, + paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, + xaxis: { title: { text: t('eje_x') }, range: [0, curvas.months_max + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, + yaxis: { title: { text: t('eje_y') }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, + legend: { orientation: 'h', y: -0.22, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 110 }, hovermode: 'closest', + }; + return { data, layout, config: { responsive: true, displaylogo: false } }; +} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html new file mode 100644 index 0000000..c15de72 --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html @@ -0,0 +1,39 @@ +

    Supervivencia

    +@let l = lectura(); +@switch (l.tipo) { + @case ('cargando') {

    Cargando resultados del modelo…

    } + @case ('no-disponible') { +

    Todavía no hay un modelo de supervivencia en producción. Cuando se entrene y se promueva en Gobernanza, sus resultados aparecerán aquí.

    + } + @case ('error') {

    No se pudieron cargar los resultados del modelo. Intenta nuevamente más tarde.

    } + @case ('listo') { + @let c = l.datos.curvas; + @if (l.datos.simulado) {

    Información simulada · Entorno DEV · Sin evaluación clínica

    } + + @if (figura(); as figure) { + + } +
    + + + + + @for (fila of filas(l.datos); track fila.meses) { + + + + + + } + +
    {{ etiquetaDe(c, 'puntos') }}
    Meses desde el reporteSupervivencia (%)IC 95 % (%)
    {{ fila.meses }}{{ fila.S | number:'1.1-1' }} %{{ fila.low | number:'1.1-1' }} % – {{ fila.high | number:'1.1-1' }} %
    +
    + @if (c.etiquetas['nota']; as nota) {

    {{ nota }}

    } + } +} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss new file mode 100644 index 0000000..18fafb7 --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss @@ -0,0 +1,11 @@ +:host { display: block; padding: 1rem 0; } +h2 { font-size: 1.25rem; margin: 0 0 .75rem; } +.simulated-label { font-weight: 600; margin: 0 0 .75rem; } +.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: .5rem 1.25rem; margin: 0 0 1rem; + div { display: flex; flex-direction: column; } dt { font-size: .8rem; opacity: .8; } dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; } } +.points-scroll { overflow-x: auto; margin-top: 1rem; &:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } } +table { border-collapse: collapse; min-width: 22rem; } +caption { text-align: left; font-weight: 600; padding-bottom: .4rem; } +th, td { padding: .4rem .75rem; border-bottom: 1px solid rgba(128, 128, 128, .35); text-align: left; } +.percentage, .interval { font-variant-numeric: tabular-nums; } +.note { margin-top: 1rem; font-size: .85rem; opacity: .85; } diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts new file mode 100644 index 0000000..6613465 --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts @@ -0,0 +1,84 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, map, Observable, of, throwError } from 'rxjs'; + +// The survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the +// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the +// 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 { + 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[] }; + km_adjusted: { months: number[]; S: number[] }; + weibull: { t: number[]; S: number[] }; + weibull_fractional: { t: number[]; S: number[] }; + points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia }; + etiquetas: Record; +} +export interface RespuestaCurvas { + simulado: boolean; + modelo: { nombre: string; version: string; mlflow_run_id: string }; + curvas: CurvasSupervivencia; +} + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length); +const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1); +const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; + +function invalid(): never { + throw new Error('Respuesta de curvas de supervivencia inválida'); +} + +function serie(v: unknown, horizons: number): SerieDeSupervivencia { + if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid(); + const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[]; + if (low.some((l, i) => l > high[i])) invalid(); + return { S: s, low, high }; +} + +/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */ +export function respuestaCurvas(v: unknown): RespuestaCurvas { + if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid(); + const m = v['modelo'] as Record, c = v['curvas'] as Record; + if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid(); + const horizons = c['horizons_months']; + if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events']) + || !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid(); + const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points']; + if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length) + || !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid(); + if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid(); + for (const curve of [weibull, fractional]) { + if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid(); + } + if (!record(points)) invalid(); + const p = points as Record, h = (horizons as number[]).length; + const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record : {}; + return { + simulado: v['simulado'] === true, + modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string }, + curvas: { + 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'], + weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'], + points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas, + }, + }; +} + +@Injectable({ providedIn: 'root' }) +export class CamaSupervivenciaService { + private readonly http = inject(HttpClient); + + /** The production version's curves, or `null` when there is none (a 404). */ + curvas(): Observable { + return this.http.get('/cama/modelo/curvas').pipe( + map(respuestaCurvas), + catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), + ); + } +} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts new file mode 100644 index 0000000..539f2c8 --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts @@ -0,0 +1,157 @@ +// Covers CaMa's survival tab: the boundary validation of `GET /cama/modelo/curvas` (a malformed record never draws a partial +// curve), the figure built from the record (the model's diamonds at 6, 12 and 18 months with their interval, the curves, +// the labels from the model's settings), and the component's states and table. Fixtures: `curvasEjemplo`, a record like a +// training run publishes; a stub Plotly runtime, so the chart is not drawn for real. +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; +import { CamaSupervivencia } from './cama-supervivencia'; +import { respuestaCurvas } from './cama-supervivencia.service'; +import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivencia } from './cama-supervivencia-figura'; + +const meses = Array.from({ length: 25 }, (_, i) => i); +const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24)); + +function curvasEjemplo(): any { + const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) }); + return { + simulado: true, + modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' }, + curvas: { + version: 1, n: 245, 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: { eje_x: 'Meses desde la biopsia', nota: 'Datos simulados. Sin validación clínica.' }, + }, + }; +} + +describe('Supervivencia CaMa: respuesta', () => { + // Fails if a record with an impossible value is accepted and drawn. + it('accepts a record as published and keeps it', () => { + const r = respuestaCurvas(curvasEjemplo()); + expect(r.modelo.version).toBe('3'); + expect(r.curvas.points.COMB.S).toEqual([0.925, 0.845, 0.775]); + }); + + it.each([ + ['a probability above 1', (d: any) => { d.curvas.km.S[3] = 1.2; }], + ['a curve shorter than its months', (d: any) => { d.curvas.km_adjusted.S.pop(); }], + ['an inverted interval', (d: any) => { d.curvas.points.COMB.low[0] = 0.99; }], + ['a series with another number of horizons', (d: any) => { d.curvas.points.LR.S.pop(); }], + ['no model version', (d: any) => { delete d.modelo.version; }], + ['a missing curve', (d: any) => { delete d.curvas.weibull_fractional; }], + ])('rejects %s', (_, estropear) => { + const d = curvasEjemplo(); + estropear(d); + expect(() => respuestaCurvas(d)).toThrow('Respuesta de curvas de supervivencia inválida'); + }); +}); + +describe('Supervivencia CaMa: figura', () => { + const figura = () => figuraSupervivencia(respuestaCurvas(curvasEjemplo()).curvas); + const traza = (nombre: string) => figura().data.find(t => t['name'] === nombre) as any; + + // Fails if the diamonds move off 6, 12 and 18 months, or their interval bars stop being the record's interval. + it('draws the combined model as diamonds at the horizons with its interval', () => { + const rombos = traza(ETIQUETAS_PREDETERMINADAS['puntos']); + expect(rombos.x).toEqual([6, 12, 18]); + expect(rombos.y).toEqual([0.925, 0.845, 0.775]); + 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]); + expect(rombos.error_y.arrayminus.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]); + }); + + // Fails if the observed and adjusted curves, the band and the fractional Weibull are not all there, or LR and HBN start visible. + it('draws the Kaplan-Meier with its band, the adjusted curve and the fractional Weibull; LR and HBN start hidden', () => { + const f = figura(), nombres = f.data.map(t => t['name']); + expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_crudo']); + expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_ajustada']); + expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['weibull_fraccional']); + expect(f.data.some(t => t['fill'] === 'tonexty')).toBe(true); + expect(traza(ETIQUETAS_PREDETERMINADAS['LR']).visible).toBe('legendonly'); + expect(traza(ETIQUETAS_PREDETERMINADAS['HBN']).visible).toBe('legendonly'); + }); + + // Fails if the axis titles stop coming from the model's settings, or a label it leaves out stops falling back. + it('takes the labels from the record and falls back for the ones it leaves out', () => { + const l = figura().layout as any; + expect(l.xaxis.title.text).toBe('Meses desde la biopsia'); + expect(l.yaxis.title.text).toBe(ETIQUETAS_PREDETERMINADAS['eje_y']); + expect(l.title.text).toContain('(n = 245)'); + }); + + // Fails if the y axis hides a curve or an interval below its range, or leaves survival above 100 %. + it('fits the y range to the lowest curve or interval and stops at 100 %', () => { + const [bajo, alto] = (figura().layout as any).yaxis.range; + expect(bajo).toBeLessThan(0.6); + expect(bajo).toBeGreaterThanOrEqual(0); + expect(alto).toBeCloseTo(1.005); + }); +}); + +describe('Supervivencia CaMa: componente', () => { + let http: HttpTestingController; + 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()) }; + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); + const montar = (active: boolean) => { + const f = TestBed.createComponent(CamaSupervivencia); + f.componentRef.setInput('active', active); + f.detectChanges(); + return f; + }; + const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + + // Fails if the tab asks for the results before it is shown, or asks again when it is shown again. + it('asks once, the first time the tab is shown', () => { + const f = montar(false); + http.expectNone('/cama/modelo/curvas'); + f.componentRef.setInput('active', true); + f.detectChanges(); + http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); + f.componentRef.setInput('active', false); + f.detectChanges(); + f.componentRef.setInput('active', true); + f.detectChanges(); + http.expectNone('/cama/modelo/curvas'); + }); + + // Fails if the model, its version, the counts, the simulated label, the table of the diamonds or the note are not shown. + it('shows the model, the counts, the simulated label, the table of the horizons and the note', () => { + const f = montar(true); + http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); + f.detectChanges(); + + const t = texto(f); + expect(t).toContain('cama-survival, versión 3'); + expect(t).toContain('245'); + expect(t).toContain('Información simulada'); + expect(t).toContain('92.5 %'); + expect(t).toContain('88.5 % – 96.5 %'); + expect(t).toContain('Datos simulados. Sin validación clínica.'); + expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['6', '12', '18']); + }); + + // Fails if no model in production is shown as an error, or a failed or malformed answer as a chart. + it('says there is no model yet on a 404 and fails closed on an error or a malformed record', () => { + const sinModelo = montar(true); + http.expectOne('/cama/modelo/curvas').flush({ error: 'sin curvas' }, { status: 404, statusText: 'Not Found' }); + sinModelo.detectChanges(); + expect(texto(sinModelo)).toContain('Todavía no hay un modelo de supervivencia en producción'); + + const roto = montar(true); + http.expectOne('/cama/modelo/curvas').flush({ curvas: {} }); + roto.detectChanges(); + expect(texto(roto)).toContain('No se pudieron cargar los resultados del modelo'); + expect((roto.nativeElement as HTMLElement).querySelector('app-plotly-chart')).toBeNull(); + }); +}); diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts new file mode 100644 index 0000000..6b887bb --- /dev/null +++ b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts @@ -0,0 +1,51 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { DecimalPipe } from '@angular/common'; +import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; +import { Tema } from '../indicadores.models'; +import { CamaSupervivenciaService, RespuestaCurvas } from './cama-supervivencia.service'; +import { etiquetaDe, figuraSupervivencia } from './cama-supervivencia-figura'; + +type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaCurvas }; + +/** + * CaMa's survival results: the cohort's survival curves and the model's survival at 6, 12 and 18 months with its + * interval, as the production version of the model published them. Population results, never a patient's: a patient's own + * risk is in her record. Loads once, the first time the tab is shown. + */ +@Component({ + selector: 'app-cama-supervivencia', + imports: [PlotlyChart, DecimalPipe], + templateUrl: './cama-supervivencia.html', + styleUrl: './cama-supervivencia.scss', +}) +export class CamaSupervivencia { + readonly active = input(false); + readonly tema = input('claro'); + private readonly service = inject(CamaSupervivenciaService); + private readonly destroy = inject(DestroyRef); + readonly lectura = signal({ tipo: 'cargando' }); + private pedido = false; + readonly figura = computed(() => { + const l = this.lectura(); + return l.tipo === 'listo' ? figuraSupervivencia(l.datos.curvas, this.tema()) : null; + }); + readonly etiquetaDe = etiquetaDe; + + constructor() { + effect(() => { + if (!this.active() || this.pedido) return; + this.pedido = true; + this.service.curvas().pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }), + error: () => this.lectura.set({ tipo: 'error' }), + }); + }); + } + + /** The combined model's survival at each horizon, for the table that says what the figure's diamonds say. */ + filas(datos: RespuestaCurvas) { + const c = datos.curvas, p = c.points.COMB; + return c.horizons_months.map((meses, i) => ({ meses, S: p.S[i] * 100, low: p.low[i] * 100, high: p.high[i] * 100 })); + } +} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index 0a7f3c5..e06b388 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => { http.match(() => true); } - it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => { + it('CaMa oculta Análisis y conserva Histórico, Supervivencia 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', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); fixture.componentInstance.changeSection('analisis'); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 55283b3..bb1625a 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -138,6 +138,12 @@
    } + @if (conSupervivencia) { +
    + +
    + } +
    ('resumen'); readonly fichaPacienteAbierta = signal(false); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index c441f5e..e0c2ad1 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[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'] + // TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos and adds Supervivencia; CaCu keeps its three. + const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones'] : domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', '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))); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 1fef561..95b15c9 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -33,6 +33,12 @@ + +

    Riesgo de muerte

    + + + +

    Pronóstico y recomendaciones

    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 4b413d7..ef28957 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -2,6 +2,8 @@ // carries, "No disponible" for the rest, placeholders for recurrence, survival and prognostic factors), and its focus // and back behaviour. Fixture: fixtures/cama_seguimiento.json. import { TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +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'; @@ -39,6 +41,8 @@ describe('Ficha CaMa: resumen', () => { describe('Ficha CaMa: componente', () => { let fixture: ReturnType>; 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) } }] })); function montar(summary: CamaPatientSummary) { fixture = TestBed.createComponent(CamaPatientCard); fixture.componentRef.setInput('summary', summary); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index a59872c..26c4e59 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -3,6 +3,7 @@ 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 { CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, } from './cama-patient.models'; @@ -13,7 +14,7 @@ import { */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule], + imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts new file mode 100644 index 0000000..be28fba --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -0,0 +1,98 @@ +// 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= +// 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 { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { INTERVALO, prediccion } from './paciente-riesgo.testing'; + +const CS = 'https://isssteleon.org/fhir/CodeSystem'; + +/** TEST ONLY. Patient 7's current CaMa `RiskAssessment`: mortality at 6, 12 and 18 months from the model's index date. */ +function riesgoCamaEjemplo(): any { + const muerte = (p: number, fin: string) => { + const item = prediccion(p, '2025-06-19', fin); + item.outcome = { coding: [{ system: `${CS}/desenlace`, code: 'muerte', display: 'Muerte por cualquier causa' }] }; + return item; + }; + return { + resourceType: 'Bundle', type: 'searchset', total: 1, + entry: [{ + fullUrl: 'http://localhost/cama/fhir/RiskAssessment/3-7', + resource: { + resourceType: 'RiskAssessment', id: '3-7', status: 'final', + meta: { tag: [{ system: `${CS}/etiqueta`, code: 'simulado', display: 'Datos simulados' }] }, + subject: { reference: 'Patient/7' }, occurrenceDateTime: '2026-01-02T10:00:00Z', + method: { coding: [{ system: `${CS}/modelo`, code: 'cama-survival', version: '1' }] }, + prediction: [muerte(0.07, '2025-12-19'), muerte(0.178, '2026-06-19'), muerte(0.251, '2026-12-19')], + }, + search: { mode: 'match' }, + }], + }; +} + +const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({ + patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null, + birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19', + daysMammographyToDiagnosis: null, +}); + +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 } }] }); + }); + + // Fails if the table stops asking the domain it was given, or if CaCu's call changes shape (`obtener(pacId)` only). + it('asks its domain for the patient, and CaCu with the id alone', () => { + const cama = TestBed.createComponent(PacienteRiesgoTabla); + cama.componentRef.setInput('pacId', '7'); + cama.componentRef.setInput('dominio', 'cama'); + cama.detectChanges(); + const cacu = TestBed.createComponent(PacienteRiesgoTabla); + cacu.componentRef.setInput('pacId', '7'); + cacu.detectChanges(); + + expect(obtener).toHaveBeenNthCalledWith(1, '7', 'cama'); + expect(obtener).toHaveBeenNthCalledWith(2, '7'); + expect(cama.nativeElement.textContent).toContain('Riesgo individual CaMa'); + expect(cacu.nativeElement.textContent).toContain('Riesgo individual CaCu'); + }); + + // Fails if the mortality, its outcome, the model or the index date of the Bundle are not what the card shows. + it('shows the model, the index date, the outcome and the mortality at each horizon', () => { + const f = TestBed.createComponent(PacienteRiesgoTabla); + f.componentRef.setInput('pacId', '7'); + f.componentRef.setInput('dominio', 'cama'); + f.detectChanges(); + + const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + expect(text).toContain('cama-survival'); + expect(text).toContain('2025-06-19'); + expect(text).toContain('Muerte por cualquier causa'); + expect(text).toContain('7 %'); + expect(text).toContain('17.8 %'); + expect(text).toContain('25.1 %'); + 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(); + + 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(INTERVALO).toContain('intervalo-confianza'); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 0cf617b..69612d0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -1,4 +1,4 @@ -

    Riesgo individual CaCu

    +

    Riesgo individual {{ rotulo() }}

    @let lectura = estado(); @switch (lectura.tipo) { @case ('cargando') {

    Cargando riesgo individual…

    } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index bf02e1a..7d9f119 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,5 +1,6 @@ -import { Component, effect, inject, input } from '@angular/core'; +import { Component, computed, effect, inject, input } from '@angular/core'; import { DecimalPipe } from '@angular/common'; +import { DominioRiesgo } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -13,11 +14,14 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; export class PacienteRiesgoTabla { /** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */ readonly pacId = input.required(); + /** The domain whose model scored her: CaCu unless said otherwise. */ + readonly dominio = input('cacu'); + readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu'); private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; constructor() { - effect(() => this.state.pacId.set(this.pacId())); + effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index dd56a2c..4acb7cc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -2,6 +2,9 @@ import { Observable } from 'rxjs'; export type EstadoEvaluacionCacu = 'preliminary' | 'final'; +/** The domain whose patient's risk is read: its FHIR endpoint is `//fhir`. CaCu unless said otherwise. */ +export type DominioRiesgo = 'cacu' | 'cama'; + export interface HorizonteRiesgoCacu { /** Years from the risk's index date: the length of the prediction's `whenPeriod`; 0 is the immediate risk. */ horizonte_anios: number; @@ -35,7 +38,7 @@ export interface RiesgoPacienteCacu { /** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */ export interface PacienteRiesgoProvider { - obtener(pacId: string): Observable; + obtener(pacId: string, dominio?: DominioRiesgo): Observable; } export type PacienteRiesgoEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 5b4cf95..3027caa 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -4,12 +4,13 @@ import { catchError, of, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; // The patient's risk is a FHIR `RiskAssessment` searched by `subject=Patient/`, the identifier a follow-up row -// carries as `pac_id`; an empty Bundle (or a 404) is a patient without risk data. +// carries as `pac_id`, in the domain's endpoint (`/cacu/fhir`, or `/cama/fhir`); an empty Bundle (or a 404) is a patient +// without risk data. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { providedIn: 'root', factory: () => { const http = inject(HttpClient); return { - obtener: (pacId: string) => http.get('/cacu/fhir/RiskAssessment', { + obtener: (pacId: string, dominio = 'cacu') => http.get(`/${dominio}/fhir/RiskAssessment`, { params: new HttpParams().set('subject', `Patient/${pacId}`), }).pipe( catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 3a5ed61..5ac300c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -1,7 +1,7 @@ -import { Injectable, inject, signal } from '@angular/core'; +import { Injectable, computed, inject, signal } from '@angular/core'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, startWith, switchMap } from 'rxjs'; -import { PacienteRiesgoEstado } from './paciente-riesgo.models'; +import { DominioRiesgo, PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; @@ -12,8 +12,11 @@ export class PacienteRiesgoState { private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); // `undefined` until the input is set; `null` is a patient without `pac_id`. readonly pacId = signal(undefined); - readonly estado = toSignal(toObservable(this.pacId).pipe( - switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe( + readonly dominio = signal('cacu'); + // The patient and her domain are one query, so changing both never asks for the patient in the wrong domain. + private readonly consulta = computed(() => ({ id: this.pacId(), dominio: this.dominio() })); + readonly estado = toSignal(toObservable(this.consulta).pipe( + switchMap(({ id, dominio }) => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => dominio === 'cacu' ? this.provider.obtener(id) : this.provider.obtener(id, dominio)).pipe( map((respuesta): PacienteRiesgoEstado => { const datos = respuesta === null ? null : riesgoPacienteResponse(respuesta, id); return datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos }; diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts index b1a242b..05eda5d 100644 --- a/src/app/features/indicadores/paciente-identidad.spec.ts +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -72,7 +72,11 @@ describe('Tabla de seguimiento con pac_id', () => { fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); }); - afterEach(() => { fixture.destroy(); http.verify(); }); + // 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 }); }); + fixture.destroy(); http.verify(); + }); const root = () => fixture.nativeElement as HTMLElement; const cargar = (respuesta: Record) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); }; const enlaces = () => [...root().querySelectorAll('tbody button.patient-link')]; From cc802cbb57c5c1957072d84ea020d11ca3dcf940 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 03:00:10 -0600 Subject: [PATCH 09/21] The CaMa risk spec builds a summary with the clinical scenario --- .../indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index be28fba..553ce66 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -38,7 +38,7 @@ function riesgoCamaEjemplo(): any { const resumen = (idField: 'pac_id' | 'id_seudonimo'): CamaPatientSummary => ({ patientId: '7', idField, idLabel: 'pac_id', cutoff: '2026-01-01', ageGroup: '50-59', status: null, priority: null, birads: 'B5', mammographyDate: '2025-06-01', histopathology: 'CARCINOMA_INVASOR', biopsyDate: '2025-06-19', - daysMammographyToDiagnosis: null, + daysMammographyToDiagnosis: null, clinicalScenario: null, }); describe('Riesgo individual de la paciente CaMa', () => { From c5cbaaab135125e1b055e35d3ad704449de38d86 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 03:28:13 -0600 Subject: [PATCH 10/21] CaMa development view on the survival tab; governance trains any scenario in the background --- .../cama-desarrollo/cama-desarrollo.html | 52 ++++++++++ .../cama-desarrollo/cama-desarrollo.scss | 14 +++ .../cama-desarrollo.service.ts | 58 +++++++++++ .../cama-desarrollo/cama-desarrollo.spec.ts | 97 +++++++++++++++++++ .../cama-desarrollo/cama-desarrollo.ts | 73 ++++++++++++++ .../indicadores/indicadores-page.html | 1 + .../features/indicadores/indicadores-page.ts | 3 +- src/app/governance/api/governance.api.ts | 16 +++ src/app/governance/api/governance.types.ts | 25 +++++ .../model-versions-panel.html | 39 +++++++- .../model-versions-panel.scss | 26 +++++ .../model-versions-panel.spec.ts | 83 ++++++++++++++++ .../model-versions-panel.ts | 77 ++++++++++++--- 13 files changed, 544 insertions(+), 20 deletions(-) create mode 100644 src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html create mode 100644 src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss create mode 100644 src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts create mode 100644 src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts create mode 100644 src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts create mode 100644 src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html new file mode 100644 index 0000000..e488cbb --- /dev/null +++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.html @@ -0,0 +1,52 @@ +

    Desarrollo del modelo

    +@let l = lectura(); +@switch (l.tipo) { + @case ('cargando') {

    Cargando el desarrollo del modelo…

    } + @case ('no-disponible') { +

    La versión en producción no trae el desarrollo del modelo. Entrena una nueva versión en Gobernanza para generarlo.

    + } + @case ('error') {

    No se pudo cargar el desarrollo del modelo. Intenta nuevamente más tarde.

    } + @case ('listo') { +

    + Depuración de variables, balanceo, regresión logística y red bayesiana, bootstrap, curvas por subgrupo y factores de + riesgo, calculados sobre las {{ l.datos.desarrollo.n }} pacientes de la cohorte (versión {{ l.datos.modelo.version }}). +

    + @if (l.datos.desarrollo.variables_no_disponibles.length) { +

    + El hospital todavía no reporta: {{ l.datos.desarrollo.variables_no_disponibles.join(', ') }}. Entran como «Desconocido» + y no explican nada hasta que existan. +

    + } +
      + @for (e of l.datos.desarrollo.etapas; track e.etapa) { +
    • Etapa {{ e.etapa }}: {{ e.estado === 'error' ? 'con error' : 'completa' }}
    • + } +
    + @for (error of errores(l.datos); track error[0]) { + + } + @for (t of tablas(l.datos); track t.id) { +
    + {{ t.titulo }} ({{ t.filas.length }}) +
    + + @for (c of t.columnas; track c) { } + + @for (fila of t.filas; track $index) { + @for (c of t.columnas; track c) { } + } + +
    {{ c }}
    {{ celda(fila[c]) }}
    +
    +
    + } + @if (figuras(l.datos).length) { +

    Figuras

    +
    + @for (f of figuras(l.datos); track f.id) { +
    {{ f.id.replaceAll('_', ' ') }}
    + } +
    + } + } +} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss new file mode 100644 index 0000000..f1b291e --- /dev/null +++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss @@ -0,0 +1,14 @@ +:host { display: block; margin-top: 2rem; } +.lead, .note { max-width: 70ch; } +.note { color: var(--mat-sys-on-surface-variant, #444); } +.stages { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; padding: 0; list-style: none; } +.stages .failed { font-weight: 600; } +details { margin: 0.5rem 0; } +summary { cursor: pointer; font-weight: 600; } +.scroll { overflow-x: auto; max-height: 26rem; } +table { border-collapse: collapse; font-size: 0.85rem; } +th, td { padding: 0.25rem 0.6rem; text-align: left; border-bottom: 1px solid var(--mat-sys-outline-variant, #ccc); white-space: nowrap; } +.figures { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; } +figure { margin: 0; } +img { max-width: 100%; height: auto; background: #fff; } +figcaption { font-size: 0.8rem; text-transform: capitalize; } diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts new file mode 100644 index 0000000..8b3fa2e --- /dev/null +++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts @@ -0,0 +1,58 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, map, Observable, of, throwError } from 'rxjs'; + +// The development results of CaMa's model in production, `GET /cama/modelo/desarrollo`: what the SEER stages found over +// the cohort (variables kept, odds ratios, Bayesian network arcs, risk factors, subgroup curves) as tables, and their +// figures. They describe the cohort, never a patient. A 404 is "no version with a development record yet". +export type FilaDeTabla = Record; +export interface RegistroDesarrollo { + n: number; + etapas: { etapa: string; estado: string; segundos: number }[]; + errores: Record; + variables_no_disponibles: string[]; + tablas: Record; + figuras: Record; +} +export interface RespuestaDesarrollo { + simulado: boolean; + modelo: { nombre: string; version: string; mlflow_run_id: string }; + desarrollo: RegistroDesarrollo; +} + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; + +function invalid(): never { + throw new Error('Respuesta de desarrollo del modelo inválida'); +} + +/** Validate at the boundary: the record's shapes, so a partial answer never reaches the page. */ +export function respuestaDesarrollo(v: unknown): RespuestaDesarrollo { + if (!record(v) || !record(v['modelo']) || !record(v['desarrollo'])) invalid(); + const m = v['modelo'] as Record, d = v['desarrollo'] as Record; + if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid(); + if (typeof d['n'] !== 'number' || !Array.isArray(d['etapas']) || !record(d['errores']) || !Array.isArray(d['variables_no_disponibles']) + || !record(d['tablas']) || !record(d['figuras'])) invalid(); + for (const e of d['etapas'] as unknown[]) if (!record(e) || !text(e['etapa']) || !text(e['estado'])) invalid(); + for (const rows of Object.values(d['tablas'] as Record)) if (!Array.isArray(rows) || !rows.every(record)) invalid(); + for (const png of Object.values(d['figuras'] as Record)) if (!text(png) || !/^[A-Za-z0-9+/=]+$/.test(png)) invalid(); + return { + simulado: v['simulado'] === true, + modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string }, + desarrollo: d as unknown as RegistroDesarrollo, + }; +} + +@Injectable({ providedIn: 'root' }) +export class CamaDesarrolloService { + private readonly http = inject(HttpClient); + + /** The production version's development record, or `null` when there is none (a 404). */ + desarrollo(): Observable { + return this.http.get('/cama/modelo/desarrollo').pipe( + map(respuestaDesarrollo), + catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), + ); + } +} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts new file mode 100644 index 0000000..b338941 --- /dev/null +++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts @@ -0,0 +1,97 @@ +// Covers CaMa's development view: the boundary validation of `GET /cama/modelo/desarrollo` (a malformed record never +// reaches the page) and the component's states, its tables, its figures and the notice of what the hospital does not +// report yet. Fixtures: `registroEjemplo`, a record like a training run publishes. +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { TestBed } from '@angular/core/testing'; +import { CamaDesarrollo } from './cama-desarrollo'; +import { respuestaDesarrollo } from './cama-desarrollo.service'; + +function registroEjemplo(): any { + return { + simulado: true, + modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' }, + desarrollo: { + n: 500, etapas: [{ etapa: '01', estado: 'ok', segundos: 0 }, { etapa: '05', estado: 'error', segundos: 0 }], + errores: { '05': 'ValueError: sin subgrupos' }, variables_no_disponibles: ['Estadio_cat', 'Radioterapia_cat'], + tablas: { or_lr_balanceada: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }], hbn_arcos: [] }, + figuras: { sens_esp_edad: 'iVBORw0KGgo=' }, + }, + }; +} + +describe('Desarrollo CaMa: respuesta', () => { + it('accepts a record as published', () => { + expect(respuestaDesarrollo(registroEjemplo()).desarrollo.n).toBe(500); + }); + + // Fails if a record that would break the page (or inject markup through a figure) is accepted. + it.each([ + ['no model version', (d: any) => { delete d.modelo.version; }], + ['a table that is not rows', (d: any) => { d.desarrollo.tablas.hbn_arcos = 'x'; }], + ['a figure that is not base64', (d: any) => { d.desarrollo.figuras.sens_esp_edad = '" onerror="x'; }], + ['no stages', (d: any) => { delete d.desarrollo.etapas; }], + ])('rejects %s', (_, estropear) => { + const d = registroEjemplo(); + estropear(d); + expect(() => respuestaDesarrollo(d)).toThrow('Respuesta de desarrollo del modelo inválida'); + }); +}); + +describe('Desarrollo CaMa: componente', () => { + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => http.verify()); + const montar = (active: boolean) => { + const f = TestBed.createComponent(CamaDesarrollo); + f.componentRef.setInput('active', active); + f.detectChanges(); + return f; + }; + const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + + // Fails if the view asks before it is shown or asks again. + it('asks once, the first time it is shown', () => { + const f = montar(false); + http.expectNone('/cama/modelo/desarrollo'); + f.componentRef.setInput('active', true); + f.detectChanges(); + http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo()); + f.componentRef.setInput('active', false); + f.detectChanges(); + f.componentRef.setInput('active', true); + f.detectChanges(); + http.expectNone('/cama/modelo/desarrollo'); + }); + + // Fails if a table, a figure, a failed stage or the missing-variables notice stops being shown. + it('shows the tables that have rows, the figures, the failed stage and what the hospital does not report', () => { + const f = montar(true); + http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo()); + f.detectChanges(); + + const el = f.nativeElement as HTMLElement, t = texto(f); + expect(t).toContain('Razones de momios de la regresión logística (1)'); + expect(t).not.toContain('Arcos de la red bayesiana'); + expect(t).toContain('0.01235'); + expect(t).toContain('Estadio_cat, Radioterapia_cat'); + expect(t).toContain('Etapa 05 no pudo calcularse'); + expect(el.querySelector('img')!.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KGgo='); + }); + + // Fails if no version with a record is shown as an error, or a failure as a page. + it('says there is no record on a 404 and fails closed on an error', () => { + const sin = montar(true); + http.expectOne('/cama/modelo/desarrollo').flush({ error: 'x' }, { status: 404, statusText: 'Not Found' }); + sin.detectChanges(); + expect(texto(sin)).toContain('no trae el desarrollo del modelo'); + + const roto = montar(true); + http.expectOne('/cama/modelo/desarrollo').flush({ desarrollo: {} }); + roto.detectChanges(); + expect(texto(roto)).toContain('No se pudo cargar el desarrollo del modelo'); + }); +}); diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts new file mode 100644 index 0000000..54187e8 --- /dev/null +++ b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts @@ -0,0 +1,73 @@ +import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { CamaDesarrolloService, FilaDeTabla, RespuestaDesarrollo } from './cama-desarrollo.service'; + +type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaDesarrollo }; + +/** Names the tables are shown under, in the order they are shown. */ +export const TABLAS: [string, string][] = [ + ['factores_riesgo', 'Factores de riesgo (cuatro criterios)'], + ['factores_riesgo_variables', 'Resumen de factores de riesgo por variable'], + ['or_lr_balanceada', 'Razones de momios de la regresión logística'], + ['hbn_arcos', 'Arcos de la red bayesiana'], + ['metricas_diferenciacion', 'Métricas de diferenciación (LR y HBN)'], + ['auc_validacion_interna', 'AUC de validación interna'], + ['auc_bootstrap', 'AUC por réplica bootstrap'], + ['seleccion_bootstrap', 'Frecuencia de selección en el bootstrap'], + ['subgrupos_weibull', 'Subgrupos: Kaplan-Meier y Weibull fraccional'], + ['subgrupos_puntos', 'Subgrupos: supervivencia de LR y HBN'], + ['prueba_edad', 'Prueba de la edad continua contra la categorizada'], + ['cortes_edad', 'Comparación de cortes de edad'], + ['cortes_tumor', 'Comparación de cortes de tamaño tumoral'], + ['pesos_combinacion', 'Pesos de la combinación LR y HBN'], +]; + +/** + * How CaMa's model was developed, from the production version's record: the SEER stages' tables and figures over the + * cohort. Population results, never a patient's. Loads once, the first time the tab is shown. + */ +@Component({ + selector: 'app-cama-desarrollo', + templateUrl: './cama-desarrollo.html', + styleUrl: './cama-desarrollo.scss', +}) +export class CamaDesarrollo { + readonly active = input(false); + private readonly service = inject(CamaDesarrolloService); + private readonly destroy = inject(DestroyRef); + readonly lectura = signal({ tipo: 'cargando' }); + private pedido = false; + + constructor() { + effect(() => { + if (!this.active() || this.pedido) return; + this.pedido = true; + this.service.desarrollo().pipe(takeUntilDestroyed(this.destroy)).subscribe({ + next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }), + error: () => this.lectura.set({ tipo: 'error' }), + }); + }); + } + + /** The tables the record holds, in display order, with their rows' columns. */ + tablas(datos: RespuestaDesarrollo): { id: string; titulo: string; columnas: string[]; filas: FilaDeTabla[] }[] { + return TABLAS.filter(([id]) => datos.desarrollo.tablas[id]?.length) + .map(([id, titulo]) => { + const filas = datos.desarrollo.tablas[id]; + return { id, titulo, columnas: Object.keys(filas[0]), filas }; + }); + } + + figuras(datos: RespuestaDesarrollo): { id: string; src: string }[] { + return Object.entries(datos.desarrollo.figuras).map(([id, png]) => ({ id, src: `data:image/png;base64,${png}` })); + } + + errores(datos: RespuestaDesarrollo): [string, string][] { + return Object.entries(datos.desarrollo.errores); + } + + celda(valor: string | number | boolean | null): string { + if (valor === null) return ''; + return typeof valor === 'number' && !Number.isInteger(valor) ? valor.toPrecision(4) : String(valor); + } +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index bb1625a..a1fd68e 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -141,6 +141,7 @@ @if (conSupervivencia) {
    +
    } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index c13ac9f..3c0960c 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresHistorico } from './indicadores-historico'; import { CamaSupervivencia } from './cama-supervivencia/cama-supervivencia'; +import { CamaDesarrollo } from './cama-desarrollo/cama-desarrollo'; import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; @@ -54,7 +55,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, CamaSupervivencia, CamaDesarrollo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) diff --git a/src/app/governance/api/governance.api.ts b/src/app/governance/api/governance.api.ts index 2c700c3..b2c8637 100644 --- a/src/app/governance/api/governance.api.ts +++ b/src/app/governance/api/governance.api.ts @@ -10,6 +10,8 @@ import { ModelVersion, PromotionCheck, ReportField, + TrainableScenario, + TrainingJob, OcrJob, OcrRowStatus, OcrRowsResponse, @@ -39,6 +41,20 @@ export class GovernanceApi { return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {}); } + /** The scenarios that can be trained from here. */ + trainableScenarios(): Observable<{ scenarios: TrainableScenario[] }> { + return this.http.get<{ scenarios: TrainableScenario[] }>('/governance/scenarios'); + } + + /** Starts the training in the background: 202 with the job, 409 with the running one, 503 with no dbt manifest. */ + startTrainingJob(domain: string, scenario: string): Observable<{ job: TrainingJob }> { + return this.http.post<{ job: TrainingJob }>(`/governance/model-versions/${domain}/${scenario}/train-jobs`, {}); + } + + trainingJobs(): Observable<{ jobs: TrainingJob[] }> { + return this.http.get<{ jobs: TrainingJob[] }>('/governance/training-jobs'); + } + retireModelVersion(domain: string, scenario: string, version: string): Observable { return this.http.post(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {}); } diff --git a/src/app/governance/api/governance.types.ts b/src/app/governance/api/governance.types.ts index 4f7ba44..d8f4abf 100644 --- a/src/app/governance/api/governance.types.ts +++ b/src/app/governance/api/governance.types.ts @@ -136,3 +136,28 @@ export interface OcrRunSummary { failed: number; needs_review: number; } + +/** A scenario governance can train (`GET /governance/scenarios`); `produccion` is its version in production, if any. */ +export interface TrainableScenario { + domain: string; + scenario: string; + cohort: string | null; + outcome: string | null; + description: string; + kind: 'cohorte' | 'referencia'; + produccion: string | null; +} + +export type TrainingJobState = 'en_curso' | 'completado' | 'entrenado_sin_promover' | 'fallido' | 'interrumpido'; + +/** A training in the background (`/governance/training-jobs`), with the tail of its outputs. */ +export interface TrainingJob { + id: string; + domain: string; + scenario: string; + iniciado: string; + estado: TrainingJobState; + codigo: number | null; + salida: string; + error: string; +} diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.html b/src/app/governance/components/model-versions-panel/model-versions-panel.html index ade612e..77bb1e0 100644 --- a/src/app/governance/components/model-versions-panel/model-versions-panel.html +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.html @@ -6,22 +6,51 @@ } - + @if (offered().length) { + + Modelo a entrenar + + @for (s of offered(); track keyOf(s)) { + {{ keyOf(s) }}{{ s.produccion ? ' · en producción v' + s.produccion : '' }} + } + + + + } - @if (loading() || training()) { + @if (loading() || starting() || running()) { } @if (loadError(); as error) { } + @if (jobs().length) { +
    +

    Entrenamientos recientes

    +
      + @for (job of jobs(); track job.id) { +
    • + {{ job.domain }}/{{ job.scenario }} · {{ job.iniciado | date: 'short' }} · {{ estados[job.estado] }} + @if (job.salida || job.error) { +
      + Salida +
      {{ job.error || job.salida }}
      +
      + } +
    • + } +
    +
    + } + diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.scss b/src/app/governance/components/model-versions-panel/model-versions-panel.scss index 202edef..f9578b9 100644 --- a/src/app/governance/components/model-versions-panel/model-versions-panel.scss +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.scss @@ -70,3 +70,29 @@ gap: var(--space-2); margin: 0; } + +.models__scenario { + min-width: 18rem; +} + +.models__jobs ul { + list-style: none; + margin: 0; + padding: 0; +} + +.models__jobs li { + padding: var(--space-1) 0; +} + +.models__job--failed { + color: var(--mat-sys-error); +} + +.models__jobs pre { + font-size: 0.8rem; + margin: var(--space-1) 0; + max-height: 12rem; + overflow: auto; + white-space: pre-wrap; +} diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts b/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts new file mode 100644 index 0000000..95b07fc --- /dev/null +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.spec.ts @@ -0,0 +1,83 @@ +// Covers the model versions panel's training: the scenarios the account can train are offered, a training starts in the +// background and its state is shown while it runs, and the versions are read again when it ends. Fixtures: a stub of +// `GovernanceApi` with the scenarios, the versions and the jobs the test sets, and an account that reaches every domain. +import { TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { vi } from 'vitest'; +import { AuthService } from '../../../auth/auth.service'; +import { GovernanceApi } from '../../api/governance.api'; +import { TrainingJob } from '../../api/governance.types'; +import { ModelVersionsPanel } from './model-versions-panel'; + +const SCENARIOS = [ + { domain: 'cacu', scenario: 'cin2_logistic', cohort: 'cacu/x', outcome: 'cin2', description: '', kind: 'cohorte', produccion: null }, + { domain: 'cama', scenario: 'survival', cohort: 'cama/cohorte_total', outcome: 'muerte', description: '', kind: 'cohorte', produccion: '2' }, +]; +const job = (estado: TrainingJob['estado']): TrainingJob => ({ + id: 'j1', domain: 'cama', scenario: 'survival', iniciado: '2026-01-01T00:00:00+00:00', estado, codigo: null, salida: 'trained: version 3', error: '', +}); + +describe('ModelVersionsPanel training', () => { + let api: Record>; + let jobs: TrainingJob[]; + + beforeEach(() => { + jobs = []; + api = { + listModelVersions: vi.fn(() => of({ model_versions: [] })), + trainableScenarios: vi.fn(() => of({ scenarios: SCENARIOS })), + trainingJobs: vi.fn(() => of({ jobs })), + startTrainingJob: vi.fn(() => of({ job: job('en_curso') })), + }; + TestBed.configureTestingModule({ + providers: [ + { provide: GovernanceApi, useValue: api }, + { provide: AuthService, useValue: { puedeVer: () => true, dominios: () => ['cacu', 'cama', 'tea'], esAdministrador: () => true, usuario: () => ({ dominios: ['cacu', 'cama', 'tea'] }) } }, + ], + }); + }); + + // Fails if the panel goes back to offering one hardcoded scenario, or hides a scenario the account can train. + it('offers every trainable scenario of the domains shown', () => { + const f = TestBed.createComponent(ModelVersionsPanel); + f.detectChanges(); + const panel = f.componentInstance; + + panel.domain.set(null); + expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cacu/cin2_logistic', 'cama/survival']); + panel.domain.set('cama'); + expect(panel.offered().map((s) => panel.keyOf(s))).toEqual(['cama/survival']); + }); + + // Fails if the button trains another scenario than the selected one, or waits for the training to end. + it('starts the selected scenario in the background and reads the jobs again', () => { + const f = TestBed.createComponent(ModelVersionsPanel); + f.detectChanges(); + const panel = f.componentInstance; + panel.domain.set(null); + panel.selected.set('cama/survival'); + + panel.train(); + + expect(api['startTrainingJob']).toHaveBeenCalledExactlyOnceWith('cama', 'survival'); + expect(api['trainingJobs']).toHaveBeenCalledTimes(2); + }); + + // Fails if the running state is lost or the versions are not read again when the running training ends. + it('knows a training is running and reads the versions when it ends', () => { + const f = TestBed.createComponent(ModelVersionsPanel); + jobs = [job('en_curso')]; + f.detectChanges(); + const panel = f.componentInstance; + expect(panel.running()).toBe(true); + const reads = api['listModelVersions'].mock.calls.length; + + jobs = [job('completado')]; + panel.refreshJobs(); + + expect(panel.running()).toBe(false); + expect(api['listModelVersions'].mock.calls.length).toBe(reads + 1); + f.detectChanges(); + expect((f.nativeElement as HTMLElement).textContent).toContain('Entrenado y promovido'); + }); +}); diff --git a/src/app/governance/components/model-versions-panel/model-versions-panel.ts b/src/app/governance/components/model-versions-panel/model-versions-panel.ts index faa612b..a73a198 100644 --- a/src/app/governance/components/model-versions-panel/model-versions-panel.ts +++ b/src/app/governance/components/model-versions-panel/model-versions-panel.ts @@ -1,11 +1,14 @@ import { DatePipe } from '@angular/common'; import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core'; +import { timer } from 'rxjs'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatDialog } from '@angular/material/dialog'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; import { MatChipsModule } from '@angular/material/chips'; import { MatIconModule } from '@angular/material/icon'; +import { MatSelectModule } from '@angular/material/select'; +import { MatFormFieldModule } from '@angular/material/form-field'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar'; import { MatTableModule } from '@angular/material/table'; @@ -15,18 +18,27 @@ import { AuthService } from '../../../auth/auth.service'; import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios'; import { apiErrorMessage } from '../../../connect/api/api.types'; import { GovernanceApi } from '../../api/governance.api'; -import { ModelVersion } from '../../api/governance.types'; +import { ModelVersion, TrainableScenario, TrainingJob } from '../../api/governance.types'; import { ModelStatusChip } from '../model-status-chip/model-status-chip'; import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog'; -/** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */ -const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' }; +/** Milliseconds between asking for the state of a training that is still running. */ +export const SONDEO_MS = 3000; + +export const ESTADOS: Record = { + en_curso: 'En curso', + completado: 'Entrenado y promovido', + entrenado_sin_promover: 'Entrenado; faltan sus informes para promoverlo', + fallido: 'Falló', + interrumpido: 'Interrumpido', +}; /** * Every registered model version with its status (desarrollo, candidata, * en producción, retirada). The detail dialog holds the promotion - * checklist, lineage, artifacts and reports. The toolbar also offers - * training the one scenario with a trainer, over HTTP instead of a shell. + * checklist, lineage, artifacts and reports. The toolbar trains any scenario + * that has a trainer, in the background, and lists the latest trainings with + * their state while they run. */ @Component({ selector: 'app-model-versions-panel', @@ -37,6 +49,8 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' }; MatChipsModule, MatIconModule, MatProgressBarModule, + MatSelectModule, + MatFormFieldModule, MatSnackBarModule, MatTableModule, MatTooltipModule, @@ -61,12 +75,28 @@ export class ModelVersionsPanel implements OnInit { readonly versions = signal([]); readonly loading = signal(false); readonly loadError = signal(null); - readonly training = signal(false); + readonly scenarios = signal([]); + readonly selected = signal(null); + readonly jobs = signal([]); + readonly starting = signal(false); + readonly estados = ESTADOS; + /** The scenarios of the domain being shown, and only of the account's domains. */ + readonly offered = computed(() => + this.scenarios().filter((s) => this.auth.puedeVer(s.domain) && (this.domain() === null || s.domain === this.domain()))); + readonly running = computed(() => this.jobs().some((j) => j.estado === 'en_curso')); readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones']; ngOnInit(): void { this.reload(); + this.api.trainableScenarios().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: ({ scenarios }) => this.scenarios.set(scenarios), + error: () => this.scenarios.set([]), + }); + this.refreshJobs(); + timer(SONDEO_MS, SONDEO_MS).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { + if (this.running()) this.refreshJobs(); + }); } setDomain(domain: string | null): void { @@ -108,22 +138,41 @@ export class ModelVersionsPanel implements OnInit { return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value })); } + /** Asks for the latest trainings; when one that was running has ended, the versions are read again. */ + refreshJobs(): void { + const before = this.running(); + this.api.trainingJobs().pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: ({ jobs }) => { + this.jobs.set(jobs.slice(0, 8)); + if (before && !this.running()) this.reload(); + }, + error: () => undefined, + }); + } + train(): void { - this.training.set(true); + const key = this.selected() ?? (this.offered().length === 1 ? this.keyOf(this.offered()[0]) : null); + const scenario = this.offered().find((s) => this.keyOf(s) === key); + if (!scenario) return; + this.starting.set(true); this.api - .trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario) + .startTrainingJob(scenario.domain, scenario.scenario) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe({ next: () => { - this.training.set(false); - this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 }); - this.reload(); + this.starting.set(false); + this.snackBar.open(`Entrenamiento de ${key} iniciado.`, 'OK', { duration: 3000 }); + this.refreshJobs(); }, error: (error) => { - this.training.set(false); - this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 }); - if (error?.status === 409) this.reload(); + this.starting.set(false); + this.snackBar.open(apiErrorMessage(error, 'No se pudo iniciar el entrenamiento.'), 'OK', { duration: 5000 }); + if (error?.status === 409) this.refreshJobs(); }, }); } + + keyOf(s: { domain: string; scenario: string }): string { + return `${s.domain}/${s.scenario}`; + } } From d6c52c85361ffc789fb4e498aae334773c6de654 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 04:24:19 -0600 Subject: [PATCH 11/21] Governance: risk batches of CaMa beside CaCu's --- src/app/governance/api/risk-batches.api.ts | 2 +- .../risk-batches-panel.html | 5 ++++ .../risk-batches-panel/risk-batches-panel.ts | 26 +++++++++++++++---- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/app/governance/api/risk-batches.api.ts b/src/app/governance/api/risk-batches.api.ts index f4358db..d8fccbc 100644 --- a/src/app/governance/api/risk-batches.api.ts +++ b/src/app/governance/api/risk-batches.api.ts @@ -4,7 +4,7 @@ import { Observable } from 'rxjs'; import { PendingRiskBatch } from './risk-batches.types'; /** `//riesgos/lotes`: risk batches a model produced and nobody has reviewed yet (ADR-MD-008). Only `cacu` - * is served today. */ + * and `cama` are served. */ @Injectable({ providedIn: 'root' }) export class RiskBatchesApi { private readonly http = inject(HttpClient); diff --git a/src/app/governance/components/risk-batches-panel/risk-batches-panel.html b/src/app/governance/components/risk-batches-panel/risk-batches-panel.html index b010b58..f2e9c3b 100644 --- a/src/app/governance/components/risk-batches-panel/risk-batches-panel.html +++ b/src/app/governance/components/risk-batches-panel/risk-batches-panel.html @@ -1,5 +1,10 @@
    + + @for (option of domains; track option.id) { + {{ option.label }} + } +
    Versión
    - @for (c of t.columnas; track c) { } - - @for (fila of t.filas; track $index) { - @for (c of t.columnas; track c) { } - } - -
    {{ c }}
    {{ celda(fila[c]) }}
    - - - } - @if (figuras(l.datos).length) { -

    Figuras

    -
    - @for (f of figuras(l.datos); track f.id) { -
    {{ f.id.replaceAll('_', ' ') }}
    - } -
    - } - } -} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss deleted file mode 100644 index f1b291e..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.scss +++ /dev/null @@ -1,14 +0,0 @@ -:host { display: block; margin-top: 2rem; } -.lead, .note { max-width: 70ch; } -.note { color: var(--mat-sys-on-surface-variant, #444); } -.stages { display: flex; flex-wrap: wrap; gap: 0.5rem 1.5rem; padding: 0; list-style: none; } -.stages .failed { font-weight: 600; } -details { margin: 0.5rem 0; } -summary { cursor: pointer; font-weight: 600; } -.scroll { overflow-x: auto; max-height: 26rem; } -table { border-collapse: collapse; font-size: 0.85rem; } -th, td { padding: 0.25rem 0.6rem; text-align: left; border-bottom: 1px solid var(--mat-sys-outline-variant, #ccc); white-space: nowrap; } -.figures { display: grid; grid-template-columns: repeat(auto-fill, minmax(20rem, 1fr)); gap: 1rem; } -figure { margin: 0; } -img { max-width: 100%; height: auto; background: #fff; } -figcaption { font-size: 0.8rem; text-transform: capitalize; } diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts deleted file mode 100644 index 49f1f62..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.service.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { HttpClient, HttpErrorResponse } from '@angular/common/http'; -import { inject, Injectable } from '@angular/core'; -import { catchError, map, Observable, of, throwError } from 'rxjs'; - -// The development results of CaMa's model in production, `GET /cama/modelo/desarrollo`: what the SEER stages found over -// the cohort (variables kept, odds ratios, Bayesian network arcs, risk factors, subgroup curves) as tables, and their -// figures. They describe the cohort, never a patient. A 404 is "no version with a development record yet". -export type FilaDeTabla = Record; -export interface TablaDesarrollo { columnas: string[]; filas: FilaDeTabla[]; } -export interface RegistroDesarrollo { - n: number; - etapas: { etapa: string; estado: string; segundos: number }[]; - errores: Record; - variables_no_disponibles: string[]; - tablas: Record; - figuras: Record; -} -export interface RespuestaDesarrollo { - simulado: boolean; - modelo: { nombre: string; version: string; mlflow_run_id: string }; - desarrollo: RegistroDesarrollo; -} - -const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); -const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; - -function invalid(): never { - throw new Error('Respuesta de desarrollo del modelo inválida'); -} - -/** Validate at the boundary: the record's shapes, so a partial answer never reaches the page. */ -export function respuestaDesarrollo(v: unknown): RespuestaDesarrollo { - if (!record(v) || !record(v['modelo']) || !record(v['desarrollo'])) invalid(); - const m = v['modelo'] as Record, d = v['desarrollo'] as Record; - if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid(); - if (typeof d['n'] !== 'number' || !Array.isArray(d['etapas']) || !record(d['errores']) || !Array.isArray(d['variables_no_disponibles']) - || !record(d['tablas']) || !record(d['figuras'])) invalid(); - for (const e of d['etapas'] as unknown[]) if (!record(e) || !text(e['etapa']) || !text(e['estado'])) invalid(); - for (const t of Object.values(d['tablas'] as Record)) { - if (!record(t) || !Array.isArray(t['columnas']) || !t['columnas'].every(text) || !Array.isArray(t['filas']) || !t['filas'].every(record)) invalid(); - } - for (const png of Object.values(d['figuras'] as Record)) if (!text(png) || !/^[A-Za-z0-9+/=]+$/.test(png)) invalid(); - return { - simulado: v['simulado'] === true, - modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string }, - desarrollo: d as unknown as RegistroDesarrollo, - }; -} - -@Injectable({ providedIn: 'root' }) -export class CamaDesarrolloService { - private readonly http = inject(HttpClient); - - /** The production version's development record, or `null` when there is none (a 404). */ - desarrollo(): Observable { - return this.http.get('/cama/modelo/desarrollo').pipe( - map(respuestaDesarrollo), - catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), - ); - } -} diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts deleted file mode 100644 index 3e83872..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Covers CaMa's development view: the boundary validation of `GET /cama/modelo/desarrollo` (a malformed record never -// reaches the page) and the component's states, its tables, its figures and the notice of what the hospital does not -// report yet. Fixtures: `registroEjemplo`, a record like a training run publishes. -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { TestBed } from '@angular/core/testing'; -import { CamaDesarrollo } from './cama-desarrollo'; -import { respuestaDesarrollo } from './cama-desarrollo.service'; - -function registroEjemplo(): any { - return { - simulado: true, - modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' }, - desarrollo: { - n: 500, etapas: [{ etapa: '01', estado: 'ok', segundos: 0 }, { etapa: '05', estado: 'error', segundos: 0 }], - errores: { '05': 'ValueError: sin subgrupos' }, variables_no_disponibles: ['Estadio_cat', 'Radioterapia_cat'], - tablas: { or_lr_balanceada: { columnas: ['indice', 'OR', 'p'], filas: [{ indice: 'Grado_G3', OR: 2.5, p: 0.0123456 }] }, hbn_arcos: { columnas: [], filas: [] } }, - figuras: { sens_esp_edad: 'iVBORw0KGgo=' }, - }, - }; -} - -describe('Desarrollo CaMa: respuesta', () => { - it('accepts a record as published', () => { - expect(respuestaDesarrollo(registroEjemplo()).desarrollo.n).toBe(500); - }); - - // Fails if a record that would break the page (or inject markup through a figure) is accepted. - it.each([ - ['no model version', (d: any) => { delete d.modelo.version; }], - ['a table that is not rows', (d: any) => { d.desarrollo.tablas.hbn_arcos = { columnas: ['a'], filas: 'x' }; }], - ['a figure that is not base64', (d: any) => { d.desarrollo.figuras.sens_esp_edad = '" onerror="x'; }], - ['no stages', (d: any) => { delete d.desarrollo.etapas; }], - ])('rejects %s', (_, estropear) => { - const d = registroEjemplo(); - estropear(d); - expect(() => respuestaDesarrollo(d)).toThrow('Respuesta de desarrollo del modelo inválida'); - }); -}); - -describe('Desarrollo CaMa: componente', () => { - let http: HttpTestingController; - beforeEach(() => { - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); - http = TestBed.inject(HttpTestingController); - }); - afterEach(() => http.verify()); - const montar = (active: boolean) => { - const f = TestBed.createComponent(CamaDesarrollo); - f.componentRef.setInput('active', active); - f.detectChanges(); - return f; - }; - const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - - // Fails if the view asks before it is shown or asks again. - it('asks once, the first time it is shown', () => { - const f = montar(false); - http.expectNone('/cama/modelo/desarrollo'); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo()); - f.componentRef.setInput('active', false); - f.detectChanges(); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectNone('/cama/modelo/desarrollo'); - }); - - // Fails if a table, a figure, a failed stage or the missing-variables notice stops being shown. - it('shows the tables that have rows, the figures, the failed stage and what the hospital does not report', () => { - const f = montar(true); - http.expectOne('/cama/modelo/desarrollo').flush(registroEjemplo()); - f.detectChanges(); - - const el = f.nativeElement as HTMLElement, t = texto(f); - expect(t).toContain('Razones de momios de la regresión logística (1)'); - expect(t).not.toContain('Arcos de la red bayesiana'); - expect(t).toContain('0.01235'); - expect([...el.querySelectorAll('th')].map(th => th.textContent!.trim())).toEqual(['indice', 'OR', 'p']); - expect(t).toContain('Estadio_cat, Radioterapia_cat'); - expect(t).toContain('Etapa 05 no pudo calcularse'); - expect(el.querySelector('img')!.getAttribute('src')).toBe('data:image/png;base64,iVBORw0KGgo='); - }); - - // Fails if no version with a record is shown as an error, or a failure as a page. - it('says there is no record on a 404 and fails closed on an error', () => { - const sin = montar(true); - http.expectOne('/cama/modelo/desarrollo').flush({ error: 'x' }, { status: 404, statusText: 'Not Found' }); - sin.detectChanges(); - expect(texto(sin)).toContain('no trae el desarrollo del modelo'); - - const roto = montar(true); - http.expectOne('/cama/modelo/desarrollo').flush({ desarrollo: {} }); - roto.detectChanges(); - expect(texto(roto)).toContain('No se pudo cargar el desarrollo del modelo'); - }); -}); diff --git a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts b/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts deleted file mode 100644 index 9bc7e4b..0000000 --- a/src/app/features/indicadores/cama-desarrollo/cama-desarrollo.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { Component, DestroyRef, effect, inject, input, signal } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { CamaDesarrolloService, FilaDeTabla, RespuestaDesarrollo } from './cama-desarrollo.service'; - -type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaDesarrollo }; - -/** Names the tables are shown under, in the order they are shown. */ -export const TABLAS: [string, string][] = [ - ['factores_riesgo', 'Factores de riesgo (cuatro criterios)'], - ['factores_riesgo_variables', 'Resumen de factores de riesgo por variable'], - ['or_lr_balanceada', 'Razones de momios de la regresión logística'], - ['hbn_arcos', 'Arcos de la red bayesiana'], - ['metricas_diferenciacion', 'Métricas de diferenciación (LR y HBN)'], - ['auc_validacion_interna', 'AUC de validación interna'], - ['auc_bootstrap', 'AUC por réplica bootstrap'], - ['seleccion_bootstrap', 'Frecuencia de selección en el bootstrap'], - ['subgrupos_weibull', 'Subgrupos: Kaplan-Meier y Weibull fraccional'], - ['subgrupos_puntos', 'Subgrupos: supervivencia de LR y HBN'], - ['prueba_edad', 'Prueba de la edad continua contra la categorizada'], - ['cortes_edad', 'Comparación de cortes de edad'], - ['cortes_tumor', 'Comparación de cortes de tamaño tumoral'], - ['pesos_combinacion', 'Pesos de la combinación LR y HBN'], -]; - -/** - * How CaMa's model was developed, from the production version's record: the SEER stages' tables and figures over the - * cohort. Population results, never a patient's. Loads once, the first time the tab is shown. - */ -@Component({ - selector: 'app-cama-desarrollo', - templateUrl: './cama-desarrollo.html', - styleUrl: './cama-desarrollo.scss', -}) -export class CamaDesarrollo { - readonly active = input(false); - private readonly service = inject(CamaDesarrolloService); - private readonly destroy = inject(DestroyRef); - readonly lectura = signal({ tipo: 'cargando' }); - private pedido = false; - - constructor() { - effect(() => { - if (!this.active() || this.pedido) return; - this.pedido = true; - this.service.desarrollo().pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }), - error: () => this.lectura.set({ tipo: 'error' }), - }); - }); - } - - /** The tables the record holds, in display order, with their rows' columns. */ - tablas(datos: RespuestaDesarrollo): { id: string; titulo: string; columnas: string[]; filas: FilaDeTabla[] }[] { - return TABLAS.filter(([id]) => datos.desarrollo.tablas[id]?.filas.length) - .map(([id, titulo]) => { - const { columnas, filas } = datos.desarrollo.tablas[id]; - return { id, titulo, columnas, filas }; - }); - } - - figuras(datos: RespuestaDesarrollo): { id: string; src: string }[] { - return Object.entries(datos.desarrollo.figuras).map(([id, png]) => ({ id, src: `data:image/png;base64,${png}` })); - } - - errores(datos: RespuestaDesarrollo): [string, string][] { - return Object.entries(datos.desarrollo.errores); - } - - celda(valor: string | number | boolean | null): string { - if (valor === null) return ''; - return typeof valor === 'number' && !Number.isInteger(valor) ? valor.toPrecision(4) : String(valor); - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts deleted file mode 100644 index e9f088d..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia-figura.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { PlotlyFigure, Tema } from '../indicadores.models'; -import { CurvasSupervivencia, SerieDeSupervivencia } from './cama-supervivencia.service'; - -/** The clinicians' wording of the chart: what the model's run published (`[config.etiquetas]`), and these defaults for - * a label it leaves out. The labels are settings, not code, so they can be defined with the clinicians. */ -export const ETIQUETAS_PREDETERMINADAS: Readonly> = { - titulo: 'Supervivencia después del primer reporte de biopsia con carcinoma invasor', - eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', - km_crudo: 'Kaplan-Meier (observada)', km_ajustada: 'Kaplan-Meier ajustada por covariables', - weibull: 'Weibull ajustada', weibull_fraccional: 'Weibull fraccional ajustada', - puntos: 'Modelo (LR + red bayesiana) con IC 95 %', LR: 'Regresión logística', HBN: 'Red bayesiana', COMB: 'Modelo combinado', -}; - -export const COLORES = { km_crudo: '#9aa5b1', km_ajustada: '#3d4852', weibull: '#e0a060', fraccional: '#d1495b', modelo: '#6a3d9a', lr: '#1f77b4', hbn: '#2a9d8f' } as const; - -export const etiquetaDe = (curvas: CurvasSupervivencia, clave: string) => curvas.etiquetas[clave] ?? ETIQUETAS_PREDETERMINADAS[clave] ?? clave; - -function puntos(curvas: CurvasSupervivencia, serie: SerieDeSupervivencia, nombre: string, color: string, visible: true | 'legendonly', tamano: number): Record { - const h = curvas.horizons_months; - return { - type: 'scatter', mode: 'markers', name: nombre, x: h, y: serie.S, visible, legendgroup: nombre, - marker: { symbol: 'diamond', size: tamano, color, line: { color: 'white', width: 1 } }, - error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 1.8, width: 5, - array: serie.high.map((hi, i) => hi - serie.S[i]), arrayminus: serie.S.map((s, i) => s - serie.low[i]) }, - customdata: serie.low.map((lo, i) => [lo, serie.high[i]]), - hovertemplate: `${nombre}
    %{x} meses: %{y:.1%}
    IC 95 %: %{customdata[0]:.1%} a %{customdata[1]:.1%}`, - }; -} - -/** The figure of the model's results: the cohort's Kaplan-Meier with its band, the covariate-adjusted curve, the fitted - * Weibull curves, and the model's survival at each horizon as diamonds with their bootstrap interval. */ -export function figuraSupervivencia(curvas: CurvasSupervivencia, tema: Tema = 'claro'): PlotlyFigure { - const km = curvas.km, ajustada = curvas.km_adjusted, t = (clave: string) => etiquetaDe(curvas, clave); - const texto = tema === 'oscuro' ? '#e5e9f0' : '#1f2933', rejilla = tema === 'oscuro' ? 'rgba(229,233,240,.18)' : 'rgba(31,41,51,.12)'; - const todos = [...km.low, ...ajustada.S, ...curvas.weibull_fractional.S, ...curvas.points.COMB.low]; - const minimo = Math.max(0, Math.min(...todos) - 0.03); - const data: Record[] = [ - { 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: 'rgba(154,165,177,.35)', line: { width: 0, shape: 'hv' }, - name: `${t('km_crudo')}, IC 95 %`, hoverinfo: 'skip', legendgroup: 'km' }, - { type: 'scatter', mode: 'lines', x: km.months, y: km.S, line: { color: COLORES.km_crudo, width: 1.4, dash: 'dot', shape: 'hv' }, name: t('km_crudo'), legendgroup: 'km', - hovertemplate: '%{x} meses: %{y:.1%}' + t('km_crudo') + '' }, - { type: 'scatter', mode: 'lines', x: ajustada.months, y: ajustada.S, line: { color: COLORES.km_ajustada, width: 2, shape: 'hv' }, name: t('km_ajustada'), - hovertemplate: '%{x} meses: %{y:.1%}' + t('km_ajustada') + '' }, - { type: 'scatter', mode: 'lines', x: curvas.weibull.t, y: curvas.weibull.S, line: { color: COLORES.weibull, width: 2, dash: 'dash' }, name: t('weibull'), visible: 'legendonly' }, - { type: 'scatter', mode: 'lines', x: curvas.weibull_fractional.t, y: curvas.weibull_fractional.S, line: { color: COLORES.fraccional, width: 2.6 }, name: t('weibull_fraccional'), - hovertemplate: '%{x:.1f} meses: %{y:.1%}' + t('weibull_fraccional') + '' }, - puntos(curvas, curvas.points.LR, t('LR'), COLORES.lr, 'legendonly', 9), - puntos(curvas, curvas.points.HBN, t('HBN'), COLORES.hbn, 'legendonly', 9), - puntos(curvas, curvas.points.COMB, t('puntos'), COLORES.modelo, true, 12), - ]; - const layout: Record = { - title: { text: `${t('titulo')} (n = ${curvas.n.toLocaleString('es-MX')})`, x: 0, xanchor: 'left', font: { size: 16, color: texto } }, - paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, - xaxis: { title: { text: t('eje_x') }, range: [0, curvas.months_max + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, - yaxis: { title: { text: t('eje_y') }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, - legend: { orientation: 'h', y: -0.22, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 110 }, hovermode: 'closest', - }; - return { data, layout, config: { responsive: true, displaylogo: false } }; -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html deleted file mode 100644 index c15de72..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.html +++ /dev/null @@ -1,39 +0,0 @@ -

    Supervivencia

    -@let l = lectura(); -@switch (l.tipo) { - @case ('cargando') {

    Cargando resultados del modelo…

    } - @case ('no-disponible') { -

    Todavía no hay un modelo de supervivencia en producción. Cuando se entrene y se promueva en Gobernanza, sus resultados aparecerán aquí.

    - } - @case ('error') {

    No se pudieron cargar los resultados del modelo. Intenta nuevamente más tarde.

    } - @case ('listo') { - @let c = l.datos.curvas; - @if (l.datos.simulado) {

    Información simulada · Entorno DEV · Sin evaluación clínica

    } - - @if (figura(); as figure) { - - } -
    - - - - - @for (fila of filas(l.datos); track fila.meses) { - - - - - - } - -
    {{ etiquetaDe(c, 'puntos') }}
    Meses desde el reporteSupervivencia (%)IC 95 % (%)
    {{ fila.meses }}{{ fila.S | number:'1.1-1' }} %{{ fila.low | number:'1.1-1' }} % – {{ fila.high | number:'1.1-1' }} %
    -
    - @if (c.etiquetas['nota']; as nota) {

    {{ nota }}

    } - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss deleted file mode 100644 index 18fafb7..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.scss +++ /dev/null @@ -1,11 +0,0 @@ -:host { display: block; padding: 1rem 0; } -h2 { font-size: 1.25rem; margin: 0 0 .75rem; } -.simulated-label { font-weight: 600; margin: 0 0 .75rem; } -.metadata { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: .5rem 1.25rem; margin: 0 0 1rem; - div { display: flex; flex-direction: column; } dt { font-size: .8rem; opacity: .8; } dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; } } -.points-scroll { overflow-x: auto; margin-top: 1rem; &:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } } -table { border-collapse: collapse; min-width: 22rem; } -caption { text-align: left; font-weight: 600; padding-bottom: .4rem; } -th, td { padding: .4rem .75rem; border-bottom: 1px solid rgba(128, 128, 128, .35); text-align: left; } -.percentage, .interval { font-variant-numeric: tabular-nums; } -.note { margin-top: 1rem; font-size: .85rem; opacity: .85; } diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts deleted file mode 100644 index 6613465..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.service.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { HttpClient, HttpErrorResponse } from '@angular/common/http'; -import { inject, Injectable } from '@angular/core'; -import { catchError, map, Observable, of, throwError } from 'rxjs'; - -// The survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the -// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the -// 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 { - 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[] }; - km_adjusted: { months: number[]; S: number[] }; - weibull: { t: number[]; S: number[] }; - weibull_fractional: { t: number[]; S: number[] }; - points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia }; - etiquetas: Record; -} -export interface RespuestaCurvas { - simulado: boolean; - modelo: { nombre: string; version: string; mlflow_run_id: string }; - curvas: CurvasSupervivencia; -} - -const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); -const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); -const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length); -const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1); -const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; - -function invalid(): never { - throw new Error('Respuesta de curvas de supervivencia inválida'); -} - -function serie(v: unknown, horizons: number): SerieDeSupervivencia { - if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid(); - const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[]; - if (low.some((l, i) => l > high[i])) invalid(); - return { S: s, low, high }; -} - -/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */ -export function respuestaCurvas(v: unknown): RespuestaCurvas { - if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid(); - const m = v['modelo'] as Record, c = v['curvas'] as Record; - if (!text(m['nombre']) || !text(m['version']) || !text(m['mlflow_run_id'])) invalid(); - const horizons = c['horizons_months']; - if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events']) - || !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid(); - const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points']; - if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length) - || !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid(); - if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid(); - for (const curve of [weibull, fractional]) { - if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid(); - } - if (!record(points)) invalid(); - const p = points as Record, h = (horizons as number[]).length; - const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record : {}; - return { - simulado: v['simulado'] === true, - modelo: { nombre: m['nombre'] as string, version: m['version'] as string, mlflow_run_id: m['mlflow_run_id'] as string }, - curvas: { - 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'], - weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'], - points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas, - }, - }; -} - -@Injectable({ providedIn: 'root' }) -export class CamaSupervivenciaService { - private readonly http = inject(HttpClient); - - /** The production version's curves, or `null` when there is none (a 404). */ - curvas(): Observable { - return this.http.get('/cama/modelo/curvas').pipe( - map(respuestaCurvas), - catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), - ); - } -} diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts deleted file mode 100644 index 539f2c8..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.spec.ts +++ /dev/null @@ -1,157 +0,0 @@ -// Covers CaMa's survival tab: the boundary validation of `GET /cama/modelo/curvas` (a malformed record never draws a partial -// curve), the figure built from the record (the model's diamonds at 6, 12 and 18 months with their interval, the curves, -// the labels from the model's settings), and the component's states and table. Fixtures: `curvasEjemplo`, a record like a -// training run publishes; a stub Plotly runtime, so the chart is not drawn for real. -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { TestBed } from '@angular/core/testing'; -import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; -import { CamaSupervivencia } from './cama-supervivencia'; -import { respuestaCurvas } from './cama-supervivencia.service'; -import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivencia } from './cama-supervivencia-figura'; - -const meses = Array.from({ length: 25 }, (_, i) => i); -const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 24)); - -function curvasEjemplo(): any { - const serie = (S: number[]) => ({ S, low: S.map(s => s - 0.04), high: S.map(s => Math.min(1, s + 0.04)) }); - return { - simulado: true, - modelo: { nombre: 'cama-survival', version: '3', mlflow_run_id: 'run-1' }, - curvas: { - version: 1, n: 245, 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: { eje_x: 'Meses desde la biopsia', nota: 'Datos simulados. Sin validación clínica.' }, - }, - }; -} - -describe('Supervivencia CaMa: respuesta', () => { - // Fails if a record with an impossible value is accepted and drawn. - it('accepts a record as published and keeps it', () => { - const r = respuestaCurvas(curvasEjemplo()); - expect(r.modelo.version).toBe('3'); - expect(r.curvas.points.COMB.S).toEqual([0.925, 0.845, 0.775]); - }); - - it.each([ - ['a probability above 1', (d: any) => { d.curvas.km.S[3] = 1.2; }], - ['a curve shorter than its months', (d: any) => { d.curvas.km_adjusted.S.pop(); }], - ['an inverted interval', (d: any) => { d.curvas.points.COMB.low[0] = 0.99; }], - ['a series with another number of horizons', (d: any) => { d.curvas.points.LR.S.pop(); }], - ['no model version', (d: any) => { delete d.modelo.version; }], - ['a missing curve', (d: any) => { delete d.curvas.weibull_fractional; }], - ])('rejects %s', (_, estropear) => { - const d = curvasEjemplo(); - estropear(d); - expect(() => respuestaCurvas(d)).toThrow('Respuesta de curvas de supervivencia inválida'); - }); -}); - -describe('Supervivencia CaMa: figura', () => { - const figura = () => figuraSupervivencia(respuestaCurvas(curvasEjemplo()).curvas); - const traza = (nombre: string) => figura().data.find(t => t['name'] === nombre) as any; - - // Fails if the diamonds move off 6, 12 and 18 months, or their interval bars stop being the record's interval. - it('draws the combined model as diamonds at the horizons with its interval', () => { - const rombos = traza(ETIQUETAS_PREDETERMINADAS['puntos']); - expect(rombos.x).toEqual([6, 12, 18]); - expect(rombos.y).toEqual([0.925, 0.845, 0.775]); - 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]); - expect(rombos.error_y.arrayminus.map((v: number) => +v.toFixed(3))).toEqual([0.04, 0.04, 0.04]); - }); - - // Fails if the observed and adjusted curves, the band and the fractional Weibull are not all there, or LR and HBN start visible. - it('draws the Kaplan-Meier with its band, the adjusted curve and the fractional Weibull; LR and HBN start hidden', () => { - const f = figura(), nombres = f.data.map(t => t['name']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_crudo']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['km_ajustada']); - expect(nombres).toContain(ETIQUETAS_PREDETERMINADAS['weibull_fraccional']); - expect(f.data.some(t => t['fill'] === 'tonexty')).toBe(true); - expect(traza(ETIQUETAS_PREDETERMINADAS['LR']).visible).toBe('legendonly'); - expect(traza(ETIQUETAS_PREDETERMINADAS['HBN']).visible).toBe('legendonly'); - }); - - // Fails if the axis titles stop coming from the model's settings, or a label it leaves out stops falling back. - it('takes the labels from the record and falls back for the ones it leaves out', () => { - const l = figura().layout as any; - expect(l.xaxis.title.text).toBe('Meses desde la biopsia'); - expect(l.yaxis.title.text).toBe(ETIQUETAS_PREDETERMINADAS['eje_y']); - expect(l.title.text).toContain('(n = 245)'); - }); - - // Fails if the y axis hides a curve or an interval below its range, or leaves survival above 100 %. - it('fits the y range to the lowest curve or interval and stops at 100 %', () => { - const [bajo, alto] = (figura().layout as any).yaxis.range; - expect(bajo).toBeLessThan(0.6); - expect(bajo).toBeGreaterThanOrEqual(0); - expect(alto).toBeCloseTo(1.005); - }); -}); - -describe('Supervivencia CaMa: componente', () => { - let http: HttpTestingController; - 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()) }; - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - http = TestBed.inject(HttpTestingController); - }); - afterEach(() => { http.verify(); vi.unstubAllGlobals(); }); - const montar = (active: boolean) => { - const f = TestBed.createComponent(CamaSupervivencia); - f.componentRef.setInput('active', active); - f.detectChanges(); - return f; - }; - const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - - // Fails if the tab asks for the results before it is shown, or asks again when it is shown again. - it('asks once, the first time the tab is shown', () => { - const f = montar(false); - http.expectNone('/cama/modelo/curvas'); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); - f.componentRef.setInput('active', false); - f.detectChanges(); - f.componentRef.setInput('active', true); - f.detectChanges(); - http.expectNone('/cama/modelo/curvas'); - }); - - // Fails if the model, its version, the counts, the simulated label, the table of the diamonds or the note are not shown. - it('shows the model, the counts, the simulated label, the table of the horizons and the note', () => { - const f = montar(true); - http.expectOne('/cama/modelo/curvas').flush(curvasEjemplo()); - f.detectChanges(); - - const t = texto(f); - expect(t).toContain('cama-survival, versión 3'); - expect(t).toContain('245'); - expect(t).toContain('Información simulada'); - expect(t).toContain('92.5 %'); - expect(t).toContain('88.5 % – 96.5 %'); - expect(t).toContain('Datos simulados. Sin validación clínica.'); - expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['6', '12', '18']); - }); - - // Fails if no model in production is shown as an error, or a failed or malformed answer as a chart. - it('says there is no model yet on a 404 and fails closed on an error or a malformed record', () => { - const sinModelo = montar(true); - http.expectOne('/cama/modelo/curvas').flush({ error: 'sin curvas' }, { status: 404, statusText: 'Not Found' }); - sinModelo.detectChanges(); - expect(texto(sinModelo)).toContain('Todavía no hay un modelo de supervivencia en producción'); - - const roto = montar(true); - http.expectOne('/cama/modelo/curvas').flush({ curvas: {} }); - roto.detectChanges(); - expect(texto(roto)).toContain('No se pudieron cargar los resultados del modelo'); - expect((roto.nativeElement as HTMLElement).querySelector('app-plotly-chart')).toBeNull(); - }); -}); diff --git a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts b/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts deleted file mode 100644 index 6b887bb..0000000 --- a/src/app/features/indicadores/cama-supervivencia/cama-supervivencia.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Component, computed, DestroyRef, effect, inject, input, signal } from '@angular/core'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { DecimalPipe } from '@angular/common'; -import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; -import { Tema } from '../indicadores.models'; -import { CamaSupervivenciaService, RespuestaCurvas } from './cama-supervivencia.service'; -import { etiquetaDe, figuraSupervivencia } from './cama-supervivencia-figura'; - -type Lectura = { tipo: 'cargando' } | { tipo: 'no-disponible' } | { tipo: 'error' } | { tipo: 'listo'; datos: RespuestaCurvas }; - -/** - * CaMa's survival results: the cohort's survival curves and the model's survival at 6, 12 and 18 months with its - * interval, as the production version of the model published them. Population results, never a patient's: a patient's own - * risk is in her record. Loads once, the first time the tab is shown. - */ -@Component({ - selector: 'app-cama-supervivencia', - imports: [PlotlyChart, DecimalPipe], - templateUrl: './cama-supervivencia.html', - styleUrl: './cama-supervivencia.scss', -}) -export class CamaSupervivencia { - readonly active = input(false); - readonly tema = input('claro'); - private readonly service = inject(CamaSupervivenciaService); - private readonly destroy = inject(DestroyRef); - readonly lectura = signal({ tipo: 'cargando' }); - private pedido = false; - readonly figura = computed(() => { - const l = this.lectura(); - return l.tipo === 'listo' ? figuraSupervivencia(l.datos.curvas, this.tema()) : null; - }); - readonly etiquetaDe = etiquetaDe; - - constructor() { - effect(() => { - if (!this.active() || this.pedido) return; - this.pedido = true; - this.service.curvas().pipe(takeUntilDestroyed(this.destroy)).subscribe({ - next: datos => this.lectura.set(datos === null ? { tipo: 'no-disponible' } : { tipo: 'listo', datos }), - error: () => this.lectura.set({ tipo: 'error' }), - }); - }); - } - - /** The combined model's survival at each horizon, for the table that says what the figure's diamonds say. */ - filas(datos: RespuestaCurvas) { - const c = datos.curvas, p = c.points.COMB; - return c.horizons_months.map((meses, i) => ({ meses, S: p.S[i] * 100, low: p.low[i] * 100, high: p.high[i] * 100 })); - } -} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index e06b388..0a7f3c5 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => { http.match(() => true); } - it('CaMa oculta Análisis y conserva Histórico, Supervivencia y Análisis de Riesgos', () => { + 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', 'Supervivencia', '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(); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a1fd68e..55283b3 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -138,13 +138,6 @@
    } - @if (conSupervivencia) { -
    - - -
    - } -
    ('resumen'); readonly fichaPacienteAbierta = signal(false); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index e0c2ad1..c441f5e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - // TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos and adds Supervivencia; CaCu keeps its three. - const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Supervivencia', 'Análisis de Riesgos', 'Datos y definiciones'] + // 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']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 02394df..d31d610 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -76,11 +76,11 @@ describe('Ficha CaMa: componente', () => { }); // 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, survival and prognostic factors', () => { + 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', 'survival', 'factors']); - expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Probabilidad de recurrencia', 'Supervivencia', 'Factores pronóstico']); + 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/); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index 26c4e59..f45587e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -9,8 +9,8 @@ import { } from './cama-patient.models'; /** - * Individual record of a CaMa follow-up patient. It shows only what the follow-up list carries; recurrence, - * survival and prognostic factors are placeholders until a validated model supplies them. + * Individual record of a CaMa follow-up patient. 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. */ @Component({ selector: 'app-cama-patient-card', diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index fc49e84..1c75e67 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -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, survival and prognostic factors, and +// 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 // 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, survival, prognostic factors and recommendations', () => { + it('has placeholders, with no figures, for recurrence, prognostic factors and recommendations', () => { const found = texts(definition()['content']); - 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); + 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); }); // Fails if the document carries a platform identifier field. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index 192bef5..879d65c 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -27,10 +27,10 @@ export interface CamaPatientSummary { daysMammographyToDiagnosis: number | null; } -/** Placeholders for results that exist only once a validated model and its clinical definition do. */ +/** 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). */ 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.'; diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts new file mode 100644 index 0000000..2f33227 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -0,0 +1,65 @@ +import { PlotlyFigure, Tema } from '../../indicadores.models'; +import { HorizonteRiesgoCacu } from '../paciente-riesgo.models'; +import { tieneIntervalo } from '../paciente-riesgo.validation'; + +/** The clinicians' wording of the chart. */ +export const ETIQUETAS_PACIENTE = { + titulo: 'Supervivencia de la paciente desde el primer reporte de biopsia con carcinoma invasor', + eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', + curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana) con IC 95 %', +} as const; +export const COLOR_MODELO = '#6a3d9a'; +/** 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((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) }; +} + +/** The figure of one patient's survival: the model's curve and its survival at each horizon as diamonds, with the interval + * when the evaluation carries one. */ +export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], tema: Tema = 'claro'): PlotlyFigure | null { + const puntos = puntosDeSupervivencia(horizontes); + if (puntos.length === 0) return null; + const curva = curvaMensual(puntos), conIntervalo = puntos.every(p => p.bajo !== null); + 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.min(...curva.S, ...puntos.map(p => p.bajo ?? 1)) - 0.05); + const data: Record[] = [ + { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: ETIQUETAS_PACIENTE.curva, line: { color: COLOR_MODELO, width: 2.6 }, + hovertemplate: '%{x} meses: %{y:.1%}' }, + { type: 'scatter', mode: 'markers', name: ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), + marker: { symbol: 'diamond', size: 12, color: COLOR_MODELO, line: { color: 'white', width: 1 } }, + ...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLOR_MODELO, thickness: 1.8, width: 5, + array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}), + hovertemplate: '%{x} meses: %{y:.1%}' }, + ]; + const layout: Record = { + title: { text: ETIQUETAS_PACIENTE.titulo, x: 0, xanchor: 'left', font: { size: 15, color: texto } }, + paper_bgcolor: 'rgba(0,0,0,0)', plot_bgcolor: 'rgba(0,0,0,0)', font: { color: texto }, + xaxis: { title: { text: ETIQUETAS_PACIENTE.eje_x }, range: [0, curva.meses[curva.meses.length - 1] + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, + yaxis: { title: { text: ETIQUETAS_PACIENTE.eje_y }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, + legend: { orientation: 'h', y: -0.25, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 100 }, hovermode: 'closest', + }; + return { data, layout, config: { responsive: true, displaylogo: false } }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 553ce66..70a95ab 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -9,6 +9,7 @@ import { CamaPatientSummary } from './cama/cama-patient.models'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; 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'; @@ -41,6 +42,46 @@ 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]); + }); + + // Fails if the figure keeps no diamonds at the horizons, or draws their interval when the evaluation has none. + it('puts the diamonds at the horizons, with bars only when there is an interval', () => { + const con = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 }])!; + const sin = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07 }])!; + const rombos = (f: typeof con) => f.data.find(t => (t as any).mode === 'markers') as any; + + expect(rombos(con).x).toEqual([6]); + expect(rombos(con).marker.symbol).toBe('diamond'); + expect(rombos(con).error_y).toBeDefined(); + expect(rombos(sin).error_y).toBeUndefined(); + expect(figuraSupervivenciaPaciente([])).toBeNull(); + }); +}); + describe('Riesgo individual de la paciente CaMa', () => { const obtener = vi.fn(); beforeEach(() => { @@ -72,12 +113,14 @@ describe('Riesgo individual de la paciente CaMa', () => { f.detectChanges(); const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); expect(text).toContain('cama-survival'); expect(text).toContain('2025-06-19'); expect(text).toContain('Muerte por cualquier causa'); expect(text).toContain('7 %'); expect(text).toContain('17.8 %'); expect(text).toContain('25.1 %'); + expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/); expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 69612d0..c2a131d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -7,7 +7,6 @@ } @case ('error') {

    No se pudo validar o cargar el riesgo individual.

    } @case ('disponible') { -

    Información simulada · Entorno DEV · Sin evaluación clínica

    @let riesgo = lectura.datos.riesgo;
    Modelo y evaluación
    @if (riesgo.horizontes.length) {
    - - +
    Probabilidades simuladas por horizonte desde la fecha índice
    + @@ -39,6 +38,9 @@
    Probabilidades por horizonte desde la fecha índice
    Horizonte (años) Probabilidad (%)
    } @else {

    Sin horizontes evaluados en el lote vigente.

    } + @if (figura(); as figure) { + + } } }

    Recomendaciones no disponibles.

    diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 7d9f119..e59798d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,12 +1,14 @@ import { Component, computed, effect, inject, input } from '@angular/core'; import { DecimalPipe } from '@angular/common'; +import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; +import { figuraSupervivenciaPaciente } from './cama/cama-supervivencia-paciente'; 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], + imports: [DecimalPipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -20,6 +22,11 @@ export class PacienteRiesgoTabla { private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; + /** CaMa's survival figure of this patient, from the horizons of her current evaluation; CaCu's has none. */ + readonly figura = computed(() => { + const lectura = this.estado(); + return this.dominio() === 'cama' && lectura.tipo === 'disponible' ? figuraSupervivenciaPaciente(lectura.datos.riesgo.horizontes) : null; + }); constructor() { effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 76caafc..51c685d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -55,8 +55,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { } // The record no longer shows the cohort's internals (its definition, version or model variables). expect(root.textContent).not.toMatch(/cohorte_vigilancia|Variables del modelo|tipo_censura/); - expect(root.querySelector('table')!.getAttribute('aria-describedby')).toBe('riesgo-simulado'); - expect(root.querySelector('#riesgo-simulado')!.textContent).toContain('Información simulada · Entorno DEV'); + // The record never says its data are test data: with real information it makes real predictions. + expect(root.textContent).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica|simuladas/); expect(root.textContent).not.toMatch(/Caso nuevo observado|BAJO|INTERMEDIO|ALTO|CIN3/); // The resource id (batch and patient) stays in the contract, never in a UI label. expect(root.textContent).not.toMatch(/lote_id|12-42/); From a7b5f4c50bfae10de7edf6e67c09e9b460f6213e Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 10:53:41 -0600 Subject: [PATCH 15/21] CaMa patient survival figure: the legend claims an interval only when one is drawn --- .../paciente-detalle/cama/cama-supervivencia-paciente.ts | 4 ++-- .../indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts index 2f33227..fac1ee3 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -6,7 +6,7 @@ import { tieneIntervalo } from '../paciente-riesgo.validation'; export const ETIQUETAS_PACIENTE = { titulo: 'Supervivencia de la paciente desde el primer reporte de biopsia con carcinoma invasor', eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', - curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana) con IC 95 %', + curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana)', puntosConIntervalo: 'Modelo (LR + red bayesiana) con IC 95 %', } as const; export const COLOR_MODELO = '#6a3d9a'; /** The curve runs to this many months, as the cohort's does. */ @@ -48,7 +48,7 @@ export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgo const data: Record[] = [ { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: ETIQUETAS_PACIENTE.curva, line: { color: COLOR_MODELO, width: 2.6 }, hovertemplate: '%{x} meses: %{y:.1%}' }, - { type: 'scatter', mode: 'markers', name: ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), + { type: 'scatter', mode: 'markers', name: conIntervalo ? ETIQUETAS_PACIENTE.puntosConIntervalo : ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), marker: { symbol: 'diamond', size: 12, color: COLOR_MODELO, line: { color: 'white', width: 1 } }, ...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLOR_MODELO, thickness: 1.8, width: 5, array: puntos.map(p => p.alto! - p.S), arrayminus: puntos.map(p => p.S - p.bajo!) } } : {}), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 70a95ab..187c2ce 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -78,6 +78,9 @@ describe('Supervivencia individual de la paciente CaMa', () => { expect(rombos(con).marker.symbol).toBe('diamond'); expect(rombos(con).error_y).toBeDefined(); expect(rombos(sin).error_y).toBeUndefined(); + // The legend claims an interval only when one is drawn. + expect(rombos(con).name).toContain('IC 95 %'); + expect(rombos(sin).name).not.toContain('IC'); expect(figuraSupervivenciaPaciente([])).toBeNull(); }); }); From 7adceb86bf0b5811a7b0a64cb3f1dfbb08dfcbfc Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 12:07:21 -0600 Subject: [PATCH 16/21] CaMa patient record: the pipeline's survival figure with her curve, computed live and comparable with her subgroup --- .../cama/cama-curvas.service.ts | 105 +++++++++++++ ...cama-supervivencia-paciente.component.html | 18 +++ ...cama-supervivencia-paciente.component.scss | 3 + ...a-supervivencia-paciente.component.spec.ts | 141 ++++++++++++++++++ .../cama-supervivencia-paciente.component.ts | 62 ++++++++ .../cama/cama-supervivencia-paciente.ts | 83 ++++++++--- .../paciente-riesgo-cama.spec.ts | 18 +-- .../paciente-riesgo-tabla.html | 4 +- .../paciente-detalle/paciente-riesgo-tabla.ts | 11 +- 9 files changed, 393 insertions(+), 52 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts new file mode 100644 index 0000000..ef17d37 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -0,0 +1,105 @@ +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, map, Observable, of, throwError } from 'rxjs'; + +// The cohort's survival results of CaMa's model in production, `GET /cama/modelo/curvas`: the cohort's survival curves and the +// model's survival at each horizon with its interval. They describe the cohort, never a patient; the answer names the +// 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 { + 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[] }; + km_adjusted: { months: number[]; S: number[] }; + weibull: { t: number[]; S: number[] }; + weibull_fractional: { t: number[]; S: number[] }; + points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia }; + etiquetas: Record; +} +export interface RespuestaCurvas { + modelo: { nombre: string; version: string }; + curvas: CurvasSupervivencia; +} + +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +const numbers = (v: unknown, length?: number): v is number[] => Array.isArray(v) && v.every(finite) && (length === undefined || v.length === length); +const probabilities = (v: unknown, length?: number): v is number[] => numbers(v, length) && v.every(p => p >= 0 && p <= 1); +const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; + +function invalid(): never { + throw new Error('Respuesta de curvas de supervivencia inválida'); +} + +function serie(v: unknown, horizons: number): SerieDeSupervivencia { + if (!record(v) || !probabilities(v['S'], horizons) || !probabilities(v['low'], horizons) || !probabilities(v['high'], horizons)) invalid(); + const s = v['S'] as number[], low = v['low'] as number[], high = v['high'] as number[]; + if (low.some((l, i) => l > high[i])) invalid(); + return { S: s, low, high }; +} + +/** Validate at the boundary: the record's shapes and ranges, so the chart never draws a partial or impossible curve. */ +export function respuestaCurvas(v: unknown): RespuestaCurvas { + if (!record(v) || !record(v['modelo']) || !record(v['curvas'])) invalid(); + const m = v['modelo'] as Record, c = v['curvas'] as Record; + if (!text(m['nombre']) || !text(m['version'])) invalid(); + const horizons = c['horizons_months']; + if (!numbers(horizons) || horizons.length === 0 || !finite(c['months_max']) || !finite(c['n']) || !finite(c['events']) + || !finite(c['median_follow_up_months']) || !finite(c['bootstrap_replicas'])) invalid(); + const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points']; + if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length) + || !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid(); + if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid(); + for (const curve of [weibull, fractional]) { + if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid(); + } + if (!record(points)) invalid(); + const p = points as Record, h = (horizons as number[]).length; + const etiquetas = record(c['etiquetas']) ? Object.fromEntries(Object.entries(c['etiquetas']).filter(([, value]) => typeof value === 'string')) as Record : {}; + return { + modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, + curvas: { + 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'], + weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'], + points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas, + }, + }; +} + +/** What can be selected, and the patient's own value of each covariate (`GET /cama/modelo/curvas/opciones?paciente=`). */ +export interface OpcionesCurvas { + n: number; events: number; + covariables: Record; + periodo: { desde: string; hasta: string }; + limites: { miembros_min: number; muertes_min: number }; + paciente: Record | null; +} +export interface ConsultaCurvas { filtros?: Record; periodo?: { desde?: string; hasta?: string }; } +/** The selection was refused with a reason (a 422): too few patients, or invalid. */ +export class SeleccionRechazada extends Error {} + +@Injectable({ providedIn: 'root' }) +export class CamaCurvasService { + private readonly http = inject(HttpClient); + + /** The values that can be selected, and `pacId`'s own; `null` when there is no model in production or no cohort yet. */ + opciones(pacId: string): Observable { + return this.http.get<{ opciones: OpcionesCurvas }>('/cama/modelo/curvas/opciones', { params: { paciente: pacId } }).pipe( + map(r => r.opciones), + catchError(() => of(null)), + ); + } + + /** 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 { + return this.http.post('/cama/modelo/curvas/consulta', consulta).pipe( + map(respuestaCurvas), + catchError(error => error instanceof HttpErrorResponse && error.status === 422 + ? throwError(() => new SeleccionRechazada(String(error.error?.error ?? 'La selección no se puede calcular.'))) + : throwError(() => error)), + ); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html new file mode 100644 index 0000000..b5299c5 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html @@ -0,0 +1,18 @@ +
    +
    Supervivencia de la paciente
    + @if (cruzables().length) { +
    + Comparar con las pacientes que comparten + @for (c of cruzables(); track c.clave) { + + } +
    + } + @let l = lectura(); + @if (l.tipo === 'cargando') {

    Calculando con los datos más recientes…

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

    {{ l.motivo }} Quita algún criterio para comparar con más pacientes.

    } + @if (l.tipo === 'error') {

    No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.

    } + @if (figura(); as figure) { + + } +
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss new file mode 100644 index 0000000..6ce8457 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss @@ -0,0 +1,3 @@ +.compare { border: 1px solid var(--mat-sys-outline-variant, #ccc); margin: 0 0 1rem; padding: .5rem .75rem; display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; } +.compare legend { font-weight: 600; padding: 0 .25rem; } +label { display: inline-flex; align-items: center; gap: .35rem; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts new file mode 100644 index 0000000..f3e779b --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts @@ -0,0 +1,141 @@ +// 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 }]; +const opciones = { n: 500, events: 133, covariables: {}, periodo: { desde: '2024-01-01', hasta: '2026-01-01' }, limites: { miembros_min: 30, muertes_min: 5 }, + paciente: { grade: 'G2', er: 'POSITIVO', her2: 'NA', age_group: '60-74' } }; + +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 = traza(f, ETIQUETAS_PREDETERMINADAS['paciente_puntos']); + + 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(traza(f, ETIQUETAS_PREDETERMINADAS['paciente']).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 the subgroup the reader chose is not what the title says. + it('names the subgroup in the title', () => { + const f = figuraSupervivenciaPaciente(horizontes, cohorte().curvas, 'claro', 'Pacientes con Grado de Nottingham G2')!; + + expect((f.layout as any).title.text).toContain('Pacientes con Grado de Nottingham G2'); + }); +}); + +describe('Supervivencia de la paciente: componente', () => { + let consulta: ReturnType; + 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: { opciones: () => of(opciones), 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) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + + // Fails if the cohort's curves are not asked for everyone first, or the covariates she has no value for are offered. + it('asks the cohort live, for everyone, and offers the covariates she has a value for', () => { + const f = montar(); + + expect(consulta).toHaveBeenCalledWith({ filtros: {} }); + expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + const t = texto(f); + expect(t).toContain('Grado de Nottingham: G2'); + expect(t).toContain('Receptor de estrógeno: POSITIVO'); + expect(t).not.toContain('HER2:'); + }); + + // Fails if ticking a covariate does not ask the cohort for the patients who share it, or unticking does not go back. + it('asks for her subgroup when a covariate is ticked, and for everyone when it is unticked', () => { + const f = montar(); + + f.componentInstance.alternar('grade'); + f.detectChanges(); + expect(consulta).toHaveBeenLastCalledWith({ filtros: { grade: ['G2'] } }); + f.componentInstance.alternar('grade'); + f.detectChanges(); + expect(consulta).toHaveBeenLastCalledWith({ filtros: {} }); + }); + + // 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(); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts new file mode 100644 index 0000000..b4080ae --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts @@ -0,0 +1,62 @@ +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 { HorizonteRiesgoCacu } from '../paciente-riesgo.models'; +import { CamaCurvasService, ConsultaCurvas, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; +import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente'; + +/** What the reader calls each covariate of the model. */ +export const COVARIABLES: Record = { + age_group: 'Grupo de edad', histologic_type: 'Tipo histológico', grade: 'Grado de Nottingham', er: 'Receptor de estrógeno', + pr: 'Receptor de progesterona', her2: 'HER2', ki67_group: 'Ki-67 (%)', size_group: 'Tamaño de la lesión (mm)', +}; + +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, for everyone or for the patients who share the covariates the + * reader ticks with her (her subgroup, as the pipeline draws its subgroups). 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(); + readonly horizontes = input.required(); + private readonly service = inject(CamaCurvasService); + /** The covariates she is compared on. */ + readonly cruces = signal([]); + readonly opciones = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.opciones(id)))); + /** The covariates she has a value for, to offer. */ + readonly cruzables = computed(() => { + const suyas = this.opciones()?.paciente; + return suyas ? Object.keys(COVARIABLES).filter(c => suyas[c] && suyas[c] !== 'NA').map(c => ({ clave: c, etiqueta: COVARIABLES[c], valor: suyas[c] })) : []; + }); + private readonly consulta = computed(() => { + const suyas = this.opciones()?.paciente; + return { filtros: Object.fromEntries(this.cruces().filter(c => suyas?.[c]).map(c => [c, [suyas![c]]])) }; + }); + readonly lectura = toSignal(toObservable(this.consulta).pipe(switchMap(q => this.service.consulta(q).pipe( + map((datos): Lectura => ({ tipo: 'lista', datos })), + catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), + startWith({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura }); + private readonly descripcion = computed(() => { + const suyas = this.opciones()?.paciente; + const partes = this.cruces().filter(c => suyas?.[c]).map(c => `${COVARIABLES[c]} ${suyas![c]}`); + return partes.length ? `Pacientes con ${partes.join(' · ')}` : null; + }); + /** 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, 'claro', this.descripcion()); + }); + alternar(clave: string): void { + this.cruces.update(actuales => actuales.includes(clave) ? actuales.filter(c => c !== clave) : [...actuales, clave]); + } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts index fac1ee3..761687e 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -1,14 +1,18 @@ 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 clinicians' wording of the chart. */ -export const ETIQUETAS_PACIENTE = { - titulo: 'Supervivencia de la paciente desde el primer reporte de biopsia con carcinoma invasor', - eje_x: 'Meses desde el reporte de biopsia', eje_y: 'Probabilidad de supervivencia', - curva: 'Supervivencia estimada', puntos: 'Modelo (LR + red bayesiana)', puntosConIntervalo: 'Modelo (LR + red bayesiana) con IC 95 %', -} as const; -export const COLOR_MODELO = '#6a3d9a'; +/** 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> = { + 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: supervivencia estimada', + paciente_puntos: 'Paciente: modelo en cada horizonte', +}; +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; @@ -37,29 +41,60 @@ export function curvaMensual(puntos: readonly PuntoDeSupervivencia[], hasta = ME return { meses, S: S.reduce((acc, v) => [...acc, Math.min(v, acc.length ? acc[acc.length - 1] : 1)], []) }; } -/** The figure of one patient's survival: the model's curve and its survival at each horizon as diamonds, with the interval - * when the evaluation carries one. */ -export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgoCacu[], tema: Tema = 'claro'): PlotlyFigure | null { +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); + 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 minimo = Math.max(0, Math.min(...curva.S, ...puntos.map(p => p.bajo ?? 1)) - 0.05); - const data: Record[] = [ - { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: ETIQUETAS_PACIENTE.curva, line: { color: COLOR_MODELO, width: 2.6 }, - hovertemplate: '%{x} meses: %{y:.1%}' }, - { type: 'scatter', mode: 'markers', name: conIntervalo ? ETIQUETAS_PACIENTE.puntosConIntervalo : ETIQUETAS_PACIENTE.puntos, x: puntos.map(p => p.meses), y: puntos.map(p => p.S), - marker: { symbol: 'diamond', size: 12, color: COLOR_MODELO, line: { color: 'white', width: 1 } }, - ...(conIntervalo ? { error_y: { type: 'data', symmetric: false, visible: true, color: COLOR_MODELO, thickness: 1.8, width: 5, + const data: Record[] = []; + 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}' + t('km_crudo') + '' }, + { 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}' + t('weibull') + '' }, + { 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}' + t('weibull_fraccional') + '' }, + { 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}' + t('puntos') + '' }); + } + data.push( + { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), line: { color: COLORES.paciente, width: 3 }, + hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente') + '' }, + { type: 'scatter', mode: 'markers', name: t('paciente_puntos'), 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:.1%}' }, - ]; + hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente_puntos') + '' }); + const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20); + const base = descripcion ?? t('titulo'); + const titulo = cohorte ? `${base}
    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 = { - title: { text: ETIQUETAS_PACIENTE.titulo, x: 0, xanchor: 'left', font: { size: 15, color: texto } }, + 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: { title: { text: ETIQUETAS_PACIENTE.eje_x }, range: [0, curva.meses[curva.meses.length - 1] + 0.8], dtick: 3, gridcolor: rejilla, zeroline: false }, - yaxis: { title: { text: ETIQUETAS_PACIENTE.eje_y }, range: [minimo, 1.005], tickformat: '.0%', gridcolor: rejilla, zeroline: false }, - legend: { orientation: 'h', y: -0.25, x: 0 }, margin: { l: 70, r: 20, t: 60, b: 100 }, hovermode: 'closest', + 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 } }; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 187c2ce..895a996 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -67,22 +67,6 @@ describe('Supervivencia individual de la paciente CaMa', () => { expect(S.every((v, i) => i === 0 || v <= S[i - 1] + 1e-12)).toBe(true); expect(S[24]).toBeLessThan(S[18]); }); - - // Fails if the figure keeps no diamonds at the horizons, or draws their interval when the evaluation has none. - it('puts the diamonds at the horizons, with bars only when there is an interval', () => { - const con = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07, ic_bajo: 0.05, ic_alto: 0.1 }])!; - const sin = figuraSupervivenciaPaciente([{ horizonte_anios: 0.5, probabilidad: 0.07 }])!; - const rombos = (f: typeof con) => f.data.find(t => (t as any).mode === 'markers') as any; - - expect(rombos(con).x).toEqual([6]); - expect(rombos(con).marker.symbol).toBe('diamond'); - expect(rombos(con).error_y).toBeDefined(); - expect(rombos(sin).error_y).toBeUndefined(); - // The legend claims an interval only when one is drawn. - expect(rombos(con).name).toContain('IC 95 %'); - expect(rombos(sin).name).not.toContain('IC'); - expect(figuraSupervivenciaPaciente([])).toBeNull(); - }); }); describe('Riesgo individual de la paciente CaMa', () => { @@ -116,7 +100,7 @@ describe('Riesgo individual de la paciente CaMa', () => { f.detectChanges(); const text = (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + 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'); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index c2a131d..474b7c5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -38,8 +38,8 @@ } @else {

    Sin horizontes evaluados en el lote vigente.

    } - @if (figura(); as figure) { - + @if (dominio() === 'cama' && pacId(); as id) { + } } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index e59798d..d7af53f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,14 +1,13 @@ import { Component, computed, effect, inject, input } from '@angular/core'; import { DecimalPipe } from '@angular/common'; -import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; -import { figuraSupervivenciaPaciente } from './cama/cama-supervivencia-paciente'; +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, PlotlyChart], + imports: [DecimalPipe, CamaSupervivenciaPaciente], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -22,12 +21,6 @@ export class PacienteRiesgoTabla { private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; - /** CaMa's survival figure of this patient, from the horizons of her current evaluation; CaCu's has none. */ - readonly figura = computed(() => { - const lectura = this.estado(); - return this.dominio() === 'cama' && lectura.tipo === 'disponible' ? figuraSupervivenciaPaciente(lectura.datos.riesgo.horizontes) : null; - }); - constructor() { effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); } From e8ce7a487b046fe1cb12701f98ef645c7f9d12ea Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:03:19 -0600 Subject: [PATCH 17/21] CaMa patient record: no subgroup panel, one legend entry for the patient --- .../cama/cama-curvas.service.ts | 16 ------- ...cama-supervivencia-paciente.component.html | 10 +---- ...cama-supervivencia-paciente.component.scss | 4 +- ...a-supervivencia-paciente.component.spec.ts | 41 +++++++----------- .../cama-supervivencia-paciente.component.ts | 42 ++++--------------- .../cama/cama-supervivencia-paciente.ts | 9 ++-- 6 files changed, 28 insertions(+), 94 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts index ef17d37..07f7a7b 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -68,14 +68,6 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas { }; } -/** What can be selected, and the patient's own value of each covariate (`GET /cama/modelo/curvas/opciones?paciente=`). */ -export interface OpcionesCurvas { - n: number; events: number; - covariables: Record; - periodo: { desde: string; hasta: string }; - limites: { miembros_min: number; muertes_min: number }; - paciente: Record | null; -} export interface ConsultaCurvas { filtros?: Record; periodo?: { desde?: string; hasta?: string }; } /** The selection was refused with a reason (a 422): too few patients, or invalid. */ export class SeleccionRechazada extends Error {} @@ -84,14 +76,6 @@ export class SeleccionRechazada extends Error {} export class CamaCurvasService { private readonly http = inject(HttpClient); - /** The values that can be selected, and `pacId`'s own; `null` when there is no model in production or no cohort yet. */ - opciones(pacId: string): Observable { - return this.http.get<{ opciones: OpcionesCurvas }>('/cama/modelo/curvas/opciones', { params: { paciente: pacId } }).pipe( - map(r => r.opciones), - catchError(() => of(null)), - ); - } - /** 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 { diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html index b5299c5..0499581 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html @@ -1,16 +1,8 @@
    Supervivencia de la paciente
    - @if (cruzables().length) { -
    - Comparar con las pacientes que comparten - @for (c of cruzables(); track c.clave) { - - } -
    - } @let l = lectura(); @if (l.tipo === 'cargando') {

    Calculando con los datos más recientes…

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

    {{ l.motivo }} Quita algún criterio para comparar con más pacientes.

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

    {{ l.motivo }}

    } @if (l.tipo === 'error') {

    No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.

    } @if (figura(); as figure) { diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss index 6ce8457..5804c2c 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss @@ -1,3 +1 @@ -.compare { border: 1px solid var(--mat-sys-outline-variant, #ccc); margin: 0 0 1rem; padding: .5rem .75rem; display: flex; flex-wrap: wrap; gap: .25rem 1.25rem; } -.compare legend { font-weight: 600; padding: 0 .25rem; } -label { display: inline-flex; align-items: center; gap: .35rem; } +:host { display: block; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts index f3e779b..df91518 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts @@ -25,8 +25,6 @@ function cohorte(n = 245): any { }; } const horizontes = [{ horizonte_anios: 0.5, probabilidad: 0.07 }, { horizonte_anios: 1, probabilidad: 0.18 }, { horizonte_anios: 1.5, probabilidad: 0.25 }]; -const opciones = { n: 500, events: 133, covariables: {}, periodo: { desde: '2024-01-01', hasta: '2026-01-01' }, limites: { miembros_min: 30, muertes_min: 5 }, - paciente: { grade: 'G2', er: 'POSITIVO', her2: 'NA', age_group: '60-74' } }; describe('Figura de supervivencia de la paciente', () => { const figura = (c: any = cohorte().curvas) => figuraSupervivenciaPaciente(horizontes, respuestaCurvas(c === null ? cohorte() : { ...cohorte(), curvas: c }).curvas)!; @@ -49,12 +47,12 @@ describe('Figura de supervivencia de la paciente', () => { // 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 = traza(f, ETIQUETAS_PREDETERMINADAS['paciente_puntos']); + 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(traza(f, ETIQUETAS_PREDETERMINADAS['paciente']).line.color).toBe(COLORES.paciente); + 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. @@ -68,11 +66,14 @@ describe('Figura de supervivencia de la paciente', () => { expect(l.legend.yanchor).toBe('bottom'); }); - // Fails if the subgroup the reader chose is not what the title says. - it('names the subgroup in the title', () => { - const f = figuraSupervivenciaPaciente(horizontes, cohorte().curvas, 'claro', 'Pacientes con Grado de Nottingham G2')!; + // 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((f.layout as any).title.text).toContain('Pacientes con Grado de Nottingham G2'); + 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); }); }); @@ -84,7 +85,7 @@ describe('Supervivencia de la paciente: componente', () => { addFrames: vi.fn(() => Promise.resolve()), deleteFrames: vi.fn(() => Promise.resolve()) }; consulta = vi.fn(() => of(respuestaCurvas(cohorte()))); TestBed.configureTestingModule({ providers: [ - { provide: CamaCurvasService, useValue: { opciones: () => of(opciones), consulta } }, + { provide: CamaCurvasService, useValue: { consulta } }, { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); }); afterEach(() => vi.unstubAllGlobals()); @@ -97,28 +98,14 @@ describe('Supervivencia de la paciente: componente', () => { }; const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - // Fails if the cohort's curves are not asked for everyone first, or the covariates she has no value for are offered. - it('asks the cohort live, for everyone, and offers the covariates she has a value for', () => { + // 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(); - const t = texto(f); - expect(t).toContain('Grado de Nottingham: G2'); - expect(t).toContain('Receptor de estrógeno: POSITIVO'); - expect(t).not.toContain('HER2:'); - }); - - // Fails if ticking a covariate does not ask the cohort for the patients who share it, or unticking does not go back. - it('asks for her subgroup when a covariate is ticked, and for everyone when it is unticked', () => { - const f = montar(); - - f.componentInstance.alternar('grade'); - f.detectChanges(); - expect(consulta).toHaveBeenLastCalledWith({ filtros: { grade: ['G2'] } }); - f.componentInstance.alternar('grade'); - f.detectChanges(); - expect(consulta).toHaveBeenLastCalledWith({ filtros: {} }); + 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. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts index b4080ae..ece40d4 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts @@ -1,23 +1,17 @@ -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 { 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, ConsultaCurvas, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; +import { CamaCurvasService, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; import { figuraSupervivenciaPaciente } from './cama-supervivencia-paciente'; /** What the reader calls each covariate of the model. */ -export const COVARIABLES: Record = { - age_group: 'Grupo de edad', histologic_type: 'Tipo histológico', grade: 'Grado de Nottingham', er: 'Receptor de estrógeno', - pr: 'Receptor de progesterona', her2: 'HER2', ki67_group: 'Ki-67 (%)', size_group: 'Tamaño de la lesión (mm)', -}; - 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, for everyone or for the patients who share the covariates the - * reader ticks with her (her subgroup, as the pipeline draws its subgroups). Hers is her own prediction on top of them. + * 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', @@ -29,34 +23,14 @@ export class CamaSupervivenciaPaciente { readonly pacId = input.required(); readonly horizontes = input.required(); private readonly service = inject(CamaCurvasService); - /** The covariates she is compared on. */ - readonly cruces = signal([]); - readonly opciones = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.opciones(id)))); - /** The covariates she has a value for, to offer. */ - readonly cruzables = computed(() => { - const suyas = this.opciones()?.paciente; - return suyas ? Object.keys(COVARIABLES).filter(c => suyas[c] && suyas[c] !== 'NA').map(c => ({ clave: c, etiqueta: COVARIABLES[c], valor: suyas[c] })) : []; - }); - private readonly consulta = computed(() => { - const suyas = this.opciones()?.paciente; - return { filtros: Object.fromEntries(this.cruces().filter(c => suyas?.[c]).map(c => [c, [suyas![c]]])) }; - }); - readonly lectura = toSignal(toObservable(this.consulta).pipe(switchMap(q => this.service.consulta(q).pipe( + readonly lectura = toSignal(this.service.consulta({ filtros: {} }).pipe( map((datos): Lectura => ({ tipo: 'lista', datos })), catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), - startWith({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura }); - private readonly descripcion = computed(() => { - const suyas = this.opciones()?.paciente; - const partes = this.cruces().filter(c => suyas?.[c]).map(c => `${COVARIABLES[c]} ${suyas![c]}`); - return partes.length ? `Pacientes con ${partes.join(' · ')}` : null; - }); + startWith({ 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, 'claro', this.descripcion()); + return figuraSupervivenciaPaciente(this.horizontes(), l.tipo === 'lista' ? l.datos.curvas : null); }); - alternar(clave: string): void { - this.cruces.update(actuales => actuales.includes(clave) ? actuales.filter(c => c !== clave) : [...actuales, clave]); - } } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts index 761687e..f2c1251 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts @@ -9,8 +9,7 @@ export const ETIQUETAS_PREDETERMINADAS: Readonly> = { 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: supervivencia estimada', - paciente_puntos: 'Paciente: modelo en cada horizonte', + 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. */ @@ -77,13 +76,13 @@ export function figuraSupervivenciaPaciente(horizontes: readonly HorizonteRiesgo hovertemplate: '%{x} meses: %{y:.3f}' + t('puntos') + '' }); } data.push( - { type: 'scatter', mode: 'lines', x: curva.meses, y: curva.S, name: t('paciente'), line: { color: COLORES.paciente, width: 3 }, + { 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}' + t('paciente') + '' }, - { type: 'scatter', mode: 'markers', name: t('paciente_puntos'), x: puntos.map(p => p.meses), y: puntos.map(p => p.S), + { 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}' + t('paciente_puntos') + '' }); + hovertemplate: '%{x} meses: %{y:.3f}' + t('paciente') + '' }); const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20); const base = descripcion ?? t('titulo'); const titulo = cohorte ? `${base}
    n=${cohorte.n.toLocaleString('es-MX')}, fallecidos=${cohorte.events.toLocaleString('es-MX')}` : base; From fb5a4ed5ccab68845cb9199a9b644da9e1807a6a Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:14:06 -0600 Subject: [PATCH 18/21] CaMa patient record: the pipeline's figure of each clinical scenario she belongs to, without a curve of her own --- .../cama/cama-curvas.service.ts | 24 ++-- .../cama/cama-supervivencia-figura.ts | 49 ++++++++ ...cama-supervivencia-paciente.component.html | 13 +- ...a-supervivencia-paciente.component.spec.ts | 112 ++++++++++-------- .../cama-supervivencia-paciente.component.ts | 49 +++++--- .../cama/cama-supervivencia-paciente.ts | 99 ---------------- .../paciente-riesgo-cama.spec.ts | 28 ----- .../paciente-riesgo-tabla.html | 2 +- 8 files changed, 166 insertions(+), 210 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts index 07f7a7b..3867f52 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -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,29 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas { }; } -export interface ConsultaCurvas { filtros?: Record; periodo?: { desde?: string; hasta?: string }; } -/** The selection was refused with a reason (a 422): too few patients, or invalid. */ +/** 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 { - return this.http.post('/cama/modelo/curvas/consulta', consulta).pipe( + /** The clinical scenarios the patient belongs to (the whole cohort when she is in none), or `null` when there is no model in + * production or no cohort yet. */ + escenarios(pacId: string): Observable { + return this.http.get<{ escenarios: string[] }>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( + map(r => Array.isArray(r.escenarios) ? r.escenarios.filter(e => typeof e === 'string') : null), + catchError(() => of(null)), + ); + } + + /** The figure's record of one scenario (`null`: the whole cohort), scored with the production version over the data + * ingested so far. A refused scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */ + consulta(escenario: string | null): Observable { + return this.http.post('/cama/modelo/curvas/consulta', { escenario }).pipe( map(respuestaCurvas), 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)), ); } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts new file mode 100644 index 0000000..ebca7a3 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-figura.ts @@ -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> = { + 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[] = [ + { 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}' + t('km_crudo') + '' }, + { 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}' + t('weibull') + '' }, + { 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}' + t('weibull_fraccional') + '' }, + { 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}' + t('puntos') + '' }, + ]; + const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' }; + const layout: Record = { + title: { text: `${c.escenario ?? 'Toda la cohorte'}
    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 } }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html index 0499581..3276551 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html @@ -1,10 +1,9 @@
    -
    Supervivencia de la paciente
    - @let l = lectura(); - @if (l.tipo === 'cargando') {

    Calculando con los datos más recientes…

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

    {{ l.motivo }}

    } - @if (l.tipo === 'error') {

    No se pudo calcular la curva de la cohorte; se muestra solo la de la paciente.

    } - @if (figura(); as figure) { - +
    Supervivencia
    + @let lista = escenarios(); + @if (lista === undefined) {

    Buscando los escenarios clínicos de la paciente…

    } + @if (lista === null) {

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

    } + @if (lista) { + @for (nombre of lista; track nombre) { } }
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts index df91518..37334ef 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts @@ -1,37 +1,36 @@ -// 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. +// Covers the patient's survival in her CaMa record: the figure of each clinical scenario she belongs to is computed live (one +// request per scenario, none for her own curve), a refused scenario says why, no model in production says so, and the figure +// has the SEER pipeline's look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds). Fixtures: a stub of +// `CamaCurvasService` that records each scenario asked, and a 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'; +import { COLORES, ETIQUETAS_PREDETERMINADAS, figuraSupervivencia } from './cama-supervivencia-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)) }); -function cohorte(n = 245): any { +function respuesta(escenario = '< 45 años', 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, + 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 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)!; +describe('Figura de supervivencia de un escenario', () => { + const figura = (r: any = respuesta()) => figuraSupervivencia(respuestaCurvas(r).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', () => { + // Fails if the figure loses a piece of the pipeline's chart: the band, the steps, the two Weibull or the diamonds with their bars. + it('has the 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); @@ -44,85 +43,100 @@ describe('Figura de supervivencia de la paciente', () => { 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 anything but the pipeline's own curves is drawn: the patient's own curve is not part of the figure. + it('draws only the pipeline\'s curves, none of the patient\'s own', () => { + expect(figura().data.map((t: any) => t.name).filter(Boolean).sort()).toEqual( + ['Kaplan-Meier (IC 95 % Greenwood)', 'LR + HBN combinado (IC 95 % bootstrap)', 'Weibull', 'Weibull fraccional'].sort()); }); - // 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', () => { + // Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, the scenario, n and deaths. + it('is titled with the scenario, its patients and deaths, and scaled as the pipeline\'s figure', () => { const l = figura().layout as any; + expect(l.title.text).toBe('< 45 años
    n=245, fallecidos=67'); 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[]; + // Fails if a label the model's run publishes is ignored, which would take the wording out of the clinicians' hands. + it('takes the wording from the record when the model publishes it', () => { + const r = respuesta(); + r.curvas.etiquetas = { eje_y: 'Probabilidad de sobrevivir' }; - 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); + expect((figura(r).layout as any).yaxis.title.text).toBe('Probabilidad de sobrevivir'); }); }); describe('Supervivencia de la paciente: componente', () => { let consulta: ReturnType; + let escenarios: ReturnType; 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()))); + consulta = vi.fn((nombre: string | null) => of(respuesta(nombre ?? 'Toda la cohorte'))); + escenarios = vi.fn(() => of(['< 45 años', 'Jóvenes (<45) · HER2−'])); TestBed.configureTestingModule({ providers: [ - { provide: CamaCurvasService, useValue: { consulta } }, + { provide: CamaCurvasService, useValue: { escenarios, 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) => (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', () => { + // Fails if the patient's scenarios are not asked for her, or a scenario she is in has no figure. + it('draws the figure of each scenario the patient belongs to, asked live', () => { const f = montar(); + f.detectChanges(); - 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'); + expect(escenarios).toHaveBeenCalledWith('7'); + expect(consulta.mock.calls.map(c => c[0])).toEqual(['< 45 años', 'Jóvenes (<45) · HER2−']); + expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2); }); - // 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.'))); + // Fails if a patient in no scenario is left without a figure, or the whole cohort is asked as a named scenario. + it('asks for the whole cohort when the patient is in no scenario', () => { + escenarios.mockReturnValue(of(['Toda la cohorte'])); const f = montar(); + f.detectChanges(); - expect(texto(f)).toContain('La selección tiene 3 pacientes'); + expect(consulta).toHaveBeenCalledExactlyOnceWith(null); + expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1); + }); + + // Fails if the record offers choices the reader did not ask for. + it('offers no choices', () => { + const f = montar(); + f.detectChanges(); + + expect(f.nativeElement.querySelector('input, fieldset, select')).toBeNull(); + }); + + // Fails if a refused scenario draws a figure, or does not say why. + it('says why when a scenario is refused and draws nothing for it', () => { + escenarios.mockReturnValue(of(['Estadio IV'])); + consulta.mockReturnValue(throwError(() => new SeleccionRechazada('El escenario tiene 3 pacientes y 0 defunciones.'))); + const f = montar(); + f.detectChanges(); + + expect(texto(f)).toContain('Estadio IV: El escenario 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'))); + // Fails if no model in production is shown as an error or a blank. + it('says there is no model yet', () => { + escenarios.mockReturnValue(of(null)); const f = montar(); + f.detectChanges(); - expect(texto(f)).toContain('se muestra solo la de la paciente'); - expect(f.nativeElement.querySelector('app-plotly-chart')).not.toBeNull(); + expect(texto(f)).toContain('Todavía no hay un modelo de supervivencia en producción'); + expect(consulta).not.toHaveBeenCalled(); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts index ece40d4..2fa52e7 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts @@ -1,36 +1,47 @@ import { Component, computed, inject, input } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { catchError, map, of, startWith } from 'rxjs'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { catchError, map, of, startWith, switchMap } 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'; +import { figuraSupervivencia } from './cama-supervivencia-figura'; -/** What the reader calls each covariate of the model. */ type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas }; +/** One clinical scenario's figure, computed when it is shown. */ +@Component({ + selector: 'app-cama-figura-escenario', + imports: [PlotlyChart], + template: ` + @let l = lectura(); + @if (l.tipo === 'cargando') {

    Calculando {{ escenario() }} con los datos más recientes…

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

    {{ escenario() }}: {{ l.motivo }}

    } + @if (l.tipo === 'error') {

    No se pudo calcular la supervivencia de {{ escenario() }}.

    } + @if (figura(); as figure) { }`, +}) +export class CamaFiguraEscenario { + readonly escenario = input.required(); + private readonly service = inject(CamaCurvasService); + readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => this.service.consulta(nombre === 'Toda la cohorte' ? null : nombre).pipe( + map((datos): Lectura => ({ tipo: 'lista', datos })), + catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), + startWith({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura }); + readonly figura = computed(() => { const l = this.lectura(); return l.tipo === 'lista' ? figuraSupervivencia(l.datos.curvas) : null; }); +} + /** - * 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. + * The patient's survival: the figure of each clinical scenario she belongs to (the whole cohort when she is in none), as the SEER + * pipeline draws them. Patients of one scenario share its figure; it is computed from the data ingested so far with the model + * in production. */ @Component({ selector: 'app-cama-supervivencia-paciente', - imports: [PlotlyChart], + imports: [CamaFiguraEscenario], templateUrl: './cama-supervivencia-paciente.component.html', styleUrl: './cama-supervivencia-paciente.component.scss', }) export class CamaSupervivenciaPaciente { readonly pacId = input.required(); - readonly horizontes = input.required(); private readonly service = inject(CamaCurvasService); - readonly lectura = toSignal(this.service.consulta({ filtros: {} }).pipe( - map((datos): Lectura => ({ tipo: 'lista', datos })), - catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), - startWith({ 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); - }); + /** Her scenarios; `undefined` while they load, `null` when there is no model in production yet. */ + readonly escenarios = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id)))); } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts deleted file mode 100644 index f2c1251..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.ts +++ /dev/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> = { - 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((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[] = []; - 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}' + t('km_crudo') + '' }, - { 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}' + t('weibull') + '' }, - { 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}' + t('weibull_fraccional') + '' }, - { 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}' + t('puntos') + '' }); - } - 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}' + t('paciente') + '' }, - { 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}' + t('paciente') + '' }); - const minimo = Math.max(0, Math.floor((Math.min(...bajos) - 0.02) * 20) / 20); - const base = descripcion ?? t('titulo'); - const titulo = cohorte ? `${base}
    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 = { - 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 } }; -} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 895a996..19ca9ee 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -9,7 +9,6 @@ import { CamaPatientSummary } from './cama/cama-patient.models'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; 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,33 +41,6 @@ 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(() => { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 474b7c5..10a704c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -39,7 +39,7 @@ } @else {

    Sin horizontes evaluados en el lote vigente.

    } @if (dominio() === 'cama' && pacId(); as id) { - + } } } From 50948806221a650cdc55e2eb080900e1cb301dce Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 13:34:56 -0600 Subject: [PATCH 19/21] CaMa patient record: the recurrence figures of the scenarios she meets --- .../cama/cama-patient-card.html | 6 + .../cama/cama-patient-card.spec.ts | 6 +- .../cama/cama-patient-card.ts | 3 +- .../cama/cama-patient-pdf.spec.ts | 8 +- .../cama/cama-patient.models.ts | 5 +- .../cama/cama-recurrencia-figura.ts | 53 ++++++++ .../cama-recurrencia-paciente.component.html | 10 ++ ...ama-recurrencia-paciente.component.spec.ts | 122 ++++++++++++++++++ .../cama-recurrencia-paciente.component.ts | 34 +++++ .../cama/cama-recurrencia.service.ts | 55 ++++++++ .../indicadores/paciente-identidad.spec.ts | 2 + 11 files changed, 293 insertions(+), 11 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index f4d5a28..a449fcc 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -40,6 +40,12 @@ + @if (p.idField === 'pac_id') { + +

    Recurrencia

    + +
    + }

    Pronóstico y recomendaciones

    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index d31d610..1491def 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -76,11 +76,11 @@ describe('Ficha CaMa: componente', () => { }); // 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', () => { + it('has a placeholder, with no figures, for the 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']); + expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['factors']); + expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['Factores pronóstico']); for (const item of items) { expect(item.querySelector('span')!.textContent).toBe(PROGNOSIS_UNAVAILABLE); expect(item.textContent).not.toMatch(/\d/); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index f45587e..2919444 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -3,6 +3,7 @@ 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 { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component'; import { PacienteRiesgoTabla } from '../paciente-riesgo-tabla'; import { CamaPatientSummary, NOT_AVAILABLE, PROGNOSIS_PLACEHOLDERS, PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE, @@ -14,7 +15,7 @@ import { */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla], + imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla, CamaRecurrenciaPaciente], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index 1c75e67..78548ef 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -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 the prognostic factors (survival and recurrence are drawn in the record from the models' figures), 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 the 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 ['Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t); + expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(1); }); // Fails if the document carries a platform identifier field. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index 879d65c..c0a4fa4 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -27,10 +27,9 @@ 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 (survival and recurrence are drawn + * from the models' figures, not placeholders). */ export const PROGNOSIS_PLACEHOLDERS = [ - { key: 'recurrence', label: 'Probabilidad de recurrencia' }, { 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.'; diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts new file mode 100644 index 0000000..e2ddebf --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-figura.ts @@ -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[] { + 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}' + nombre + '' }, + { 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(...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[] = [ + { 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}' + L.km + '' }, + ...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}' + L.puntos + '' }, + ]; + const eje = { gridcolor: rejilla, zeroline: false, showline: true, linecolor: texto, mirror: false, ticks: 'outside' }; + const layout: Record = { + title: { text: `${f.escenario}
    ${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 } }; +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html new file mode 100644 index 0000000..0da5b1e --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html @@ -0,0 +1,10 @@ +
    +
    Probabilidad de recurrencia
    + @let r = respuesta(); + @if (r === undefined) {

    Buscando los escenarios clínicos de recurrencia de la paciente…

    } + @if (r === null) {

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

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

    La paciente no cumple ninguno de los escenarios clínicos del análisis de recurrencia.

    } + @for (f of r.escenarios; track f.cohorte + f.escenario) { } + } +
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts new file mode 100644 index 0000000..f0eda6e --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts @@ -0,0 +1,122 @@ +// Covers CaMa's recurrence figures in a patient's record: the boundary validation of `GET /cama/modelo/recurrencia` (a malformed +// answer never draws a partial curve), the figure of a scenario in the pipeline's style (the Greenwood band, the Kaplan-Meier steps, +// the solid and dotted Weibull, the diamonds with their interval, "Libre de recaída S(t)"), and the component's states. Fixtures: a +// figure like the recurrence version publishes, and a stub of `CamaRecurrenciaService`. +import { TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { vi } from 'vitest'; +import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime'; +import { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component'; +import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service'; +import { COLORES_RECURRENCIA, ETIQUETAS_RECURRENCIA, figuraRecurrencia } from './cama-recurrencia-figura'; + +const meses = Array.from({ length: 61 }, (_, i) => i); +const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 60)); +const grilla = Array.from({ length: 289 }, (_, i) => i * 0.25); +function figura(escenario = 'RE− · grado 3', cohorte = 'metabric'): any { + return { + cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, condiciones: { Grado_histologico: ['3'] }, n: 300, recaidas: 180, + horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72, + km: { months: meses, S: decreciente(0.5), low: decreciente(0.45), high: decreciente(0.55) }, + weibull: { t: grilla, S: grilla.map(t => Math.exp(-t / 90)) }, weibull_fractional: { t: grilla, S: grilla.map(t => Math.exp(-t / 85)) }, + points: { COMB: { S: [0.9, 0.7, 0.55], low: [0.88, 0.67, 0.5], high: [0.92, 0.73, 0.6] } }, bootstrap_replicas: 200, + }; +} +const respuesta = (escenarios = [figura()]): any => ({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios }); + +describe('Recurrencia CaMa: respuesta', () => { + // Fails if a record with an impossible value is accepted and drawn. + it('accepts an answer as published', () => { + expect(respuestaRecurrencia(respuesta()).escenarios[0].escenario).toBe('RE− · grado 3'); + }); + + it.each([ + ['a probability above 1', (d: any) => { d.escenarios[0].km.S[3] = 1.2; }], + ['an inverted interval', (d: any) => { d.escenarios[0].points.COMB.low[0] = 0.99; }], + ['a series with another number of horizons', (d: any) => { d.escenarios[0].points.COMB.S.pop(); }], + ['a missing curve', (d: any) => { delete d.escenarios[0].weibull_fractional; }], + ['no model version', (d: any) => { delete d.modelo.version; }], + ])('rejects %s', (_, estropear) => { + const d = respuesta(); + estropear(d); + expect(() => respuestaRecurrencia(d)).toThrow('Respuesta de recurrencia inválida'); + }); +}); + +describe('Recurrencia CaMa: figura', () => { + const f = () => figuraRecurrencia(respuestaRecurrencia(respuesta()).escenarios[0]); + const traza = (nombre: string) => f().data.find((t: any) => t.name === nombre) as any; + + // Fails if the figure loses a piece of the pipeline's chart. + it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => { + expect(f().data.some((t: any) => t.fill === 'tonexty')).toBe(true); + expect(traza(ETIQUETAS_RECURRENCIA.km).line).toMatchObject({ color: COLORES_RECURRENCIA.km, shape: 'hv' }); + expect(traza(ETIQUETAS_RECURRENCIA.weibull).line.color).toBe(COLORES_RECURRENCIA.weibull); + expect(traza(ETIQUETAS_RECURRENCIA.weibull_fraccional).line).toMatchObject({ color: COLORES_RECURRENCIA.fraccional, dash: 'dash' }); + const rombos = traza(ETIQUETAS_RECURRENCIA.puntos); + expect(rombos.x).toEqual([12, 36, 60]); + expect(rombos.error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.02, 0.03, 0.05]); + }); + + // Fails if the Weibull stops being dotted past the follow-up the cohort has, which would present an extrapolation as observed. + it('draws the Weibull dotted past the follow-up', () => { + const punteadas = f().data.filter((t: any) => t.line?.dash === 'dot') as any[]; + + expect(punteadas).toHaveLength(2); + expect(punteadas.every(t => Math.min(...t.x) >= 60)).toBe(true); + }); + + // Fails if the labels or the title leave the pipeline's: recurrence-free S(t), the scenario, the cohort, n and recurrences. + it('is titled with the scenario, the cohort, its patients and recurrences', () => { + const l = f().layout as any; + + expect(l.title.text).toBe('RE− · grado 3
    METABRIC · n=300, recaídas=180'); + expect(l.yaxis.title.text).toBe('Libre de recaída S(t)'); + expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico'); + }); +}); + +describe('Recurrencia de la paciente: componente', () => { + let recurrencia: ReturnType; + 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()) }; + recurrencia = vi.fn(() => of(respuestaRecurrencia(respuesta([figura(), figura('Grado 3', 'scanb')])))); + TestBed.configureTestingModule({ providers: [{ provide: CamaRecurrenciaService, useValue: { recurrencia } }, + { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); + }); + afterEach(() => vi.unstubAllGlobals()); + const montar = () => { + const f = TestBed.createComponent(CamaRecurrenciaPaciente); + f.componentRef.setInput('pacId', '7'); + f.detectChanges(); + f.detectChanges(); + return f; + }; + const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + + // Fails if a scenario she meets in either cohort has no figure. + it('draws a figure for each scenario she meets, in each cohort', () => { + const f = montar(); + + expect(recurrencia).toHaveBeenCalledWith('7'); + expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2); + }); + + // Fails if a patient in no scenario sees nothing, or an error. + it('says so when she meets none of the scenarios', () => { + recurrencia.mockReturnValue(of(respuestaRecurrencia(respuesta([])))); + const f = montar(); + + expect(texto(f)).toContain('no cumple ninguno de los escenarios clínicos'); + expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull(); + }); + + // Fails if no model in production is shown as an error or a blank. + it('says there is no recurrence model yet', () => { + recurrencia.mockReturnValue(of(null)); + + expect(texto(montar())).toContain('Todavía no hay un modelo de recurrencia en producción'); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts new file mode 100644 index 0000000..9761ee9 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts @@ -0,0 +1,34 @@ +import { Component, computed, inject, input } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { switchMap } from 'rxjs'; +import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; +import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service'; +import { figuraRecurrencia } from './cama-recurrencia-figura'; + +/** One scenario's recurrence figure. */ +@Component({ + selector: 'app-cama-figura-recurrencia', + imports: [PlotlyChart], + template: `@if (figura(); as figure) { }`, +}) +export class CamaFiguraRecurrencia { + readonly datos = input.required(); + readonly figura = computed(() => figuraRecurrencia(this.datos())); +} + +/** + * The patient's probability of recurrence: the figure of each clinical scenario of the recurrence analysis that her covariates meet, + * in each external cohort (METABRIC and SCAN-B). Patients in one scenario share its figure; it describes that scenario's patients in + * the cohort the analysis was made on. + */ +@Component({ + selector: 'app-cama-recurrencia-paciente', + imports: [CamaFiguraRecurrencia], + templateUrl: './cama-recurrencia-paciente.component.html', +}) +export class CamaRecurrenciaPaciente { + readonly pacId = input.required(); + private readonly service = inject(CamaRecurrenciaService); + /** The answer; `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)))); +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts new file mode 100644 index 0000000..09886de --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts @@ -0,0 +1,55 @@ +import { HttpClient } from '@angular/common/http'; +import { inject, Injectable } from '@angular/core'; +import { catchError, map, Observable, of } from 'rxjs'; + +// 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[]; } + +const record = (v: unknown): v is Record => !!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; + 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, h = (v['horizontes'] as number[]).length; + if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid(); + 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)) }; +} + +@Injectable({ providedIn: 'root' }) +export class CamaRecurrenciaService { + private readonly http = inject(HttpClient); + + /** The figures of the scenarios the patient meets, or `null` when there is no recurrence model in production or it fails. */ + recurrencia(pacId: string): Observable { + return this.http.get('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe( + map(respuestaRecurrencia), catchError(() => of(null))); + } +} diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts index 05eda5d..f52d03f 100644 --- a/src/app/features/indicadores/paciente-identidad.spec.ts +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -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 also asks for the recurrence figures of the patient; there is no model for them here. + http.match(r => r.url === '/cama/modelo/recurrencia').forEach(r => { if (!r.cancelled) r.flush({ error: 'sin recurrencia' }, { status: 404, statusText: 'Not Found' }); }); fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; From 08f1d812acdd98a7f70549310f9744ed8af20da0 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 14:43:46 -0600 Subject: [PATCH 20/21] CaMa patient record as specified: recurrence and survival analyses with a scenario selector and their risk factors --- .../cama-analisis-recurrencia.component.html | 33 ++++ .../cama-analisis-recurrencia.component.ts | 51 ++++++ ...cama-analisis-supervivencia.component.html | 26 +++ .../cama-analisis-supervivencia.component.ts | 37 ++++ .../cama/cama-analisis.component.scss | 5 + .../cama/cama-analisis.component.spec.ts | 168 ++++++++++++++++++ .../cama/cama-curvas.service.ts | 41 ++++- .../cama/cama-factores-riesgo.component.html | 17 ++ .../cama/cama-factores-riesgo.component.scss | 9 + .../cama/cama-factores-riesgo.component.ts | 26 +++ .../cama/cama-patient-card.html | 33 ++-- .../cama/cama-patient-card.spec.ts | 39 ++-- .../cama/cama-patient-card.ts | 15 +- .../cama/cama-patient-pdf.spec.ts | 8 +- .../cama/cama-patient.models.ts | 6 +- .../cama-recurrencia-paciente.component.html | 10 -- ...ama-recurrencia-paciente.component.spec.ts | 122 ------------- .../cama-recurrencia-paciente.component.ts | 34 ---- .../cama/cama-recurrencia.service.ts | 16 +- ...cama-supervivencia-paciente.component.html | 9 - ...cama-supervivencia-paciente.component.scss | 1 - ...a-supervivencia-paciente.component.spec.ts | 142 --------------- .../cama-supervivencia-paciente.component.ts | 47 ----- .../paciente-riesgo-cama.spec.ts | 28 +-- .../paciente-riesgo-tabla.html | 3 - .../paciente-detalle/paciente-riesgo-tabla.ts | 3 +- .../indicadores/paciente-identidad.spec.ts | 4 +- 27 files changed, 487 insertions(+), 446 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.html create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.scss create mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts delete mode 100644 src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html new file mode 100644 index 0000000..16b0a97 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.html @@ -0,0 +1,33 @@ +@let r = respuesta(); +
    +
    Análisis de recurrencia
    + @if (r === undefined) {

    Buscando el análisis de recurrencia…

    } + @if (r === null) {

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

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

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

    } + @else { + + + @if (figura(); as figure) { } + } + } +
    +
    +
    Factores de riesgo
    + @if (r && r.escenarios.length) { + + + } @else {

    Se muestran al elegir un escenario clínico.

    } +
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.ts new file mode 100644 index 0000000..e2e3b56 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-recurrencia.component.ts @@ -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(); + 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(null); + private readonly escenarioElegido = signal(null); + readonly horizonte = signal(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); } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.html new file mode 100644 index 0000000..08f6d46 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.html @@ -0,0 +1,26 @@ +
    +
    Análisis de supervivencia
    + @let m = menu(); + @if (m === undefined) {

    Buscando los escenarios clínicos…

    } + @if (m === null) {

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

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

    Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.

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

    Calculando con los datos más recientes…

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

    {{ $any(l).motivo }}

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

    No se pudo calcular la supervivencia de este escenario.

    } + @if (figura(); as figure) { } + } + } +
    +
    +
    Factores de riesgo
    + @if (lectura()?.tipo === 'lista') { } + @else {

    Se muestran al elegir un escenario clínico.

    } +
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts new file mode 100644 index 0000000..512bd71 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis-supervivencia.component.ts @@ -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(); + 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(null); + readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null); + readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of(null) : this.service.consulta(nombre).pipe( + map((datos): Lectura => ({ tipo: 'lista', datos })), + catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), + startWith({ 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); } +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.scss new file mode 100644 index 0000000..d4c2660 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.scss @@ -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; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts new file mode 100644 index 0000000..eb14a55 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-analisis.component.spec.ts @@ -0,0 +1,168 @@ +// 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'; + +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; + 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', () => { + 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('.horizons select')!.value).toBe('60'); + + elegir(f, 'Horizonte', '12'); + + expect(texto(f)).toContain('Marca=scanb-12'); + expect(texto(f)).not.toContain('Marca=scanb-60'); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts index 3867f52..b3a4f0f 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-curvas.service.ts @@ -70,6 +70,26 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas { }; } +/** 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; + 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 {} @@ -77,20 +97,23 @@ export class SeleccionRechazada extends Error {} export class CamaCurvasService { private readonly http = inject(HttpClient); - /** The clinical scenarios the patient belongs to (the whole cohort when she is in none), or `null` when there is no model in - * production or no cohort yet. */ - escenarios(pacId: string): Observable { - return this.http.get<{ escenarios: string[] }>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( - map(r => Array.isArray(r.escenarios) ? r.escenarios.filter(e => typeof e === 'string') : null), + /** 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 { + return this.http.get('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe( + map(r => { + if (!record(r) || !Array.isArray(r['escenarios'])) invalid(); + const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; }); + return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null }; + }), catchError(() => of(null)), ); } - /** The figure's record of one scenario (`null`: the whole cohort), scored with the production version over the data - * ingested so far. A refused scenario fails with `SeleccionRechazada` and its reason; any other failure is the error as it came. */ - consulta(escenario: string | null): Observable { + /** 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 { return this.http.post('/cama/modelo/curvas/consulta', { escenario }).pipe( - map(respuestaCurvas), + 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 ?? 'El escenario no se puede calcular.'))) : throwError(() => error)), diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.html new file mode 100644 index 0000000..8f54a9f --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.html @@ -0,0 +1,17 @@ +@if (hay()) { +

    Factores de riesgo de este escenario

    + @if (definitorios().length) { +
    +
      + @for (e of definitorios(); track e.texto) {
    • {{ e.texto }}
    • } +
    + } + @if (mayoritarios().length) { +
    +
      + @for (e of mayoritarios(); track e.texto) {
    • {{ e.texto }}
    • } +
    + } +} @else { +

    Sin factores de riesgo identificados en este escenario.

    +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.scss new file mode 100644 index 0000000..ba7c256 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.scss @@ -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; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.ts new file mode 100644 index 0000000..8e61ec7 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-factores-riesgo.component.ts @@ -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(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); +} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index a449fcc..949fd51 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -34,27 +34,24 @@
    - -

    Riesgo de muerte

    - - - -
    - @if (p.idField === 'pac_id') { - -

    Recurrencia

    - -
    - }

    Pronóstico y recomendaciones

    -
      - @for (item of placeholders; track item.key) { -
    • {{ item.label }}{{ prognosisUnavailable }}
    • - } -
    -

    {{ recommendationsUnavailable }}

    + @if (p.idField === 'pac_id') { } +
    +
    Recomendaciones
    +

    {{ recommendationsUnavailable }}

    +
    +
    +
    + +

    Riesgo de muerte

    + + @if (p.idField === 'pac_id') { } +
    +
    Recomendaciones
    +

    {{ recommendationsUnavailable }}

    +
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 1491def..34d00ad 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -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 = () => ({ ...complete(), pac_id: '7', id_seudonimo: null }); 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>; 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,18 @@ 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 a placeholder, with no figures, for the prognostic factors', () => { - montar(toCamaPatientSummary(complete(), '2026-10-20')!); - const items = [...root().querySelectorAll('[data-pronostico]')]; - expect(items.map(i => i.getAttribute('data-pronostico'))).toEqual(['factors']); - expect(items.map(i => i.querySelector('strong')!.textContent)).toEqual(['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(), '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 the record opens without moving focus to its title, which strands keyboard and screen-reader users. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index 2919444..eb09566 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -3,19 +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 { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component'; -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 recommendations are not available yet. */ @Component({ selector: 'app-cama-patient-card', - imports: [MatButtonModule, MatCardModule, MatIconModule, PacienteRiesgoTabla, CamaRecurrenciaPaciente], + imports: [MatButtonModule, MatCardModule, MatIconModule, CamaAnalisisRecurrencia, CamaAnalisisSupervivencia], templateUrl: './cama-patient-card.html', styleUrl: './cama-patient-card.scss', }) @@ -23,8 +24,6 @@ export class CamaPatientCard implements AfterViewInit { readonly summary = input.required(); readonly back = output(); readonly notAvailable = NOT_AVAILABLE; - readonly placeholders = PROGNOSIS_PLACEHOLDERS; - readonly prognosisUnavailable = PROGNOSIS_UNAVAILABLE; readonly recommendationsUnavailable = RECOMMENDATIONS_UNAVAILABLE; private readonly title = viewChild>('title'); readonly generating = signal(false); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index 78548ef..fc49e84 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -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 the prognostic factors (survival and recurrence are drawn in the record from the models' figures), 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 the 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 ['Factores pronóstico', PROGNOSIS_UNAVAILABLE, RECOMMENDATIONS_UNAVAILABLE]) expect(found).toContain(t); - expect(found.filter(t => t === PROGNOSIS_UNAVAILABLE)).toHaveLength(1); + 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. diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index c0a4fa4..2a948de 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -27,9 +27,11 @@ export interface CamaPatientSummary { daysMammographyToDiagnosis: number | null; } -/** Placeholders for results that exist only once a validated model and its clinical definition do (survival and recurrence are drawn - * from the models' figures, not placeholders). */ +/** 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.'; diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html deleted file mode 100644 index 0da5b1e..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.html +++ /dev/null @@ -1,10 +0,0 @@ -
    -
    Probabilidad de recurrencia
    - @let r = respuesta(); - @if (r === undefined) {

    Buscando los escenarios clínicos de recurrencia de la paciente…

    } - @if (r === null) {

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

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

    La paciente no cumple ninguno de los escenarios clínicos del análisis de recurrencia.

    } - @for (f of r.escenarios; track f.cohorte + f.escenario) { } - } -
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts deleted file mode 100644 index f0eda6e..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.spec.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Covers CaMa's recurrence figures in a patient's record: the boundary validation of `GET /cama/modelo/recurrencia` (a malformed -// answer never draws a partial curve), the figure of a scenario in the pipeline's style (the Greenwood band, the Kaplan-Meier steps, -// the solid and dotted Weibull, the diamonds with their interval, "Libre de recaída S(t)"), and the component's states. Fixtures: a -// figure like the recurrence version publishes, and a stub of `CamaRecurrenciaService`. -import { TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { vi } from 'vitest'; -import { PLOTLY_LOADER } from '../../../../shared/plotly/plotly-runtime'; -import { CamaRecurrenciaPaciente } from './cama-recurrencia-paciente.component'; -import { CamaRecurrenciaService, respuestaRecurrencia } from './cama-recurrencia.service'; -import { COLORES_RECURRENCIA, ETIQUETAS_RECURRENCIA, figuraRecurrencia } from './cama-recurrencia-figura'; - -const meses = Array.from({ length: 61 }, (_, i) => i); -const decreciente = (fin: number) => meses.map(m => 1 - (1 - fin) * (m / 60)); -const grilla = Array.from({ length: 289 }, (_, i) => i * 0.25); -function figura(escenario = 'RE− · grado 3', cohorte = 'metabric'): any { - return { - cohorte, cohorte_nombre: cohorte === 'scanb' ? 'SCAN-B' : 'METABRIC', escenario, condiciones: { Grado_histologico: ['3'] }, n: 300, recaidas: 180, - horizons_months: [12, 36, 60], observado_hasta: 60, months_max: 72, - km: { months: meses, S: decreciente(0.5), low: decreciente(0.45), high: decreciente(0.55) }, - weibull: { t: grilla, S: grilla.map(t => Math.exp(-t / 90)) }, weibull_fractional: { t: grilla, S: grilla.map(t => Math.exp(-t / 85)) }, - points: { COMB: { S: [0.9, 0.7, 0.55], low: [0.88, 0.67, 0.5], high: [0.92, 0.73, 0.6] } }, bootstrap_replicas: 200, - }; -} -const respuesta = (escenarios = [figura()]): any => ({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60], escenarios }); - -describe('Recurrencia CaMa: respuesta', () => { - // Fails if a record with an impossible value is accepted and drawn. - it('accepts an answer as published', () => { - expect(respuestaRecurrencia(respuesta()).escenarios[0].escenario).toBe('RE− · grado 3'); - }); - - it.each([ - ['a probability above 1', (d: any) => { d.escenarios[0].km.S[3] = 1.2; }], - ['an inverted interval', (d: any) => { d.escenarios[0].points.COMB.low[0] = 0.99; }], - ['a series with another number of horizons', (d: any) => { d.escenarios[0].points.COMB.S.pop(); }], - ['a missing curve', (d: any) => { delete d.escenarios[0].weibull_fractional; }], - ['no model version', (d: any) => { delete d.modelo.version; }], - ])('rejects %s', (_, estropear) => { - const d = respuesta(); - estropear(d); - expect(() => respuestaRecurrencia(d)).toThrow('Respuesta de recurrencia inválida'); - }); -}); - -describe('Recurrencia CaMa: figura', () => { - const f = () => figuraRecurrencia(respuestaRecurrencia(respuesta()).escenarios[0]); - const traza = (nombre: string) => f().data.find((t: any) => t.name === nombre) as any; - - // Fails if the figure loses a piece of the pipeline's chart. - it('has the Kaplan-Meier with its band, both Weibull and the diamonds with their interval', () => { - expect(f().data.some((t: any) => t.fill === 'tonexty')).toBe(true); - expect(traza(ETIQUETAS_RECURRENCIA.km).line).toMatchObject({ color: COLORES_RECURRENCIA.km, shape: 'hv' }); - expect(traza(ETIQUETAS_RECURRENCIA.weibull).line.color).toBe(COLORES_RECURRENCIA.weibull); - expect(traza(ETIQUETAS_RECURRENCIA.weibull_fraccional).line).toMatchObject({ color: COLORES_RECURRENCIA.fraccional, dash: 'dash' }); - const rombos = traza(ETIQUETAS_RECURRENCIA.puntos); - expect(rombos.x).toEqual([12, 36, 60]); - expect(rombos.error_y.array.map((v: number) => +v.toFixed(2))).toEqual([0.02, 0.03, 0.05]); - }); - - // Fails if the Weibull stops being dotted past the follow-up the cohort has, which would present an extrapolation as observed. - it('draws the Weibull dotted past the follow-up', () => { - const punteadas = f().data.filter((t: any) => t.line?.dash === 'dot') as any[]; - - expect(punteadas).toHaveLength(2); - expect(punteadas.every(t => Math.min(...t.x) >= 60)).toBe(true); - }); - - // Fails if the labels or the title leave the pipeline's: recurrence-free S(t), the scenario, the cohort, n and recurrences. - it('is titled with the scenario, the cohort, its patients and recurrences', () => { - const l = f().layout as any; - - expect(l.title.text).toBe('RE− · grado 3
    METABRIC · n=300, recaídas=180'); - expect(l.yaxis.title.text).toBe('Libre de recaída S(t)'); - expect(l.xaxis.title.text).toBe('Meses desde el diagnóstico'); - }); -}); - -describe('Recurrencia de la paciente: componente', () => { - let recurrencia: ReturnType; - 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()) }; - recurrencia = vi.fn(() => of(respuestaRecurrencia(respuesta([figura(), figura('Grado 3', 'scanb')])))); - TestBed.configureTestingModule({ providers: [{ provide: CamaRecurrenciaService, useValue: { recurrencia } }, - { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - }); - afterEach(() => vi.unstubAllGlobals()); - const montar = () => { - const f = TestBed.createComponent(CamaRecurrenciaPaciente); - f.componentRef.setInput('pacId', '7'); - f.detectChanges(); - f.detectChanges(); - return f; - }; - const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - - // Fails if a scenario she meets in either cohort has no figure. - it('draws a figure for each scenario she meets, in each cohort', () => { - const f = montar(); - - expect(recurrencia).toHaveBeenCalledWith('7'); - expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2); - }); - - // Fails if a patient in no scenario sees nothing, or an error. - it('says so when she meets none of the scenarios', () => { - recurrencia.mockReturnValue(of(respuestaRecurrencia(respuesta([])))); - const f = montar(); - - expect(texto(f)).toContain('no cumple ninguno de los escenarios clínicos'); - expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull(); - }); - - // Fails if no model in production is shown as an error or a blank. - it('says there is no recurrence model yet', () => { - recurrencia.mockReturnValue(of(null)); - - expect(texto(montar())).toContain('Todavía no hay un modelo de recurrencia en producción'); - }); -}); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts deleted file mode 100644 index 9761ee9..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia-paciente.component.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Component, computed, inject, input } from '@angular/core'; -import { toObservable, toSignal } from '@angular/core/rxjs-interop'; -import { switchMap } from 'rxjs'; -import { PlotlyChart } from '../../../../shared/plotly/plotly-chart'; -import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service'; -import { figuraRecurrencia } from './cama-recurrencia-figura'; - -/** One scenario's recurrence figure. */ -@Component({ - selector: 'app-cama-figura-recurrencia', - imports: [PlotlyChart], - template: `@if (figura(); as figure) { }`, -}) -export class CamaFiguraRecurrencia { - readonly datos = input.required(); - readonly figura = computed(() => figuraRecurrencia(this.datos())); -} - -/** - * The patient's probability of recurrence: the figure of each clinical scenario of the recurrence analysis that her covariates meet, - * in each external cohort (METABRIC and SCAN-B). Patients in one scenario share its figure; it describes that scenario's patients in - * the cohort the analysis was made on. - */ -@Component({ - selector: 'app-cama-recurrencia-paciente', - imports: [CamaFiguraRecurrencia], - templateUrl: './cama-recurrencia-paciente.component.html', -}) -export class CamaRecurrenciaPaciente { - readonly pacId = input.required(); - private readonly service = inject(CamaRecurrenciaService); - /** The answer; `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)))); -} diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts index 09886de..5811472 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-recurrencia.service.ts @@ -1,6 +1,7 @@ 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 @@ -13,7 +14,13 @@ export interface FiguraRecurrencia { 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[]; } +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 => !!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); @@ -39,15 +46,18 @@ 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, 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)) }; + 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 figures of the scenarios the patient meets, or `null` when there is no recurrence model in production or it fails. */ + /** 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 { return this.http.get('/cama/modelo/recurrencia', { params: { paciente: pacId } }).pipe( map(respuestaRecurrencia), catchError(() => of(null))); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html deleted file mode 100644 index 3276551..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.html +++ /dev/null @@ -1,9 +0,0 @@ -
    -
    Supervivencia
    - @let lista = escenarios(); - @if (lista === undefined) {

    Buscando los escenarios clínicos de la paciente…

    } - @if (lista === null) {

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

    } - @if (lista) { - @for (nombre of lista; track nombre) { } - } -
    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss deleted file mode 100644 index 5804c2c..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.scss +++ /dev/null @@ -1 +0,0 @@ -:host { display: block; } diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts deleted file mode 100644 index 37334ef..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.spec.ts +++ /dev/null @@ -1,142 +0,0 @@ -// Covers the patient's survival in her CaMa record: the figure of each clinical scenario she belongs to is computed live (one -// request per scenario, none for her own curve), a refused scenario says why, no model in production says so, and the figure -// has the SEER pipeline's look (the Greenwood band, the Kaplan-Meier steps, the two Weibull, the diamonds). Fixtures: a stub of -// `CamaCurvasService` that records each scenario asked, and a 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, figuraSupervivencia } from './cama-supervivencia-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)) }); -function respuesta(escenario = '< 45 años', n = 245): any { - return { - 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: {}, - }, - }; -} - -describe('Figura de supervivencia de un escenario', () => { - const figura = (r: any = respuesta()) => figuraSupervivencia(respuestaCurvas(r).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 diamonds with their bars. - it('has the 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 anything but the pipeline's own curves is drawn: the patient's own curve is not part of the figure. - it('draws only the pipeline\'s curves, none of the patient\'s own', () => { - expect(figura().data.map((t: any) => t.name).filter(Boolean).sort()).toEqual( - ['Kaplan-Meier (IC 95 % Greenwood)', 'LR + HBN combinado (IC 95 % bootstrap)', 'Weibull', 'Weibull fraccional'].sort()); - }); - - // Fails if the labels, the axes or the title leave the pipeline's: S(t), months from the diagnosis, the scenario, n and deaths. - it('is titled with the scenario, its patients and deaths, and scaled as the pipeline\'s figure', () => { - const l = figura().layout as any; - - expect(l.title.text).toBe('< 45 años
    n=245, fallecidos=67'); - 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.legend.yanchor).toBe('bottom'); - }); - - // Fails if a label the model's run publishes is ignored, which would take the wording out of the clinicians' hands. - it('takes the wording from the record when the model publishes it', () => { - const r = respuesta(); - r.curvas.etiquetas = { eje_y: 'Probabilidad de sobrevivir' }; - - expect((figura(r).layout as any).yaxis.title.text).toBe('Probabilidad de sobrevivir'); - }); -}); - -describe('Supervivencia de la paciente: componente', () => { - let consulta: ReturnType; - let escenarios: ReturnType; - 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((nombre: string | null) => of(respuesta(nombre ?? 'Toda la cohorte'))); - escenarios = vi.fn(() => of(['< 45 años', 'Jóvenes (<45) · HER2−'])); - TestBed.configureTestingModule({ providers: [ - { provide: CamaCurvasService, useValue: { escenarios, consulta } }, - { provide: PLOTLY_LOADER, useValue: () => Promise.resolve(runtime) }] }); - }); - afterEach(() => vi.unstubAllGlobals()); - const montar = () => { - const f = TestBed.createComponent(CamaSupervivenciaPaciente); - f.componentRef.setInput('pacId', '7'); - f.detectChanges(); - return f; - }; - const texto = (f: ReturnType) => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); - - // Fails if the patient's scenarios are not asked for her, or a scenario she is in has no figure. - it('draws the figure of each scenario the patient belongs to, asked live', () => { - const f = montar(); - f.detectChanges(); - - expect(escenarios).toHaveBeenCalledWith('7'); - expect(consulta.mock.calls.map(c => c[0])).toEqual(['< 45 años', 'Jóvenes (<45) · HER2−']); - expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(2); - }); - - // Fails if a patient in no scenario is left without a figure, or the whole cohort is asked as a named scenario. - it('asks for the whole cohort when the patient is in no scenario', () => { - escenarios.mockReturnValue(of(['Toda la cohorte'])); - const f = montar(); - f.detectChanges(); - - expect(consulta).toHaveBeenCalledExactlyOnceWith(null); - expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1); - }); - - // Fails if the record offers choices the reader did not ask for. - it('offers no choices', () => { - const f = montar(); - f.detectChanges(); - - expect(f.nativeElement.querySelector('input, fieldset, select')).toBeNull(); - }); - - // Fails if a refused scenario draws a figure, or does not say why. - it('says why when a scenario is refused and draws nothing for it', () => { - escenarios.mockReturnValue(of(['Estadio IV'])); - consulta.mockReturnValue(throwError(() => new SeleccionRechazada('El escenario tiene 3 pacientes y 0 defunciones.'))); - const f = montar(); - f.detectChanges(); - - expect(texto(f)).toContain('Estadio IV: El escenario tiene 3 pacientes'); - expect(f.nativeElement.querySelector('app-plotly-chart')).toBeNull(); - }); - - // Fails if no model in production is shown as an error or a blank. - it('says there is no model yet', () => { - escenarios.mockReturnValue(of(null)); - const f = montar(); - f.detectChanges(); - - expect(texto(f)).toContain('Todavía no hay un modelo de supervivencia en producción'); - expect(consulta).not.toHaveBeenCalled(); - }); -}); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts deleted file mode 100644 index 2fa52e7..0000000 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-supervivencia-paciente.component.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Component, computed, inject, input } 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, RespuestaCurvas, SeleccionRechazada } from './cama-curvas.service'; -import { figuraSupervivencia } from './cama-supervivencia-figura'; - -type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: RespuestaCurvas }; - -/** One clinical scenario's figure, computed when it is shown. */ -@Component({ - selector: 'app-cama-figura-escenario', - imports: [PlotlyChart], - template: ` - @let l = lectura(); - @if (l.tipo === 'cargando') {

    Calculando {{ escenario() }} con los datos más recientes…

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

    {{ escenario() }}: {{ l.motivo }}

    } - @if (l.tipo === 'error') {

    No se pudo calcular la supervivencia de {{ escenario() }}.

    } - @if (figura(); as figure) { }`, -}) -export class CamaFiguraEscenario { - readonly escenario = input.required(); - private readonly service = inject(CamaCurvasService); - readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => this.service.consulta(nombre === 'Toda la cohorte' ? null : nombre).pipe( - map((datos): Lectura => ({ tipo: 'lista', datos })), - catchError(error => of(error instanceof SeleccionRechazada ? { tipo: 'rechazada', motivo: error.message } : { tipo: 'error' })), - startWith({ tipo: 'cargando' })))), { initialValue: { tipo: 'cargando' } as Lectura }); - readonly figura = computed(() => { const l = this.lectura(); return l.tipo === 'lista' ? figuraSupervivencia(l.datos.curvas) : null; }); -} - -/** - * The patient's survival: the figure of each clinical scenario she belongs to (the whole cohort when she is in none), as the SEER - * pipeline draws them. Patients of one scenario share its figure; it is computed from the data ingested so far with the model - * in production. - */ -@Component({ - selector: 'app-cama-supervivencia-paciente', - imports: [CamaFiguraEscenario], - templateUrl: './cama-supervivencia-paciente.component.html', - styleUrl: './cama-supervivencia-paciente.component.scss', -}) -export class CamaSupervivenciaPaciente { - readonly pacId = input.required(); - private readonly service = inject(CamaCurvasService); - /** Her scenarios; `undefined` while they load, `null` when there is no model in production yet. */ - readonly escenarios = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id)))); -} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 19ca9ee..423dc9d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -1,12 +1,15 @@ // 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'; @@ -45,7 +48,9 @@ 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). @@ -72,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'); @@ -83,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'); }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 10a704c..30a796b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -38,9 +38,6 @@ } @else {

    Sin horizontes evaluados en el lote vigente.

    } - @if (dominio() === 'cama' && pacId(); as id) { - - } } }

    Recomendaciones no disponibles.

    diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index d7af53f..cd4626e 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -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', diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts index f52d03f..a7db11f 100644 --- a/src/app/features/indicadores/paciente-identidad.spec.ts +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -75,8 +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 also asks for the recurrence figures of the patient; there is no model for them here. - http.match(r => r.url === '/cama/modelo/recurrencia').forEach(r => { if (!r.cancelled) r.flush({ error: 'sin recurrencia' }, { status: 404, statusText: 'Not Found' }); }); + // 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; From 72e5f9bf93363c92bda723cfffcc265da49708b5 Mon Sep 17 00:00:00 2001 From: rockdrigo Date: Sat, 21 Nov 2026 14:57:30 -0600 Subject: [PATCH 21/21] CaMa record: the recurrence analysis only for patients after treatment --- .../paciente-detalle/cama/cama-patient-card.html | 2 +- .../cama/cama-patient-card.spec.ts | 14 ++++++++++++-- .../paciente-detalle/cama/cama-patient-card.ts | 4 +++- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 949fd51..eb4fcfc 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -37,7 +37,7 @@

    Pronóstico y recomendaciones

    - @if (p.idField === 'pac_id') { } + @if (p.idField === 'pac_id' && p.clinicalScenario === postTreatment) { }
    Recomendaciones

    {{ recommendationsUnavailable }}

    diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 34d00ad..d3dd5fe 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -14,7 +14,7 @@ import { CamaPatientSummary, RECOMMENDATIONS_UNAVAILABLE, toCamaPatientSummary } 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 = () => ({ ...complete(), pac_id: '7', id_seudonimo: 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. @@ -84,7 +84,7 @@ describe('Ficha CaMa: componente', () => { // 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(), '2026-10-20')!); + 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()); @@ -95,6 +95,16 @@ describe('Ficha CaMa: componente', () => { 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. it('moves focus to its title when it opens', () => { montar(toCamaPatientSummary(complete(), '2026-10-20')!); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts index eb09566..04c8d89 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.ts @@ -12,7 +12,7 @@ import { /** * 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 recommendations are not available yet. + * scenario at a time (the recurrence analysis only for patients after treatment); the recommendations are not available yet. */ @Component({ selector: 'app-cama-patient-card', @@ -24,6 +24,8 @@ export class CamaPatientCard implements AfterViewInit { readonly summary = input.required(); readonly back = output(); readonly notAvailable = NOT_AVAILABLE; + /** 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>('title'); readonly generating = signal(false);