From 68b5e927e7833e159edea0fae4ff3503f3d773df Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:04:13 -0600 Subject: [PATCH] CaCu follow-up table: the latest biopsy, and the probabilities of the status filtered A column with each patient's latest biopsy. The probability columns follow the follow-up status chosen, its scenario's models: a case shows survival, pre-colposcopy LIEAG+ and cancer, post-colposcopy and post-treatment LIEAG+, every patient none. A horizon selector, and an order by the most recent study or one of the columns shown, which the API applies to the whole list. --- .../indicadores/cacu-seguimiento.models.ts | 25 +++++++++- .../indicadores/cacu-seguimiento.service.ts | 15 +++++- .../indicadores/cacu-seguimiento.spec.ts | 48 ++++++++++++++++++- .../indicadores/indicadores-tracking.html | 18 ++++++- .../indicadores/indicadores-tracking.ts | 34 +++++++++++-- 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 4fbd27f..40e7fad 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,4 +1,6 @@ -export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } +export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia'; +export type OrdenSeguimiento = 'reciente' | ProbabilidadClave; +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } // A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`. export interface SeguimientoPaciente { @@ -9,13 +11,20 @@ export interface SeguimientoPaciente { ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; dias_toma_diagnostico: number | null; + /** CaCu: her latest biopsy reported by the cut-off, with its grade. */ + ultima_biopsia?: { fecha: string; grado: string | null } | null; + /** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */ + probabilidades?: Partial> | null; prioridad: SeguimientoStatus | null; } +export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; } export interface SeguimientoResponse { simulado: boolean; corte: string; ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string }; - filtros: { estatus: string | null }; + filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number }; + /** The horizons the models give, in years, for ordering and showing the probabilities. */ + horizontes_disponibles?: number[]; estatus_disponibles: SeguimientoStatus[]; reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[]; paginacion: { page: number; page_size: number; total_items: number; total_pages: number }; @@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string { export function latestStudy(item: SeguimientoPaciente): string | null { return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null; } +/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */ +export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined { + return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte); +} +/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival). + * Every patient or an unknown status shows none: each scenario has its own models. */ +export const COLUMNAS_DE_PROBABILIDAD: Readonly> = { + CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'], +}; +export const ETIQUETA_PROBABILIDAD: Readonly> = { + lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia', +}; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index d073b33..a1e68fc 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -7,6 +7,14 @@ import { PAGE_SIZE_MAX } from './seguimiento-tabla.service'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; +const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia']; +const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0; +const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1; +// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates. +const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string'); +const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) => + ['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad']) + && (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto'])))); export function validSeguimientoQuery(q: SeguimientoQuery) { return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX; } @@ -17,6 +25,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const p = v['paginacion'], window = v['ventana'], filters = v['filtros']; if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta']) || !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string') + || (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string)) + || (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios))) || !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status) || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages']) @@ -25,7 +35,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const c = item['ultima_citologia'], h = item['ultimo_vph']; return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) - && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); + && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])) + && biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']); }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @@ -37,6 +48,8 @@ export class CacuSeguimientoService { let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size); if (query.corte) params = params.set('corte', query.corte); if (query.estatus) params = params.set('estatus', query.estatus); + if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden); + if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte); return this.http.get('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse)); } } diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 679d629..e9e24c6 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -42,7 +42,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(root.textContent).toContain('Insatisfactoria'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte'); - expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8); + expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9); expect(root.querySelector('form input[name="corte"]')).not.toBeNull(); expect(root.querySelector('form select[name="meses"]')).not.toBeNull(); expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull(); @@ -97,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => { for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); http.expectNone(()=>true); }); + // Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the + // horizon stop reaching the API (the list is paginated, so ordering happens there). + it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' }, + probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }], + cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] }, + } : item); + const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } }; + open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const fila = root.querySelector('tbody tr')!; + expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %'); + expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)'); + expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']); + + fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1'); + req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges(); + expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)'); + }); + + // Fails if the columns stop following the status filtered: each scenario has its own models. + it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' }, + probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item); + const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } }; + open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim()); + expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)'); + expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false); + expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)'); + expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']); + + fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia'; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.has('orden')).toBe(false); + req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges(); + expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false); + expect(root.querySelector('select[name="orden"]')).toBeNull(); + }); }); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 0ad6b25..0af754a 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -48,6 +48,18 @@ @for (t of tiposAlteracion; track t.codigo) { } } + @if (dominio === 'cacu') { + @if (columnasDelEstatus(draft.estatus).length) { + + } + @if (columnasDelEstatus(draft.estatus).length) { + + } + } @@ -107,16 +119,18 @@
- + @for (c of columnasProbabilidad(); track c) {} @for (item of response.items; track identidad(item).id) { + + @for (c of columnasProbabilidad(); track c) { } - } @empty { } + } @empty { }
Resultados disponibles por paciente
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHÚltima biopsia{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)Estudio más recienteDías de toma a diagnósticoPrioridad
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible }@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}Fecha: {{ b.fecha }} } @else { No disponible }{{ probabilidad(item, c) ?? 'No disponible' }}{{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
No hay registros para los filtros aplicados.
No hay registros para los filtros aplicados.
diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 3c6d847..d49291a 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -5,7 +5,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service'; -import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion'; import { MatButtonModule } from '@angular/material/button'; import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; @@ -64,6 +65,28 @@ export class IndicadoresTracking implements OnChanges { private metadataLoaded = false; categories: Record = {}; draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 }; + /** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */ + horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; } + horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; } + readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD; + /** The probability columns of a follow-up status (its scenario's models); none for every patient. */ + columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] { + return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : []; + } + /** The probability columns of the list shown: those of the status it was filtered by. */ + columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); } + /** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */ + ordenes(): { codigo: string; etiqueta: string }[] { + return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' }, + ...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))]; + } + /** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */ + probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null { + const h = probabilidadAl(item, clave, this.horizonteMostrado()); + if (!h) return null; + const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : ''; + return `${porcentaje(h.probabilidad)} %${ic}`; + } private applied: SeguimientoQuery = { ...this.draft }; readonly latestStudy = latestStudy; readonly gruposEdad = GRUPOS_EDAD_TEA; @@ -87,7 +110,7 @@ export class IndicadoresTracking implements OnChanges { if (result.data) { const data = result.data; this.statuses = data.estatus_disponibles; - this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; + this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size }; this.draft = { ...this.applied }; if (!this.metadataLoaded) { this.metadataLoaded = true; @@ -131,7 +154,12 @@ export class IndicadoresTracking implements OnChanges { this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q }; (this.dominio === 'tea' ? this.teaRequests : this.requests).next(q); } - apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); } + apply() { + this.draft.page_size = acotarTamano(this.draft.page_size); + // an order by a column the chosen status doesn't show goes back to the most recent study + if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente'; + this.load({ ...this.draft, page: 1 }); + } retry() { this.load(this.applied); } navigate(page: number) { if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;