diff --git a/src/app/features/indicadores/barras-horizontales.spec.ts b/src/app/features/indicadores/barras-horizontales.spec.ts new file mode 100644 index 0000000..a36c4f2 --- /dev/null +++ b/src/app/features/indicadores/barras-horizontales.spec.ts @@ -0,0 +1,85 @@ +import { TestBed } from '@angular/core/testing'; +import { BarrasHorizontales } from './barras-horizontales'; +import { ConjuntoBarras, FilaBarra, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras'; + +const fila = (id: string, etiqueta: string, n: number | null, estado: FilaBarra['estado'] = 'Publicado'): FilaBarra => ({ id, etiqueta, n, estado, color: '#438B53' }); +const suma = (fs: FilaBarra[]) => fs.some(f => f.n === null) ? null : fs.reduce((s, f) => s + f.n!, 0); +// Cytology with more than 95 % normal results: the others are small counts, one of them a single record. +const normales = [fila('NORMAL', 'Normal', 912)]; +const anormales = [fila('ASC-US', 'ASC-US', 14), fila('LIEBG', 'LIEBG', 9), fila('ASC-H', 'ASC-H', 3), fila('LIEAG', 'LIEAG', 5), fila('CIS', 'Carcinoma in situ', 1)]; +const citologia = (activas: string[] | null = null): ConjuntoBarras => ({ den: 944, unidad: 'pacientes con resultado', activas: activas ? new Set(activas) : null, grupos: [ + { id: 'SIN', etiqueta: 'Sin anomalía', color: '#247A71', subtotal: 912, filas: normales }, { id: 'ANORMAL', etiqueta: 'Anormal', color: '#656677', subtotal: suma(anormales), filas: anormales }] }); +const plano = (filas: FilaBarra[], den: number | null): ConjuntoBarras => ({ den, unidad: 'reportes de VPH elegibles', activas: null, grupos: [{ id: null, etiqueta: null, color: '#8A9199', subtotal: den, filas }] }); + +describe('Barras horizontales: escala', () => { + it('el límite es un número redondo y par que contiene la barra o el subtotal más largo', () => { + expect([0, 1, 5, 44, 63, 912, 946, 1892].map(limiteEscala)).toEqual([2, 2, 6, 50, 80, 1000, 1000, 2000]); + expect(maximoDelConjunto(citologia())).toBe(912); + // A group's subtotal can exceed its categories: the scale holds it. + expect(maximoDelConjunto({ den: 108, unidad: 'x', activas: null, grupos: [{ id: 'g', etiqueta: 'g', color: '#000', subtotal: 63, filas: [fila('a', 'a', 44), fila('b', 'b', 13), fila('c', 'c', 6)] }] })).toBe(63); + }); + it('la suma de lo seleccionado es nula sin selección o con una celda desconocida', () => { + expect(sumaActivas(citologia())).toBeNull(); expect(sumaActivas(citologia(['ASC-US', 'CIS']))).toBe(15); + expect(sumaActivas({ ...plano([fila('a', 'a', null, 'Suprimido'), fila('b', 'b', 2)], 2), activas: new Set(['a', 'b']) })).toBeNull(); + }); +}); + +describe('Barras horizontales: componente', () => { + beforeEach(() => TestBed.configureTestingModule({})); + function montar(conjunto: ConjuntoBarras) { + const f = TestBed.createComponent(BarrasHorizontales); + f.componentRef.setInput('conjunto', conjunto); f.componentRef.setInput('titulo', 'Resultados'); f.detectChanges(); + return f.nativeElement as HTMLElement; + } + const texto = (e: Element | null) => (e?.textContent ?? '').replace(/\s+/g, ' ').trim(); + const filas = (r: HTMLElement) => [...r.querySelectorAll('.filas .fila')]; + + it('denominador y unidad, escala absoluta rotulada y sin barra de longitud artificial', () => { + const r = montar(citologia()); + expect(texto(r.querySelector('.den'))).toContain('Total: 944 pacientes con resultado'); expect(texto(r.querySelector('.titulo-eje'))).toBe('Escala: cantidad de pacientes con resultado (de 0 a 1,000)'); + expect([...r.querySelectorAll('.marcas span')].map(x => x.textContent)).toEqual(['0', '500', '1,000']); + const ancho = (etiqueta: string) => (filas(r).find(x => texto(x).startsWith(etiqueta))!.querySelector('.pista i') as HTMLElement).style.width; + expect(ancho('Normal')).toBe('91.2%'); expect(ancho('ASC-US')).toBe('1.4%'); expect(ancho('Carcinoma in situ')).toBe('0.1%'); + // The count and the percentage are always written, whatever the bar length. + expect(filas(r).map(x => texto(x))).toEqual(['Normal 912 96.6 %', 'ASC-US 14 1.5 %', 'LIEBG 9 1.0 %', 'ASC-H 3 0.3 %', 'LIEAG 5 0.5 %', 'Carcinoma in situ 1 0.1 %']); + }); + it('un valor demasiado corto para verse lleva un marcador hueco en su posición, sin alargar la barra', () => { + const r = montar(citologia()); + const ci = filas(r).find(x => texto(x).startsWith('Carcinoma'))!; + expect((ci.querySelector('.minima') as HTMLElement).style.left).toBe('0.1%'); + expect(filas(r).find(x => texto(x).startsWith('Normal'))!.querySelector('.minima')).toBeNull(); + expect(filas(r).find(x => texto(x).startsWith('ASC-US'))!.querySelector('.minima')).not.toBeNull(); + }); + it('los grupos son encabezados con su subtotal y no cuentan como categorías de la distribución', () => { + const r = montar(citologia()); + const grupos = [...r.querySelectorAll('.grupo')]; + expect(grupos.map(g => g.getAttribute('aria-label'))).toEqual(['Sin anomalía', 'Anormal']); + expect(grupos.map(g => texto(g.querySelector('.cabecera')))).toEqual(['Grupo Sin anomalía 912 96.6 %', 'Grupo Anormal 32 3.4 %']); + expect(filas(r)).toHaveLength(6); expect(r.querySelectorAll('.cabecera')).toHaveLength(2); + // The subtotals add up to the total once, never together with their categories. + expect(912 + 32).toBe(944); + }); + it('un cero publicado tiene marca punteada y ninguna barra; lo no disponible se rotula y no es cero', () => { + const r = montar(plano([fila('a', 'Negativo', 5), fila('b', 'Positivo 16 y 18', 0), fila('c', 'Indeterminado', null, 'No disponible'), fila('d', 'Otro', null, 'Suprimido')], 5)); + const [a, b, c, d] = filas(r); + expect(b.querySelector('.pista i')).toBeNull(); expect(b.querySelector('.cero-marca')).not.toBeNull(); expect(texto(b)).toBe('Positivo 16 y 18 0 0.0 %'); + expect(c.classList.contains('nd')).toBe(true); expect(c.querySelector('.pista i')).toBeNull(); expect(texto(c)).toBe('Indeterminado No disponible'); expect(texto(d)).toBe('Otro Suprimido'); + expect(a.querySelector('.cero-marca')).toBeNull(); expect(c.querySelector('.cero-marca')).toBeNull(); + }); + it('sin denominador se muestran las cantidades y se dice que el porcentaje no está disponible', () => { + const r = montar(plano([fila('a', 'Negativo', 5)], null)); + expect(texto(r.querySelector('.den'))).toContain('no disponible'); expect(texto(filas(r)[0])).toBe('Negativo 5 % no disponible'); + }); + it('la selección atenúa lo no seleccionado y dice cuánto suma; sin selección nada se atenúa', () => { + const r = montar(citologia(['ASC-US', 'CIS'])); + expect(filas(r).filter(x => x.classList.contains('atenuada')).map(x => texto(x).split(' ')[0])).toEqual(['Normal', 'LIEBG', 'ASC-H', 'LIEAG']); + expect(r.querySelectorAll('.cabecera.atenuada')).toHaveLength(1); expect(texto(r.querySelector('.seleccion'))).toBe('Selección: 15 de 944 (1.6 %)'); + const s = montar(citologia()); expect(s.querySelectorAll('.atenuada')).toHaveLength(0); expect(s.querySelector('.seleccion')).toBeNull(); + }); + it('accesibilidad: el nombre del conjunto, barras decorativas y cada dato leído una sola vez', () => { + const r = montar(citologia()); + expect(r.querySelector('[role=group]')!.getAttribute('aria-label')).toBe('Resultados'); + expect([...r.querySelectorAll('.pista, .eje')].every(e => e.getAttribute('aria-hidden') === 'true')).toBe(true); + expect(r.querySelectorAll('[role=img]')).toHaveLength(0); expect(r.querySelectorAll('[aria-label]:not(.barras):not(.grupo)')).toHaveLength(0); + }); +}); diff --git a/src/app/features/indicadores/barras-horizontales.ts b/src/app/features/indicadores/barras-horizontales.ts new file mode 100644 index 0000000..ef4507e --- /dev/null +++ b/src/app/features/indicadores/barras-horizontales.ts @@ -0,0 +1,98 @@ +import { Component, computed, input } from '@angular/core'; +import { NgTemplateOutlet } from '@angular/common'; +import { shareText } from './indicadores-format'; +import { ConjuntoBarras, FilaBarra, GrupoBarras, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras'; + +/** + * Horizontal bars of one indicator: a bar per category with its name at the left and «count · % of the total» at the + * right, clinical groups as headers with their subtotal. The scale is the absolute count, from 0 to a rounded upper + * limit that is written under the bars; the bar of a value is exactly its share of that limit (no minimum length). + * A value too short to see keeps its figure and gets a hollow marker at its position; a published zero has a dotted + * tick and no bar; an unavailable value has a hatched track and says so. + */ +@Component({ + selector: 'app-barras-horizontales', + imports: [NgTemplateOutlet], + template: ` + @let c = conjunto(); +
+

@if (c.den !== null) { Total: {{ c.den.toLocaleString('es-MX') }} {{ c.unidad }}. Barras en cantidades; porcentaje del total. } @else { Total de {{ c.unidad }} no disponible: se muestran las cantidades publicadas, sin porcentaje. }

+ @if (seleccionado(); as s) {

Selección: {{ s.toLocaleString('es-MX') }}@if (c.den !== null) { de {{ c.den.toLocaleString('es-MX') }} ({{ pct(s) }}) }

} + @for (g of c.grupos; track g.id ?? $index) { + @if (g.etiqueta) { +
+
+ Grupo {{ g.etiqueta }}{{ ' ' }} + {{ ' ' }} + @if (g.subtotal !== null) { {{ g.subtotal.toLocaleString('es-MX') }}{{ ' ' }}@if (c.den !== null) { {{ pct(g.subtotal) }} } } @else { No disponible } +
+ +
+ } @else { + + } + } + +

Escala: cantidad de {{ c.unidad }} (de 0 a {{ limite().toLocaleString('es-MX') }})

+
+ +
  • + {{ f.etiqueta }}{{ ' ' }} + + @if (f.n === null) { {{ f.estado === 'Suprimido' ? 'Suprimido' : 'No disponible' }} } + @else { {{ f.n.toLocaleString('es-MX') }}{{ ' ' }}@if (c.den !== null) { {{ pct(f.n) }} } @else { % no disponible } } +
  • +
    + `, + styles: ` + :host { display: block; min-width: 0; container-type: inline-size; } + .den, .seleccion, .titulo-eje { margin: 0 0 .4rem; font-size: .85rem; color: var(--issste-text-secondary); } + .den strong, .seleccion strong { color: var(--issste-text); } + .titulo-eje { margin: .15rem 0 0; font-size: .75rem; } + ul { margin: 0; padding: 0; list-style: none; } + .filas { display: grid; gap: .3rem; } + .fila { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; align-items: center; gap: .5rem; transition: opacity .15s; } + .fila.atenuada { opacity: .45; } + .et { font-size: .85rem; line-height: 1.2; overflow-wrap: anywhere; } + .pista { position: relative; height: 1rem; background: linear-gradient(90deg, var(--issste-border) 1px, transparent 1px) 0 0 / 50% 100% repeat-x, linear-gradient(270deg, var(--issste-border) 1px, transparent 1px); } + .pista i { position: absolute; inset: 0 auto 0 0; background: var(--c); border-radius: 0 2px 2px 0; } + .minima { position: absolute; top: 50%; width: .5rem; height: .5rem; box-sizing: border-box; border: 2px solid var(--c); border-radius: 50%; background: var(--issste-surface); transform: translate(-50%, -50%); } + .cero-marca { position: absolute; inset: .15rem auto .15rem 0; border-left: 2px dotted var(--c); } + .nd .pista { background: repeating-linear-gradient(45deg, var(--issste-border) 0 4px, var(--issste-surface) 4px 8px); } + .v { text-align: end; font-variant-numeric: tabular-nums; font-size: .85rem; white-space: nowrap; } + .v small { margin-inline-start: .3rem; color: var(--issste-text-secondary); font-size: .8rem; } + .grupo { margin-top: .5rem; } + .cabecera { font-weight: 600; } + .cabecera .pista { height: .4rem; background: var(--issste-border); } + .cabecera .pista i { opacity: .45; border-radius: 0; } + .marca-grupo { display: inline-block; margin-inline-end: .25rem; padding: 0 .3rem; border: 1px solid currentColor; border-radius: 3px; font-size: .65rem; font-weight: 500; color: var(--issste-text-secondary); text-transform: uppercase; } + .hijas { margin: .25rem 0 0; padding-inline-start: .75rem; border-inline-start: 3px solid var(--c); } + .eje { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; gap: .5rem; margin-top: .25rem; font-size: .7rem; color: var(--issste-text-secondary); } + .marcas { display: flex; justify-content: space-between; } + @container (max-width: 25rem) { + .fila, .eje { grid-template-columns: minmax(0, 1fr) auto; row-gap: .1rem; } + .fila .pista { grid-column: 1 / -1; grid-row: 2; } + .eje > span:first-child, .eje > span:last-child { display: none; } + .eje { grid-template-columns: 1fr; } + .hijas { padding-inline-start: .5rem; } + } + `, +}) +export class BarrasHorizontales { + readonly conjunto = input.required(); + /** Accessible name of the whole chart. */ + readonly titulo = input.required(); + readonly limite = computed(() => limiteEscala(maximoDelConjunto(this.conjunto()))); + readonly seleccionado = computed(() => sumaActivas(this.conjunto())); + ancho(n: number) { return 100 * n / this.limite(); } + pct(n: number) { const d = this.conjunto().den; return d ? shareText(n, d) : ''; } + /** With a selection, what is not selected is dimmed, as the donut did. */ + atenuado(x: FilaBarra | GrupoBarras) { + const a = this.conjunto().activas; + if (!a) return false; + return 'filas' in x ? !x.filas.some(f => a.has(f.id)) : !a.has(x.id); + } +} diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 40e7fad..74ac433 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,12 +1,22 @@ +import { RutaResumen } from './ruta-tamizaje/ruta-tamizaje'; 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 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; + /** CaCu: partial identifier search, applied by the server before it counts and paginates. */ + q?: string; + /** CaCu: asks for the screening route block of each row. */ + incluir?: 'ruta_tamizaje'; + /** CaCu: inclusive age range at the cut-off date, applied by the server. */ + edad_min?: number; edad_max?: number; + 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 { pac_id?: string; id_seudonimo?: string; grupo_edad: string; + /** CaCu: her age in whole years at the cut-off date (`edad_al_corte`), when the service gives it. */ + edad_al_corte?: number | null; estatus: SeguimientoStatus; ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; @@ -16,13 +26,16 @@ export interface SeguimientoPaciente { /** 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; + /** CaCu: present only when the list was asked `incluir=ruta_tamizaje`; null when the row has no selected cytology. */ + ruta_tamizaje?: RutaResumen | 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; orden?: OrdenSeguimiento; horizonte?: number }; + /** `q`, `edad_min` and `edad_max` are the parameters the server applied (null: none); older servers omit them. */ + filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number; q?: string | null; edad_min?: number | null; edad_max?: number | null }; /** The horizons the models give, in years, for ordering and showing the probabilities. */ horizontes_disponibles?: number[]; estatus_disponibles: SeguimientoStatus[]; @@ -35,6 +48,38 @@ export function isoDate(value: unknown): value is string { const date = new Date(value + 'T00:00:00Z'); return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value; } +/** Her exact age in whole years; null when the service does not give one. It is never derived from the age group. */ +export function edadAnios(item: Pick): number | null { + const edad = item.edad_al_corte; + return typeof edad === 'number' && Number.isInteger(edad) && edad >= 0 ? edad : null; +} +export function edadTexto(item: Pick): string { + const edad = edadAnios(item); + return edad === null ? 'No disponible' : `${edad} ${edad === 1 ? 'año' : 'años'}`; +} +/** The search text as sent: trimmed, inner whitespace collapsed; empty means no search. */ +export function normalizarConsulta(texto: string | undefined): string { return (texto ?? '').trim().replace(/\s+/g, ' '); } +/** The search text WebApi admits, in characters, once normalized. */ +export const CONSULTA_MAXIMA = 100; +/** A bound is a whole number of years, 0 or more (as WebApi admits); the range needs min <= max. */ +export function rangoEdadValido(min: number | undefined, max: number | undefined): boolean { + const entero = (n: number | undefined) => n === undefined || (Number.isInteger(n) && n >= 0); + return entero(min) && entero(max) && (min === undefined || max === undefined || min <= max); +} +/** True when a returned row breaks the query it answers: the server did not apply the search or the age range. */ +export function incumpleConsulta(q: Pick, id: string, item: Pick): boolean { + const texto = normalizarConsulta(q.q).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase(); + if (texto && !id.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().includes(texto)) return true; + const edad = edadAnios(item); + // Under an age range a row with no age is outside the contract: WebApi leaves those out. + if (q.edad_min === undefined && q.edad_max === undefined) return false; + return edad === null || (q.edad_min !== undefined && edad < q.edad_min) || (q.edad_max !== undefined && edad > q.edad_max); +} +/** The search and age range the server says it applied, against the ones asked: every active parameter must come back equal. */ +export function filtrosConfirmados(q: Pick, filtros: SeguimientoResponse['filtros']): boolean { + const texto = normalizarConsulta(q.q); + return (!texto || filtros.q === texto) && (q.edad_min === undefined || filtros.edad_min === q.edad_min) && (q.edad_max === undefined || filtros.edad_max === q.edad_max); +} export function latestStudy(item: SeguimientoPaciente): string | null { return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null; } diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index a1e68fc..7fcec24 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -1,13 +1,16 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; -import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; +import { CONSULTA_MAXIMA, isoDate, normalizarConsulta, rangoEdadValido, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; import { identidadDe, identidadesDe } from './paciente-identidad'; +import { RutaDetalle, rutaDetalleValida, rutaResumenValida, urlDetalleValida } from './ruta-tamizaje/ruta-tamizaje'; 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']; +// The exact age is optional: an API that does not give it still validates, and the table says so. +const edad = (v: unknown) => v === undefined || v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 130; 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. @@ -16,7 +19,8 @@ const probabilidades = (p: unknown) => p === undefined || p === null || record(p ['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; + 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 + && rangoEdadValido(q.edad_min, q.edad_max) && normalizarConsulta(q.q).length <= CONSULTA_MAXIMA; } export function seguimientoResponse(v: unknown): SeguimientoResponse { // The current authorization covers demonstration records only. Validate this @@ -25,24 +29,32 @@ 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['q'] !== undefined && filters['q'] !== null && typeof filters['q'] !== 'string') + || !edad(filters['edad_min']) || !edad(filters['edad_max']) || (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']) || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => { - if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; + if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !edad(item['edad_al_corte']) || !status(item['estatus'])) return false; 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'])) - && biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']); + && biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']) + && (item['ruta_tamizaje'] === undefined || item['ruta_tamizaje'] === null || rutaResumenValida(item['ruta_tamizaje'])); }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @Injectable({ providedIn: 'root' }) export class CacuSeguimientoService { private readonly http = inject(HttpClient); + /** The detail of one route, from the `detalle_url` of the list; only a path of this service's own routes is requested. */ + detalleRuta(url: string) { + if (!urlDetalleValida(url)) throw new Error('Ruta de detalle inválida'); + return this.http.get(url).pipe(map((v): RutaDetalle => { if (!rutaDetalleValida(v)) throw new Error('Detalle de ruta inválido'); return v; })); + } consultar(query: SeguimientoQuery) { if (!validSeguimientoQuery(query)) throw new Error('Parámetros de seguimiento inválidos'); let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size); @@ -50,6 +62,11 @@ export class CacuSeguimientoService { 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); + const q = normalizarConsulta(query.q); + if (q) params = params.set('q', q); + if (query.edad_min !== undefined) params = params.set('edad_min', query.edad_min); + if (query.edad_max !== undefined) params = params.set('edad_max', query.edad_max); + if (query.incluir) params = params.set('incluir', query.incluir); 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 291a2af..bcd89e2 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -4,6 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common import fixtureData from './fixtures/cacu_seguimiento.json'; import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service'; import { latestStudy } from './cacu-seguimiento.models'; +import { tablaExportacionCaCu } from './export/cacu-tracking-export'; import { IndicadoresTracking } from './indicadores-tracking'; describe('Seguimiento CaCu con contrato de demostración', () => { @@ -24,10 +25,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order); fixture.componentInstance.apply(); let req = http.expectOne(r => r.url === '/cacu/seguimiento'); - expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']); + expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']); req.flush(fixtureData); fixture.detectChanges(); fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento'); - expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']); + expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']); expect(req.request.params.get('page')).toBe('2'); req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } }); }); @@ -78,61 +79,214 @@ describe('Seguimiento CaCu con contrato de demostración', () => { fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true); expect(fixture.componentInstance.data?.paginacion.page).toBe(2); }); - it('busca parcialmente por identificador en la página, conserva la búsqueda al paginar y permite limpiarla', () => { - const items = fixtureData.items.slice(0, 2).map((item, i) => ({ ...item, id_seudonimo: ['PRUEBA-Á42', 'PRUEBA-73'][i] })); - const pagina = { ...fixtureData, items }; - open().flush(pagina); - http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); - fixture.detectChanges(); - const root: HTMLElement = fixture.nativeElement; + // API-01: the search and the age range are the server's; WebApp sends them, shows what comes back and nothing else. + describe('búsqueda global y rango de edad', () => { + const consultas = () => http.match(r => r.url === '/cacu/seguimiento'); const escribir = (texto: string) => { - const input = root.querySelector('input[type="search"]')!; - input.value = texto; - input.dispatchEvent(new Event('input', { bubbles: true })); - fixture.detectChanges(); + const input = fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement; + input.value = texto; input.dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges(); }; - escribir(' a42 '); - expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1); - expect(root.querySelector('tr[data-paciente]')?.textContent).toContain('PRUEBA-Á42'); - expect(root.querySelector('#alcance-busqueda-cacu')?.textContent).toContain('1 de 2 registros de esta página'); - http.expectNone(() => true); + const filas = () => [...fixture.nativeElement.querySelectorAll('tr[data-paciente]')].map((tr: Element) => tr.getAttribute('data-paciente')); + const respuesta = (ids: string[], extra: object = {}) => ({ ...fixtureData, ...extra, + items: ids.map((id, i) => ({ ...fixtureData.items[i], id_seudonimo: id, edad_al_corte: 45 })), paginacion: { ...fixtureData.paginacion, total_items: ids.length, total_pages: 1, ...((extra as { paginacion?: object }).paginacion ?? {}) } }); + // The server echoes the parameters it applied in `filtros`, as WebApi does. + const eco = (req: { request: { params: { get(k: string): string | null } } }) => { const n = (k: string) => req.request.params.get(k) === null ? null : Number(req.request.params.get(k)); return { q: req.request.params.get('q'), edad_min: n('edad_min'), edad_max: n('edad_max') }; }; + const responder = (req: { request: { params: { get(k: string): string | null } }; flush(b: unknown): void }, ids: string[], extra: Record = {}) => + req.flush(respuesta(ids, { ...extra, filtros: { ...((extra['filtros'] as object) ?? fixtureData.filtros), ...eco(req) } })); + beforeEach(() => { vi.useFakeTimers(); }); + afterEach(() => { vi.useRealTimers(); }); - root.querySelectorAll('nav button')[1].click(); - const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2'); - expect(siguiente.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']); - siguiente.flush({ ...pagina, items: items.slice(1), paginacion: { ...pagina.paginacion, page: 2 } }); - fixture.detectChanges(); - expect(root.textContent).toContain('No hay coincidencias en esta página.'); - expect(root.querySelector('input[type="search"]')?.value).toBe(' a42 '); - [...root.querySelectorAll('button')].find(button => button.textContent === 'Limpiar búsqueda')!.click(); - fixture.detectChanges(); - expect(root.querySelectorAll('tr[data-paciente]')).toHaveLength(1); - http.expectNone(() => true); + it('espera tras la última tecla, pide la página 1 con q normalizada y muestra solo lo que devuelve el servidor', () => { + respond(); + escribir('a'); escribir(' a4 2 '); + vi.advanceTimersByTime(399); expect(consultas()).toHaveLength(0); + vi.advanceTimersByTime(2); + const [req] = consultas(); expect(consultas()).toHaveLength(0); + expect(req.request.params.get('q')).toBe('a4 2'); expect(req.request.params.get('page')).toBe('1'); + fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando seguimiento'); + responder(req, ['PRUEBA-A4 2', 'PRUEBA-A4 25']); fixture.detectChanges(); + expect(filas()).toEqual(['PRUEBA-A4 2', 'PRUEBA-A4 25']); + expect(fixture.nativeElement.querySelector('#alcance-busqueda-cacu').textContent).toContain('2 registros coinciden'); + // The input keeps its text and focus target while the list reloads. + expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe(' a4 2 '); + }); + it('conserva la búsqueda al paginar, reinicia a la página 1 al cambiarla y se puede limpiar', () => { + respond(); escribir('P'); vi.advanceTimersByTime(401); + responder(consultas()[0], ['P-1'], { paginacion: { total_items: 120, total_pages: 3 } }); fixture.detectChanges(); + fixture.componentInstance.navigate(2); + let [req] = consultas(); expect(req.request.params.get('q')).toBe('P'); expect(req.request.params.get('page')).toBe('2'); + responder(req, ['P-2'], { paginacion: { page: 2, total_items: 120, total_pages: 3 } }); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('nav').textContent).toContain('120 registros'); + escribir('PR'); vi.advanceTimersByTime(401); + [req] = consultas(); expect(req.request.params.get('page')).toBe('1'); expect(req.request.params.get('q')).toBe('PR'); + responder(req, ['PR-1']); fixture.detectChanges(); + ([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click(); + [req] = consultas(); expect(req.request.params.has('q')).toBe(false); expect(req.request.params.get('page')).toBe('1'); + responder(req, ['X-1']); fixture.detectChanges(); + expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe(''); + }); + // Why: a slow answer to an old search must never replace the answer to the current one. + it('una respuesta obsoleta se cancela y no sustituye a la vigente', () => { + respond(); escribir('ab'); vi.advanceTimersByTime(401); + const [vieja] = consultas(); + escribir('abc'); vi.advanceTimersByTime(401); + const [nueva] = consultas(); + expect(vieja.cancelled).toBe(true); + responder(nueva, ['ABC-1']); fixture.detectChanges(); + expect(filas()).toEqual(['ABC-1']); + }); + it('sin coincidencias lo dice y no cae en la lista local', () => { + respond(); escribir('zzz'); vi.advanceTimersByTime(401); + const [vacia] = consultas(); vacia.flush({ ...respuesta([]), filtros: { ...fixtureData.filtros, ...eco(vacia) }, paginacion: { ...fixtureData.paginacion, total_items: 0, total_pages: 0 } }); fixture.detectChanges(); + expect(filas()).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay coincidencias para la búsqueda y el rango de edad.'); + }); + it('el rango de edad se envía con uno o ambos límites, se limpia y no pide nada si es inválido', () => { + respond(); + const c = fixture.componentInstance; + c.draft.edad_min = 40; c.apply(); + let [req] = consultas(); expect(req.request.params.get('edad_min')).toBe('40'); expect(req.request.params.has('edad_max')).toBe(false); + responder(req, ['E-1']); fixture.detectChanges(); + c.draft.edad_max = 49; c.apply(); + [req] = consultas(); expect([req.request.params.get('edad_min'), req.request.params.get('edad_max')]).toEqual(['40', '49']); + responder(req, ['E-2']); fixture.detectChanges(); + c.draft.edad_min = 60; c.apply(); fixture.detectChanges(); + expect(consultas()).toHaveLength(0); expect(fixture.nativeElement.querySelector('#error-edad').textContent).toContain('desde 0'); + for (const malo of [-1, 40.5]) { c.draft.edad_min = malo; c.draft.edad_max = undefined; c.apply(); expect(consultas()).toHaveLength(0); } + c.limpiarRangoEdad(); + [req] = consultas(); expect(req.request.params.has('edad_min') || req.request.params.has('edad_max')).toBe(false); + responder(req, ['E-3']); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('#error-edad')).toBeNull(); + }); + it('el rango de edad se combina con la búsqueda y con los filtros existentes sin cambiar el orden ni el horizonte', () => { + respond(); escribir('P'); vi.advanceTimersByTime(401); + responder(consultas()[0], ['P-1'], { filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 }, horizontes_disponibles: [1, 3, 5] }); fixture.detectChanges(); + const c = fixture.componentInstance; c.draft.edad_max = 50; c.apply(); + const [req] = consultas(); + expect(['q', 'edad_max', 'estatus', 'orden', 'horizonte', 'page'].map(k => req.request.params.get(k))).toEqual(['P', '50', 'PRE_COLPOSCOPIA', 'lieag', '3', '1']); + }); + // Why: an older server ignores the new parameters; a partial local result must not pass as a global search. + it('si el servidor no aplica la búsqueda o la edad, no presenta resultados parciales', () => { + respond(); escribir('a42'); vi.advanceTimersByTime(401); + consultas()[0].flush(respuesta(['OTRO-1', 'A42-2'])); fixture.detectChanges(); + expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó la búsqueda'); + ([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click(); + responder(consultas()[0], ['OTRO-1']); fixture.detectChanges(); + const c = fixture.componentInstance; c.draft.edad_min = 40; c.apply(); + responder(consultas()[0], ['OTRO-1'], {}); fixture.detectChanges(); + expect(filas()).toEqual(['OTRO-1']); + c.draft.edad_min = 40; c.apply(); + const conEdad = respuesta(['E-1']); (conEdad.items[0] as { edad_al_corte?: number }).edad_al_corte = 30; + { const [r] = consultas(); r.flush({ ...conEdad, filtros: { ...conEdad.filtros, ...eco(r) } }); } fixture.detectChanges(); + expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó'); + // A row without age under an age range is outside the contract too. + c.draft.edad_min = 40; c.apply(); const sinEdad = respuesta(['E-2']); (sinEdad.items[0] as { edad_al_corte?: number | null }).edad_al_corte = null; + { const [r] = consultas(); r.flush({ ...sinEdad, filtros: { ...sinEdad.filtros, ...eco(r) } }); } fixture.detectChanges(); + expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó'); + }); + // Why: WebApi answers 400 over 100 characters; WebApp does not send it, and a backend 400 shows its message and no rows. + it('q admite 100 caracteres: más no se envía; un 400 del servidor se anuncia sin filas', () => { + respond(); escribir('1'.repeat(101)); vi.advanceTimersByTime(401); + expect(consultas()).toHaveLength(0); fixture.detectChanges(); + expect(fixture.nativeElement.textContent).toContain('hasta 100 caracteres'); + escribir('1'.repeat(100)); vi.advanceTimersByTime(401); + const [req] = consultas(); expect(req.request.params.get('q')).toHaveLength(100); + req.flush({ error: 'x' }, { status: 400, statusText: 'Bad Request' }); fixture.detectChanges(); + expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('Revisa'); + }); + // Why: the file must hold the query the server confirms, not the one WebApp hoped for. + it('la exportación valida y usa los filtros efectivos que el servidor confirma', () => { + respond(); + const pedir = (filtros: Record) => { + let tabla: { filtros: Record } | undefined, error: unknown; + fixture.componentInstance.origenExportacionCaCu.consultar('cacu', { corte: fixtureData.corte, meses: 12, page: 1, page_size: 200, filtros } as never).subscribe({ next: t => tabla = t as never, error: e => error = e }); + return { req: http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200'), get tabla() { return tabla; }, get error() { return error; } }; + }; + const sinEco = pedir({ q: 'P', edad_min: '30' }); + expect(sinEco.req.request.params.get('incluir')).toBeNull(); + sinEco.req.flush(respuesta(['P-1'])); + expect(sinEco.error).toBeInstanceOf(Error); expect(sinEco.tabla).toBeUndefined(); + const conEco = pedir({ q: 'P', edad_min: '30' }); + responder(conEco.req, ['P-1']); + expect(conEco.tabla!.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: null }); + const sinFiltros = pedir({}); sinFiltros.req.flush(respuesta(['X-1'])); + expect(sinFiltros.tabla).toBeDefined(); + }); + it('la exportación lleva la consulta completa: q, edad_min, edad_max y los demás filtros, y dice qué se aplicó', () => { + respond(); escribir('P'); vi.advanceTimersByTime(401); + responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges(); + const c = fixture.componentInstance; c.draft.edad_min = 30; c.draft.edad_max = 60; c.apply(); + responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges(); + const tabla = c.exportacionCaCu!; + expect(tabla.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: '60' }); + expect(tabla.filtros_disponibles.filter(f => ['q', 'edad_min', 'edad_max'].includes(f.clave)).map(f => f.opciones[0].etiqueta)).toEqual(['P', '30', '60']); + const root: HTMLElement = fixture.nativeElement; + ([...root.querySelectorAll('app-seguimiento-exportar button')] as HTMLButtonElement[]).find(x => x.textContent!.includes('Excel'))!.click(); + const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200'); + expect(['q', 'edad_min', 'edad_max', 'page'].map(k => exportacion.request.params.get(k))).toEqual(['P', '30', '60', '1']); + responder(exportacion, ['P-1'], { paginacion: { total_items: 1, total_pages: 1 } }); + }); }); - it('muestra el grupo de edad y señala la ausencia de edad exacta y fecha de nacimiento', () => { + it('sin edad exacta del servicio dice «No disponible», no muestra el grupo de edad y señala la ausencia de fecha de nacimiento', () => { respond(); const root: HTMLElement = fixture.nativeElement; const fila = root.querySelector('tr[data-paciente]')!; expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad'); expect(fila.querySelector('td:nth-child(2)')?.textContent).toContain('No disponible'); - expect(root.querySelector('td small')?.textContent).toContain('Grupo de edad'); + expect(fila.querySelector('td:nth-child(2)')?.textContent?.trim()).toBe('No disponible'); + expect(root.textContent).not.toContain('Grupo de edad'); fila.querySelector('button')!.click(); fixture.detectChanges(); const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento'); expect(nacimiento?.nextElementSibling?.textContent).toBe('No disponible'); http.expectNone(() => true); }); - it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, incluso con la búsqueda de página activa', formato => { + // Why: the exact age is shown only when the service gives it, as whole years, and never estimated from the age group. + it('muestra la edad exacta en años y distingue la edad ausente de una edad de 0 años', () => { + const items = [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], edad_al_corte: 1 }, { ...fixtureData.items[2], edad_al_corte: 0 }, + { ...fixtureData.items[3], edad_al_corte: null, grupo_edad: '40-49' }, { ...fixtureData.items[4], grupo_edad: '40-49' }]; + open().flush({ ...fixtureData, items, paginacion: { ...fixtureData.paginacion, total_items: 5 } }); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect([...root.querySelectorAll('tbody tr')].map(tr => tr.querySelector('td:nth-child(2)')!.textContent!.trim())) + .toEqual(['42 años', '1 año', '0 años', 'No disponible', 'No disponible']); + expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad'); + expect(root.textContent).not.toContain('Grupo de edad'); + http.expectNone(() => true); + }); + it('la edad exacta solo se acepta como años enteros no negativos', () => { + const con = (edad: unknown) => () => seguimientoResponse({ ...fixtureData, items: [{ ...fixtureData.items[0], edad_al_corte: edad }] }); + for (const valida of [0, 1, 42, null]) expect(con(valida)).not.toThrow(); + for (const invalida of [-1, 41.5, '42', 131, Number.NaN]) expect(con(invalida)).toThrow(); + }); + it('el listado no tiene la columna «Estudio más reciente» y conserva su opción de orden', () => { + open().flush({ ...fixtureData, filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5] }); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).not.toContain('Estudio más reciente'); + expect(fixture.componentInstance.ordenes().map(o => o.etiqueta)).toContain('Estudio más reciente'); + expect(root.querySelectorAll('thead th')).toHaveLength(9 + fixture.componentInstance.columnasProbabilidad().length); + }); + // Why: the exports must list the same columns as the screen; the study stays only as an ordering option. + it('la tabla de exportación coincide con el listado: Edad exacta, sin «Estudio más reciente» y con su opción de orden', () => { + const respuesta = seguimientoResponse({ ...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5], + items: [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], grupo_edad: '40-49' }] }); + const tabla = tablaExportacionCaCu(respuesta, () => 'Citología', () => null); + const claves = tabla.columnas.map(c => c.clave); + expect(claves).toContain('edad'); expect(claves).not.toContain('grupo_edad'); expect(claves).not.toContain('reciente'); + expect(tabla.columnas.map(c => c.etiqueta)).not.toContain('Estudio más reciente'); + expect(tabla.items.map(item => item['edad'])).toEqual(['42 años', null]); + expect(tabla.items.every(item => !('reciente' in item))).toBe(true); + expect(tabla.filtros_disponibles.find(f => f.clave === 'orden')!.opciones.map(o => o.etiqueta)).toContain('Estudio más reciente'); + }); + it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, con los filtros de la consulta', formato => { const pagina = { ...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 }, paginacion: { ...fixtureData.paginacion, total_items: 201 }, }; open().flush(pagina); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); - fixture.componentInstance.busquedaCaCu = 'no coincide'; fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; - expect(root.querySelector('tr[data-paciente]')).toBeNull(); const botones = () => [...root.querySelectorAll('app-seguimiento-exportar button')]; botones().find(button => button.textContent!.includes(formato))!.click(); const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200'); diff --git a/src/app/features/indicadores/export/cacu-tracking-export.ts b/src/app/features/indicadores/export/cacu-tracking-export.ts index ed86f9c..c708d7f 100644 --- a/src/app/features/indicadores/export/cacu-tracking-export.ts +++ b/src/app/features/indicadores/export/cacu-tracking-export.ts @@ -1,4 +1,4 @@ -import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse } from '../cacu-seguimiento.models'; +import { COLUMNAS_DE_PROBABILIDAD, edadAnios, edadTexto, ETIQUETA_PROBABILIDAD, normalizarConsulta, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse } from '../cacu-seguimiento.models'; import { ETIQUETA_IDENTIDAD, identidadDe } from '../paciente-identidad'; import { SeguimientoTablaQuery, SeguimientoTablaResponse } from '../seguimiento-tabla.service'; @@ -12,6 +12,10 @@ export function consultaExportacionCaCu(q: SeguimientoTablaQuery): SeguimientoQu corte, meses, page, page_size, estatus: filtros?.['estatus'], orden: orden === 'lieag' || orden === 'cancer' || orden === 'supervivencia' ? orden : 'reciente', horizonte: filtros?.['horizonte'] === undefined ? undefined : Number(filtros['horizonte']), + // The whole query: the file holds every record the search and the age range select, not the page on screen. + q: normalizarConsulta(filtros?.['q']) || undefined, + edad_min: filtros?.['edad_min'] === undefined ? undefined : Number(filtros['edad_min']), + edad_max: filtros?.['edad_max'] === undefined ? undefined : Number(filtros['edad_max']), }; } @@ -20,7 +24,11 @@ export function tablaExportacionCaCu( respuesta: SeguimientoResponse, citologia: (estudio: NonNullable) => string, probabilidad: (item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number) => string | null, + consulta: Pick = {}, ): SeguimientoTablaResponse { + // The effective query is the one the server confirms; the one asked fills in for servers that do not say. + const q = normalizarConsulta(respuesta.filtros.q ?? consulta.q); + const edadMin = respuesta.filtros.edad_min ?? consulta.edad_min, edadMax = respuesta.filtros.edad_max ?? consulta.edad_max; const identidad = (respuesta.items[0] && identidadDe(respuesta.items[0]))?.campo ?? 'id_seudonimo'; const { estatus, orden, horizonte } = respuesta.filtros; const probabilidades = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : []; @@ -30,28 +38,32 @@ export function tablaExportacionCaCu( corte: respuesta.corte, ventana: respuesta.ventana, paginacion: respuesta.paginacion, - filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.toString() ?? null }, + filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.toString() ?? null, + q: q || null, edad_min: edadMin?.toString() ?? null, edad_max: edadMax?.toString() ?? null }, filtros_disponibles: [ { clave: 'estatus', etiqueta: 'Estatus de seguimiento', opciones: respuesta.estatus_disponibles }, { clave: 'orden', etiqueta: 'Orden', opciones: [ORDEN_RECIENTE, ...probabilidades.map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))] }, { clave: 'horizonte', etiqueta: 'Horizonte de la probabilidad', opciones: (respuesta.horizontes_disponibles ?? [0, 1, 3, 5]) .map(h => ({ codigo: String(h), etiqueta: `${h} ${h === 1 ? 'año' : 'años'}` })) }, + // Free values: the only option is the value applied, so the files say what was searched. + { clave: 'q', etiqueta: 'Identificador contiene', opciones: q ? [{ codigo: q, etiqueta: q }] : [] }, + { clave: 'edad_min', etiqueta: 'Edad mínima (años)', opciones: edadMin == null ? [] : [{ codigo: String(edadMin), etiqueta: String(edadMin) }] }, + { clave: 'edad_max', etiqueta: 'Edad máxima (años)', opciones: edadMax == null ? [] : [{ codigo: String(edadMax), etiqueta: String(edadMax) }] }, ], columnas: [ { clave: identidad, etiqueta: ETIQUETA_IDENTIDAD[identidad] }, - { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, + { clave: 'edad', etiqueta: 'Edad' }, { clave: 'estatus', etiqueta: 'Estatus de seguimiento' }, { clave: 'citologia', etiqueta: 'Última citología', detalles: [{ clave: 'fecha_citologia', etiqueta: 'Fecha' }, { clave: 'calidad', etiqueta: 'Calidad' }] }, { clave: 'vph', etiqueta: 'Último resultado de VPH', detalles: [{ clave: 'fecha_vph', etiqueta: 'Fecha' }, { clave: 'genotipo', etiqueta: 'Genotipo 16/18' }] }, { clave: 'biopsia', etiqueta: 'Última biopsia', detalles: [{ clave: 'fecha_biopsia', etiqueta: 'Fecha' }] }, ...probabilidades.map(clave => ({ clave, etiqueta: `${ETIQUETA_PROBABILIDAD[clave]} a ${horizonteMostrado} años (%)` })), - { clave: 'reciente', etiqueta: 'Estudio más reciente' }, { clave: 'dias', etiqueta: 'Días de toma a diagnóstico' }, { clave: 'prioridad', etiqueta: 'Prioridad' }, ], items: respuesta.items.map(item => ({ [identidad]: identidadDe(item)!.id, - grupo_edad: item.grupo_edad === 'sin_dato' ? null : item.grupo_edad, + edad: edadAnios(item) === null ? null : edadTexto(item), estatus: item.estatus.etiqueta, citologia: item.ultima_citologia ? citologia(item.ultima_citologia) : null, fecha_citologia: item.ultima_citologia?.fecha ?? null, @@ -62,7 +74,6 @@ export function tablaExportacionCaCu( biopsia: item.ultima_biopsia ? item.ultima_biopsia.grado ?? 'Sin grado' : null, fecha_biopsia: item.ultima_biopsia?.fecha ?? null, ...Object.fromEntries(probabilidades.map(c => [c, probabilidad(item, c, horizonteMostrado)])), - reciente: latestStudy(item), dias: item.dias_toma_diagnostico, prioridad: item.prioridad?.etiqueta ?? null, })), diff --git a/src/app/features/indicadores/indicador-cacu-donas.ts b/src/app/features/indicadores/indicador-cacu-donas.ts new file mode 100644 index 0000000..b89e7ce --- /dev/null +++ b/src/app/features/indicadores/indicador-cacu-donas.ts @@ -0,0 +1,76 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, SimpleChanges } from '@angular/core'; +import { catchError, of, Subscription } from 'rxjs'; +import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; +import { describePeriods, GlobalApplied } from './indicadores-memory'; +import { IndicadoresService } from './indicadores.service'; +import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; +import { IndicadorVphGenotipo } from './indicador-vph-genotipo'; +import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; + +// Three independent CaCu distributions sharing the general period filter. +@Component({ + selector: 'app-indicador-cacu-donas', + imports: [IndicadorEu7Escenario, IndicadorVphGenotipo, IndicadorConfirmacionCitologia], + template: ` +

    Filtro general aplicado: {{ filtro }}

    +
    + + + @if (confirmacion && confirmacionApplied) { + + } +
    + `, + styles: ` + :host { display: block; min-width: 0; } + .filtro { margin: 0 0 var(--issste-space-2); color: var(--issste-text-secondary); } + .donas { display: flex; flex-direction: column; } + .donas > * { display: block; min-width: 0; padding-block: var(--issste-space-3); } + .donas > * + * { border-top: 1px solid var(--issste-border); } + `, +}) +export class IndicadorCacuDonas implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + // The biopsy donut belongs to the histopathological confirmation indicator. + @Input() confirmacion?: Indicador; + @Input() confirmacionApplied?: GlobalApplied; + // HPV by genotype: its Measure, when the server publishes it. + @Input() vph?: Indicador; + @Input() vphApplied?: GlobalApplied; + readonly metadataRequested = output(); + get filtro() { return describePeriods(this.applied.tipo, this.applied.selection); } + get vphFiltroPropio() { return !!this.vphApplied && describePeriods(this.vphApplied.tipo, this.vphApplied.selection) !== this.filtro; } + // A donut whose effective period differs from the card's keeps its own line. + get filtroPropio() { return !!this.confirmacionApplied && describePeriods(this.confirmacionApplied.tipo, this.confirmacionApplied.selection) !== this.filtro; } + confirmacionMetadata?: IndicadorMetadatos; + private readonly indicators = inject(IndicadoresService); + private readonly changeDetector = inject(ChangeDetectorRef); + private metadataSubscription?: Subscription; + private metadataKey = ''; + + ngOnChanges(changes: SimpleChanges) { + if (changes['confirmacion'] && this.metadataKey !== '') { + this.metadataSubscription?.unsubscribe(); this.metadataKey = ''; this.confirmacionMetadata = undefined; + } + } + loadConfirmacionMetadata() { + if (!this.confirmacion) return; + const key = JSON.stringify([this.dominio, this.confirmacion.id]); + if (this.metadataKey === key) return; + this.metadataKey = key; + this.metadataSubscription?.unsubscribe(); + this.metadataSubscription = this.indicators.metadatos(this.dominio, this.confirmacion.id) + .pipe(catchError(() => of(undefined))).subscribe(value => { + if (this.metadataKey !== key) return; + if (!value) this.metadataKey = ''; + this.confirmacionMetadata = value; + this.changeDetector.markForCheck(); + }); + } + ngOnDestroy() { this.metadataSubscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 2e21b53..63d4384 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -14,7 +14,7 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { filterCompatibility } from './indicadores-memory'; import { DonutSelection } from './indicadores-donut-drilldown'; import { IndicadoresService } from './indicadores.service'; -import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; +import { IndicadorCacuDonas } from './indicador-cacu-donas'; import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; @@ -29,13 +29,13 @@ const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacient @Component({ selector: 'app-indicador-catalog-card', host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], + imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorCacuDonas, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], template: ` @if (!conteos) {
    -

    {{ indicador.titulo }}

    +

    {{ titulo }}

    } @@ -50,7 +50,7 @@ const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacient @if (!sobrio) { } @if (isEu7) {
    - +
    } @else if (isConfirmacion) {
    @@ -144,6 +144,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { // TEA's stacked case charts span two columns of its three-column grid. get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); } get pair() { return dualFigures(this.indicador); } + // CaCu's first card gathers the three donuts, so it carries its own name. + get titulo() { return this.isEu7 ? 'Resultados de citología, VPH y biopsia' : this.indicador.titulo; } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } // CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu. @@ -175,6 +177,12 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() independentPeriods = false; + // The histopathological confirmation indicator, whose biopsy donut sits on the EU7 card. + @Input() companion?: Indicador; + @Input() companionApplied?: GlobalApplied; + // The HPV-by-genotype indicator, whose donut sits on the same card. + @Input() vph?: Indicador; + @Input() vphApplied?: GlobalApplied; @Input() pinned = false; // Draws the indicator alone even when it belongs to a connected pair. @Input() individual = false; diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.html b/src/app/features/indicadores/indicador-confirmacion-citologia.html index a0b7330..0dadc8f 100644 --- a/src/app/features/indicadores/indicador-confirmacion-citologia.html +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.html @@ -1,38 +1,41 @@ -
    -

    Filtro general aplicado: {{ appliedSummary }}

    +
    +
    + @if (mostrarFiltro) {

    Filtro general aplicado: {{ appliedSummary }}

    } @if (helpOpen) {
    - @if (metadata) { + @if (!permitirSeleccion && vista === 'dona') { +

    Cada barra muestra mujeres por grado de biopsia y su porcentaje del total con biopsia. Los encabezados reúnen los grados en grupos clínicos. Los casos sin biopsia o sin grado se informan fuera de la distribución.

    + } @else if (metadata) { @for (guide of readingGuide; track guide.figura) {

    {{ guide.nombre }}

    @if (guide.descripcion) {

    {{ guide.descripcion }}

    } @if (guide.como_leer.length) {
      @for (line of guide.como_leer; track $index) {
    • {{ line }}
    • }
    }
    - } @empty {

    El servicio no publica instrucciones de lectura para estas figuras.

    } + } @empty {

    El servicio no publica instrucciones de lectura para {{ vista === 'dona' ? 'esta figura' : 'estas figuras' }}.

    } } @else {

    Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

    }
    } @switch (status()) { @case ('deferred') {

    La vista se cargará al acercarse a esta región.

    } - @case ('loading') {

    Cargando el mismo periodo para tasas y dona…

    } + @case ('loading') {

    {{ vista === 'dona' ? 'Cargando resultados de biopsia…' : 'Cargando tasas de confirmación…' }}

    } @case ('error') {

    {{ message }}

    } @case ('incompatible') {

    Respuesta incompatible: {{ message }}

    } } @if (status() === 'ready' || status() === 'empty') { @if (periods.length > 1) { -
    diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.scss b/src/app/features/indicadores/indicador-confirmacion-citologia.scss index 61f9815..d45ca26 100644 --- a/src/app/features/indicadores/indicador-confirmacion-citologia.scss +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.scss @@ -23,7 +23,6 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse button:disabled { opacity: .5; cursor: default; } button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; } -.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; } .figure { min-width: 0; border-top: 1px solid var(--issste-border); } h3 { font-size: 1rem; line-height: 1.5; } app-plotly-chart { --plot-height: 440px; } @@ -59,9 +58,8 @@ caption { text-align: start; font-weight: 600; } app-plotly-chart { --plot-height: 360px; } .rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); } .rate-states:empty { display: none; } -/* Rates on the left, donut on the right (the reverse of EU7). */ +.aparte { color: var(--issste-text-secondary); } @media (min-width: 1100px) { - .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } .histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; } } diff --git a/src/app/features/indicadores/indicador-confirmacion-citologia.ts b/src/app/features/indicadores/indicador-confirmacion-citologia.ts index 4a55021..8749001 100644 --- a/src/app/features/indicadores/indicador-confirmacion-citologia.ts +++ b/src/app/features/indicadores/indicador-confirmacion-citologia.ts @@ -4,20 +4,25 @@ import { Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { BarrasHorizontales } from './barras-horizontales'; +import { ConjuntoBarras } from './indicadores-barras'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; -import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION, +import { clicConfirmacion, barrasBiopsia, ConfirmacionIncompatible, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION, lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta, - Celda, tasas } from './indicadores-confirmacion-citologia'; + Celda, tasas, totalesPublicados } from './indicadores-confirmacion-citologia'; -// Figures of the kit whose "Cómo leer" describes this coordinated view. -const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const; +// Figure of the kit whose "Cómo leer" describes each view of this indicator. +const FIGURAS = { + dona: [['fig_c2_donas', 'Grados de biopsia']], + tasas: [['fig_c2_barras', 'Tasas por resultado de la citología']], +} as const; @Component({ selector: 'app-indicador-confirmacion-citologia', - imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, BarrasHorizontales], templateUrl: './indicador-confirmacion-citologia.html', styleUrl: './indicador-confirmacion-citologia.scss', }) @@ -27,6 +32,11 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; + // False when the card above already says the general filter this view follows. + @Input() mostrarFiltro = true; + @Input() permitirSeleccion = true; + // The indicator has two views with their own selection: the biopsy donut and the rates by cytology. + @Input() vista: 'dona' | 'tasas' = 'tasas'; @Input() metadata?: IndicadorMetadatos; readonly metadataRequested = output(); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); @@ -35,7 +45,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { periods: string[] = []; periodIndex = 0; model?: ModeloConfirmacion; - donutFigure?: PlotlyFigure; + barras?: ConjuntoBarras; ratesFigure?: PlotlyFigure; helpOpen = false; private readonly snapshots = inject(IndicadoresSnapshots); @@ -48,6 +58,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } + get totales() { return this.model ? totalesPublicados(this.model) : undefined; } get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } readonly estadoTasa = estadoTasa; @@ -55,7 +66,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); } get readingGuide() { const details = this.metadata?.figuras_detalle ?? []; - return FIGURAS.flatMap(([figura, nombre]) => { + return FIGURAS[this.vista].flatMap(([figura, nombre]) => { const detail = details.find(item => item.figura === figura); const descripcion = detail?.descripcion?.trim() ?? ''; const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); @@ -73,12 +84,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { if (!this.visible) { this.status.set('deferred'); return; } this.load(); } else if (this.visible && !this.loaded) this.load(); - else if (this.model && changes['tema']) this.draw(); + else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) this.draw(); } retry() { if (this.visible) this.load(); } private clear() { this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; - this.donutFigure = undefined; this.ratesFigure = undefined; + this.barras = undefined; this.ratesFigure = undefined; } private load() { this.subscription?.unsubscribe(); @@ -123,17 +134,16 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy { this.periodIndex += step; this.activatePeriod(); } select(trace: string, index = 0) { - if (!this.model || !this.selection || this.status() !== 'ready') return; + if (!this.permitirSeleccion || !this.model || !this.selection || this.status() !== 'ready') return; this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw(); } - plotClicked(event: unknown) { - const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; - if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); - } private draw() { if (!this.model || !this.selection) return; - this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema); - this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); + if (this.vista === 'dona') { + const barras = barrasBiopsia(this.model, this.selection); + this.barras = this.permitirSeleccion ? barras : { ...barras, activas: null }; + } + else this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); this.changeDetector.markForCheck(); } ngOnDestroy() { this.subscription?.unsubscribe(); } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.html b/src/app/features/indicadores/indicador-eu7-escenario.html index 82fcc06..68d435a 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.html +++ b/src/app/features/indicadores/indicador-eu7-escenario.html @@ -1,38 +1,41 @@ -
    -

    Filtro general aplicado: {{ appliedSummary }}

    +
    +
    + @if (mostrarFiltro) {

    Filtro general aplicado: {{ appliedSummary }}

    } @if (helpOpen) {
    - @if (metadata) { + @if (!permitirSeleccion) { +

    Cada barra muestra pacientes por resultado citológico y su porcentaje del total con resultado disponible. Los encabezados reúnen las categorías en grupos clínicos. «Sin dato» se informa fuera de la distribución.

    + } @else if (metadata) { @for (guide of readingGuide; track guide.figura) {

    {{ guide.nombre }}

    @if (guide.descripcion) {

    {{ guide.descripcion }}

    } @if (guide.como_leer.length) {
      @for (line of guide.como_leer; track $index) {
    • {{ line }}
    • }
    }
    - } @empty {

    El servicio no publica instrucciones de lectura para estas figuras.

    } + } @empty {

    El servicio no publica instrucciones de lectura para esta figura.

    } } @else {

    Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

    }
    } @switch (status()) { @case ('deferred') {

    La vista se cargará al acercarse a esta región.

    } - @case ('loading') {

    Cargando el mismo periodo para dona y barras…

    } + @case ('loading') {

    Cargando resultados citológicos…

    } @case ('error') {

    {{ message }}

    } @case ('incompatible') {

    Respuesta incompatible: {{ message }}

    } } @if (status() === 'ready' || status() === 'empty') { @if (periods.length > 1) { -
    diff --git a/src/app/features/indicadores/indicador-eu7-escenario.scss b/src/app/features/indicadores/indicador-eu7-escenario.scss index 9a784ff..656563c 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.scss +++ b/src/app/features/indicadores/indicador-eu7-escenario.scss @@ -15,10 +15,8 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse button:disabled { opacity: .5; cursor: default; } button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; } -.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; } .figure { min-width: 0; border-top: 1px solid var(--issste-border); } h3 { font-size: 1rem; line-height: 1.5; } -app-plotly-chart { --plot-height: 440px; } .periods { display: flex; align-items: center; justify-content: center; gap: .75rem; } .periods span { text-align: center; } .periods button { min-width: 44px; font-size: 1.5rem; } @@ -27,7 +25,6 @@ summary { cursor: pointer; padding-block: .75rem; } table { border-collapse: collapse; width: 100%; margin-block: 1rem; } th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } caption { text-align: start; font-weight: 600; } -@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } } .reading-guide h3 { margin: 0 0 .25rem; } .reading-guide + .reading-guide { margin-top: 1rem; } .reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } diff --git a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts index e45862e..dcc2061 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.spec.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.spec.ts @@ -1,4 +1,3 @@ -import { Component, input, output } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -8,15 +7,9 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresSnapshots } from './indicadores-snapshots'; -import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { GlobalApplied } from './indicadores-memory'; import { Indicador } from './indicadores.models'; -@Component({ selector: 'app-plotly-chart', template: '' }) -class ChartStub { - figure = input(); label = input(); showNotes = input(); animated = input(); - plotClick = output(); -} describe('EU7 integración Angular y caché compartida', () => { const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0', @@ -27,7 +20,6 @@ describe('EU7 integración Angular y caché compartida', () => { let data: typeof fixtureData; beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); - TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData); f = TestBed.createComponent(IndicadorEu7Escenario); f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador); @@ -46,21 +38,16 @@ describe('EU7 integración Angular y caché compartida', () => { const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe(); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); flush(); expect(f.componentInstance.model!.total).toBe(946); - expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]); - const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement; - expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1); - expect((f.componentInstance.barsFigure!.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).not.toContain('Total válido'); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); + expect(f.nativeElement.querySelector('app-barras-horizontales .den').textContent).toContain('946'); const general = data.general; const original = structuredClone(applied); const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf).find(b => b.textContent!.includes('Anormal'))!; anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); - const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub; - chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges(); + f.componentInstance.select('categorias', 4); f.detectChanges(); expect(f.componentInstance.selection.categoria).toBe('LIEAG'); expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG'); f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); - f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); - expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839'); expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe(); }); it('desde TOTAL, elegir un hijo activa y abre su grupo sin volver a pedir datos', () => { @@ -73,7 +60,7 @@ describe('EU7 integración Angular y caché compartida', () => { expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' }); expect(parent.getAttribute('aria-pressed')).toBe('true'); expect(child.getAttribute('aria-pressed')).toBe('true'); - expect((f.componentInstance.donutFigure!.data[2]['values'] as number[])[0]).toBe(0); + expect([...f.componentInstance.barras!.activas!]).toEqual(['LIEAG']); child.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' }); parent.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); http.expectNone(() => true); @@ -86,15 +73,26 @@ describe('EU7 integración Angular y caché compartida', () => { } f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush(); expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364); - const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub); + const barrasAntes = f.nativeElement.querySelectorAll('app-barras-horizontales')[0]; f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges(); expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2'); expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682); - expect(f.componentInstance.barsFigure!.layout['barmode']).toBe('group'); - expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts); - expect(charts.map(chart => chart.animated())).toEqual([true, true]); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')[0]).toBe(barrasAntes); expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2'); - expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true); + http.expectNone(() => true); + }); + // The card draws one donut whatever is selected: no scenario bars in any selection state, and the scenario values stay in the table. + it('no dibuja barras por escenario en ningún estado de selección y conserva sus valores en la tabla', () => { + f.detectChanges(); flush(); + const estados: [string, number][] = [['grupos', 1], ['categorias', 4], ['centro', 0]]; + for (const [traza, indice] of [['', 0] as [string, number], ...estados]) { + if (traza) f.componentInstance.select(traza, indice); + f.detectChanges(); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); + expect((f.componentInstance as unknown as { barsFigure?: unknown }).barsFigure).toBeUndefined(); + expect(f.nativeElement.textContent).not.toContain('por escenario clínico,'); + } + expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').textContent).toContain('Denominador válido'); }); it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => { f.detectChanges(); const r = requests(); r.general.flush(data.general); @@ -114,7 +112,7 @@ describe('EU7 integración Angular y caché compartida', () => { it('error de red permite reintento sin figuras engañosas', () => { f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges(); expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error'); - expect(f.componentInstance.donutFigure).toBeUndefined(); + expect(f.componentInstance.barras).toBeUndefined(); f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready'); }); it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => { @@ -127,12 +125,12 @@ describe('EU7 integración Angular y caché compartida', () => { }); it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => { data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush(); - expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(f.componentInstance.status()).toBe('incompatible'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0); }); it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => { data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = []; f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty'); - expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0); expect(f.nativeElement.textContent).toContain('No hay pacientes publicados'); }); it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => { @@ -149,13 +147,13 @@ describe('EU7 integración Angular y caché compartida', () => { }); it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => { f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges(); - const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure; + const barras = f.componentInstance.barras; f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges(); f.componentRef.setInput('visible', true); f.detectChanges(); - expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars); + expect(f.componentInstance.barras).toBe(barras); expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true); }); - it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => { + it('«Cómo leer» muestra solo la descripción y el como_leer publicados de la dona, sin la ficha', () => { f.componentRef.setInput('visible', false); f.detectChanges(); const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested); const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement; @@ -174,11 +172,10 @@ describe('EU7 integración Angular y caché compartida', () => { }); f.detectChanges(); const help = f.nativeElement.querySelector('.methodology') as HTMLElement; const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[]; - expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']); + expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Distribución de resultados citológicos']); expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']); - expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.'); - expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']); - for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior']) + expect(help.textContent).not.toContain('Lee las barras así.'); + for (const absent of ['Barras por escenario', 'Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior']) expect(help.textContent).not.toContain(absent); expect(help.querySelector('details')).toBeNull(); f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges(); diff --git a/src/app/features/indicadores/indicador-eu7-escenario.ts b/src/app/features/indicadores/indicador-eu7-escenario.ts index e405cfd..3729aff 100644 --- a/src/app/features/indicadores/indicador-eu7-escenario.ts +++ b/src/app/features/indicadores/indicador-eu7-escenario.ts @@ -3,21 +3,23 @@ import { HttpErrorResponse } from '@angular/common/http'; import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { BarrasHorizontales } from './barras-horizontales'; +import { ConjuntoBarras } from './indicadores-barras'; +import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models'; import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; import { percentText } from './indicadores-format'; import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified'; -import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, +import { barrasCitologia, Celda, clic, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; -const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const; +// Only the donut is drawn; the scenario figure has no entry in the reading guide. +const EU7_FIGURES = [['fig_c2_donas', 'Distribución de resultados citológicos']] as const; @Component({ selector: 'app-indicador-eu7-escenario', - imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales], templateUrl: './indicador-eu7-escenario.html', styleUrl: './indicador-eu7-escenario.scss', }) @@ -27,6 +29,9 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; + // False when the card above already says the general filter this view follows. + @Input() mostrarFiltro = true; + @Input() permitirSeleccion = true; @Input() metadata?: IndicadorMetadatos; readonly metadataRequested = output(); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); @@ -35,8 +40,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { periods: string[] = []; periodIndex = 0; model?: Modelo; - donutFigure?: PlotlyFigure; - barsFigure?: PlotlyFigure; + barras?: ConjuntoBarras; helpOpen = false; private readonly snapshots = inject(IndicadoresSnapshots); private readonly changeDetector = inject(ChangeDetectorRef); @@ -51,9 +55,9 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { if (!m) return ''; if (m.vacio) return 'No hay registros publicados en este periodo.'; const n = m.sinDato.n; - return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.` - : m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.` - : `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`; + return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la distribución.` + : m.total === null ? `Fuera de la distribución: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la distribución no disponible.` + : `Fuera de la distribución: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`; } get generalCells() { const m = this.model; @@ -86,18 +90,18 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { if (key !== this.key) { this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.pages = []; this.periods = []; this.model = undefined; - this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; + this.selection = {}; this.barras = undefined; if (!this.visible) { this.status.set('deferred'); return; } this.load(); } else if (this.visible && !this.loaded) this.load(); - else if (this.model && changes['tema']) this.draw(); + else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) this.draw(); // Visibility and metadata changes must not restart Plotly rendering. } retry() { if (this.visible) this.load(); } private load() { this.subscription?.unsubscribe(); this.loaded = true; this.model = undefined; this.pages = []; this.periods = []; - this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; + this.selection = {}; this.barras = undefined; const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2' || !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras') @@ -125,7 +129,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { }); } private failure(error: unknown) { - this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined; + this.model = undefined; this.barras = undefined; this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof Eu7Incompatible ? error.message : httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit' @@ -142,17 +146,12 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy { this.periodIndex += step; this.activatePeriod(); } select(trace: string, index = 0) { - if (!this.model || this.status() !== 'ready') return; + if (!this.permitirSeleccion || !this.model || this.status() !== 'ready') return; this.selection = clic(this.model, this.selection, trace, index); this.draw(); } - plotClicked(event: unknown) { - const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; - if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); - } private draw() { if (!this.model) return; - this.donutFigure = dona(this.model, this.selection, this.tema); - this.barsFigure = barras(this.model, this.selection, this.tema); + this.barras = barrasCitologia(this.model, this.permitirSeleccion ? this.selection : {}); this.changeDetector.markForCheck(); } ngOnDestroy() { this.subscription?.unsubscribe(); } diff --git a/src/app/features/indicadores/indicador-vph-genotipo.ts b/src/app/features/indicadores/indicador-vph-genotipo.ts new file mode 100644 index 0000000..4e9cfee --- /dev/null +++ b/src/app/features/indicadores/indicador-vph-genotipo.ts @@ -0,0 +1,155 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { BarrasHorizontales } from './barras-horizontales'; +import { ConjuntoBarras } from './indicadores-barras'; +import { Dominio, Indicador, Tema } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { barrasVph, ModeloVph, modeloVph, periodosVph, porcentajeVph, VphIncompatible } from './indicadores-vph-genotipo'; + +/** + * HPV result by genotype, on its own: no selection, no link to the cytology or biopsy donuts, its own request, states + * and errors. Without the Measure (an older server) it says so and nothing else changes. + */ +@Component({ + selector: 'app-indicador-vph-genotipo', + imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales], + template: ` +
    + @if (mostrarFiltro && indicador) {

    Filtro general aplicado: {{ appliedSummary }}

    } + @switch (status()) { + @case ('loading') {

    Cargando resultados de VPH…

    } + @case ('error') {

    {{ message }}

    } + @case ('incompatible') {

    Respuesta incompatible: {{ message }}

    } + } + @if (periods.length > 1 && (status() === 'ready')) { + + } +
    +
    +

    Resultados de VPH por genotipo@if (model) {, {{ model.periodo }}}

    + @if (!indicador) {

    No disponible: el servicio todavía no publica este indicador. No se muestran valores.

    } + @else if (status() === 'deferred') {

    La vista se cargará al acercarse a esta región.

    } + @else if (model; as m) { + @switch (m.estado) { + @case ('ausente') {

    Sin reporte publicado para {{ m.periodo }}.

    } + @case ('cero') {

    Sin reportes de VPH elegibles en {{ m.periodo }}: no hay distribución que mostrar.

    } + @default { + + } + } + @if (m.estado === 'datos') { +
    Valores publicados +
    + + + @for (c of m.categorias; track c.id) { } + +
    Reportes de VPH por categoría, {{ m.periodo }}
    CategoríaReportesPorcentaje
    {{ c.etiqueta }}{{ c.n.toLocaleString('es-MX') }}{{ pct(c.n, m.total!) }}
    Total de reportes{{ m.total!.toLocaleString('es-MX') }}
    +
    +
    + } + } +
    + `, + styles: ` + :host { display: block; min-width: 0; } + .vph { min-width: 0; border-top: 1px solid var(--issste-border); } + .encabezado { padding-top: var(--issste-space-3); } + h3 { font-size: 1rem; line-height: 1.5; } + h3, p, summary, li { overflow-wrap: anywhere; } + .applied-summary, .nota { color: var(--issste-text-secondary); } + .estado { display: flex; align-items: center; justify-content: center; box-sizing: border-box; margin: 0; padding: 1rem; text-align: center; + border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); } + .periods { display: flex; align-items: center; justify-content: center; gap: .75rem; } + button { min-height: 44px; padding: .5rem .8rem; border: 1px solid var(--issste-border); border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; } + button:disabled { opacity: .5; cursor: default; } + button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + .periods button { min-width: 44px; font-size: 1.5rem; } + summary { cursor: pointer; padding-block: .75rem; } + .table-scroll { overflow: auto; max-height: 28rem; } + table { border-collapse: collapse; width: 100%; margin-block: 1rem; } + th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } + caption { text-align: start; font-weight: 600; } + `, +}) +export class IndicadorVphGenotipo implements OnChanges, OnDestroy { + @Input() dominio: Dominio = 'cacu'; + /** The published indicator; absent when the server does not publish the Measure. */ + @Input() indicador?: Indicador; + @Input() tema: Tema = 'claro'; + @Input() applied?: GlobalApplied; + @Input() visible = true; + @Input() mostrarFiltro = true; + readonly status = signal<'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'>('idle'); + message = ''; + periods: string[] = []; + periodIndex = 0; + model?: ModeloVph; + barras?: ConjuntoBarras; + readonly pct = porcentajeVph; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + private pages: ModeloVph[] = []; + get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : ''; } + + ngOnChanges(changes: SimpleChanges) { + if (!this.indicador || !this.applied) { this.subscription?.unsubscribe(); this.clear(); this.key = ''; this.status.set('idle'); return; } + const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + } + retry() { if (this.visible) this.load(); } + private clear() { this.pages = []; this.periods = []; this.model = undefined; this.barras = undefined; } + private load() { + const indicador = this.indicador!, applied = this.applied!; + this.subscription?.unsubscribe(); this.loaded = true; this.clear(); + const compatibility = filterCompatibility(applied, indicador.tipos_periodo); + if (indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.'; + this.status.set('incompatible'); return; + } + const key = this.key, periods = applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = this.snapshots.datos(this.dominio, indicador.id, applied.tipo, periods, indicador.version).pipe(timeout({ first: 40000 })).subscribe({ + next: datos => { + if (key !== this.key) return; + try { + this.periods = periodosVph(datos, applied.tipo, periods); + this.pages = this.periods.map(p => modeloVph(datos, p)); + this.periodIndex = this.periods.length ? this.periods.length - 1 : 0; this.activate(); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof VphIncompatible ? error.message + : httpMessage(error); + this.status.set(error instanceof VphIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)) ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + private activate() { this.model = this.pages[this.periodIndex]; this.draw(); this.status.set('ready'); this.changeDetector.markForCheck(); } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.activate(); + } + private draw() { this.barras = this.model?.estado === 'datos' ? barrasVph(this.model) : undefined; this.changeDetector.markForCheck(); } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-barras.ts b/src/app/features/indicadores/indicadores-barras.ts new file mode 100644 index 0000000..e35ed5d --- /dev/null +++ b/src/app/features/indicadores/indicadores-barras.ts @@ -0,0 +1,36 @@ +// Data shape of the horizontal bars that show the CaCu results (cytology, HPV by genotype, biopsy): one bar per +// category, optional clinical groups as headers with their subtotal, absolute counts as the scale and the +// percentage of the published denominator beside each count. A group is a header, not a category of the distribution. +export type EstadoCelda = 'Publicado' | 'Suprimido' | 'No disponible'; +export interface FilaBarra { id: string; etiqueta: string; n: number | null; estado: EstadoCelda; color: string; } +export interface GrupoBarras { + /** Null for a flat distribution (HPV): no header. */ + id: string | null; etiqueta: string | null; color: string; + /** Sum of its categories; null when any of them is unknown. */ + subtotal: number | null; filas: FilaBarra[]; +} +export interface ConjuntoBarras { + grupos: GrupoBarras[]; + /** The published denominator the percentages use; null when it is not available. */ + den: number | null; + /** What the denominator counts: «pacientes con resultado», «reportes de VPH elegibles»… */ + unidad: string; + /** The ids of the categories the selection highlights; null when nothing is selected. */ + activas: ReadonlySet | null; +} + +const BASES = [2, 4, 6, 8, 10, 12, 16, 20, 24, 30, 40, 50, 60, 80, 100]; +/** The upper limit of the count scale: the smallest round, even number that holds the largest bar or subtotal. */ +export function limiteEscala(maximo: number): number { + if (!(maximo > 0)) return 2; + for (let potencia = 1; ; potencia *= 10) for (const base of BASES) if (base * potencia / 10 >= maximo && Number.isInteger(base * potencia / 10 / 2)) return base * potencia / 10; +} +export function maximoDelConjunto(c: ConjuntoBarras): number { + return Math.max(0, ...c.grupos.flatMap(g => [g.subtotal ?? 0, ...g.filas.map(f => f.n ?? 0)])); +} +/** Sum of the categories the selection highlights, or null when there is no selection or any of them is unknown. */ +export function sumaActivas(c: ConjuntoBarras): number | null { + if (!c.activas) return null; + const filas = c.grupos.flatMap(g => g.filas).filter(f => c.activas!.has(f.id)); + return filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0); +} diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index 1e506b9..d12b682 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -67,6 +67,19 @@ describe('Identificadores de CaCu entre FHIR y la página', () => { }); describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => { + it('rechaza una categoría EU7 publicada que no figura en la Measure, sin descartar su conteo', () => { + const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]); + const cod = (value: string) => ({ coding: [{ code: value }] }); + const report = { resourceType: 'MeasureReport', period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ + code: cod('TOTAL'), population: [{ code: cod('initial-population'), count: 2 }], + stratifier: [{ code: [cod('estatus_seguimiento'), cod('resultado')], stratum: [{ + component: [{ code: cod('estatus_seguimiento'), value: cod('PRE_COLPOSCOPIA') }, + { code: cod('resultado'), value: cod('NEGATIVO') }], population: [{ count: 2 }], + }] }], + }] } as unknown as Report; + expect(() => datosDeReportes(measure, [report], 'semestre', { estrato: 'estatus_seguimiento' })) + .toThrow('Categoría no declarada en el estrato'); + }); it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => { // Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum // (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.ts b/src/app/features/indicadores/indicadores-cacu-fhir.ts index 12e4e14..4580e42 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.ts @@ -18,5 +18,6 @@ export const CACU_MEASURE_IDS: Readonly> = { 'CACU-EU13': 'cacu_eu13', 'CACU-EU7': 'cacu_eu7', 'CACU-RIESGO-BANDA': 'cacu_riesgo_banda', + 'CACU-VPH-GENOTIPO': 'cacu_vph_genotipo', 'IND1': 'ind1', }; diff --git a/src/app/features/indicadores/indicadores-cacu-palette.ts b/src/app/features/indicadores/indicadores-cacu-palette.ts index c835ed7..587472f 100644 --- a/src/app/features/indicadores/indicadores-cacu-palette.ts +++ b/src/app/features/indicadores/indicadores-cacu-palette.ts @@ -12,6 +12,15 @@ const CATEGORY_COLORS: Readonly> = Object.freeze({ CARCINOMA: '#925078', SIN_DATO: '#C9CDD2', SIN_BIOPSIA: '#C9CDD2', + // HPV by genotype: outside the coffee hues, apart from the cytology and biopsy colours; unknown and inconsistent stay grey. + NEGATIVO: '#5F9EA0', + POSITIVO_16: '#3E6FB0', + POSITIVO_18: '#7B5EA7', + POSITIVO_16_18: '#B0457A', + POSITIVO_SIN_16_18: '#4F7942', + POSITIVO_INCOMPLETO: '#9A9A2F', + INDETERMINADO: '#8A9199', + INCONSISTENTE: '#C9CDD2', }); const GROUP_COLORS: Readonly> = Object.freeze({ diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index c024863..8c1a22b 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -56,7 +56,7 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(titulos('.kpi-section .catalog-grid')).toEqual([]); expect(root().querySelector('app-indicador-screening-route')).not.toBeNull(); expect(titulos('.graphic-section .catalog-grid')).toEqual([ - 'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']); + 'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']); }); it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => { @@ -83,7 +83,7 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = // figure («Progresión por grupo de riesgo», withdrawn) comes back. abrir(CACU); expect(titulos('.graphic-section .catalog-grid')).toEqual([ - 'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']); + 'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']); expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull(); }); diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts index c609412..cec241f 100644 --- a/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.spec.ts @@ -3,7 +3,10 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { By } from '@angular/platform-browser'; +import eu7Fixture from './fixtures/eu7-c2-ejemplos.json'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; +import { IndicadorCacuDonas } from './indicador-cacu-donas'; +import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; @@ -11,10 +14,10 @@ import { GlobalApplied } from './indicadores-memory'; import { Indicador, IndicadorDatos } from './indicadores.models'; import { recolorFigure } from './indicadores-c2-palette'; import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion, - periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia'; + periodosConfirmacion, rangoTasas, seleccionBase, tasas, totalesPublicados, wilson } from './indicadores-confirmacion-citologia'; @Component({ selector: 'app-plotly-chart', template: '' }) -class ChartStub { figure = input(); label = input(); showNotes = input(); plotClick = output(); } +class ChartStub { figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA']; // Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and @@ -170,21 +173,22 @@ describe('Confirmación histopatológica: componente', () => { expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2'); r.flush(body as Record); f.detectChanges(); } - it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => { + it('carga diferida, solo las tasas (la dona vive en otra tarjeta), leyenda accesible, periodos y tabla', () => { f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); flush(); expect(f.componentInstance.status()).toBe('ready'); expect(f.componentInstance.model!.periodo).toBe('2026-S2'); - const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[]; - expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']); - const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub); + const figures = [...f.nativeElement.querySelectorAll('.figure')] as HTMLElement[]; + expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas']); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1); + expect(f.componentInstance.barras).toBeUndefined(); const normal = [...f.nativeElement.querySelectorAll('.legend .child, .legend .tab')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement; normal.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' }); expect(normal.getAttribute('aria-pressed')).toBe('true'); expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos'); - charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges(); + ([...f.nativeElement.querySelectorAll('.legend .tab')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === 'LIEAG o más')!.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' }); const table = f.nativeElement.querySelector('table') as HTMLTableElement; expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']); @@ -205,7 +209,7 @@ describe('Confirmación histopatológica: componente', () => { f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges(); expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); }); - it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => { + it('«Cómo leer» de las tasas muestra solo descripción y como_leer de fig_c2_barras', () => { f.componentRef.setInput('visible', false); f.detectChanges(); const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested); (f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges(); @@ -216,8 +220,8 @@ describe('Confirmación histopatológica: componente', () => { { figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges(); const help = f.nativeElement.querySelector('.methodology') as HTMLElement; - expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']); - for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent); + expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']); + for (const absent of ['Lee la dona.', 'No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent); }); it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => { f.componentRef.setInput('visible', false); f.detectChanges(); @@ -233,3 +237,162 @@ describe('Confirmación histopatológica: componente', () => { card.destroy(); http.expectNone(() => true); }); }); + +describe('Confirmación histopatológica: vista de la dona de biopsia', () => { + const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1', + figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] }; + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 }; + let f: ReturnType>; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + f = TestBed.createComponent(IndicadorConfirmacionCitologia); + f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('vista', 'dona'); + f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); }); + const flush = (body: IndicadorDatos = respuesta(['2026-S1', '2026-S2'])) => { + http.expectOne(req => req.url.endsWith('/datos')).flush(body as Record); f.detectChanges(); + }; + const apartado = () => (f.nativeElement.querySelector('.aparte').textContent as string).replace(/\s+/g, ' '); + // Why: the donut moved to the first card; it must draw only itself, answer its own buttons and keep what it leaves out. + it('dibuja solo las barras de la biopsia, responde a sus botones y dice qué queda fuera de la distribución', () => { + f.detectChanges(); flush(); + expect(f.componentInstance.ratesFigure).toBeUndefined(); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + // Two group headers with their subtotals; the six grades are the bars (a group is not a category). + const grupos = [...f.nativeElement.querySelectorAll('.grupo .cabecera')] as HTMLElement[]; + expect(grupos.map(g => g.textContent!.replace(/\s+/g, ' ').trim())).toEqual(['Grupo Menor que LIEAG 45 41.7 %', 'Grupo LIEAG o más 63 58.3 %']); + expect([...f.nativeElement.querySelectorAll('.filas .fila')].map((x: Element) => x.textContent!.replace(/\s+/g, ' ').trim())).toEqual([ + 'NORMAL 22 20.4 %', 'LIEBG 22 20.4 %', 'CIN2 1 0.9 %', 'LIEAG 44 40.7 %', 'Carcinoma in situ 13 12.0 %', 'CARCINOMA 6 5.6 %']); + const button = (name: string) => ([...f.nativeElement.querySelectorAll('.legend button')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === name)!; + button('NORMAL').click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' }); + expect(f.nativeElement.querySelector('.selection-status').textContent).not.toContain('Falsos positivos'); + button('LIEAG o más').click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' }); + expect(f.nativeElement.querySelector('.seleccion').textContent.replace(/\s+/g, ' ')).toContain('Selección: 63 de 108 (58.3 %)'); + expect(apartado()).toContain('Sin biopsia aún: 53; Sin dato: 6.'); + expect(f.nativeElement.querySelector('[aria-label="Tabla de resultados de biopsia"]').textContent).toContain('Sin biopsia aún'); + http.expectNone(() => true); + }); + it('«Cómo leer» muestra solo la guía de la figura de biopsia', () => { + f.componentRef.setInput('metadata', { figuras_detalle: [ + { figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, + { figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] }] }); + f.componentRef.setInput('visible', false); f.detectChanges(); + (f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges(); + const help = f.nativeElement.querySelector('.methodology') as HTMLElement; + expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.']); + }); + it('una celda fuera de la dona suprimida se dice «Suprimido» y no se convierte en cero', () => { + const datos = respuesta(['2026-S1', '2026-S2']); + Object.assign(datos.filas.find(r => r['periodo'] === '2026-S2' && r['estrato'] === 'LIEAG' && r['categoria'] === 'SIN_BIOPSIA')!, { n: 987654, suprimido: 1 }); + f.detectChanges(); flush(datos); + expect(apartado()).toContain('Sin biopsia aún: Suprimido'); expect(apartado()).not.toContain('987654'); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); + }); + it('totalesPublicados suma por grado y deja desconocido lo suprimido', () => { + const t = totalesPublicados(modeloConfirmacion(respuesta(['2026-S2']), '2026-S2')); + expect(t.grados.map(g => [g.id, g.n])).toEqual([['NORMAL', 22], ['LIEBG', 22], ['LIEAG', 44], ['CIS', 13], ['CARCINOMA', 6], ['CIN2', 1]]); + expect(t.aparte.map(a => [a.id, a.n, a.estado])).toEqual([['SIN_BIOPSIA', 53, 'Publicado'], ['SIN_DATO', 6, 'Publicado']]); + const datos = respuesta(['2026-S2']); + Object.assign(datos.filas.find(r => r['estrato'] === 'CIS' && r['categoria'] === 'SIN_DATO')!, { suprimido: 1 }); + const s = totalesPublicados(modeloConfirmacion(datos, '2026-S2')); + expect(s.aparte.find(a => a.id === 'SIN_DATO')).toMatchObject({ n: null, estado: 'Suprimido' }); + expect(s.aparte.find(a => a.id === 'SIN_BIOPSIA')!.n).toBe(53); + }); +}); + +describe('Tres donas de CaCu: independencia y reparto de solicitudes', () => { + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; + const eu7: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0', + figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'], + filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] }; + const confirmacion: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1', + figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] }; + let http: HttpTestingController; + let f: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorCacuDonas], providers: [provideHttpClient(), provideHttpClientTesting()] }); + for (const component of [IndicadorEu7Escenario, IndicadorConfirmacionCitologia]) + TestBed.overrideComponent(component, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + f = TestBed.createComponent(IndicadorCacuDonas); + f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', eu7); + f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + f.componentRef.setInput('confirmacion', confirmacion); f.componentRef.setInput('confirmacionApplied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); }); + const eu7Requests = () => ({ + general: http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')), + escenarios: http.expectOne(r => r.url.includes('/cacu_eu7/') && r.params.get('estrato') === 'estatus_seguimiento'), + }); + const biopsia = () => http.expectOne(r => r.url.includes('/cacu_confirmacion_citologia/')); + const eu7Component = () => f.debugElement.query(By.directive(IndicadorEu7Escenario)).componentInstance as IndicadorEu7Escenario; + const biopsiaComponent = () => f.debugElement.query(By.directive(IndicadorConfirmacionCitologia)).componentInstance as IndicadorConfirmacionCitologia; + it('muestra las distribuciones completas sin controles ni atenuación en la tarjeta', () => { + f.detectChanges(); + const e = eu7Requests(); const b = biopsia(); + e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento)); + b.flush(respuesta(['2025-S2']) as Record); f.detectChanges(); + expect([...f.nativeElement.querySelectorAll('h3')].map((h: HTMLElement) => h.textContent!.replace(/, 2025-S2$/, ''))).toEqual([ + 'Distribución de resultados citológicos', 'Resultados de VPH por genotipo', 'Resultado de la biopsia']); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2); + expect(f.nativeElement.querySelectorAll('.legend button, .selection-status, .seleccion, .atenuada')).toHaveLength(0); + expect(eu7Component().barras!.activas).toBeNull(); + expect(biopsiaComponent().barras!.activas).toBeNull(); + eu7Component().select('grupos', 1); biopsiaComponent().select('categorias', 0); f.detectChanges(); + expect(eu7Component().selection).toEqual({}); + expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' }); + expect(f.nativeElement.querySelectorAll('.atenuada, .seleccion')).toHaveLength(0); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales .cabecera').length).toBeGreaterThan(0); + expect(f.nativeElement.querySelectorAll('details.published-values')).toHaveLength(2); + const vph = f.nativeElement.querySelector('app-indicador-vph-genotipo') as HTMLElement; + expect(vph.textContent).toContain('No disponible'); expect(vph.querySelectorAll('button')).toHaveLength(0); + http.expectNone(() => true); + }); + // Why: the general filter is said once in the card header; a donut with a different effective period keeps its own line. + it('dice el filtro general una vez y conserva una indicación propia solo si el periodo efectivo difiere', () => { + f.detectChanges(); + expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(0); + expect(f.nativeElement.querySelector('.filtro').textContent).toContain('2025-S2'); + f.componentRef.setInput('confirmacionApplied', { ...applied, selection: { mode: 'explicit', periodos: ['2025-S1'] } }); + f.detectChanges(); + expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(1); + expect(f.nativeElement.querySelector('app-indicador-confirmacion-citologia .applied-summary').textContent).toContain('2025-S1'); + http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')).flush({}, { status: 500, statusText: 'x' }); + http.match(() => true); + }); + // Why: one failing donut must not hide the other two, and its retry repeats only its own request. + it('un error en la dona de biopsia no oculta la dona citológica y el reintento solo repite su solicitud', () => { + f.detectChanges(); + const e = eu7Requests(); const b = biopsia(); + e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento)); + b.flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + expect(biopsiaComponent().status()).toBe('error'); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); + expect(f.nativeElement.querySelector('app-indicador-eu7-escenario [role=alert]')).toBeNull(); + expect(f.nativeElement.querySelector('app-indicador-vph-genotipo').textContent).toContain('No disponible'); + biopsiaComponent().retry(); http.expectNone(r => r.url.includes('/cacu_eu7/')); + biopsia().flush(respuesta(['2025-S2']) as Record); f.detectChanges(); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2); + }); + // Why: the bars and the rates read the same source; a second HTTP request would double the load. + it('la dona y las tasas de la confirmación comparten una sola solicitud y conservan selecciones propias', () => { + const tasas = TestBed.createComponent(IndicadorConfirmacionCitologia); + tasas.componentRef.setInput('dominio', 'cacu'); tasas.componentRef.setInput('indicador', confirmacion); + tasas.componentRef.setInput('tema', 'claro'); tasas.componentRef.setInput('applied', applied); + f.detectChanges(); tasas.detectChanges(); + eu7Requests(); + biopsia().flush(respuesta(['2025-S2']) as Record); f.detectChanges(); tasas.detectChanges(); + expect(tasas.componentInstance.status()).toBe('ready'); + biopsiaComponent().select('grupos', 0); tasas.componentInstance.select('categorias', 0); + expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' }); + expect(biopsiaComponent().barras!.activas).toBeNull(); + expect(tasas.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' }); + http.expectNone(() => true); tasas.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts index 8d93106..74ea596 100644 --- a/src/app/features/indicadores/indicadores-confirmacion-citologia.ts +++ b/src/app/features/indicadores/indicadores-confirmacion-citologia.ts @@ -2,6 +2,7 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Theme } from './indicadores-c2-palette'; import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette'; import { percentNumber, shareText } from './indicadores-format'; +import { ConjuntoBarras } from './indicadores-barras'; // Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia): // a C2 stratified by the last valid cytology of the period; the category is the grade @@ -42,6 +43,7 @@ export interface ModeloConfirmacion { } export interface SeleccionConfirmacion { grupo: string; categoria?: string; } export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } +export interface TotalPublicado { id: string; etiqueta: string; n: number | null; estado: Celda['estado']; } export class ConfirmacionIncompatible extends Error {} const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); @@ -151,6 +153,34 @@ export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion) export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string { return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta; } +/** + * Women per grade (what the donut draws) and per category kept outside it, summed over the cytology rows. + * An unknown or suppressed cell makes its total unknown, never zero. + */ +export function totalesPublicados(m: ModeloConfirmacion): { grados: TotalPublicado[]; aparte: TotalPublicado[] } { + return { + grados: m.grados.map(g => { + const n = m.totales[g.id] ?? null; + return { id: g.id, etiqueta: g.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(m.filas.map(f => ({ n: f.den, estado: f.estado }))) }; + }), + aparte: m.aparte.map(a => { + const celdas = m.filas.map(f => f.aparte[a.id]), n = suma(celdas); + return { id: a.id, etiqueta: a.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(celdas) }; + }), + }; +} +/** The biopsy bars: the two groups of grades as headers, the grades as bars; what has no biopsy or no grade stays outside. */ +export function barrasBiopsia(m: ModeloConfirmacion, sel: SeleccionConfirmacion): ConjuntoBarras { + const t = totalesPublicados(m); + return { + grupos: m.grupos.map(g => { + const filas = g.grados.map(id => { const grado = m.grados.find(x => x.id === id)!, total = t.grados.find(x => x.id === id)!; + return { id, etiqueta: grado.etiqueta, n: total.n, estado: total.estado, color: grado.color }; }); + return { id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0), filas }; + }), + den: m.conBiopsia, unidad: 'mujeres con biopsia', activas: new Set(seleccionados(m, sel)), + }; +} /** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */ export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion { if (traza === 'centro') return seleccionBase(m); diff --git a/src/app/features/indicadores/indicadores-eu7-escenario.ts b/src/app/features/indicadores/indicadores-eu7-escenario.ts index d3a9060..fa55cd9 100644 --- a/src/app/features/indicadores/indicadores-eu7-escenario.ts +++ b/src/app/features/indicadores/indicadores-eu7-escenario.ts @@ -2,6 +2,7 @@ import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Theme } from './indicadores-c2-palette'; import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette'; import { percentNumber, shareText } from './indicadores-format'; +import { ConjuntoBarras } from './indicadores-barras'; // Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts. // This boundary is intentionally specific to EU7. Unknown cells never become zero. @@ -163,6 +164,15 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe } const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo); const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id])); +/** The cytology bars: the groups of the inner ring as headers, the categories of the outer ring as bars; «Sin dato» stays outside. */ +export function barrasCitologia(m: Modelo, sel: Seleccion): ConjuntoBarras { + return { + grupos: m.grupos.map(g => ({ id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: nGrupo(m, g.id), + filas: hijas(m, g.id).map(c => ({ id: c.id, etiqueta: c.etiqueta, n: m.celdas[c.id].n, estado: m.celdas[c.id].estado, color: c.color })) })), + den: m.total, unidad: 'pacientes con resultado', + activas: sel.categoria ? new Set([sel.categoria]) : sel.grupo ? new Set(hijas(m, sel.grupo).map(c => c.id)) : null, + }; +} export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string { return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta : sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL'; @@ -212,7 +222,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure { labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true), textfont: { size: 11 }, hovertext: hoverText(exterior), marker: { colors: m.categorias.map(c => cacuRgba(c.color, alpha(c.id))), line: { color: p.background, width: 2 } } }, - ], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, + ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } /** Absolute counts, one independent bar per category inside each clinical scenario. The selection only chooses which diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a9d5a44..96a060c 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -130,7 +130,7 @@
    @for (item of clinicosItems(); track cardIdentity(item)) { + [pinned]="isPinned(item)" [companion]="companion(item)" [companionApplied]="companionApplied(item)" [vph]="vph(item)" [vphApplied]="vphApplied(item)" (pinChanged)="togglePinned(item)" /> } @if (histopatologiaPendiente) { }
    diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 2ac3df6..7d499f9 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -24,6 +24,8 @@ import { IndicadorScreeningRoute } from './indicador-screening-route'; import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { IndicadorFiguraPendiente } from './indicador-figura-pendiente'; +import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; +import { ID_VPH } from './indicadores-vph-genotipo'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; import { identityElementId, indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; @@ -326,6 +328,11 @@ export class IndicadoresPage { }; readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] }; figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); } + // The biopsy donut of the histopathological confirmation indicator is drawn on CaCu's EU7 card. + companion(item: Indicador) { return this.dominio === 'cacu' && item.id === 'cacu_eu7' ? this.catalog().find(other => other.id === ID_CONFIRMACION) : undefined; } + companionApplied(item: Indicador) { const other = this.companion(item); return other ? this.figureApplied(other) : undefined; } + vph(item: Indicador) { return this.dominio === 'cacu' && item.id === 'cacu_eu7' ? this.catalog().find(other => other.id === ID_VPH) : undefined; } + vphApplied(item: Indicador) { const other = this.vph(item); return other ? this.figureApplied(other) : undefined; } independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); } kpiIndicator(id: string) { const published = this.catalog().find(item => item.id === id); @@ -442,7 +449,8 @@ export class IndicadoresPage { const items = this.searchResults().items; if (this.dominio === 'cacu') { // The opportunity section already presents the time figures and the treatment KPIs. - const clinicos = items.filter(item => item.figuras.length && !this.esKpiTratamientoCacu(item.id) + // HPV by genotype is drawn on the donut card, not as a card of its own. + const clinicos = items.filter(item => item.figuras.length && item.id !== ID_VPH && !this.esKpiTratamientoCacu(item.id) && !CACU_FIGURAS_OPORTUNIDAD.some(figura => figura.id === item.id)); return [...CACU_FIGURAS_CLINICAS.flatMap(id => clinicos.filter(item => item.id === id)), ...clinicos.filter(item => !CACU_FIGURAS_CLINICAS.includes(item.id))]; } diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 24a79b9..dfe8842 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -63,6 +63,9 @@ } @if (dominio === 'cacu') { + + + @if (columnasDelEstatus(draft.estatus).length) { + @if (errorBusqueda) {

    {{ errorBusqueda }}

    } + @if (errorEdad) { } + @if (dominio === 'cacu') { + + } @if (status === 'loading') {

    Cargando seguimiento…

    } @if (status === 'pending') {

    El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.

    } @if (message && status !== 'pending') {

    {{ message }}

    } @@ -131,35 +145,32 @@
    } @else if (data; as response) { - - @let visibles = pacientesVisibles(response);

    - @if (buscandoCaCu) { {{ visibles.length }} de {{ response.items.length }} registros de esta página coinciden. } + @if (buscandoCaCu || rangoEdadAplicado) { {{ response.paginacion.total_items }} {{ response.paginacion.total_items === 1 ? 'registro coincide' : 'registros coinciden' }} con la búsqueda y el rango de edad en toda la consulta. } Los archivos de exportación incluyen toda la consulta.

    +
    - @for (c of columnasProbabilidad(); track c) {} + @for (c of columnasProbabilidad(); track c) {} - @for (item of visibles; track identidad(item).id) { + @for (item of response.items; track identidad(item).id) { - + @for (c of columnasProbabilidad(); track c) { } - + + + @if (rutaAbierta === identidad(item).id && item.ruta_tamizaje; as ruta) { + + } } @empty { }
    Resultados disponibles por paciente
    {{ etiquetaIdentidad(response) }}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
    {{ etiquetaIdentidad(response) }}EdadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHÚltima biopsia{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)Días de toma a diagnósticoPrioridadEtapas
    No disponible @if (item.grupo_edad !== 'sin_dato') { Grupo de edad: {{ item.grupo_edad }} }{{ item.estatus.etiqueta }}{{ edadTexto(item) }}{{ 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' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
    - {{ buscandoCaCu ? 'No hay coincidencias en esta página.' : 'No hay registros para los filtros aplicados.' }} + {{ buscandoCaCu || rangoEdadAplicado ? 'No hay coincidencias para la búsqueda y el rango de edad.' : 'No hay registros para los filtros aplicados.' }}
    diff --git a/src/app/features/indicadores/indicadores-tracking.scss b/src/app/features/indicadores/indicadores-tracking.scss index 0acc15d..6d7e87d 100644 --- a/src/app/features/indicadores/indicadores-tracking.scss +++ b/src/app/features/indicadores/indicadores-tracking.scss @@ -46,3 +46,5 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); } // TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page. .ficha-tea > button { margin-bottom: .5rem; } + +tr.detalle-ruta > td { padding: 1rem; background: var(--issste-background); } diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 4576ce2..a0cafde 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -2,10 +2,12 @@ import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Inje import { FormsModule } from '@angular/forms'; import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; +import { catchError, debounceTime, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; import { acotarTamano, PAGE_SIZE_MAX, SeguimientoTablaResponse, SeguimientoTablaService } from './seguimiento-tabla.service'; -import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { EtapasCompacta, EtapasLeyenda } from './ruta-tamizaje/etapas-compacta'; +import { EtapasDetalle } from './ruta-tamizaje/etapas-detalle'; +import { COLUMNAS_DE_PROBABILIDAD, edadTexto, ETIQUETA_PROBABILIDAD, filtrosConfirmados, CONSULTA_MAXIMA, incumpleConsulta, normalizarConsulta, probabilidadAl, rangoEdadValido, 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'; @@ -19,11 +21,10 @@ import { TeaPacienteResumen } from './tea-paciente-resumen'; import { TrackingExportBar } from './export/tracking-export-bar'; import { consultaExportacionCaCu, tablaExportacionCaCu } from './export/cacu-tracking-export'; -const normalizarBusqueda = (texto: string) => texto.trim().normalize('NFD').replace(/\p{M}/gu, '').toLowerCase(); @Component({ selector: 'app-indicadores-tracking', - imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla, TrackingExportBar], + imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla, TrackingExportBar, EtapasCompacta, EtapasDetalle, EtapasLeyenda], providers: [PacienteDetalleState], templateUrl: './indicadores-tracking.html', styleUrl: './indicadores-tracking.scss', @@ -64,16 +65,50 @@ export class IndicadoresTracking implements OnChanges { data?: SeguimientoResponse; exportacionCaCu?: SeguimientoTablaResponse; readonly origenExportacionCaCu: Pick = { - consultar: (_dominio, q) => this.service.consultar(consultaExportacionCaCu(q)).pipe(map(respuesta => this.tablaExportacion(respuesta))), + // The file is built from the query the server confirms; an answer that does not confirm it is not exported. + consultar: (_dominio, q) => { + const consulta = consultaExportacionCaCu(q); + return this.service.consultar(consulta).pipe(map(respuesta => { + if (!filtrosConfirmados(consulta, respuesta.filtros)) throw new Error('El servicio no confirmó la búsqueda o el rango de edad de la exportación.'); + return this.tablaExportacion(respuesta, consulta); + })); + }, }; + // The identifier search is the server's: the text waits a moment after the last key, then asks for page 1 of the + // whole query. The rows shown are exactly the ones the server returns; nothing filters them again here. busquedaCaCu = ''; - get buscandoCaCu() { return !!normalizarBusqueda(this.busquedaCaCu); } - pacientesVisibles(respuesta: SeguimientoResponse) { - const consulta = normalizarBusqueda(this.busquedaCaCu); - return consulta ? respuesta.items.filter(item => normalizarBusqueda(this.identidad(item).id).includes(consulta)) : respuesta.items; + private readonly busquedas = new Subject(); + /** The search applied to the answer on screen. */ + get buscandoCaCu() { return !!this.applied.q; } + /** Set when the age range typed is not valid; no request goes out until it is. */ + errorEdad = ''; + errorBusqueda = ''; + get rangoEdadAplicado() { return this.applied.edad_min !== undefined || this.applied.edad_max !== undefined; } + readonly consultaMaxima = CONSULTA_MAXIMA; + escribirBusqueda(texto: string) { this.busquedaCaCu = texto; this.busquedas.next(texto); } + limpiarBusqueda() { this.busquedaCaCu = ''; this.buscar(''); } + buscar(texto: string) { + const q = normalizarConsulta(texto) || undefined; + if (this.dominio !== 'cacu' || q === this.applied.q) return; + if (q && q.length > CONSULTA_MAXIMA) { this.errorBusqueda = `La búsqueda admite hasta ${CONSULTA_MAXIMA} caracteres.`; this.changeDetector.markForCheck(); return; } + this.errorBusqueda = ''; + this.load({ ...this.applied, q, page: 1 }); } - private tablaExportacion(respuesta: SeguimientoResponse) { - return tablaExportacionCaCu(respuesta, estudio => this.cytologyLabel(estudio), (item, clave, horizonte) => this.probabilidad(item, clave, horizonte)); + limpiarRangoEdad() { this.draft.edad_min = undefined; this.draft.edad_max = undefined; this.apply(); } + private tablaExportacion(respuesta: SeguimientoResponse, consulta?: Pick) { + return tablaExportacionCaCu(respuesta, estudio => this.cytologyLabel(estudio), (item, clave, horizonte) => this.probabilidad(item, clave, horizonte), consulta); + } + // An older server ignores `q`, `edad_min` and `edad_max`. If a returned row breaks the query asked, the answer is not + // shown as a search of the whole list: the user is told, and no partial result is presented. + private respuestaDeLaConsulta(q: SeguimientoQuery, data: SeguimientoResponse) { + const consulta = { q: q.q, edad_min: q.edad_min, edad_max: q.edad_max }; + const filtrada = !!(q.q || q.edad_min !== undefined || q.edad_max !== undefined); + // The server must say the parameters it applied (`filtros`); the rows are a second check, never the only one. + if (filtrada && (!filtrosConfirmados(q, data.filtros) || data.items.some(item => incumpleConsulta(q, this.identidad(item).id, item)))) { + return { data: undefined, consulta, status: 'error' as const, + message: 'El servicio no confirmó la búsqueda o el rango de edad, así que no se muestran resultados parciales. Quita la búsqueda y el rango, o actualiza el servicio.' }; + } + return { data, consulta, message: '', status: 'ready' as const }; } teaData?: TeaSeguimientoResponse; // One open summary at a time, like an accordion. @@ -108,7 +143,10 @@ export class IndicadoresTracking implements OnChanges { return `${porcentaje(h.probabilidad)} %${ic}`; } private applied: SeguimientoQuery = { ...this.draft }; - readonly latestStudy = latestStudy; + readonly edadTexto = edadTexto; + /** The patient whose route detail is open; one at a time, and any new list closes it. */ + rutaAbierta?: string; + alternarRuta(id: string) { this.rutaAbierta = this.rutaAbierta === id ? undefined : id; } readonly gruposEdad = GRUPOS_EDAD_TEA; readonly rangosMchat = RANGOS_MCHAT; readonly rangosCss = RANGOS_CSS; @@ -122,16 +160,18 @@ export class IndicadoresTracking implements OnChanges { const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const, message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.' : error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' }); + this.busquedas.pipe(debounceTime(400), takeUntilDestroyed(this.destroy)).subscribe(texto => this.buscar(texto)); this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe( - map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => { + map(data => this.respuestaDeLaConsulta(q, data)), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => { if (!result) return; this.changeDetector.markForCheck(); this.status = result.status; this.data = result.data; this.message = result.message; - this.exportacionCaCu = result.data && this.tablaExportacion(result.data); + this.exportacionCaCu = result.data && this.tablaExportacion(result.data, result.consulta); 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, orden: data.filtros.orden, horizonte: data.filtros.horizonte, 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, + q: result.consulta?.q, edad_min: result.consulta?.edad_min, edad_max: result.consulta?.edad_max }; this.draft = { ...this.applied }; if (!this.metadataLoaded) { this.metadataLoaded = true; @@ -166,7 +206,7 @@ export class IndicadoresTracking implements OnChanges { this.teaFicha = undefined; this.controlTea = undefined; this.pacienteDetalle.cerrar(); this.controlPaciente = undefined; this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined; - this.exportacionCaCu = undefined; this.busquedaCaCu = ''; + this.exportacionCaCu = undefined; this.busquedaCaCu = ''; this.errorEdad = ''; this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft }; } if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); } @@ -175,15 +215,26 @@ export class IndicadoresTracking implements OnChanges { private load(q: SeguimientoQuery) { if (this.dominio !== 'cacu' && this.dominio !== 'tea') return; if (!validSeguimientoQuery(q)) { this.message = `Revisa la fecha, la ventana y el tamaño de página (1 a ${PAGE_SIZE_MAX}).`; return; } + this.changeDetector.markForCheck(); + this.rutaAbierta = undefined; this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q }; this.exportacionCaCu = undefined; - (this.dominio === 'tea' ? this.teaRequests : this.requests).next(q); + // CaCu's rows come with their screening route summary; the detail is asked only when a row opens. + (this.dominio === 'tea' ? this.teaRequests : this.requests).next(this.dominio === 'cacu' ? { ...q, incluir: 'ruta_tamizaje' } : q); } 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 }); + for (const clave of ['edad_min', 'edad_max'] as const) { + const valor = this.draft[clave] as number | null | undefined; + this.draft[clave] = valor === null || valor === undefined || (valor as unknown) === '' ? undefined : Number(valor); + } + if (this.dominio === 'cacu' && !rangoEdadValido(this.draft.edad_min, this.draft.edad_max)) { + this.errorEdad = 'Las edades son años enteros desde 0 y la mínima no puede superar a la máxima.'; this.changeDetector.markForCheck(); return; + } + this.errorEdad = ''; this.changeDetector.markForCheck(); + this.load({ ...this.draft, q: this.applied.q, page: 1 }); } retry() { this.load(this.applied); } navigate(page: number) { diff --git a/src/app/features/indicadores/indicadores-vph-genotipo.spec.ts b/src/app/features/indicadores/indicadores-vph-genotipo.spec.ts new file mode 100644 index 0000000..212cf6a --- /dev/null +++ b/src/app/features/indicadores/indicadores-vph-genotipo.spec.ts @@ -0,0 +1,183 @@ +import { Component, input, output } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import eu7Fixture from './fixtures/eu7-c2-ejemplos.json'; +import { IndicadorVphGenotipo } from './indicador-vph-genotipo'; +import { IndicadorCacuDonas } from './indicador-cacu-donas'; +import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; +import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { datosDeReportes, indicadorDeMeasure, Measure, Report } from './indicadores-fhir'; +import { GlobalApplied } from './indicadores-memory'; +import { Indicador, IndicadorDatos } from './indicadores.models'; +import { barrasVph, modeloVph, periodosVph, VphIncompatible } from './indicadores-vph-genotipo'; +import { isCoffeeColor } from './indicadores-c2-palette'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); showNotes = input(); animated = input(); plotClick = output(); } + +// The Measure and reports follow the shapes WebApi publishes for CACU-VPH-GENOTIPO (synthetic counts written for these tests). +const CATEGORIAS = [['NEGATIVO', 'Negativo', '#9DBFE3'], ['POSITIVO_16', 'Positivo 16 exclusivamente', '#2F6DB3'], ['POSITIVO_18', 'Positivo 18 exclusivamente', '#E8C28E'], + ['POSITIVO_16_18', 'Positivo 16 y 18', '#D98E4A'], ['POSITIVO_SIN_16_18', 'Positivo sin detección de 16/18', '#B55A1F'], + ['POSITIVO_INCOMPLETO', 'Positivo con genotipificación incompleta', '#7A2E0E'], ['INDETERMINADO', 'Indeterminado', '#A0A0A0'], ['INCONSISTENTE', 'No clasificable o inconsistente', '#C9CDD2']]; +const MEASURE = { + resourceType: 'Measure', id: 'CACU-VPH-GENOTIPO', url: 'https://isssteleon.org/fhir/Measure/CACU-VPH-GENOTIPO', version: '0.1.0', title: 'Resultados de VPH por genotipo', + subjectCodeableConcept: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/unidad', code: 'examen' }] }, + extension: [ + { url: 'https://isssteleon.org/fhir/StructureDefinition/contrato', valueCode: 'C2' }, + { url: 'https://isssteleon.org/fhir/StructureDefinition/tipos-periodo', valueCode: 'semestre' }, { url: 'https://isssteleon.org/fhir/StructureDefinition/tipos-periodo', valueCode: 'mes' }, + { url: 'https://isssteleon.org/fhir/StructureDefinition/figuras', valueString: 'fig_c2_donas' }, + ...CATEGORIAS.map(([codigo, etiqueta, color]) => ({ url: 'https://isssteleon.org/fhir/StructureDefinition/categoria', + extension: [{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: etiqueta }, { url: 'color', valueString: color }] })), + ], + group: [{ code: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/grupo-medida', code: 'TOTAL' }] } }], +} as unknown as Measure; +const informe = (inicio: string, fin: string, total: number, estratos: [string, number][]): Report => ({ + resourceType: 'MeasureReport', status: 'complete', period: { start: inicio, end: fin }, + group: [{ code: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/grupo-medida', code: 'TOTAL' }] }, + population: [{ code: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/measure-population', code: 'initial-population' }] }, count: total }], + stratifier: [{ code: [{ coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/estratificador', code: 'categoria' }] }], + stratum: estratos.map(([codigo, n]) => ({ value: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/categoria', code: codigo }] }, + population: [{ code: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/measure-population', code: 'initial-population' }] }, count: n }] })) }] }], +}) as unknown as Report; +const SEMESTRAL = informe('2025-01-01', '2025-06-30', 2, [['POSITIVO_16', 1], ['POSITIVO_SIN_16_18', 1]]); +const MENSUAL_CERO = informe('2025-03-01', '2025-03-31', 0, []); +const datos = (reportes: Report[], tipo: 'semestre' | 'mes' = 'semestre') => datosDeReportes(MEASURE, reportes, tipo); +const indicador: Indicador = indicadorDeMeasure(MEASURE); + +describe('VPH por genotipo: modelo', () => { + it('el Measure se publica con el id de WebApp y sus ocho categorías en el orden publicado', () => { + expect(indicador.id).toBe('cacu_vph_genotipo'); expect(indicador.contrato).toBe('C2'); expect(indicador.tipos_periodo).toEqual(['semestre', 'mes']); + const m = modeloVph(datos([SEMESTRAL]), '2025-S1'); + expect(m.categorias.map(c => c.id)).toEqual(CATEGORIAS.map(c => c[0])); + expect(m.categorias.map(c => c.etiqueta)).toEqual(CATEGORIAS.map(c => c[1])); + }); + it('distribución válida: total de reportes, conteos y ceros publicados, sin convertir lo incompleto o indeterminado en negativo', () => { + const m = modeloVph(datos([SEMESTRAL]), '2025-S1'); + expect(m.estado).toBe('datos'); expect(m.total).toBe(2); + expect(Object.fromEntries(m.categorias.map(c => [c.id, c.n]))).toEqual({ NEGATIVO: 0, POSITIVO_16: 1, POSITIVO_18: 0, POSITIVO_16_18: 0, POSITIVO_SIN_16_18: 1, POSITIVO_INCOMPLETO: 0, INDETERMINADO: 0, INCONSISTENTE: 0 }); + expect(m.categorias.reduce((s, c) => s + c.n, 0)).toBe(m.total); + }); + it('población cero no es una distribución; un periodo sin reporte es ausencia', () => { + const cero = modeloVph(datos([MENSUAL_CERO], 'mes'), '2025-03'); + expect(cero.estado).toBe('cero'); expect(cero.total).toBe(0); expect(barrasVph(cero).den).toBe(0); + const ausente = modeloVph(datos([SEMESTRAL]), '2025-S2'); + expect(ausente.estado).toBe('ausente'); expect(ausente.total).toBeNull(); expect(barrasVph(ausente).grupos[0].filas).toEqual([]); + }); + it('rechaza lo que no puede dibujar: otro indicador, categorías que no suman, población no publicada', () => { + expect(() => periodosVph({ ...datos([SEMESTRAL]), id: 'cacu_eu7' } as IndicadorDatos, 'semestre')).toThrow(VphIncompatible); + expect(() => modeloVph(datos([informe('2025-01-01', '2025-06-30', 3, [['POSITIVO_16', 1]])]), '2025-S1')).toThrow(VphIncompatible); + expect(() => modeloVph({ ...datos([SEMESTRAL]), unidades_periodo: {} } as IndicadorDatos, '2025-S1')).toThrow(VphIncompatible); + }); + it('periodos: los solicitados en su orden o, sin pedirlos, los reportados', () => { + const d = datos([SEMESTRAL]); + expect(periodosVph(d, 'semestre', ['2025-S2', '2025-S1'])).toEqual(['2025-S2', '2025-S1']); expect(periodosVph(d, 'semestre')).toEqual(['2025-S1']); + }); + it('las barras: ocho categorías planas en el orden publicado, sin grupos, y colores de CaCu fuera de los cafés', () => { + const m = modeloVph(datos([SEMESTRAL]), '2025-S1'), b = barrasVph(m); + expect(b.grupos).toHaveLength(1); expect(b.grupos[0].etiqueta).toBeNull(); expect(b.den).toBe(2); expect(b.unidad).toBe('reportes de VPH elegibles'); expect(b.activas).toBeNull(); + expect(b.grupos[0].filas.map(f => [f.id, f.n])).toEqual(CATEGORIAS.map(c => [c[0], c[0] === 'POSITIVO_16' || c[0] === 'POSITIVO_SIN_16_18' ? 1 : 0])); + const colores = m.categorias.map(c => c.color); + expect(new Set(colores).size).toBe(8); expect(colores.filter(c => isCoffeeColor(c))).toEqual([]); + }); +}); + +describe('VPH por genotipo: componente', () => { + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 }; + let http: HttpTestingController, f: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorVphGenotipo], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorVphGenotipo, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); f = TestBed.createComponent(IndicadorVphGenotipo); + f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('applied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); }); + const pedir = () => http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')); + const texto = () => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' '); + + it('una solicitud; dona, categorías con conteos y porcentajes, total de reportes y la definición provisional', () => { + f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); + const r = pedir(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(datos([SEMESTRAL]) as never); f.detectChanges(); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); + expect(texto()).toContain('Resultados de VPH por genotipo, 2025-S1'); + expect(texto()).toContain('Positivo 16 exclusivamente 1 50.0 %'); expect(texto()).toContain('Positivo 16 y 18 0 0.0 %'); + expect(f.nativeElement.querySelectorAll('.filas .fila')).toHaveLength(8); expect(f.nativeElement.querySelectorAll('.grupo')).toHaveLength(0); + expect(texto()).toContain('Total: 2 reportes de VPH elegibles'); + expect(texto()).not.toContain('Definición provisional, pendiente de ratificación clínica'); + expect(texto()).not.toContain('no identifica otro genotipo específico'); + expect((f.nativeElement as HTMLElement).querySelectorAll('button')).toHaveLength(0); + http.expectNone(() => true); + }); + it('población cero y ausencia de reporte se dicen y no dibujan dona', () => { + f.detectChanges(); pedir().flush(datos([MENSUAL_CERO], 'mes') as never); + f.componentRef.setInput('applied', { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-03', '2025-04'] } }); f.detectChanges(); + http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush(datos([MENSUAL_CERO], 'mes') as never); f.detectChanges(); + // The most recent requested period (2025-04) has no report; the previous one has zero units. + expect(texto()).toContain('Sin reporte publicado para 2025-04'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0); + f.componentInstance.changePeriod(-1); f.detectChanges(); + expect(texto()).toContain('Sin reportes de VPH elegibles en 2025-03'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0); + expect(texto()).not.toContain('Total de reportes'); + }); + it('cambiar de periodo no pide datos y cambiar el periodo aplicado pide los nuevos', () => { + const dos = datos([SEMESTRAL, informe('2025-07-01', '2025-12-31', 3, [['NEGATIVO', 3]])]); + f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] } }); f.detectChanges(); + pedir().flush(dos as never); f.detectChanges(); + expect(texto()).toContain('2025-S2, 2 de 2'); expect(texto()).toContain('Negativo 3 100.0 %'); + f.componentInstance.changePeriod(-1); f.detectChanges(); expect(texto()).toContain('Positivo 16 exclusivamente 1 50.0 %'); http.expectNone(() => true); + f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('loading'); pedir(); + }); + it('un error de servicio se anuncia y el reintento repite la solicitud; una respuesta que no suma es incompatible', () => { + f.detectChanges(); pedir().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect((f.nativeElement as HTMLElement).querySelector('[role=alert]')).not.toBeNull(); + f.componentInstance.retry(); pedir().flush(datos([informe('2025-01-01', '2025-06-30', 5, [['POSITIVO_16', 1]])]) as never); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0); + }); + // Why: a server without the Measure keeps working; the section says so and asks for nothing. + it('sin el Measure (servidor anterior) dice «No disponible» y no hace solicitudes', () => { + f.componentRef.setInput('indicador', undefined); f.detectChanges(); + expect(texto()).toContain('No disponible: el servicio todavía no publica este indicador'); http.expectNone(() => true); + }); + it('fuera de vista no pide datos hasta ser visible', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); + f.componentRef.setInput('visible', true); f.detectChanges(); pedir(); + }); +}); + +describe('VPH por genotipo en la tarjeta de tres donas', () => { + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 }; + const eu7: Indicador = { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2', version: '0.3.0', figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'], + filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] }; + let http: HttpTestingController, f: ReturnType>; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorCacuDonas], providers: [provideHttpClient(), provideHttpClientTesting()] }); + for (const c of [IndicadorEu7Escenario, IndicadorConfirmacionCitologia, IndicadorVphGenotipo]) TestBed.overrideComponent(c, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); f = TestBed.createComponent(IndicadorCacuDonas); + f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', eu7); f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + f.componentRef.setInput('vph', indicador); f.componentRef.setInput('vphApplied', applied); + }); + afterEach(() => { f.destroy(); http.match(() => true); }); + // Why: HPV must never touch the cytology and biopsy donuts: its own request, its own failure. + it('un error de VPH no afecta las barras citológicas y el filtro común se dice una vez', () => { + f.detectChanges(); + http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')).flush(structuredClone(eu7Fixture.general)); + http.expectOne(r => r.url.includes('/cacu_eu7/') && r.params.get('estrato') === 'estatus_seguimiento').flush(structuredClone(eu7Fixture.estatus_seguimiento)); + http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + const vph = f.nativeElement.querySelector('app-indicador-vph-genotipo') as HTMLElement; + expect(vph.querySelector('[role=alert]')).not.toBeNull(); + expect(f.nativeElement.querySelectorAll('app-barras-horizontales').length).toBe(1); + expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(0); + expect(f.nativeElement.querySelectorAll('app-indicador-eu7-escenario .legend button')).toHaveLength(0); + expect(f.nativeElement.querySelectorAll('app-indicador-eu7-escenario .atenuada')).toHaveLength(0); + expect(vph.querySelector('[role=alert]')).not.toBeNull(); expect(vph.querySelectorAll('button').length).toBe(1); + }); + it('VPH con datos comparte la fila del cuerpo y no pide más de una solicitud', () => { + f.detectChanges(); + const d = datos([informe('2025-07-01', '2025-12-31', 3, [['NEGATIVO', 3]])]); + http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush(d as never); f.detectChanges(); + expect(f.nativeElement.querySelector('app-indicador-vph-genotipo h3').textContent).toContain('Resultados de VPH por genotipo, 2025-S2'); + expect(f.nativeElement.querySelectorAll('app-indicador-vph-genotipo .filas .fila')).toHaveLength(8); + }); +}); diff --git a/src/app/features/indicadores/indicadores-vph-genotipo.ts b/src/app/features/indicadores/indicadores-vph-genotipo.ts new file mode 100644 index 0000000..8007e02 --- /dev/null +++ b/src/app/features/indicadores/indicadores-vph-genotipo.ts @@ -0,0 +1,62 @@ +import { IndicadorDatos } from './indicadores.models'; +import { cacuClinicalColor } from './indicadores-cacu-palette'; +import { shareText } from './indicadores-format'; +import { ConjuntoBarras } from './indicadores-barras'; + +// HPV result by genotype (CACU-VPH-GENOTIPO, a C2 composition): the unit is the eligible HPV report linked to a +// sample, not the patient, so one patient may contribute several; the period is the sample's. The definition is +// provisional, pending clinical ratification. A category with no reports in a period is a zero, and a period whose +// units are zero is not a distribution. +export const ID_VPH = 'cacu_vph_genotipo'; +export class VphIncompatible extends Error {} + +export interface CategoriaVph { id: string; etiqueta: string; color: string; n: number; } +export type EstadoVph = 'ausente' | 'cero' | 'datos'; +export interface ModeloVph { periodo: string; estado: EstadoVph; total: number | null; categorias: CategoriaVph[]; } + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const fail = (message: string): never => { throw new VphIncompatible(message); }; + +function validar(datos: IndicadorDatos, tipo: string) { + if (datos.id !== ID_VPH || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || !Array.isArray(datos.periodos) + || datos.periodos.some(p => typeof p !== 'string')) return fail('Los datos no corresponden a VPH por genotipo o al periodo aplicado.'); +} + +/** The periods to offer: the requested ones in order (one without a report is shown as absent) or, with none requested, the reported ones. */ +export function periodosVph(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { + validar(datos, tipo); + return solicitados ? [...solicitados] : [...datos.periodos].sort(); +} + +/** One period of the response: absent (no report), zero units, or the distribution of its eligible reports. */ +export function modeloVph(datos: IndicadorDatos, periodo: string): ModeloVph { + validar(datos, datos.tipo_periodo); + const cats = datos['categorias']; + if (!registro(cats) || !Object.keys(cats).length) return fail('Catálogo de categorías de VPH incompleto.'); + const definidas = Object.entries(cats).map(([id, c]) => { + if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim()) return fail('Categoría de VPH incompatible.'); + return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, typeof c['color'] === 'string' ? c['color'] : null) }; + }); + if (!datos.periodos.includes(periodo)) return { periodo, estado: 'ausente', total: null, categorias: [] }; + const unidades = registro(datos['unidades_periodo']) ? datos['unidades_periodo'][periodo] : undefined; + if (typeof unidades !== 'number' || !Number.isSafeInteger(unidades) || unidades < 0) return fail('La población del periodo no se publica.'); + const filas = new Map(); + for (const f of datos.filas.filter(r => r['periodo'] === periodo)) { + const categoria = f['categoria'], n = f['n']; + if (typeof categoria !== 'string' || !definidas.some(d => d.id === categoria) || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) return fail('Fila de VPH inválida.'); + filas.set(categoria, n); + } + const categorias = definidas.map(d => ({ ...d, n: filas.get(d.id) ?? 0 })); + // Categories that do not add up to the report's units cannot be drawn as a partition: say so, never undercount. + if (categorias.reduce((s, c) => s + c.n, 0) !== unidades) return fail('Los conteos por categoría no suman los reportes del periodo.'); + return { periodo, estado: unidades === 0 ? 'cero' : 'datos', total: unidades, categorias }; +} + +export const porcentajeVph = (n: number, total: number) => shareText(n, total); + +/** The HPV bars: the eight categories in the published order, flat, with no selection. */ +export function barrasVph(m: ModeloVph): ConjuntoBarras { + return { grupos: [{ id: null, etiqueta: null, color: '#8A9199', subtotal: m.total, + filas: m.categorias.map(c => ({ id: c.id, etiqueta: c.etiqueta, n: c.n, estado: 'Publicado' as const, color: c.color })) }], + den: m.total, unidad: 'reportes de VPH elegibles', activas: null }; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index 47fb10b..a276722 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -64,7 +64,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { fixture.detectChanges(); } function volver() { - root.querySelector('app-paciente-detalle > button')!.click(); + root.querySelector('app-paciente-detalle .back-button')!.click(); fixture.detectChanges(); } function boton(texto: string) { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-linea.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-linea.spec.ts new file mode 100644 index 0000000..9bc4b79 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-linea.spec.ts @@ -0,0 +1,114 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { of } from 'rxjs'; +import { DominioRiesgo, LoteRiesgoCacu, PacienteRiesgoProvider } from './paciente-riesgo.models'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; +import { nodosRiesgo } from './paciente-riesgo.presentacion'; +import { prediccion, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo } from './paciente-riesgo.testing'; +import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; + +describe('Riesgo individual CaCu: línea de tiempo horizontal', () => { + function setup(data: unknown, opciones: { dominio?: DominioRiesgo; estatus?: string } = {}) { + const provider: PacienteRiesgoProvider = { obtener: () => of(data) }; + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] }); + const fixture = TestBed.createComponent(PacienteRiesgoTabla); + fixture.componentRef.setInput('pacId', '42'); + if (opciones.dominio) fixture.componentRef.setInput('dominio', opciones.dominio); + if (opciones.estatus) fixture.componentRef.setInput('estatus', opciones.estatus); + fixture.detectChanges(); fixture.detectChanges(); + return fixture; + } + afterEach(() => { TestBed.inject(HttpTestingController).verify(); }); + const texto = (e: Element | null | undefined) => (e?.textContent ?? '').replace(/\s+/g, ' ').trim(); + const nodos = (root: HTMLElement, linea = 0) => [...root.querySelectorAll('.risk-timeline')[linea].querySelectorAll('.risk-line li')]; + + // Why: the timeline replaces the table as the main view, so it must carry every value and interval the table has. + it('reproduce cada horizonte, probabilidad e intervalo de la tabla, en el mismo orden y con el mismo formato', () => { + const f = setup(riesgoCacuDosDesenlaces(), { estatus: 'PRE_COLPOSCOPIA' }), root: HTMLElement = f.nativeElement; + const lineas = [...root.querySelectorAll('.risk-timeline')]; + expect(lineas.map(l => texto(l.querySelector('h5')))).toEqual(['Probabilidad a LIEAG+', 'Probabilidad a cáncer']); + const filas = [...root.querySelectorAll('table.risk tbody tr')]; + expect(filas).toHaveLength(3); + lineas.forEach((_, columna) => { + const puntos = nodos(root, columna); + expect(puntos).toHaveLength(filas.length); + puntos.forEach((punto, fila) => { + const valor = texto(punto.querySelector('.valor')).replace('Probabilidad ', ''); + const ic = texto(punto.querySelector('.ic')).replace('Intervalo de confianza: ', '').replace('IC: ', ''); + expect(texto(filas[fila].children[columna + 1])).toBe(`${valor} (${ic})`); + expect(texto(punto.querySelector('.horizon'))).toContain(texto(filas[fila].querySelector('th')) === '1' ? '1 año' : `${texto(filas[fila].querySelector('th'))} años`); + }); + }); + expect(nodos(root, 0).map(n => texto(n.querySelector('.valor')))).toEqual(['Probabilidad 8 %', 'Probabilidad 21 %', 'Probabilidad 34 %']); + expect(nodos(root, 1).map(n => texto(n.querySelector('.ic')))).toEqual([ + 'Intervalo de confianza: IC: 0.2 – 0.8 %', 'Intervalo de confianza: IC: 0.5 – 1.6 %', 'Intervalo de confianza: IC: 0.8 – 2.8 %']); + }); + + it('muestra la fecha índice como contexto y el horizonte 0 como «Fecha índice»; el cero se distingue del dato ausente', () => { + const data = riesgoCacuEjemplo(); + data.entry[0].resource.prediction = [ + prediccion(0, '2026-06-01', '2026-06-01', [0, 0]), + prediccion(0.05, '2026-06-01', '2027-06-01'), + prediccion(0.1, '2026-06-01', '2029-06-01', [0.07, 0.14]), + ]; + const f = setup(data), root: HTMLElement = f.nativeElement; + expect(texto(root.querySelector('.timeline-context'))).toContain('Fecha índice: 2026-06-01'); + const puntos = nodos(root); + expect(puntos.map(n => texto(n.querySelector('.horizon')))).toEqual(['Fecha índice (0 años)', '1 año', '3 años']); + expect(puntos.map(n => texto(n.querySelector('.valor')))).toEqual(['Probabilidad 0 %', 'Probabilidad 5 %', 'Probabilidad 10 %']); + // A model without an interval says so; a published interval of 0–0 stays a number. + expect(texto(puntos[0].querySelector('.ic'))).toContain('0 – 0 %'); + expect(texto(puntos[1].querySelector('.ic'))).toBe('Intervalo de confianza: IC no disponible'); + }); + + it('una columna sin modelo dice «No disponible», no dibuja línea ni cifra de ceros', () => { + const f = setup(riesgoCacuConEstimando(), { estatus: 'PRE_COLPOSCOPIA' }), root: HTMLElement = f.nativeElement; + const lineas = [...root.querySelectorAll('.risk-timeline')]; + expect(lineas.map(l => texto(l.querySelector('h5')))).toEqual(['Probabilidad a LIEAG+', 'Probabilidad a cáncer']); + expect(lineas[1].querySelector('.risk-line')).toBeNull(); + expect(texto(lineas[1].querySelector('.unavailable'))).toBe('No disponible'); + expect(lineas[1].textContent).not.toContain('0 %'); + }); + + it('no atribuye clasificaciones clínicas: los puntos no llevan colores ni umbrales por riesgo', () => { + const f = setup(riesgoCacuEjemplo()), root: HTMLElement = f.nativeElement; + const puntos = [...root.querySelectorAll('.risk-line .dot')] as HTMLElement[]; + expect(puntos).toHaveLength(3); + expect(new Set(puntos.map(p => p.getAttribute('style') ?? '')).size).toBe(1); + expect(root.querySelector('.risk-line')!.textContent).not.toMatch(/alto|bajo riesgo|medio|umbral|crític/i); + }); + + // Why: the timeline is a drawing; its list and the collapsed table are the textual alternative. + it('ofrece alternativa textual: lista ordenada, textos para lectores de pantalla, región enfocable y la tabla plegada', () => { + const f = setup(riesgoCacuEjemplo()), root: HTMLElement = f.nativeElement; + expect(root.querySelector('.risk-timeline ol.risk-line')).not.toBeNull(); + expect(root.querySelector('.risk-line .dot')!.getAttribute('aria-hidden')).toBe('true'); + expect(root.querySelector('.risk-line .valor .visually-hidden')!.textContent).toContain('Probabilidad'); + const region = root.querySelector('.risk-timeline-scroll')!; + expect(region.getAttribute('role')).toBe('region'); expect(region.tabIndex).toBe(0); + expect(region.getAttribute('aria-label')).toContain('Línea de tiempo de Probabilidad a LIEAG+'); + const alternativa = root.querySelector('details.risk-table-alt')!; + expect(alternativa.open).toBe(false); expect(alternativa.querySelector('table.risk')).not.toBeNull(); + expect(getComputedStyle(region).overflowX).toBe('auto'); + }); + + it('CaMa conserva su tabla visible y no recibe la línea de tiempo', () => { + const f = setup(riesgoCacuEjemplo(), { dominio: 'cama' }), root: HTMLElement = f.nativeElement; + expect(root.querySelector('.risk-timelines')).toBeNull(); + expect(root.querySelector('details.risk-table-alt')).toBeNull(); + expect(root.querySelector('table.risk')).not.toBeNull(); + }); +}); + +// Why: only the horizons a model gives become points; nothing is interpolated between them. +describe('Riesgo individual CaCu: puntos de la línea de tiempo', () => { + it('no interpola: solo hay un punto por horizonte publicado, en orden ascendente aunque lleguen desordenados', () => { + const lote = { horizontes: [ + { horizonte_anios: 5, probabilidad: 0.3 }, { horizonte_anios: 0, probabilidad: 0.02 }, { horizonte_anios: 1.5, probabilidad: 0.1, ic_bajo: 0.05, ic_alto: 0.2 }, + ], estimando: null } as unknown as LoteRiesgoCacu; + expect(nodosRiesgo(lote).map(n => [n.horizonte_anios, n.etiqueta, n.probabilidad, n.intervalo])).toEqual([ + [0, 'Fecha índice', '2 %', 'IC no disponible'], [1.5, '1.5 años', '10 %', '5 – 20 %'], [5, '5 años', '30 %', 'IC no disponible']]); + expect(nodosRiesgo({ ...lote, estimando: { horizons_unit: 'meses' } } as LoteRiesgoCacu).map(n => n.etiqueta)).toEqual(['Fecha índice', '1.5 meses', '5 meses']); + }); +}); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index 38d81bc..22a1751 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -13,6 +13,38 @@ @let columnas = columnasDe(todos); @let filas = filasDe(lotesDe(columnas)); @if (filas.length) { + @if (dominio() === 'cacu') { +
    + @for (c of columnas; track c.encabezado) { +
    +
    {{ c.encabezado }}
    + @if (c.vacia; as vacia) {

    {{ vacia }}

    } + @else if (c.lote; as lote) { +

    Fecha índice: {{ lote.fecha_indice }}. Los puntos siguen el orden de los horizontes; la distancia entre ellos no es proporcional al tiempo.

    +
    +
      + @for (n of nodosDe(lote); track n.horizonte_anios) { +
    1. + + {{ n.etiqueta }}@if (n.horizonte_anios === 0) { (0 {{ lote.estimando?.horizons_unit ?? 'años' }})} + Probabilidad {{ n.probabilidad }} + Intervalo de confianza: @if (n.intervalo !== 'IC no disponible') {IC: }{{ n.intervalo }} +
    2. + } +
    +
    + } +
    + } +
    +
    + Ver los riesgos como tabla + +
    + } @else { + + } +
    Probabilidad en porcentaje (0 a 100 %) por horizonte desde la fecha índice @@ -33,6 +65,7 @@
    +
    @for (c of columnas; track c.encabezado) { @if (c.lote?.sin_estimacion; as motivo) {

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

    } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss index 5b1677d..8d628e5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -26,3 +26,22 @@ tbody tr:last-child > * { border-bottom: 0; } .unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; } .covariates-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 0; } table.models { min-width: 48rem; } +.risk-timelines { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; } +.risk-timeline { min-width: 0; } +.risk-timeline h5 { margin-block: .25rem; } +.timeline-context { margin: 0 0 .5rem; color: var(--issste-text-secondary); font-size: .85rem; line-height: 1.4; } +.risk-timeline-scroll { width: 100%; max-width: 100%; overflow-x: auto; padding: .75rem .5rem; box-sizing: border-box; border: 1px solid var(--issste-border); border-radius: .5rem; } +.risk-timeline-scroll:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } +.risk-line { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(7.5rem, 1fr); margin: 0; padding: 0; list-style: none; } +.risk-line li { position: relative; display: flex; flex-direction: column; align-items: center; gap: .15rem; padding-inline: .25rem; text-align: center; } +.risk-line li::before { content: ''; position: absolute; top: .45rem; inset-inline: 0; height: 2px; background: var(--issste-border); } +.risk-line li:first-child::before { inset-inline-start: 50%; } +.risk-line li:last-child::before { inset-inline-end: 50%; } +.risk-line li:only-child::before { display: none; } +.risk-line .dot { position: relative; z-index: 1; width: .9rem; height: .9rem; margin-bottom: .35rem; border: 2px solid var(--issste-accent); border-radius: 50%; background: var(--issste-surface); } +.risk-line .horizon { font-size: .85rem; color: var(--issste-text-secondary); } +.risk-line .valor { font-size: 1.25rem; font-weight: 700; color: var(--issste-text); } +.risk-line .ic { font-size: .8rem; color: var(--issste-text-secondary); } +.risk-table-alt { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } +.risk-table-alt .risk-scroll { margin-bottom: .75rem; } +.visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 215d641..0357ebc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,9 +1,9 @@ import { Component, computed, effect, inject, input, signal } from '@angular/core'; -import { LowerCasePipe } from '@angular/common'; +import { LowerCasePipe, NgTemplateOutlet } from '@angular/common'; import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; import { PlotlyFigure } from '../indicadores.models'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; -import { ColumnaRiesgo, columnasRiesgo, conRiesgo, delEstatus, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { ColumnaRiesgo, columnasRiesgo, conRiesgo, delEstatus, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, nodosRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -16,7 +16,7 @@ export const instanteUtc = (iso: string) => { @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [LowerCasePipe, PlotlyChart], + imports: [LowerCasePipe, NgTemplateOutlet, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -41,6 +41,7 @@ export class PacienteRiesgoTabla { readonly frase = fraseRiesgo; readonly filasDe = filasRiesgo; readonly conRiesgo = conRiesgo; + readonly nodosDe = nodosRiesgo; readonly covariables = covariables; columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio(), this.estatus()); } delEstatus(riesgos: LoteRiesgoCacu[]): LoteRiesgoCacu[] { return delEstatus(riesgos, this.estatus()); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts index 98b6fa7..44de9a6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -33,6 +33,27 @@ export function conIntervalo(h: HorizonteRiesgoCacu): string { return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (IC no disponible)`; } +/** One point of a risk timeline: a horizon with the model's probability and interval, written as the table writes them. */ +export interface NodoRiesgo { + horizonte_anios: number; + /** "Fecha índice" for the immediate risk (horizon 0), else "1 año", "3 años"... */ + etiqueta: string; + probabilidad: string; + /** "a – b %", or "IC no disponible" when the model gives no interval. */ + intervalo: string; +} + +/** The points of one column's timeline, in horizon order: only the horizons its model gives, no interpolation. */ +export function nodosRiesgo(lote: LoteRiesgoCacu): NodoRiesgo[] { + const unidad = lote.estimando?.horizons_unit ?? 'años'; + return [...lote.horizontes].sort((a, b) => a.horizonte_anios - b.horizonte_anios).map(h => ({ + horizonte_anios: h.horizonte_anios, + etiqueta: h.horizonte_anios === 0 ? 'Fecha índice' : `${h.horizonte_anios} ${unidad === 'años' && h.horizonte_anios === 1 ? 'año' : unidad}`, + probabilidad: `${porcentaje(h.probabilidad)} %`, + intervalo: tieneIntervalo(h) ? `${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %` : 'IC no disponible', + })); +} + /** The outcomes a domain's record always has a column for, even with no model: CaCu's CIN2+ and cancer. */ const COLUMNAS_FIJAS: Record = { cacu: [{ desenlace: 'cin2', etiqueta: 'LIEAG+' }, { desenlace: 'cancer', etiqueta: 'cáncer' }], diff --git a/src/app/features/indicadores/ruta-tamizaje/etapas-compacta.ts b/src/app/features/indicadores/ruta-tamizaje/etapas-compacta.ts new file mode 100644 index 0000000..a323b9f --- /dev/null +++ b/src/app/features/indicadores/ruta-tamizaje/etapas-compacta.ts @@ -0,0 +1,72 @@ +import { Component, computed, input, output } from '@angular/core'; +import { hitosDeRuta, RutaResumen } from './ruta-tamizaje'; + +/** Compact route of a table cell: five connected circles (state by shape and fill) and the expand control. */ +@Component({ + selector: 'app-etapas-compacta', + template: ` + @if (ruta(); as r) { +
    +
      + @for (h of hitos(); track h.codigo) { +
    1. {{ h.lectura }}
    2. + } +
    + +
    + } @else { No disponible } + `, + styles: ` + :host { display: block; } + .compacta { display: flex; align-items: center; gap: .5rem; } + .linea { display: flex; align-items: center; margin: 0; padding: 0; list-style: none; } + .linea li { position: relative; display: flex; align-items: center; } + .linea li + li::before { content: ''; width: .9rem; height: 2px; background: var(--issste-border); } + .circulo { box-sizing: border-box; width: .95rem; height: .95rem; border: 2px solid var(--issste-accent); border-radius: 50%; background: var(--issste-surface); } + li[data-estado=registrada] .circulo { background: var(--issste-accent); } + li[data-estado=pendiente] .circulo { background: linear-gradient(90deg, var(--issste-accent) 50%, var(--issste-surface) 50%); } + li[data-estado=desconocida] .circulo { border-style: dashed; border-color: var(--issste-text-secondary); } + li[data-estado=no_aplica] .circulo { border-color: var(--issste-border); background: repeating-linear-gradient(45deg, var(--issste-border) 0 2px, var(--issste-surface) 2px 4px); } + .alternar { display: inline-flex; align-items: center; justify-content: center; min-width: 44px; min-height: 44px; border: 0; background: transparent; color: var(--issste-text); cursor: pointer; } + .alternar:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + .chevron { width: .55rem; height: .55rem; border-right: 2px solid currentColor; border-bottom: 2px solid currentColor; transform: rotate(-45deg); transition: transform .15s; } + .alternar[aria-expanded=true] .chevron { transform: rotate(45deg); } + .sin-ruta { color: var(--issste-text-secondary); } + .visually-hidden { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } + `, +}) +export class EtapasCompacta { + /** Null when the service gives no route for the row: it is said, never drawn as an empty or all-pending route. */ + readonly ruta = input.required(); + readonly paciente = input.required(); + readonly abierta = input(false); + readonly controla = input(null); + readonly alternar = output(); + readonly hitos = computed(() => { const r = this.ruta(); return r ? hitosDeRuta(r) : []; }); +} + +/** The four states of the circles, once above the table. */ +@Component({ + selector: 'app-etapas-leyenda', + template: ` +
      + @for (e of estados; track e.codigo) {
    • {{ e.texto }}
    • } +
    + `, + styles: ` + .leyenda { display: flex; flex-wrap: wrap; gap: .25rem 1rem; margin: 0 0 .5rem; padding: 0; list-style: none; color: var(--issste-text-secondary); font-size: .85rem; } + li { display: inline-flex; align-items: center; gap: .35rem; } + .circulo { box-sizing: border-box; width: .85rem; height: .85rem; border: 2px solid var(--issste-accent); border-radius: 50%; background: var(--issste-surface); } + li[data-estado=registrada] .circulo { background: var(--issste-accent); } + li[data-estado=pendiente] .circulo { background: linear-gradient(90deg, var(--issste-accent) 50%, var(--issste-surface) 50%); } + li[data-estado=desconocida] .circulo { border-style: dashed; border-color: var(--issste-text-secondary); } + li[data-estado=no_aplica] .circulo { border-color: var(--issste-border); background: repeating-linear-gradient(45deg, var(--issste-border) 0 2px, var(--issste-surface) 2px 4px); } + `, +}) +export class EtapasLeyenda { + readonly estados = [ + { codigo: 'registrada', texto: 'Registrada' }, { codigo: 'pendiente', texto: 'Pendiente' }, + { codigo: 'desconocida', texto: 'Desconocida' }, { codigo: 'no_aplica', texto: 'No aplica' }, + ]; +} diff --git a/src/app/features/indicadores/ruta-tamizaje/etapas-detalle.ts b/src/app/features/indicadores/ruta-tamizaje/etapas-detalle.ts new file mode 100644 index 0000000..8560d8f --- /dev/null +++ b/src/app/features/indicadores/ruta-tamizaje/etapas-detalle.ts @@ -0,0 +1,94 @@ +import { ChangeDetectorRef, Component, computed, inject, input, OnChanges, OnDestroy, output, signal } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription } from 'rxjs'; +import { CacuSeguimientoService } from '../cacu-seguimiento.service'; +import { hitosDeRuta, RutaDetalle, RutaResumen, textoDias } from './ruta-tamizaje'; + +/** + * The expanded route of one row. Its detail is requested only when the row opens, from the `detalle_url` the list + * gave (checked by the service to be a route of the same service), and the request is cancelled when the row closes, + * the route changes or the list reloads. The opaque references the service gives change when it restarts: a 404 + * says so and offers to refresh the list; nothing is kept across lists. + */ +@Component({ + selector: 'app-etapas-detalle', + template: ` +
    + @switch (estado()) { + @case ('cargando') {

    Cargando la ruta del tamizaje…

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

    Esta ruta ya no está disponible: el servicio renueva sus referencias al reiniciar. Actualiza el listado para volver a consultarla.

    } + @case ('error') {

    No se pudo cargar la ruta del tamizaje.

    } + @case ('listo') { +

    Los hitos siguen el orden de la ruta; la distancia entre ellos no es proporcional al tiempo. Solo se muestran los intervalos que el servicio vincula a esta misma toma.

    +
    +
      + @for (h of hitos(); track h.codigo) { +
    1. + + {{ h.nombre }} + {{ h.estadoTexto }} + {{ h.fecha ?? 'Sin fecha' }} + @if (h.diasDesdeAnterior !== null) { {{ texto(h.diasDesdeAnterior) }} desde el hito anterior } + @else if (h.codigo !== 'toma') { Sin intervalo vinculado } + @if (h.diasDesdeToma !== null) { {{ texto(h.diasDesdeToma) }} desde la toma } + @for (o of h.ordenes; track $index) { Orden: {{ o }} } +
    2. + } +
    +
    +

    @if (detalle()!.dias_desde_ultimo_evento !== null) { {{ texto(detalle()!.dias_desde_ultimo_evento!) }} desde el último evento vinculado hasta el corte ({{ detalle()!.corte }}). Es tiempo transcurrido, no una demora clínica. } + @else { Sin evento vinculado para contar hasta el corte ({{ detalle()!.corte }}). }

    + } + } +
    + `, + styles: ` + :host { display: block; min-width: 0; } + .contexto, .ultimo, p { margin: 0 0 .5rem; color: var(--issste-text-secondary); font-size: .85rem; line-height: 1.4; } + .ultimo { margin: .5rem 0 0; } + .desplazable { max-width: 100%; overflow-x: auto; padding: .5rem; border: 1px solid var(--issste-border); border-radius: .5rem; box-sizing: border-box; background: var(--issste-surface); } + .desplazable:focus-visible, button:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; } + .ruta { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(9.5rem, 1fr); margin: 0; padding: 0; list-style: none; } + .ruta li { position: relative; display: flex; flex-direction: column; align-items: center; gap: .15rem; padding-inline: .25rem; text-align: center; font-size: .85rem; } + .ruta li::before { content: ''; position: absolute; top: .45rem; inset-inline: 0; height: 2px; background: var(--issste-border); } + .ruta li:first-child::before { inset-inline-start: 50%; } + .ruta li:last-child::before { inset-inline-end: 50%; } + .punto { position: relative; z-index: 1; box-sizing: border-box; width: .95rem; height: .95rem; margin-bottom: .35rem; border: 2px solid var(--issste-accent); border-radius: 50%; background: var(--issste-surface); } + li[data-estado=registrada] .punto { background: var(--issste-accent); } + li[data-estado=pendiente] .punto { background: linear-gradient(90deg, var(--issste-accent) 50%, var(--issste-surface) 50%); } + li[data-estado=desconocida] .punto { border-style: dashed; border-color: var(--issste-text-secondary); } + li[data-estado=no_aplica] .punto { border-color: var(--issste-border); background: repeating-linear-gradient(45deg, var(--issste-border) 0 2px, var(--issste-surface) 2px 4px); } + .nombre { font-weight: 600; } + .estado, .sin, .acumulado, .orden { color: var(--issste-text-secondary); } + .fecha { font-variant-numeric: tabular-nums; } + .entre { margin-top: .25rem; font-size: .95rem; } .entre strong { font-size: 1.15rem; } + .acumulado, .orden, .sin { font-size: .8rem; } + button { min-height: 44px; padding: .5rem .8rem; border: 1px solid var(--issste-border); border-radius: 4px; background: var(--issste-surface); color: inherit; font: inherit; cursor: pointer; } + `, +}) +export class EtapasDetalle implements OnChanges, OnDestroy { + readonly ruta = input.required(); + readonly paciente = input.required(); + readonly actualizar = output(); + readonly estado = signal<'cargando' | 'listo' | 'no-disponible' | 'error'>('cargando'); + readonly detalle = signal(undefined); + readonly hitos = computed(() => { const d = this.detalle(); return d ? hitosDeRuta(d) : []; }); + readonly texto = textoDias; + private readonly service = inject(CacuSeguimientoService); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private cargada = ''; + + ngOnChanges() { if (this.cargada !== this.ruta().detalle_url) this.cargar(); } + cargar() { + this.subscription?.unsubscribe(); + this.cargada = this.ruta().detalle_url; this.detalle.set(undefined); this.estado.set('cargando'); + let observable; + try { observable = this.service.detalleRuta(this.ruta().detalle_url); } catch { this.estado.set('error'); return; } + this.subscription = observable.subscribe({ + next: d => { this.detalle.set(d); this.estado.set('listo'); this.changeDetector.markForCheck(); }, + error: (e: unknown) => { this.estado.set(e instanceof HttpErrorResponse && e.status === 404 ? 'no-disponible' : 'error'); this.changeDetector.markForCheck(); }, + }); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.spec.ts b/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.spec.ts new file mode 100644 index 0000000..dddb432 --- /dev/null +++ b/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.spec.ts @@ -0,0 +1,151 @@ +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import fixtureData from '../fixtures/cacu_seguimiento.json'; +import { IndicadoresTracking } from '../indicadores-tracking'; +import { CacuSeguimientoService } from '../cacu-seguimiento.service'; +import { hitosDeRuta, rutaDetalleValida, rutaResumenValida, urlDetalleValida } from './ruta-tamizaje'; + +// Shapes follow the contract examples WebApi publishes for `ruta_tamizaje` and its detail (synthetic values written for these tests). +const URL1 = '/cacu/seguimiento/rutas/1/b71482fde592cf78fca7af9db90eae8f3b24630e22a465d97923528661cebf03?corte=2025-12-31'; +const URL4 = '/cacu/seguimiento/rutas/4/72fc7fc29d9e007409e14e4888f7adc85eaae0e1f23eecaff85dd900c19167a4?corte=2025-12-31'; +const sin = (codigo: string) => ({ codigo, estado: 'desconocida', fecha: null }); +const RUTA_DESCONOCIDA = { id: 'b71482fd', corte: '2025-12-31', toma: '2025-10-02', dias_desde_ultimo_evento: 90, detalle_url: URL1, + etapas: ['citologia', 'colposcopia', 'biopsia', 'diagnostico'].map(sin) }; +const RUTA_BIOPSIA = { id: '72fc7fc2', corte: '2025-12-31', toma: '2025-07-01', dias_desde_ultimo_evento: 152, detalle_url: URL4, + etapas: [{ codigo: 'citologia', estado: 'registrada', fecha: '2025-07-11' }, sin('colposcopia'), { codigo: 'biopsia', estado: 'registrada', fecha: '2025-08-01' }, sin('diagnostico')] }; +const etapaDetalle = (e: { codigo: string; estado: string; fecha: string | null }, extra: object = {}) => + ({ ...e, dias_desde_toma: null, dias_desde_anterior: null, evento_ref: null, eventos: [], ...extra }); +const DETALLE_BIOPSIA = { id: '72fc7fc2', corte: '2025-12-31', toma: '2025-07-01', toma_ref: 'ref-toma', dias_desde_ultimo_evento: 152, etapas: [ + etapaDetalle(RUTA_BIOPSIA.etapas[0], { dias_desde_toma: 10, dias_desde_anterior: 10, evento_ref: 'r1', eventos: [{ fecha: '2025-07-11', ref: 'r1' }] }), + etapaDetalle(RUTA_BIOPSIA.etapas[1]), + etapaDetalle(RUTA_BIOPSIA.etapas[2], { dias_desde_toma: 31, evento_ref: 'r3', eventos: [{ fecha: '2025-08-01', ref: 'r3' }], ordenes: [{ fecha: '2025-07-15', ref: 'r4' }] }), + etapaDetalle(RUTA_BIOPSIA.etapas[3])] }; + +describe('Ruta del tamizaje: contrato y vista', () => { + it('valida el resumen y el detalle del contrato y rechaza códigos o estados inventados', () => { + expect(rutaResumenValida(RUTA_DESCONOCIDA)).toBe(true); expect(rutaResumenValida(RUTA_BIOPSIA)).toBe(true); expect(rutaDetalleValida(DETALLE_BIOPSIA)).toBe(true); + expect(rutaResumenValida({ ...RUTA_BIOPSIA, etapas: [...RUTA_BIOPSIA.etapas.slice(0, 3), { codigo: 'tratamiento', estado: 'registrada', fecha: null }] })).toBe(false); + expect(rutaResumenValida({ ...RUTA_BIOPSIA, etapas: RUTA_BIOPSIA.etapas.slice(0, 3) })).toBe(false); + expect(rutaResumenValida({ ...RUTA_BIOPSIA, etapas: [{ ...RUTA_BIOPSIA.etapas[0], estado: 'completada' }, ...RUTA_BIOPSIA.etapas.slice(1)] })).toBe(false); + expect(rutaResumenValida({ ...RUTA_BIOPSIA, dias_desde_ultimo_evento: -1 })).toBe(false); + }); + // Why: the detail is requested from a URL the server wrote; it must never lead outside this service. + it('solo acepta rutas del propio servicio como detalle', () => { + expect(urlDetalleValida(URL1)).toBe(true); + for (const mala of ['https://otro.example/cacu/seguimiento/rutas/1/abc?corte=2025-12-31', '//otro.example/cacu/seguimiento/rutas/1/abc?corte=2025-12-31', + '/cacu/seguimiento/rutas/../../x/abc?corte=2025-12-31', '/otra/ruta?corte=2025-12-31', '/cacu/seguimiento/rutas/1/abc', '/cacu/seguimiento/rutas/1/abc?corte=2025-12-31&x=1', 3, null]) + expect(urlDetalleValida(mala)).toBe(false); + }); + it('los hitos son los de la ruta: biopsia registrada sin colposcopia, ninguna etapa se completa por otra y 0 no es ausencia', () => { + expect(hitosDeRuta(RUTA_BIOPSIA as never).map(h => h.estado)).toEqual(['registrada', 'registrada', 'desconocida', 'registrada', 'desconocida']); + expect(hitosDeRuta(RUTA_DESCONOCIDA as never).map(h => h.estado)).toEqual(['registrada', 'desconocida', 'desconocida', 'desconocida', 'desconocida']); + const h = hitosDeRuta({ toma: '2025-07-01', etapas: [etapaDetalle(RUTA_BIOPSIA.etapas[0], { dias_desde_toma: 0, dias_desde_anterior: 0 }) as never] }); + expect([h[1].diasDesdeToma, h[1].diasDesdeAnterior]).toEqual([0, 0]); + expect(hitosDeRuta(DETALLE_BIOPSIA as never)[3]).toMatchObject({ diasDesdeToma: 31, diasDesdeAnterior: null, ordenes: ['2025-07-15'] }); + expect(hitosDeRuta({ toma: null, etapas: [] }).map(x => x.estado)).toEqual(['desconocida', 'desconocida', 'desconocida', 'desconocida', 'desconocida']); + }); +}); + +describe('Ruta del tamizaje en Análisis de riesgos (CaCu)', () => { + let fixture: ReturnType>, http: HttpTestingController; + const items = (rutas: (object | null | undefined)[]) => rutas.map((ruta, i) => ({ ...fixtureData.items[i], id_seudonimo: String(i + 1), ...(ruta === undefined ? {} : { ruta_tamizaje: ruta }) })); + const pagina = (rutas: (object | null | undefined)[]) => ({ ...fixtureData, items: items(rutas), paginacion: { page: 1, page_size: 50, total_items: rutas.length, total_pages: 1 } }); + const lista = () => http.expectOne(r => r.url === '/cacu/seguimiento'); + const detalle = (url: string) => http.expectOne(r => r.urlWithParams === url); + const root = () => fixture.nativeElement as HTMLElement; + const toggles = () => [...root().querySelectorAll('.alternar')]; + function abrir(rutas: (object | null | undefined)[]) { + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + const r = lista(); expect(r.request.params.get('incluir')).toBe('ruta_tamizaje'); r.flush(pagina(rutas)); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + } + beforeEach(() => { + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresTracking); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('domainLabel', 'CaCu'); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + + it('agrega la columna «Etapas» con cinco círculos, leyenda de estados y ninguna solicitud de detalle al cargar', () => { + abrir([RUTA_BIOPSIA, RUTA_DESCONOCIDA, null]); + expect([...root().querySelectorAll('thead th')].at(-1)!.textContent).toBe('Etapas'); + const lineas = [...root().querySelectorAll('.linea')]; + expect(lineas).toHaveLength(2); expect(lineas[0].querySelectorAll('li')).toHaveLength(5); + expect([...lineas[0].querySelectorAll('li')].map(l => l.getAttribute('data-estado'))).toEqual(['registrada', 'registrada', 'desconocida', 'registrada', 'desconocida']); + expect([...root().querySelectorAll('.leyenda li')].map(l => l.textContent!.trim())).toEqual(['Registrada', 'Pendiente', 'Desconocida', 'No aplica']); + // A row with no route says so; it is not a route of pending stages. + const ultima = root().querySelectorAll('tbody tr[data-paciente]')[2]; + expect(ultima.querySelector('.sin-ruta')!.textContent).toBe('No disponible'); expect(ultima.querySelector('.linea')).toBeNull(); + http.expectNone(() => true); + }); + it('un servidor sin el bloque no muestra rutas ni círculos pendientes', () => { + abrir([undefined]); + expect(root().querySelector('.linea')).toBeNull(); expect(root().querySelector('tbody .sin-ruta')).not.toBeNull(); + }); + it('al expandir pide la detalle_url de esa fila, muestra los cinco hitos con intervalos solo si el servidor los da, y al cerrar cancela', () => { + abrir([RUTA_BIOPSIA, RUTA_DESCONOCIDA]); + toggles()[0].click(); fixture.detectChanges(); + expect(toggles()[0].getAttribute('aria-expanded')).toBe('true'); + const req = detalle(URL4); expect(req.request.method).toBe('GET'); + expect(root().textContent).toContain('Cargando la ruta'); + req.flush(DETALLE_BIOPSIA); fixture.detectChanges(); + const hitos = [...root().querySelectorAll('.ampliada .ruta li')] as HTMLElement[]; + expect(hitos.map(h => h.querySelector('.nombre')!.textContent)).toEqual(['Toma', 'Resultado de citología', 'Colposcopia', 'Reporte de biopsia', 'Diagnóstico']); + expect(hitos[1].querySelector('.entre')!.textContent).toContain('10 días desde el hito anterior'); + expect(hitos[1].querySelector('.acumulado')!.textContent).toContain('10 días desde la toma'); + expect(hitos[3].querySelector('.entre')).toBeNull(); expect(hitos[3].querySelector('.sin')!.textContent).toContain('Sin intervalo vinculado'); + expect(hitos[3].querySelector('.acumulado')!.textContent).toContain('31 días desde la toma'); expect(hitos[3].querySelector('.orden')!.textContent).toContain('2025-07-15'); + expect(hitos[2].textContent).not.toMatch(/días/); expect(root().querySelector('.ultimo')!.textContent).toContain('152 días desde el último evento'); + toggles()[0].click(); fixture.detectChanges(); + expect(root().querySelector('.ampliada')).toBeNull(); http.expectNone(() => true); + }); + it('el botón de expansión no abre la ficha y la ficha sigue accesible por su propio botón', () => { + abrir([RUTA_DESCONOCIDA]); + toggles()[0].click(); fixture.detectChanges(); + expect(fixture.componentInstance.pacienteDetalle.estado().tipo).toBe('cerrado'); + detalle(URL1).flush({ ...DETALLE_BIOPSIA, id: 'b71482fd' }); fixture.detectChanges(); + expect(root().querySelector('tbody button.patient-link')).not.toBeNull(); + }); + it('un día igual a cero se muestra y se distingue de la ausencia', () => { + abrir([RUTA_BIOPSIA]); toggles()[0].click(); fixture.detectChanges(); + detalle(URL4).flush({ ...DETALLE_BIOPSIA, etapas: [etapaDetalle(RUTA_BIOPSIA.etapas[0], { dias_desde_toma: 0, dias_desde_anterior: 0, eventos: [{ fecha: '2025-07-11', ref: 'r1' }] }), ...DETALLE_BIOPSIA.etapas.slice(1)] }); fixture.detectChanges(); + expect(root().querySelector('.ampliada .ruta li:nth-child(2) .entre')!.textContent).toContain('0 días desde el hito anterior'); + }); + it('un 404 dice que la ruta ya no está y «Actualizar listado» vuelve a consultar la lista', () => { + abrir([RUTA_BIOPSIA]); toggles()[0].click(); fixture.detectChanges(); + detalle(URL4).flush({ error: 'Ruta de tamizaje no disponible' }, { status: 404, statusText: 'Not Found' }); fixture.detectChanges(); + expect(root().querySelector('.ampliada [role=alert]')!.textContent).toContain('ya no está disponible'); + ([...root().querySelectorAll('.ampliada button')] as HTMLButtonElement[]).find(b => b.textContent === 'Actualizar listado')!.click(); fixture.detectChanges(); + lista().flush(pagina([RUTA_BIOPSIA])); fixture.detectChanges(); + expect(root().querySelector('.ampliada')).toBeNull(); + }); + it('otro error del detalle permite reintentar sin afectar el listado', () => { + abrir([RUTA_BIOPSIA]); toggles()[0].click(); fixture.detectChanges(); + detalle(URL4).flush({}, { status: 500, statusText: 'Error' }); fixture.detectChanges(); + expect(root().querySelector('.ampliada [role=alert]')!.textContent).toContain('No se pudo cargar'); + expect(root().querySelectorAll('tr[data-paciente]')).toHaveLength(1); + ([...root().querySelectorAll('.ampliada button')] as HTMLButtonElement[]).find(b => b.textContent === 'Reintentar')!.click(); + detalle(URL4).flush(DETALLE_BIOPSIA); fixture.detectChanges(); + expect(root().querySelector('.ampliada .ruta')).not.toBeNull(); + }); + // Why: references change when the service restarts; a new list (filters, page, search) closes the open detail and drops it. + it('un listado nuevo cierra el detalle abierto y cancela su solicitud', () => { + abrir([RUTA_BIOPSIA]); toggles()[0].click(); fixture.detectChanges(); + const pendiente = detalle(URL4); + fixture.componentInstance.apply(); fixture.detectChanges(); + expect(pendiente.cancelled).toBe(true); expect(root().querySelector('.ampliada')).toBeNull(); + lista().flush(pagina([RUTA_BIOPSIA])); fixture.detectChanges(); + expect(toggles()[0].getAttribute('aria-expanded')).toBe('false'); http.expectNone(() => true); + }); + it('el servicio no pide un detalle fuera de las rutas del servicio', () => { + const servicio = TestBed.inject(CacuSeguimientoService); + expect(() => servicio.detalleRuta('https://otro.example/x')).toThrow(); + abrir([{ ...RUTA_BIOPSIA, detalle_url: 'https://otro.example/x' }].slice(0, 0)); + }); + it('un resumen con etapa o estado desconocido para el contrato se rechaza antes de mostrarse', () => { + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + lista().flush(pagina([{ ...RUTA_BIOPSIA, etapas: [...RUTA_BIOPSIA.etapas.slice(0, 3), { codigo: 'tratamiento', estado: 'registrada', fecha: null }] }])); fixture.detectChanges(); + expect(root().querySelector('.linea')).toBeNull(); expect(root().querySelector('[role=alert]')).not.toBeNull(); + }); +}); diff --git a/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.ts b/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.ts new file mode 100644 index 0000000..a0fb0ca --- /dev/null +++ b/src/app/features/indicadores/ruta-tamizaje/ruta-tamizaje.ts @@ -0,0 +1,96 @@ +// Screening route of a CaCu patient (`ruta_tamizaje` of /cacu/seguimiento and its detail): contract types, validation and +// the view of the five milestones. A stage is completed only when the service says so; nothing is derived from the +// follow-up status or from another stage. +export type EstadoEtapa = 'registrada' | 'pendiente' | 'desconocida' | 'no_aplica'; +export type CodigoEtapa = 'citologia' | 'colposcopia' | 'biopsia' | 'diagnostico'; +export const CODIGOS_ETAPA: readonly CodigoEtapa[] = ['citologia', 'colposcopia', 'biopsia', 'diagnostico']; +const ESTADOS: readonly string[] = ['registrada', 'pendiente', 'desconocida', 'no_aplica']; + +export interface EtapaResumen { codigo: CodigoEtapa; estado: EstadoEtapa; fecha: string | null; } +export interface RutaResumen { + id: string; corte: string; toma: string | null; etapas: EtapaResumen[]; + /** Cut-off date minus the date of the last linked, known event: elapsed time, not a clinical delay. */ + dias_desde_ultimo_evento: number | null; + detalle_url: string; +} +export interface EventoRuta { fecha: string; ref: string; } +export interface EtapaDetalle extends EtapaResumen { + dias_desde_toma: number | null; dias_desde_anterior: number | null; + evento_ref: string | null; eventos: EventoRuta[]; ordenes?: EventoRuta[]; +} +export interface RutaDetalle { + id: string; corte: string; toma: string | null; toma_ref: string | null; + dias_desde_ultimo_evento: number | null; etapas: EtapaDetalle[]; +} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const fechaIso = (v: unknown): v is string => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v) && !Number.isNaN(Date.parse(v + 'T00:00:00Z')); +const fechaONula = (v: unknown) => v === null || fechaIso(v); +const diasONulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0); +const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0; +const eventos = (v: unknown) => Array.isArray(v) && v.every(e => registro(e) && fechaIso(e['fecha']) && texto(e['ref'])); + +function etapasValidas(v: unknown, extra: (e: Record) => boolean): boolean { + return Array.isArray(v) && v.length === CODIGOS_ETAPA.length && v.every((e, i) => registro(e) && e['codigo'] === CODIGOS_ETAPA[i] + && ESTADOS.includes(e['estado'] as string) && fechaONula(e['fecha']) && extra(e)); +} + +/** The list's route block: null (no selected cytology) or the contract's summary. */ +export function rutaResumenValida(v: unknown): v is RutaResumen { + return registro(v) && texto(v['id']) && fechaIso(v['corte']) && fechaONula(v['toma']) && diasONulo(v['dias_desde_ultimo_evento']) + && urlDetalleValida(v['detalle_url']) && etapasValidas(v['etapas'], () => true); +} +export function rutaDetalleValida(v: unknown): v is RutaDetalle { + return registro(v) && texto(v['id']) && fechaIso(v['corte']) && fechaONula(v['toma']) && (v['toma_ref'] === null || texto(v['toma_ref'])) + && diasONulo(v['dias_desde_ultimo_evento']) + && etapasValidas(v['etapas'], e => diasONulo(e['dias_desde_toma']) && diasONulo(e['dias_desde_anterior']) + && (e['evento_ref'] === null || texto(e['evento_ref'])) && eventos(e['eventos']) && (e['ordenes'] === undefined || eventos(e['ordenes']))); +} + +/** Only a path of this service's own routes is requested: no scheme, host, protocol-relative or dotted path. */ +export function urlDetalleValida(url: unknown): url is string { + return typeof url === 'string' && /^\/cacu\/seguimiento\/rutas\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+\?corte=\d{4}-\d{2}-\d{2}$/.test(url); +} + +export const NOMBRE_ETAPA: Readonly> = { + toma: 'Toma', citologia: 'Resultado de citología', colposcopia: 'Colposcopia', biopsia: 'Reporte de biopsia', diagnostico: 'Diagnóstico', +}; +export const ETIQUETA_ESTADO: Readonly> = { + registrada: 'Registrada', pendiente: 'Pendiente', desconocida: 'Desconocida', no_aplica: 'No aplica', +}; + +export interface HitoVista { + codigo: 'toma' | CodigoEtapa; + nombre: string; + estado: EstadoEtapa; + estadoTexto: string; + /** Null without a recorded date. */ + fecha: string | null; + /** Days only when the service gives them; 0 is a value, null is none. */ + diasDesdeToma: number | null; + diasDesdeAnterior: number | null; + /** Dates of the order(s) linked to the stage, when the detail gives them. */ + ordenes: string[]; + /** One sentence for assistive technology and tooltips. */ + lectura: string; +} + +/** The five milestones in route order, from the summary or, with days and orders, from the detail. */ +export function hitosDeRuta(ruta: { toma: string | null; etapas: (EtapaResumen | EtapaDetalle)[] }): HitoVista[] { + const toma: HitoVista = { codigo: 'toma', nombre: NOMBRE_ETAPA.toma, estado: ruta.toma ? 'registrada' : 'desconocida', + estadoTexto: ruta.toma ? ETIQUETA_ESTADO.registrada : ETIQUETA_ESTADO.desconocida, fecha: ruta.toma, diasDesdeToma: null, diasDesdeAnterior: null, ordenes: [], lectura: '' }; + toma.lectura = `${toma.nombre}: ${toma.estadoTexto.toLowerCase()}${toma.fecha ? `, ${toma.fecha}` : ''}`; + const etapas = CODIGOS_ETAPA.map((codigo): HitoVista => { + const e = ruta.etapas.find(x => x.codigo === codigo) as Partial | undefined; + const estado = e?.estado ?? 'desconocida'; + const fecha = estado === 'registrada' ? e?.fecha ?? null : null; + const h: HitoVista = { codigo, nombre: NOMBRE_ETAPA[codigo], estado, estadoTexto: ETIQUETA_ESTADO[estado], fecha, + diasDesdeToma: fecha ? e?.dias_desde_toma ?? null : null, diasDesdeAnterior: fecha ? e?.dias_desde_anterior ?? null : null, + ordenes: (e?.ordenes ?? []).map(o => o.fecha), lectura: '' }; + h.lectura = `${h.nombre}: ${h.estadoTexto.toLowerCase()}${fecha ? `, ${fecha}` : ''}`; + return h; + }); + return [toma, ...etapas]; +} + +export const textoDias = (n: number) => `${n} ${n === 1 ? 'día' : 'días'}`;