Compare commits

...

6 Commits

Author SHA1 Message Date
edgar 0fc80bd29a Merge remote-tracking branch 'origin/feature/163-cama-risk-curves' into feature/cohorts-dbt-canonical 2026-11-21 02:06:26 -06:00
rockdrigo dae8bc517e CaMa follow-up: the clinical scenario as Post-tratamiento or En observación in the list, the record and its PDF 2026-11-21 01:55:05 -06:00
edgar 7d180417d8 Merge dev into feature/cohorts-dbt-canonical
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:23:11 -06:00
edgar 00f773dd75 CaCu patient record reads the patient's FHIR RiskAssessment
The record asks GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id> 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:11:56 -06:00
edgar 3bb1c8dd84 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 23:02:48 -06:00
rockdrigo 7aa3d2c6e6 Stratified bars: a sidebar to show or hide each stratum, and the breakdown in counts or in percent of each stratum 2026-11-20 17:03:41 -06:00
20 changed files with 539 additions and 261 deletions
@@ -7,14 +7,19 @@ const HISTOLOGIA: Readonly<Record<string, string>> = {
BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ',
CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido',
};
const ESCENARIOS: Readonly<Record<string, string>> = { 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<Record<string, (codigo: string) => string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia };
const POR_CLAVE: Readonly<Record<string, (codigo: string) => 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);
@@ -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: `
<section class="figure-panel" [attr.aria-labelledby]="titleId">
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
@if (sidebar) {
<aside class="strata-sidebar" aria-label="Estratificación">
<fieldset class="sidebar-group">
<legend>Estratificar por</legend>
<div class="sidebar-list" role="radiogroup" aria-label="Dimensión de la distribución">
<button type="button" role="radio" [attr.aria-checked]="dimension === ''" [class.active]="dimension === ''"
(click)="changeDimension('')">Sin estratificar</button>
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
[disabled]="!singlePeriod" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null"
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para estratificar.</p> }
@if (dimension && estratos.length > 1) {
<fieldset class="sidebar-group">
<legend>Mostrar</legend>
<p class="sidebar-status" role="status" aria-live="polite">{{ ocultos.size ? (estratos.length - ocultos.size) + ' de ' + estratos.length : 'Todos los valores' }}</p>
<div class="sidebar-list" role="group" aria-label="Valores del estrato">
@for (e of estratos; track e.valor) {
<button type="button" class="stratum-toggle" [attr.aria-pressed]="!ocultos.has(e.valor)" [class.active]="!ocultos.has(e.valor)"
[disabled]="!ocultos.has(e.valor) && ocultos.size === estratos.length - 1"
(click)="toggleEstrato(e.valor)">{{ e.etiqueta }}</button>
}
</div>
<button type="button" class="sidebar-reset" [disabled]="!ocultos.size" (click)="mostrarTodos()">Mostrar todos</button>
</fieldset>
}
@if (dimension) {
<fieldset class="sidebar-group">
<legend>Medida</legend>
<div class="sidebar-list distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
</fieldset>
}
</aside>
}
<header class="panel-controls">
<p class="applied-summary">{{ independentPeriods ? 'Selección independiente' : 'Filtro general aplicado' }}: {{ appliedSummary }}</p>
@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' }}
</span>
}
@if (figuraId === 'fig_c2_barras' && capabilities.length) {
@if (figuraId === 'fig_c2_barras' && capabilities.length && !sidebar) {
<fieldset class="distribution-control" [attr.aria-describedby]="!singlePeriod ? distributionAvailabilityId : null">
<legend>Distribución</legend>
<div class="distribution-toggle" role="radiogroup" aria-label="Tipo de distribución">
@@ -49,10 +89,16 @@ import { MatTooltipModule } from '@angular/material/tooltip';
<div class="distribution-dimensions" role="radiogroup" aria-label="Dimensión estratificada">
@for (d of capabilities; track d) {
<button type="button" role="radio" [attr.aria-checked]="dimension === d" [class.active]="dimension === d"
(click)="changeDimension(d)">{{ d === 'grupo_edad' ? 'Por grupo de edad' : 'Por estatus de seguimiento' }}</button>
(click)="changeDimension(d)">{{ etiquetaDimension(indicador, d) }}</button>
}
</div>
}
@if (dimension) {
<div class="distribution-dimensions distribution-medida" role="radiogroup" aria-label="Medida por estrato">
<button type="button" role="radio" [attr.aria-checked]="medida === 'conteo'" [class.active]="medida === 'conteo'" (click)="changeMedida('conteo')">Conteos</button>
<button type="button" role="radio" [attr.aria-checked]="medida === 'porcentaje'" [class.active]="medida === 'porcentaje'" (click)="changeMedida('porcentaje')">Porcentaje en cada estrato</button>
</div>
}
</fieldset>
@if (!singlePeriod) { <p class="distribution-note" [id]="distributionAvailabilityId" role="status">Selecciona un periodo para consultar la distribución estratificada.</p> }
}
@@ -71,8 +117,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
@if (hasSuppressedCells) { <p role="status">Hay celdas suprimidas: no se dibuja su magnitud y no representan un cero. Consulta su estado en la tabla de valores.</p> }
@if (hasMissingCells) { <p role="status">Hay datos no disponibles; los espacios sin barra no representan un cero observado.</p> }
<details><summary>Valores publicados</summary>
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td></tr> }
<div class="cells"><table><thead><tr><th>Categoría</th><th>Estrato</th><th>Conteo</th><th>Porcentaje del estrato</th></tr></thead><tbody>
@for (cell of cells; track $index) { <tr><td>{{ cell.category }}</td><td>{{ cell.stratum }}</td><td>{{ cell.status === 'Publicado' ? cell.value : cell.status }}</td><td>{{ cell.percent === null ? '—' : cell.percent + ' %' }}</td></tr> }
</tbody></table></div>
</details>
@if (!cells.length) { <p role="status">No hay categorías publicadas para esta selección.</p> }
@@ -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<string>();
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';
@@ -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<string, unknown>[];
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.
@@ -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<typeof TestBed.createComponent<IndicadorFigurePanel>>, 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('&lt;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);
});
});
@@ -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<string, Record<string, unknown>>)['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' });
});
});
@@ -4,30 +4,53 @@ import { c2Theme, seriesColors } from './indicadores-c2-palette';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// 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<string> = 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<string, { order: number; label: string; color?: string; parent?: string }>();
const rows = new Map<string, Record<string, unknown>>();
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<string, unknown>[] : [];
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}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), 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 };
@@ -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; }
@@ -11,6 +11,7 @@
<dl class="summary">
<div><dt>{{ p.idLabel }}</dt><dd>{{ p.patientId }}</dd></div>
<div><dt>Grupo de edad</dt><dd>{{ p.ageGroup ?? notAvailable }}</dd></div>
<div><dt>Escenario clínico</dt><dd>{{ p.clinicalScenario ?? notAvailable }}</dd></div>
<div><dt>Estatus de seguimiento</dt><dd>{{ p.status ?? notAvailable }}</dd></div>
<div><dt>Prioridad</dt><dd>{{ p.priority ?? notAvailable }}</dd></div>
<div><dt>Días de mastografía a diagnóstico</dt><dd>{{ p.daysMammographyToDiagnosis ?? notAvailable }}</dd></div>
@@ -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'],
});
@@ -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],
@@ -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']),
@@ -8,33 +8,13 @@
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
@case ('disponible') {
<p class="simulated-label" id="riesgo-simulado">Información simulada · Entorno DEV · Sin evaluación clínica</p>
@if (lectura.datos.cohorte; as cohorte) {
<h5>Cohorte</h5>
<dl class="metadata">
<div><dt>Definición de cohorte</dt><dd>{{ cohorte.url }}</dd></div>
<div><dt>Versión de cohorte</dt><dd>{{ cohorte.version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ cohorte.fecha_indice }}</dd></div>
</dl>
<details>
<summary>Variables del modelo PIMM</summary>
<p class="availability">Códigos técnicos del modelo; no constituyen un diagnóstico.</p>
<dl class="metadata">
<div><dt>tipo_censura</dt><dd>{{ cohorte.tipo_censura ?? 'No disponible' }}</dd></div>
<div><dt>c (estado basal)</dt><dd>{{ cohorte.c ?? 'No disponible' }}</dd></div>
<div><dt>l (años desde índice)</dt><dd>{{ cohorte.l ?? 'No disponible' }}</dd></div>
<div><dt>r (años desde índice)</dt><dd>{{ cohorte.r ?? 'No disponible' }}</dd></div>
<div><dt>pap_0 (citología índice)</dt><dd>{{ cohorte.pap_0 ?? 'No disponible' }}</dd></div>
<div><dt>hpv_0 (VPH índice)</dt><dd>{{ cohorte.hpv_0 ?? 'No disponible' }}</dd></div>
</dl>
</details>
} @else {
<p role="status">Sin membresía en la cohorte vigente.</p>
}
@if (lectura.datos.riesgo; as riesgo) {
@let riesgo = lectura.datos.riesgo;
<h5>Modelo y evaluación</h5>
<dl class="metadata">
<div><dt>Modelo</dt><dd>{{ riesgo.modelo_nombre }}</dd></div>
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
</dl>
@@ -46,7 +26,6 @@
<th scope="col">Horizonte (años)</th>
<th scope="col">Probabilidad (%)</th>
<th scope="col">Intervalo de confianza (%)</th>
<th scope="col">Estado de evaluación</th>
</tr></thead>
<tbody>
@for (h of riesgo.horizontes; track h.horizonte_anios) {
@@ -54,14 +33,12 @@
<th scope="row">{{ h.horizonte_anios }}</th>
<td class="percentage">{{ h.probabilidad * 100 | number:'1.0-4' }} %</td>
<td class="interval">@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }</td>
<td>{{ h.estado === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</td>
</tr>
}
</tbody>
</table>
</div>
} @else { <p role="status">Sin horizontes evaluados en el lote vigente.</p> }
} @else { <p role="status">Sin riesgo disponible: no hay lote vigente.</p> }
}
}
<p class="recommendations">Recomendaciones no disponibles.</p>
@@ -1,46 +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/<pac_id>`). */
export interface LoteRiesgoCacu {
lote_id: number;
/** The resource's id, `<lote_id>-<pac_id>`. */
id: string;
modelo_nombre: string;
modelo_version: string;
/** 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<unknown>;
}
@@ -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/<pac_id>`, 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>('PacienteRiesgoProvider', {
providedIn: 'root', factory: () => {
const http = inject(HttpClient);
return {
obtener: (pacId: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe(
obtener: (pacId: string) => http.get<unknown>('/cacu/fhir/RiskAssessment', {
params: new HttpParams().set('subject', `Patient/${pacId}`),
}).pipe(
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
),
};
@@ -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,27 +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', '2023-04-15', '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 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);
});
@@ -67,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']);
@@ -86,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');
@@ -118,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);
@@ -134,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<unknown>(), 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);
});
@@ -14,8 +14,10 @@ export class PacienteRiesgoState {
readonly pacId = signal<string | null | undefined>(undefined);
readonly estado = toSignal(toObservable(this.pacId).pipe(
switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of<PacienteRiesgoEstado>({ 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<PacienteRiesgoEstado>({ tipo: 'error' })),
startWith(CARGANDO),
)),
@@ -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',
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 },
],
},
};
@@ -1,121 +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],
['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();
@@ -1,54 +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<string, unknown> => !!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<string, unknown>): { 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;
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<string, unknown>): 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. */
@@ -147,7 +147,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR
}),
};
}
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true };
const ETIQUETADAS: Readonly<Record<string, true>> = { birads: true, grupo_edad: true, biopsia: true, escenario_clinico: true };
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {