From 8b80e1d26c5484c495a81f712f322945c93951aa Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 02:09:35 -0600 Subject: [PATCH 01/35] =?UTF-8?q?Checkpoint:=20Hist=C3=B3rico=20CaCu=20int?= =?UTF-8?q?egration=20by=20Codex,=20before=20consolidating=20the=20TEA/CaC?= =?UTF-8?q?u=20section=201=20work?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/app.config.simulado.ts | 2 + src/app/features/indicadores/fhir.ts | 1 + .../fixtures/regresion_cacu_tea_mapeo.json | 12 + .../indicadores/indicadores-fhir.spec.ts | 30 ++ .../features/indicadores/indicadores-fhir.ts | 33 ++- .../indicadores-historico-cacu-fhir.spec.ts | 179 ++++++++++++ ...indicadores-historico-cacu-paneles.spec.ts | 252 +++++++++++++++++ .../indicadores-historico-config.ts | 88 ++++++ .../indicadores-historico-figures.ts | 42 ++- .../indicadores-historico-pestana.spec.ts | 9 +- .../indicadores/indicadores-historico.ts | 267 +++++++++++++----- .../indicadores/indicadores-page.html | 3 +- .../features/indicadores/indicadores-page.ts | 3 +- .../indicadores-recorrido-analisis.spec.ts | 2 +- .../indicadores/indicadores-sections.spec.ts | 5 +- 15 files changed, 843 insertions(+), 85 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts create mode 100644 src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts create mode 100644 src/app/features/indicadores/indicadores-historico-config.ts diff --git a/src/app/app.config.simulado.ts b/src/app/app.config.simulado.ts index 31b9c77..f30bf17 100644 --- a/src/app/app.config.simulado.ts +++ b/src/app/app.config.simulado.ts @@ -5,6 +5,7 @@ import { routes } from './app.routes'; import { IndicadoresService } from './features/indicadores/indicadores.service'; import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; +import { HISTORICO_CACU_DATOS } from './features/indicadores/indicadores-historico-config'; // SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento // de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`). @@ -17,5 +18,6 @@ export const appConfig: ApplicationConfig = { // (`//indicadores//datos`, `/tea/seguimiento`). { provide: IndicadoresService, useClass: FhirIndicadoresService }, { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, + { provide: HISTORICO_CACU_DATOS, useFactory: () => ['localhost', '127.0.0.1', '[::1]'].includes(globalThis.location?.hostname ?? '') }, ] }; diff --git a/src/app/features/indicadores/fhir.ts b/src/app/features/indicadores/fhir.ts index 71d0754..e7bc9ce 100644 --- a/src/app/features/indicadores/fhir.ts +++ b/src/app/features/indicadores/fhir.ts @@ -19,6 +19,7 @@ export interface Resource { } export interface Bundle extends Resource { total?: number; + link?: { relation: string; url: string }[]; entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[]; } diff --git a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json index 5942e66..1343f62 100644 --- a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json +++ b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json @@ -46,6 +46,10 @@ "version": "0.1.2", "contrato": "C2", "unidad": "paciente", + "unidades_periodo": { + "2021-S1": 0, + "2025-S2": 1 + }, "tipo_periodo": "semestre", "periodos": [ "2021-S1", @@ -662,6 +666,10 @@ "version": "0.3.3", "contrato": "C2", "unidad": "paciente", + "unidades_periodo": { + "2021-S1": 0, + "2025-S2": 89 + }, "tipo_periodo": "semestre", "periodos": [ "2021-S1", @@ -747,6 +755,10 @@ "version": "0.1.0", "contrato": "C2", "unidad": "paciente", + "unidades_periodo": { + "2021-S1": 0, + "2025-S2": 0 + }, "tipo_periodo": "semestre", "periodos": [ "2021-S1", diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index ddf545f..a2d718e 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -171,6 +171,36 @@ describe('Servicios FHIR de indicadores', () => { expect((await answer).filas.length).toBe(2); }); + it('sigue next para recuperar 201 periodos sin cambiar de endpoint ni de selección', async () => { + // The links can contain the upstream origin. The second request must stay on the application's FHIR route. + const service = TestBed.inject(FhirIndicadoresService); + const periodos = periodosDesde('2009-01-01', 'mes', 201); + const report = reports(fx.m21Semestres)[0]; + const entry = periodos.map(p => ({ resource: { ...report, period: { start: p + '-01', end: p + '-28' } } })); + const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'mes', periodos)); + http.expectOne('/tea/fhir/Measure').flush(fx.measures); + const page = http.expectOne(r => r.url === '/tea/fhir/MeasureReport'); + page.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(0, 200), + link: [{ relation: 'next', url: 'http://webapi:5050/tea/fhir/MeasureReport?_offset=200' }] }); + const next = http.expectOne(r => r.url === '/tea/fhir/MeasureReport' && r.params.get('_offset') === '200'); + expect(next.request.params.get('measure')).toBe(page.request.params.get('measure')); + expect(next.request.params.get('periodo')).toBe(periodos.join(',')); + expect(next.request.params.get('_count')).toBe('200'); + next.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(200) }); + expect((await answer).periodos).toHaveLength(201); + }); + + it('rechaza un next que repite el offset sin volver a solicitar reportes', async () => { + const service = TestBed.inject(FhirIndicadoresService); + const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre')); + const error = expect(answer).rejects.toThrow('Paginación FHIR inválida'); + http.expectOne('/tea/fhir/Measure').flush(fx.measures); + http.expectOne(r => r.url === '/tea/fhir/MeasureReport').flush({ ...fx.m21Semestres, + link: [{ relation: 'next', url: '?_offset=0' }] }); + await error; + http.expectNone(r => r.url === '/tea/fhir/MeasureReport'); + }); + it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => { // Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each // measure computes its own periods or every period is evaluated to list them. diff --git a/src/app/features/indicadores/indicadores-fhir.ts b/src/app/features/indicadores/indicadores-fhir.ts index 70c7867..55139bc 100644 --- a/src/app/features/indicadores/indicadores-fhir.ts +++ b/src/app/features/indicadores/indicadores-fhir.ts @@ -1,6 +1,6 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; -import { map, Observable, shareReplay, switchMap } from 'rxjs'; +import { EMPTY, expand, map, Observable, reduce, shareReplay, switchMap } from 'rxjs'; import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir'; import { periodLabel } from './measure-report'; import { @@ -238,6 +238,8 @@ function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly // The `/datos` answer for `measure`, from one report per period. export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos { const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id); + const cacu = measure.id !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measure.id); + const unidadesPeriodo: Record = {}; const declaradas = categorias(measure); const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map(); // The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above). @@ -308,6 +310,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) { throw new Error('Los conteos por categoría no suman las unidades del periodo'); } + if (cacu && units !== null) unidadesPeriodo[periodo] = units; Object.keys(cats).forEach((categoria, orden) => filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 })); continue; @@ -340,6 +343,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP estrato: estrato ?? null, ...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }), ...(cruzado || porEstrato ? { totales_estrato: totales } : {}), + ...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}), grupos, categorias: cats, grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure), @@ -408,6 +412,29 @@ export class FhirMeasures { reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable { return this.http.get(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') }); } + + allReports(dominio: Dominio, measure: Measure, params: HttpParams): Observable { + const path = `/${requireDominio(dominio)}/fhir/MeasureReport`; + return this.reports(dominio, measure, params).pipe( + map(bundle => ({ bundle, offset: 0 })), + expand(({ bundle, offset }) => { + const next = bundle.link?.find(link => link.relation === 'next'); + if (!next) return EMPTY; + // A reverse proxy may expose the API's own origin in the link. Keep the request on the original endpoint + // with the same measure and filters, advancing only by the offset that the server supplied. + const url = new URL(next.url, `http://localhost${path}`); + const raw = url.searchParams.get('_offset'); + const nextOffset = raw === null ? NaN : Number(raw); + if (url.pathname !== path || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) { + throw new Error('Paginación FHIR inválida'); + } + return this.reports(dominio, measure, params.set('_offset', nextOffset)).pipe( + map(page => ({ bundle: page, offset: nextOffset })), + ); + }, 1), + reduce((reports, { bundle }) => reports.concat(resources(bundle, 'MeasureReport') as Report[]), [] as Report[]), + ); + } } @Injectable() @@ -425,8 +452,8 @@ export class FhirIndicadoresService extends IndicadoresService { let params = new HttpParams().set('_count', MAX_COUNT); params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo); return this.measures.one(dominio, indicador).pipe( - switchMap(measure => this.measures.reports(dominio, measure, params).pipe( - map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope))))); + switchMap(measure => this.measures.allReports(dominio, measure, params).pipe( + map(reports => datosValidos(datosDeReportes(measure, reports, tipo, scope), indicador, tipo, periodos, scope))))); } override figura(selection: FigureSelection) { const dominio = requireDominio(selection.dominio ?? 'tea'); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts new file mode 100644 index 0000000..7236108 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -0,0 +1,179 @@ +// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the +// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and +// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports +// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group +// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down. +import { Bundle, resources } from './fhir'; +import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir'; +import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir'; +import { HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config'; +import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures'; +import measuresData from './fixtures/cacu_fhir_measures.json'; +import camaMeasuresData from './fixtures/cama_fhir_measures.json'; + +const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition'; +const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[]; +const medida = (id: string) => publicadas.find(m => m.id === id)!; +const cod = (c: string) => ({ coding: [{ code: c }] }); +const pob = (c: string, count: number) => ({ code: cod(c), count }); +const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria')) + .map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!); +const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' }; +const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' }; + +// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive. +const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({ + resourceType: 'MeasureReport', id: 'r', period, + group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)], + ...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }], +} as unknown as Report); +// A composition: the categories as the first stratifier, the units as the initial population. +const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record, unidades?: number): Report => ({ + resourceType: 'MeasureReport', id: 'r', period, + group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))], + stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }], +} as unknown as Report); +// A duration: the median and the quartiles as extensions of the score. +const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({ + resourceType: 'MeasureReport', id: 'r', period, + group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)], + ...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [ + { url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }], +} as unknown as Report); +const traza = (datos: ReturnType, i: number, opciones?: HistoricoOpciones) => + historicoFigura(datos, 'claro', opciones).figure.data[i] as Record & { x: unknown[]; y: unknown[] }; +const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true }; + +describe('Histórico de CaCu: grupo principal e identificadores reales', () => { + it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => { + // Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the + // selector of the total drops every row, which left EU13's panel empty. + const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre'); + expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 }); + expect(Object.keys(datos['grupos'] as object)).toEqual(['total']); + const figura = historicoFigura(datos, 'claro'); + expect(traza(datos, 1).y).toEqual([0]); + expect(figura.sinDato).toEqual([]); + }); + it('IND1 se publica como `ind1` y conserva su valor', () => { + const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre'); + expect(datos.id).toBe('ind1'); + expect(traza(datos, 1).y).toEqual([25, 25]); + }); + it('el intervalo de Wilson publicado usa la misma escala porcentual que el valor', () => { + // Fails if the history drops the FHIR bounds or scales them a second time. + for (const id of ['CACU-EU13', 'IND1']) { + const reporte = c1(SEMESTRE, 1, 4); + reporte.group![0].measureScore!.extension = [ + { url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, + { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }, + ]; + const datos = datosDeReportes(medida(id), [reporte], 'semestre'); + expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 }); + expect(traza(datos, 0).y).toEqual([69.9, 4.6]); + } + }); + it('un denominador cero es «sin dato», no un cero', () => { + // The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero. + const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre'); + expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 }); + expect(traza(datos, 1).y).toEqual([null, 25]); + expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']); + }); + it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => { + const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre'); + expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null }); + expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] }); + }); + it('en CaMa el grupo principal sigue siendo `total`', () => { + // Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result. + const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!; + const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre'); + expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 }); + }); + it('los paneles activos usan ids de página y contratos que el catálogo publica', () => { + // Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id + // the page gives it, and with the contract the panel expects. + const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); + const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); + expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']); + for (const panel of activos) { + expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); + expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); + } + }); + it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { + const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); + expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ + ['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'], + ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'], + ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], + ]); + // The risk bands are in the catalog and stay reserved. + expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda'); + }); +}); + +describe('Histórico de CaCu: composiciones (C2)', () => { + const eu7 = () => medida('CACU-EU7'); + const conteos = (extra: Record = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra }); + + it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => { + const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre'); + expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 }); + const figura = historicoFigura(datos, 'claro', CACU); + expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]); + expect(figura.sinDato).toEqual([]); + }); + it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => { + // Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open + // decision) is no longer a shorter bar. The adapter itself reads the report as before. + const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre'); + expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC'); + expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo'); + expect(() => historicoFigura(datos, 'claro')).not.toThrow(); + }); + it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => { + const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0])); + const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre'); + const figura = historicoFigura(datos, 'claro', CACU); + expect(figura.sinDato).toEqual(['2025 S1']); + expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true); + expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8); + }); + it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => { + // Regression: the rule is the domain's, not the figure module's. + const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0])); + const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre'); + const figura = historicoFigura(datos, 'claro'); + expect(figura.sinDato).toEqual([]); + expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true); + }); + it('la confirmación por citología declara sus categorías y se concilia igual', () => { + const m = medida('CACU-CONFIRMACION-CITOLOGIA'); + const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre'); + expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 }); + expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow(); + }); +}); + +describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => { + const m = () => medida('CACU-EU-TIEMPO-REPORTE'); + it('la mediana y los cuartiles hablan de citologías en CaCu', () => { + const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre'); + expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' }); + const figura = historicoFigura(datos, 'claro', CACU); + expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días
Q1 a Q3: 10 a 15 días
6 citologías'); + expect(figura.comoLeer).toContain('las citologías'); + expect(figura.comoLeer).not.toContain('mastograf'); + // A period without observations is missing, not zero. + expect(traza(datos, 1, CACU)['y']).toEqual([12, null]); + expect(figura.sinDato).toEqual(['2025 S2']); + }); + it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => { + // Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise. + const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre'); + expect(traza(datos, 1)['text'][0]).toContain('6 mastografías'); + expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts new file mode 100644 index 0000000..a956520 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -0,0 +1,252 @@ +// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing +// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and +// the notice. Responses are synthetic, shaped like /cacu/indicadores//periodos and /datos. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import { MatDialog } from '@angular/material/dialog'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadoresHistorico } from './indicadores-historico'; +import { AVISO_CACU, HISTORICO_CACU, HISTORICO_CACU_DATOS } from './indicadores-historico-config'; +import { Indicador } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; } + +const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`); +const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1']; +const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', + cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; +const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']; +const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; +// Every measure the catalog could publish, reserved ones included: publishing them must not activate them. +const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); + +function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) { + const contrato = opciones.contrato ?? CONTRATOS[id]; + const fila = (periodo: string, campos: Record) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos }); + const vacio = (p: string) => p === opciones.sinPoblacion; + const filas = contrato === 'C2' + ? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })]) + : contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null })) + : periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' })); + return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas, + categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } }, + ...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) }; +} + +describe('Histórico de CaCu', () => { + let fixture: ReturnType>, http: HttpTestingController; + const abrirDialogo = vi.fn(); + function montar(catalog: Indicador[] = CATALOGO, active = false, simulado = true) { + TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [ + provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }, + ...(simulado ? [{ provide: HISTORICO_CACU_DATOS, useValue: true }] : []), + ] }); + TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog); + fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active); + fixture.detectChanges(); + } + afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); }); + // Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for. + const pedidos: { id: string; periodos: string[] }[] = []; + function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) { + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + const url = r.request.url, id = url.split('/').at(-2)!; + if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; } + if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] }); + else { + const periodos = r.request.params.get('periodos')!.split(','); + pedidos.push({ id, periodos }); + r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id))); + } + } + fixture.detectChanges(); + } + } + beforeEach(() => { pedidos.length = 0; }); + const root = () => fixture.nativeElement as HTMLElement; + const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[]; + const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!; + const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo; + const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); + const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!; + + it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => { + // Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it. + montar(); + http.expectNone(() => true); + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + const vistos = new Set(); + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + vistos.add(r.request.url.split('/').at(-2)!); + const id = r.request.url.split('/').at(-2)!; + if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) }); + else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(','))); + } + fixture.detectChanges(); + } + expect([...vistos].sort()).toEqual([...ACTIVOS].sort()); + for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false); + }); + it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => { + montar(CATALOGO, true); responder(); + expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo)); + expect(paneles()).toHaveLength(9); + expect(graficas()).toHaveLength(6); + const reservados = paneles().slice(6); + expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true); + expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual( + HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo'])); + }); + it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => { + // Pins down: the state of a reserved panel comes from the config alone. + for (const catalogo of [ACTIVOS.map(item), CATALOGO]) { + montar(catalogo, true); responder(); + expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo')); + fixture.destroy(); TestBed.resetTestingModule(); + } + }); + it('el aviso de validación clínica y supresión se ve siempre', () => { + montar(); + const aviso = root().querySelector('[data-aviso="historico"]')!; + expect(aviso.textContent).toBe(AVISO_CACU); + expect(aviso.textContent).toContain('validación clínica'); + expect(aviso.textContent).toContain('supresión'); + }); + it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { + // Pins down the first request: the page asks for the latest five months, not the twelve it could. + montar(CATALOGO, true); responder(); + expect(pedidos).toHaveLength(6); + for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5)); + expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); + }); + it('elegir «Todos» pide solo los periodos que faltan y los suma', () => { + montar(CATALOGO, true); responder(); + pedidos.length = 0; + fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder(); + expect(pedidos).toHaveLength(6); + for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7)); + expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)'); + expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); + // Going back to five is local: nothing is asked again. + pedidos.length = 0; + fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder(); + expect(pedidos).toEqual([]); + expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); + }); + it.each([false, true])('acumula 5→10→Todos sin duplicados al recibir primero la segunda respuesta: %s', invertir => { + // The two expansions are disjoint. Either arrival order must preserve all twelve periods. + montar([item('ind1')], true); responder(); + fixture.componentInstance.elegirVentana(10); + fixture.componentInstance.elegirVentana(0); + fixture.componentInstance.elegirVentana(0); + const ampliaciones = http.match(r => r.url.endsWith('/datos')); + const periodos = (r: TestRequest) => r.request.params.get('periodos')!.split(','); + expect(ampliaciones.map(periodos)).toEqual([MESES.slice(2, 7), MESES.slice(0, 2)]); + for (const r of invertir ? ampliaciones.reverse() : ampliaciones) { + r.flush(datos('ind1', 'mes', periodos(r))); + fixture.detectChanges(); + } + expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); + http.expectNone(() => true); + }); + it('reintenta la ampliación fallida conservando los cinco periodos y sin repetir periodos cargados', () => { + montar([item('ind1')], true); responder(); + fixture.componentInstance.elegirVentana(0); + http.expectOne(r => r.url.endsWith('/datos')).flush('private', { status: 500, statusText: 'Error' }); + fixture.detectChanges(); + const panel = panelDe(tituloDe('ind1')); + expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(5); + expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Error'); + (panel.querySelector('button') as HTMLButtonElement).click(); + const reintento = http.expectOne(r => r.url.endsWith('/datos')); + expect(reintento.request.params.get('periodos')?.split(',')).toEqual(MESES.slice(0, 7)); + reintento.flush(datos('ind1', 'mes', MESES.slice(0, 7))); + fixture.detectChanges(); + expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); + expect(panel.querySelector('[role="alert"]')).toBeNull(); + }); + it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => { + montar(CATALOGO, true); responder(); + pedidos.length = 0; + fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); + expect(pedidos).toHaveLength(6); + for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5)); + pedidos.length = 0; + fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder(); + fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); + expect(pedidos).toEqual([]); + }); + it('una medida ausente muestra «Trabajo en desarrollo» y no se consulta', () => { + montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder(); + const panel = panelDe(tituloDe('cacu_eu13')); + expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo'); + expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false); + expect(graficas()).toHaveLength(5); + }); + it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => { + montar(CATALOGO, true); + responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') }); + const panel = panelDe(tituloDe('cacu_eu13')); + expect(panel.querySelector('[role="alert"]')).not.toBeNull(); + expect(panel.textContent).not.toContain('private'); + expect(graficas()).toHaveLength(5); + const reintentar = panel.querySelector('button') as HTMLButtonElement; + reintentar.click(); fixture.detectChanges(); responder(); + expect(graficas()).toHaveLength(6); + }); + it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => { + // Pins down the expected contract: the panel does not draw a C1 where it declared a composition. + montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} }); + const panel = panelDe(tituloDe('cacu_eu7')); + expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1'); + expect(graficas()).toHaveLength(5); + }); + it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => { + montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} }); + expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]); + expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull(); + const eu7 = panelDe(tituloDe('cacu_eu7')); + expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)'); + expect(eu7.textContent).toContain('oct 2025'); + expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]); + }); + it('los tiempos hablan de citologías', () => { + montar(CATALOGO, true); responder(); + for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) { + expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías'); + expect(panelDe(tituloDe(id)).textContent).toContain('las citologías'); + expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf'); + } + }); + it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => { + montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true); + expect(paneles()).toHaveLength(9); + expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true); + http.expectNone(() => true); + }); + it('la configuración ordinaria conserva los paneles, con los resultados restringidos', () => { + montar(CATALOGO, true, false); + expect(paneles()).toHaveLength(9); + expect(graficas()).toHaveLength(0); + expect(paneles()[0].querySelector('[role="status"]')?.textContent).toBe('Resultados disponibles en modo simulado.'); + expect(paneles()[8].querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo'); + http.expectNone(() => true); + }); + it('sin periodos con reportes un panel activo muestra «Sin datos»', () => { + montar([item('ind1')], true); + http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] }); + fixture.detectChanges(); + expect(panelDe(tituloDe('ind1')).querySelector('[role="status"]')?.textContent).toBe('Sin datos'); + expect(graficas()).toHaveLength(0); + http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts new file mode 100644 index 0000000..c8a2647 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -0,0 +1,88 @@ +import { InjectionToken } from '@angular/core'; +import { Dominio } from './indicadores.models'; +import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; + +// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is +// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws +// its whole catalog. + +export type ContratoHistorico = 'C1' | 'C2' | 'C3r'; +// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not. +export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana'; +export interface PanelHistorico { + // The page's id of the measure (what `indicadorId` gives). + id: string; + titulo: string; + contrato?: ContratoHistorico; + grafica?: GraficaHistorico; + enDesarrollo?: boolean; + // The FHIR ids the reserved panels will use even if the catalog already publishes them. + fhir?: readonly string[]; +} +export interface UnidadHistorico { plural: string; eje: string } +export interface HistoricoDominio { + paneles: readonly PanelHistorico[]; + // The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default. + unidades?: Readonly>; + // How many of the latest periods are requested when the tab opens. Without it, every period is requested. + periodosIniciales?: number; + // A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar. + conciliarC2?: boolean; + // A composition period with no units is «sin dato», not a bar of zeros. + c2SinPoblacionSinDato?: boolean; + // Shown above the panels. + aviso?: string; +} + +// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not +// publish is drawn as a pending panel instead of being left out, so what is missing stays visible. +export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ + { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, + { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' }, + { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA }, + { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, + { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, + { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, + { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, +]; + +// Enable report queries only in the isolated simulated configuration. The tab remains visible in every build. +export const HISTORICO_CACU_DATOS = new InjectionToken('Consultas del Histórico CaCu en modo simulado', { + providedIn: 'root', + factory: () => false, +}); + +export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. ' + + 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.'; + +// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. +export const HISTORICO_CACU: readonly PanelHistorico[] = [ + { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' }, + { id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' }, + { id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' }, + { id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' }, + { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, + { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, + { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', + enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] }, + { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', + enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] }, + { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', + enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] }, +]; + +const HISTORICOS: Readonly>> = { + cama: { paneles: HISTORICO_CAMA }, + cacu: { + paneles: HISTORICO_CACU, + // `examen` is the citology here. + unidades: { examen: { plural: 'citologías', eje: 'Citologías' } }, + periodosIniciales: 5, + conciliarC2: true, + c2SinPoblacionSinDato: true, + aviso: AVISO_CACU, + }, +}; + +// The domain's declared history, if it has one and the tab is on. +export const historicoDeDominio = (dominio: Dominio): HistoricoDominio | undefined => HISTORICOS[dominio]; diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 0c19349..2878033 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -31,12 +31,19 @@ export interface HistoricoOpciones { // Same vertical scale across small charts, so their heights compare. yMax?: number; pequena?: boolean; + // The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's). + unidades?: Readonly>; + // A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error. + conciliarC2?: boolean; + // A composition period with no units is «sin dato», not a bar of zeros. + c2SinPoblacionSinDato?: boolean; } // What the unit a measure publishes is called in the charts' texts. const UNIDADES: Readonly> = { paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' }, }; -const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' }; +const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) => + propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' }; function validar(data: IndicadorDatos) { for (const row of data.filas) { if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida'); @@ -107,7 +114,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { figure: { data: [ banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno), { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea }, - text: validas.map(row => row ? `${row['valor']} %
${row['numerador']} de ${row['denominador']}
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), + text: validas.map(row => { + if (!row) return ''; + const intervalo = numero(row['ic_bajo']) && numero(row['ic_alto']) ? `
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''; + return `${row['valor']} %
${row['numerador']} de ${row['denominador']}${intervalo}`; + }), hovertemplate: '%{x}
%{text}' }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', @@ -115,7 +126,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { }; } function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { - const periodos = validar(data), unidad = unidadDe(data); + const periodos = validar(data), unidad = unidadDe(data, opciones.unidades); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); const trazo = colorDeLinea(data.id, tema); return { @@ -137,8 +148,8 @@ const CONTEOS: Readonly> = { M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' }, M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' }, }; -function conteo(data: IndicadorDatos, tema: Tema): Trazo { - const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data); +function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo { + const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades); const celdas = new Map>(), categorias = new Map(); for (const row of data.filas) { const id = row['categoria'], key = JSON.stringify([id, row['periodo']]); @@ -151,7 +162,22 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo { const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))]; const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo]))); const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1)); - const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))); + // The units each report says it has, when the adapter kept them: what the categories of a period must add up to. + const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined; + const suma = (p: string) => { + const valores = estadoDe(p).map(row => row?.['n']); + return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null; + }; + if (opciones.conciliarC2 && unidades) { + for (const p of periodos) { + const total = unidades[p], contado = suma(p); + if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo'); + } + } + // A period with no units is not a period of zeros: it is drawn as a gap and listed. + const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato + ? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []); + const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])))); const curso = { frio: 0, calido: 0, neutro: 0 }; return { figure: { data: orden.map((id, i) => { @@ -159,7 +185,7 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo { const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined; const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id); const slot = tono === 'neutro' ? i : curso[tono]++; - const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; }); + const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; }); return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores, marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}%{fullData.name}' }; }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, @@ -176,7 +202,7 @@ function etiquetaCategoria(meta: Record, id: string) { // The plot follows from what the contract's numbers mean: counts add up to a total, percentages // and medians do not, so those two are never stacked. export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura { - const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema) + const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema) : data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined; if (!figura) throw new Error('Representación no soportada'); return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index dc67f13..5e59731 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -38,12 +38,13 @@ describe('Pestaña Histórico', () => { expect(root().querySelector('#panel-analisis')).toBeNull(); http.expectNone(request => request.url.startsWith('/cama/analisis')); }); - it('cacu no tiene la pestaña Histórico', () => { - // Fails if the history tab of TEA or CaMa leaks into CaCu. + it('cacu tiene Histórico y no Análisis epidemiológico', () => { + // Fails if CaCu loses its history tab or gains CaMa's analysis tab. abrir('cama', []); abrir('cacu', [item('cacu_x', 'C2')]); - expect(tabs()).toEqual(['Resumen', 'Análisis de riesgos', 'Datos y definiciones']); - expect(root().querySelector('#panel-historico')).toBeNull(); + expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(root().querySelector('#panel-historico')).not.toBeNull(); + expect(root().querySelector('#panel-analisis')).toBeNull(); }); it('tea tiene Histórico pero no Análisis epidemiológico', () => { abrir('cama', []); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index a40bb78..a686355 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -1,4 +1,4 @@ -import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core'; +import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked, viewChild } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; @@ -6,7 +6,7 @@ import { MatDialog } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelect, MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; +import { defer, map, Subscription } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; @@ -14,27 +14,34 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; +import { HISTORICO_CACU_DATOS, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config'; + +export { HISTORICO_CAMA }; const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); -type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; -type Panel = { item: Pick & { contrato?: Indicador['contrato'] }; rango?: string } & ( - { estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); +interface Carga { + disponibles?: string[]; + datos?: IndicadorDatos; + errorPeriodos?: string; + consultados: ReadonlySet; + enCurso: ReadonlySet; + fallos: ReadonlyMap; +} +type Panel = { item: Pick & { contrato?: Indicador['contrato'] }; rango?: string; mensaje?: string } & ( + { estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'restringido' | 'error' } + | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); +class ContratoHistoricoInvalido extends Error {} const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; const CASOS = 'M28_casos_por_estado'; const PERSONALIZADO = -1; - -// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not -// publish is drawn as a pending panel instead of being left out, so what is missing stays visible. -export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ - { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, - { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' }, - { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA }, - { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, - { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, - { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, - { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, -]; +function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos { + const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p))); + const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []), + ...(Array.isArray(b['reportes']) ? b['reportes'].filter(r => nuevos.has(r.periodo)) : [])]; + const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) }; + return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(f => nuevos.has(f['periodo'] as string))], + ...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) }; +} // The screening steps go together as small charts, and the case counts are followed by their in-process share. function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] { @@ -62,6 +69,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P selector: 'app-indicadores-historico', imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], template: ` + @if (aviso(); as texto) {

{{ texto }}

} + @if (consultasHabilitadas()) {

Filtros

@@ -81,18 +90,23 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P @if (ventana() === PERSONALIZADO) { }
+ }
@for (panel of paneles(); track panel.item.id) {

{{ panel.item.titulo }}

@if (panel.rango) {

{{ panel.rango }}

} + @if (panel.mensaje) { +

Error. {{ panel.mensaje }}

+
+ } @switch (panel.estado) { @case ('pendiente') {

Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.

} + @case ('desarrollo') {

Trabajo en desarrollo

} + @case ('restringido') {

Resultados disponibles en modo simulado.

} @case ('cargando') { } - @case ('vacio') {

Sin reportes publicados para este intervalo de análisis.

} - @case ('error') { -

{{ panel.mensaje }}

-
+ @case ('vacio') { +

{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}

} @case ('listo') { @if (panel.pasos; as pasos) { @@ -130,6 +144,8 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P @use '@angular/material' as mat; :host { display: block; min-width: 0; } + .aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); + border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); } .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } @@ -171,9 +187,22 @@ export class IndicadoresHistorico { readonly catalog = input.required(); readonly tema = input.required(); readonly active = input(false); - // The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere. - private readonly publicados = computed(() => this.dominio() === 'cama' - ? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog()); + readonly catalogLoading = input(false); + readonly catalogError = input(''); + readonly retryCatalog = output(); + private readonly datosCacu = inject(HISTORICO_CACU_DATOS); + readonly consultasHabilitadas = computed(() => this.dominio() !== 'cacu' || this.datosCacu); + // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. + private readonly config = computed(() => historicoDeDominio(this.dominio())); + readonly aviso = computed(() => this.config()?.aviso); + // The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active; + // the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes. + private readonly publicados = computed(() => { + const config = this.config(); + return config + ? config.paneles.filter(entrada => !entrada.enDesarrollo).flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) + : this.catalog(); + }); // Only the granularities some indicator publishes; monthly first when there is one. readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo)))); readonly elegido = signal(undefined); @@ -183,15 +212,23 @@ export class IndicadoresHistorico { }); // How many of the latest periods to show, per granularity; 0 shows them all. private readonly ventanas = signal>>({}); - readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); + // Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all. + readonly ventana = computed(() => { + const elegida = this.ventanas()[this.tipo()]; + if (elegida !== undefined) return elegida; + const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles(); + return inicial && (!total || total > inicial) ? inicial : 0; + }); readonly PERSONALIZADO = PERSONALIZADO; // The periods the user picked in the dialog, per granularity. private readonly personalizados = signal>>({}); private readonly dialogo = inject(MatDialog); private readonly selector = viewChild('selector'); // Every period published for the granularity by any indicator. - private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {}) - .flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : []))); + private readonly disponibles = computed(() => cronologico([...new Set(Object.values(this.cargas()[this.tipo()] ?? {}) + .flatMap(carga => this.config()?.periodosIniciales ? carga.disponibles ?? [] : carga.datos?.periodos ?? []))])); + private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {}) + .map(carga => (this.config()?.periodosIniciales ? carga.disponibles : carga.datos?.periodos)?.length ?? 0))); // The periods on screen, out of those an indicator publishes. private recortar(periodos: readonly string[]) { const orden = cronologico(periodos), ventana = this.ventana(); @@ -202,14 +239,13 @@ export class IndicadoresHistorico { private readonly service = inject(IndicadoresService); private readonly periodos = inject(IndicadoresPeriodos); private readonly cargas = signal>>>({}); - private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>(); - private solicitada?: string; - private catalogoCargado?: readonly Indicador[]; + private peticiones = new Subscription(); + private ambito?: { dominio: Dominio; catalogo: readonly Indicador[] }; // Steps of five, up to what the indicator with the most periods has published. readonly opciones = computed(() => { const tipo = this.tipo(); - const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); + const total = this.totalDisponibles(); const opciones = []; for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); const elegidos = this.personalizados()[tipo]?.length; @@ -221,7 +257,7 @@ export class IndicadoresHistorico { // Top of the shared scale: the highest third quartile of the steps, in the periods on screen. const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => { const carga = cargas?.[id]; - if (carga?.estado !== 'listo') return []; + if (!carga?.datos) return []; const visibles = this.recortar(carga.datos.periodos); return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0); })) * 1.05; @@ -229,56 +265,140 @@ export class IndicadoresHistorico { if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' }; const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; - if (carga.estado !== 'listo') return { item, ...carga }; - const periodos = this.recortar(carga.datos.periodos); - if (!periodos.length) return { item, estado: 'vacio' }; + const necesarios = this.necesarios(carga.disponibles ?? [], tipo); + const mensaje = carga.errorPeriodos ?? necesarios.map(p => carga.fallos.get(p)).find(Boolean); + const periodos = this.config()?.periodosIniciales + ? necesarios.filter(p => carga.datos?.periodos.includes(p)) + : this.recortar(carga.datos?.periodos ?? []); + if (!periodos.length || !carga.datos) { + if (mensaje) return { item, estado: 'error', mensaje }; + return { item, estado: !carga.disponibles || necesarios.some(p => carga.enCurso.has(p)) ? 'cargando' : 'vacio' }; + } const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`; const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`; try { - return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos }; + const propias = this.config(); + const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), + ...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) }; + const figura = historicoFigura(datos, tema, opciones); + if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) { + return { item, estado: mensaje ? 'error' : 'vacio', mensaje }; + } + return { item, rango, estado: 'listo', figura, datos, mensaje }; } catch (error) { return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } }; - if (this.dominio() === 'cama') { - if (!this.publicados().length) return []; - return HISTORICO_CAMA.map((entrada): Panel => { + const config = this.config(); + if (config) { + const cacu = this.dominio() === 'cacu'; + if (!cacu && !this.publicados().length) return []; + return config.paneles.map((entrada: PanelHistorico): Panel => { + const visible = { id: entrada.id, titulo: entrada.titulo }; + if (entrada.enDesarrollo) return { item: visible, estado: 'desarrollo' }; + if (cacu && this.catalogError()) return { item: visible, estado: 'error', mensaje: this.catalogError() }; + if (cacu && this.catalogLoading()) return { item: visible, estado: 'cargando' }; const item = this.catalog().find(i => i.id === entrada.id); - return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' }; + if (!item) return { item: visible, estado: cacu ? 'desarrollo' : 'pendiente' }; + if (!this.consultasHabilitadas()) return { item: visible, estado: 'restringido' }; + return { ...panelDe(item), item: { ...visible, contrato: item.contrato } }; }); } return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema); }); constructor() { - this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo)) - .map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))), - takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => { - this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) })); - }); + this.destruccion.onDestroy(() => this.peticiones.unsubscribe()); effect(() => { - const tipo = this.tipo(), items = this.publicados(); - if (!this.active() || !items.length) return; + const dominio = this.dominio(), catalogo = this.catalog(), tipo = this.tipo(); + const activo = this.active() && this.consultasHabilitadas() && !this.catalogLoading() && !this.catalogError(); untracked(() => { - if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; } - if (this.cargas()[tipo] || this.solicitada === tipo) return; - this.solicitada = tipo; - this.solicitudes.next({ tipo, items }); + if (this.ambito?.catalogo !== catalogo || this.ambito?.dominio !== dominio) { + this.peticiones.unsubscribe(); + this.peticiones = new Subscription(); + this.cargas.set({}); + this.ambito = { dominio, catalogo }; + } + if (activo) this.cargarVentana(tipo); }); }); } - private cargar(item: Indicador, tipo: TipoPeriodo): Observable { - return this.periodos.periodos(this.dominio(), item.id).pipe( - map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)), - switchMap((periodos): Observable => periodos.length - ? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos }))) - : of({ estado: 'vacio' })), - catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); + + private necesarios(disponibles: readonly string[], tipo: TipoPeriodo): string[] { + if (!this.config()?.periodosIniciales) return [...disponibles]; + const orden = cronologico(disponibles), ventana = this.ventanas()[tipo] ?? this.config()?.periodosIniciales; + if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[tipo] ?? []).includes(p)); + return ventana ? orden.slice(-ventana) : orden; } + + private guardarCarga(tipo: TipoPeriodo, id: string, carga: Carga) { + this.cargas.update(actual => ({ ...actual, [tipo]: { ...actual[tipo], [id]: carga } })); + } + + private cargarVentana(tipo: TipoPeriodo) { + if (!this.active() || !this.consultasHabilitadas() || this.catalogLoading() || this.catalogError()) return; + for (const { id, tipos_periodo } of this.publicados()) { + if (!tipos_periodo.includes(tipo)) continue; + const carga = this.cargas()[tipo]?.[id]; + if (carga) this.solicitarPeriodos(tipo, id, carga); + else this.descubrirPeriodos(tipo, id); + } + } + + private descubrirPeriodos(tipo: TipoPeriodo, id: string) { + const carga: Carga = { consultados: new Set(), enCurso: new Set(), fallos: new Map() }; + this.guardarCarga(tipo, id, carga); + this.peticiones.add(defer(() => this.periodos.periodos(this.dominio(), id)).subscribe({ + next: periodos => { + const descubierta = { ...carga, disponibles: [...new Set(periodos.filter(p => p.tipo === tipo).map(p => p.periodo))] }; + this.guardarCarga(tipo, id, descubierta); + if (this.active() && this.tipo() === tipo) this.solicitarPeriodos(tipo, id, descubierta); + }, + error: error => this.guardarCarga(tipo, id, { ...carga, errorPeriodos: httpMessage(error) }), + })); + } + + private solicitarPeriodos(tipo: TipoPeriodo, id: string, carga: Carga) { + if (!carga.disponibles) return; + const faltan = this.necesarios(carga.disponibles, tipo) + .filter(p => !carga.consultados.has(p) && !carga.enCurso.has(p) && !carga.fallos.has(p)); + if (!faltan.length) return; + this.guardarCarga(tipo, id, { ...carga, enCurso: new Set([...carga.enCurso, ...faltan]) }); + const solicitados = new Set(faltan); + const vigente = () => { + const actual = this.cargas()[tipo]![id]; + return { ...actual, enCurso: new Set([...actual.enCurso].filter(p => !solicitados.has(p))) }; + }; + const config = this.config(); + const esperado = config?.paneles.find(panel => panel.id === id)?.contrato; + this.peticiones.add(defer(() => this.service.datos(this.dominio(), id, tipo, faltan)).pipe(map(datos => { + if (esperado && datos.contrato !== esperado) { + throw new ContratoHistoricoInvalido(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`); + } + // Validate each batch before it is allowed to affect a series that already has valid periods. + if (esperado && datos.periodos.length) historicoFigura(datos, this.tema(), config); + return datos; + })).subscribe({ + next: datos => { + const actual = vigente(); + this.guardarCarga(tipo, id, { ...actual, consultados: new Set([...actual.consultados, ...faltan]), + datos: actual.datos ? unir(actual.datos, datos) : datos }); + }, + error: error => { + const actual = vigente(), fallos = new Map(actual.fallos); + const mensaje = error instanceof ContratoHistoricoInvalido ? error.message : httpMessage(error); + for (const periodo of faltan) fallos.set(periodo, mensaje); + this.guardarCarga(tipo, id, { ...actual, fallos }); + }, + })); + } + + private readonly destruccion = inject(DestroyRef); elegirVentana(valor: number) { if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; } this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); + this.cargarVentana(this.tipo()); } abrirPersonalizado() { const tipo = this.tipo(), periodos = this.disponibles(); @@ -286,19 +406,38 @@ export class IndicadoresHistorico { const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos; const data: PeriodosDialogoDatos = { tipo, periodos, elegidos }; this.dialogo.open(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' }) - .afterClosed().subscribe(resultado => { + .afterClosed().pipe(takeUntilDestroyed(this.destruccion)).subscribe(resultado => { if (resultado?.length) { this.personalizados.update(actual => ({ ...actual, [tipo]: resultado })); this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO })); + if (this.tipo() === tipo) this.cargarVentana(tipo); } // Cancelled, the selector goes back to what's on screen. this.selector()?.writeValue(this.ventana()); }); } - reintentar() { + reintentar(id: string) { + if (this.catalogError()) { + this.retryCatalog.emit(); + return; + } const tipo = this.tipo(); - this.solicitada = tipo; - this.cargas.update(({ [tipo]: _, ...resto }) => resto); - this.solicitudes.next({ tipo, items: this.publicados() }); + const carga = this.cargas()[tipo]?.[id]; + if (!carga) return; + if (carga.errorPeriodos) { + this.descubrirPeriodos(tipo, id); + return; + } + const seleccion = this.necesarios(carga.disponibles ?? [], tipo); + if (!seleccion.some(periodo => carga.fallos.has(periodo))) { + // A figure can fail after its reports were accepted. Reload just that panel. + if (!carga.enCurso.size) this.descubrirPeriodos(tipo, id); + return; + } + const fallos = new Map(carga.fallos); + for (const periodo of seleccion) fallos.delete(periodo); + const corregida = { ...carga, fallos }; + this.guardarCarga(tipo, id, corregida); + this.solicitarPeriodos(tipo, id, corregida); } } diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index b03db42..5c3f592 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -129,7 +129,8 @@ @if (conHistorico) {
- +
} diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 160bbbf..1f6022b 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -33,6 +33,7 @@ import { IndicadoresTracking } from './indicadores-tracking'; import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresHistorico } from './indicadores-historico'; +import { historicoDeDominio } from './indicadores-historico-config'; import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; @@ -60,7 +61,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ }) export class IndicadoresPage { get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } - get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; } + get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; } get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; } readonly activeSection = signal('resumen'); readonly fichaPacienteAbierta = signal(false); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 974b036..a5bc460 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( - dominio === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']); + ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 378d6cd..66cb6a9 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -39,9 +39,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - // TEA and CaMa also have Histórico; the follow-up tab is named Análisis de riesgos in every domain; CaCu keeps its three tabs. - const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] - : domain === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']; + // TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain. + const esperadas = ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; From 10773edcc1f6719a3eee532e3c542eda68a8788c Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 02:11:29 -0600 Subject: [PATCH 02/35] =?UTF-8?q?Hist=C3=B3rico=20CaCu:=20remove=20the=20s?= =?UTF-8?q?imulation-only=20gate=20so=20the=20tab=20and=20its=20queries=20?= =?UTF-8?q?behave=20the=20same=20in=20every=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/app.config.simulado.ts | 2 -- .../indicadores-historico-cacu-paneles.spec.ts | 13 ++----------- .../indicadores/indicadores-historico-config.ts | 7 ------- .../features/indicadores/indicadores-historico.ts | 14 ++++---------- 4 files changed, 6 insertions(+), 30 deletions(-) diff --git a/src/app/app.config.simulado.ts b/src/app/app.config.simulado.ts index f30bf17..31b9c77 100644 --- a/src/app/app.config.simulado.ts +++ b/src/app/app.config.simulado.ts @@ -5,7 +5,6 @@ import { routes } from './app.routes'; import { IndicadoresService } from './features/indicadores/indicadores.service'; import { IndicadoresPeriodos } from './features/indicadores/indicadores-periodos'; import { FhirIndicadoresPeriodos, FhirIndicadoresService } from './features/indicadores/indicadores-fhir'; -import { HISTORICO_CACU_DATOS } from './features/indicadores/indicadores-historico-config'; // SOLO para el modo «simulado» (ng serve --configuration simulado): igual que app.config.ts, pero el seguimiento // de TEA lee el contrato JSON (`/tea/seguimiento`) del servidor de prueba (`simulado/servidor.py`). @@ -18,6 +17,5 @@ export const appConfig: ApplicationConfig = { // (`//indicadores//datos`, `/tea/seguimiento`). { provide: IndicadoresService, useClass: FhirIndicadoresService }, { provide: IndicadoresPeriodos, useClass: FhirIndicadoresPeriodos }, - { provide: HISTORICO_CACU_DATOS, useFactory: () => ['localhost', '127.0.0.1', '[::1]'].includes(globalThis.location?.hostname ?? '') }, ] }; diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index a956520..1447e39 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -9,7 +9,7 @@ import { By } from '@angular/platform-browser'; import { MatDialog } from '@angular/material/dialog'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistorico } from './indicadores-historico'; -import { AVISO_CACU, HISTORICO_CACU, HISTORICO_CACU_DATOS } from './indicadores-historico-config'; +import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @@ -41,10 +41,9 @@ function datos(id: string, tipo: string, periodos: string[], opciones: { contrat describe('Histórico de CaCu', () => { let fixture: ReturnType>, http: HttpTestingController; const abrirDialogo = vi.fn(); - function montar(catalog: Indicador[] = CATALOGO, active = false, simulado = true) { + function montar(catalog: Indicador[] = CATALOGO, active = false) { TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [ provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }, - ...(simulado ? [{ provide: HISTORICO_CACU_DATOS, useValue: true }] : []), ] }); TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController); @@ -233,14 +232,6 @@ describe('Histórico de CaCu', () => { expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true); http.expectNone(() => true); }); - it('la configuración ordinaria conserva los paneles, con los resultados restringidos', () => { - montar(CATALOGO, true, false); - expect(paneles()).toHaveLength(9); - expect(graficas()).toHaveLength(0); - expect(paneles()[0].querySelector('[role="status"]')?.textContent).toBe('Resultados disponibles en modo simulado.'); - expect(paneles()[8].querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo'); - http.expectNone(() => true); - }); it('sin periodos con reportes un panel activo muestra «Sin datos»', () => { montar([item('ind1')], true); http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] }); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index c8a2647..6837fa1 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -1,4 +1,3 @@ -import { InjectionToken } from '@angular/core'; import { Dominio } from './indicadores.models'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; @@ -46,12 +45,6 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, ]; -// Enable report queries only in the isolated simulated configuration. The tab remains visible in every build. -export const HISTORICO_CACU_DATOS = new InjectionToken('Consultas del Histórico CaCu en modo simulado', { - providedIn: 'root', - factory: () => false, -}); - export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. ' + 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.'; diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index a686355..0f9a0f0 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -14,7 +14,7 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; -import { HISTORICO_CACU_DATOS, HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config'; +import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config'; export { HISTORICO_CAMA }; @@ -28,7 +28,7 @@ interface Carga { fallos: ReadonlyMap; } type Panel = { item: Pick & { contrato?: Indicador['contrato'] }; rango?: string; mensaje?: string } & ( - { estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'restringido' | 'error' } + { estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); class ContratoHistoricoInvalido extends Error {} const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; @@ -70,7 +70,6 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], template: ` @if (aviso(); as texto) {

{{ texto }}

} - @if (consultasHabilitadas()) {

Filtros

@@ -90,7 +89,6 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P @if (ventana() === PERSONALIZADO) { }
- }
@for (panel of paneles(); track panel.item.id) {
@@ -103,7 +101,6 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P @switch (panel.estado) { @case ('pendiente') {

Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.

} @case ('desarrollo') {

Trabajo en desarrollo

} - @case ('restringido') {

Resultados disponibles en modo simulado.

} @case ('cargando') { } @case ('vacio') {

{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}

@@ -190,8 +187,6 @@ export class IndicadoresHistorico { readonly catalogLoading = input(false); readonly catalogError = input(''); readonly retryCatalog = output(); - private readonly datosCacu = inject(HISTORICO_CACU_DATOS); - readonly consultasHabilitadas = computed(() => this.dominio() !== 'cacu' || this.datosCacu); // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. private readonly config = computed(() => historicoDeDominio(this.dominio())); readonly aviso = computed(() => this.config()?.aviso); @@ -301,7 +296,6 @@ export class IndicadoresHistorico { if (cacu && this.catalogLoading()) return { item: visible, estado: 'cargando' }; const item = this.catalog().find(i => i.id === entrada.id); if (!item) return { item: visible, estado: cacu ? 'desarrollo' : 'pendiente' }; - if (!this.consultasHabilitadas()) return { item: visible, estado: 'restringido' }; return { ...panelDe(item), item: { ...visible, contrato: item.contrato } }; }); } @@ -312,7 +306,7 @@ export class IndicadoresHistorico { this.destruccion.onDestroy(() => this.peticiones.unsubscribe()); effect(() => { const dominio = this.dominio(), catalogo = this.catalog(), tipo = this.tipo(); - const activo = this.active() && this.consultasHabilitadas() && !this.catalogLoading() && !this.catalogError(); + const activo = this.active() && !this.catalogLoading() && !this.catalogError(); untracked(() => { if (this.ambito?.catalogo !== catalogo || this.ambito?.dominio !== dominio) { this.peticiones.unsubscribe(); @@ -337,7 +331,7 @@ export class IndicadoresHistorico { } private cargarVentana(tipo: TipoPeriodo) { - if (!this.active() || !this.consultasHabilitadas() || this.catalogLoading() || this.catalogError()) return; + if (!this.active() || this.catalogLoading() || this.catalogError()) return; for (const { id, tipos_periodo } of this.publicados()) { if (!tipos_periodo.includes(tipo)) continue; const carga = this.cargas()[tipo]?.[id]; From e3c9849e29de5149a055938ef541e6af60f94954 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 02:20:31 -0600 Subject: [PATCH 03/35] =?UTF-8?q?Port=20TEA=20and=20CaCu=20section=201=20a?= =?UTF-8?q?djustments=20onto=20the=20Hist=C3=B3rico=20integration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TEA: Indicadores tab, opportunity summary with real contract values, ordered opportunity and clinical figures, «No aceptable» label for the EEG quality. CaCu: renamed lab-result KPI, six time figures under «Tiempo de tamizaje a diagnóstico», clinical figures with the pending «Progresión por grupo de riesgo». CaCu's colposcopy and biopsy times use the measures the screening route publishes and leave them to the route chart while it is shown. --- .../fixtures/regresion_cacu_tea_mapeo.json | 4 +- .../indicadores/indicador-catalog-card.ts | 4 +- .../indicadores/indicador-figura-pendiente.ts | 29 +++++ .../indicadores-cacu-final.spec.ts | 7 +- .../indicadores-cacu-secciones.spec.ts | 109 ++++++++++++++++++ .../indicadores/indicadores-cama-f4c.spec.ts | 2 +- .../indicadores-cama-oportunidad.spec.ts | 2 +- .../indicadores/indicadores-fhir.spec.ts | 18 +++ .../features/indicadores/indicadores-fhir.ts | 9 +- .../indicadores/indicadores-format.ts | 9 +- .../indicadores-historico-pestana.spec.ts | 12 +- .../indicadores-kpi-resultado.spec.ts | 2 +- .../indicadores/indicadores-kpi.spec.ts | 2 +- .../features/indicadores/indicadores-kpi.ts | 38 +++++- .../indicadores/indicadores-page.html | 18 ++- .../indicadores/indicadores-page.scss | 3 + .../features/indicadores/indicadores-page.ts | 49 ++++++-- .../indicadores-recorrido-analisis.spec.ts | 2 +- .../indicadores-screening-route-page.spec.ts | 3 +- .../indicadores/indicadores-sections.spec.ts | 6 +- .../indicadores-tea-secciones.spec.ts | 85 ++++++++++++++ .../indicadores/tea-resumen-periodo.spec.ts | 71 ++++++++++-- .../indicadores/tea-resumen-periodo.ts | 77 ++++++++++--- 23 files changed, 491 insertions(+), 70 deletions(-) create mode 100644 src/app/features/indicadores/indicador-figura-pendiente.ts create mode 100644 src/app/features/indicadores/indicadores-cacu-secciones.spec.ts create mode 100644 src/app/features/indicadores/indicadores-tea-secciones.spec.ts diff --git a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json index 1343f62..be738f4 100644 --- a/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json +++ b/src/app/features/indicadores/fixtures/regresion_cacu_tea_mapeo.json @@ -2268,7 +2268,7 @@ "grupo": null }, "MALO": { - "etiqueta": "Malo", + "etiqueta": "No aceptable", "color": "#B8433A", "grupo": null }, @@ -2303,7 +2303,7 @@ "grupo": null }, "MALO": { - "etiqueta": "Malo", + "etiqueta": "No aceptable", "color": "#B8433A", "grupo": null }, diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 40b0b66..d175696 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -143,7 +143,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { // CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu. get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; } // Connected time pairs replace the diagnosis card with one coordinated box plot. - get tiempos() { return parTiempos(this.dominio, this.indicador.id); } + get tiempos() { return this.individual ? undefined : parTiempos(this.dominio, this.indicador.id); } // Exams and patients of the same finding, drawn together on the exams' card. get conteos() { return parConteos(this.dominio, this.indicador.id); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } @@ -170,6 +170,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { @Input({ required: true }) applied!: GlobalApplied; @Input() independentPeriods = false; @Input() pinned = false; + // Draws the indicator alone even when it belongs to a connected pair. + @Input() individual = false; @Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE; readonly pinChanged = output(); @ViewChild('visibilityRegion') visibilityRegion?: ElementRef; diff --git a/src/app/features/indicadores/indicador-figura-pendiente.ts b/src/app/features/indicadores/indicador-figura-pendiente.ts new file mode 100644 index 0000000..f65c191 --- /dev/null +++ b/src/app/features/indicadores/indicador-figura-pendiente.ts @@ -0,0 +1,29 @@ +import { Component, Input } from '@angular/core'; +import { MatCardModule } from '@angular/material/card'; + +/** A figure the catalog does not publish yet: it keeps its place and title, with no figure and no number. */ +@Component({ + selector: 'app-indicador-figura-pendiente', + imports: [MatCardModule], + template: ` + +

{{ titulo }}

+

Integración pendiente. {{ detalle }}

+
Sin datos publicados
+
+ `, + styles: ` + :host { display: flex; min-width: 0; margin: 0; } + mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } + h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; } + p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } + .estado { color: var(--issste-text-secondary); } + .vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary); + border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); } + `, +}) +export class IndicadorFiguraPendiente { + @Input({ required: true }) titulo!: string; + @Input() detalle = 'Este indicador aún no está publicado por el catálogo institucional.'; +} diff --git a/src/app/features/indicadores/indicadores-cacu-final.spec.ts b/src/app/features/indicadores/indicadores-cacu-final.spec.ts index bc3a893..cb2bae0 100644 --- a/src/app/features/indicadores/indicadores-cacu-final.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-final.spec.ts @@ -19,7 +19,7 @@ import { figureApplied } from './indicadores-figure-selection'; class ChartStub {} const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({ id, titulo, contrato, tipos_periodo: ['semestre', 'mes'], - figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1', + figuras: contrato === 'C1' ? ['fig_c1_puntos'] : contrato === 'C2' ? ['fig_c2_barras'] : [], version: '1', }); const catalog = [ item('cacu_eu13', 'Tasa de detección histopatológica'), @@ -67,7 +67,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', ( fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); - const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); + // The clinical section only: CaCu's time figures sit in the opportunity section. + const cards = () => fixture.debugElement.query(By.css('.graphic-section')).queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); const card = (id: string) => cards().find(c => c.indicador.id === id)!; const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)) .map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!; @@ -84,7 +85,7 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', ( expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card')); expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([ - 'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento', + 'Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento', ]); for (const kpi of kpis.slice(3)) { expect(kpi.querySelectorAll('p')).toHaveLength(1); diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts new file mode 100644 index 0000000..b40d6ce --- /dev/null +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -0,0 +1,109 @@ +// Covers how the Indicadores tab arranges CaCu's figures: the six times of «Tiempo de tamizaje a diagnóstico» under +// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures with the +// pending «Progresión por grupo de riesgo». Fixtures: a CaCu catalog shaped like /cacu/indicadores. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; + +const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); +const CACU = [ + item('cacu_eu13', 'Tasa de detección histopatológica', 'C1', []), + item('cacu_eu7', 'Distribución de resultados citológicos', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado', 'C3r', ['fig_c3r_caja']), + item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']), + item('cacu_confirmacion_citologia', 'Tasa de confirmación histopatológica', 'C2', ['fig_c2_donas']), + item('ind1', 'Pacientes con citología anómala', 'C1', []), +]; + +// The route measures besides the cytology and diagnosis ones in CACU; with all of them the screening route chart appears. +const RUTA = ['cacu_dias_resultado_colposcopia', 'cacu_dias_toma_colposcopia', 'cacu_dias_colposcopia_biopsia', 'cacu_dias_toma_biopsia', 'cacu_dias_biopsia_diagnostico'] + .map(id => item(id, id, 'C3r', ['fig_c3r_caja'])); + +describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () => { + let fixture: ReturnType>, http: HttpTestingController; + const abrir = (catalogo: ReturnType[]) => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + http.expectOne('/cacu/indicadores').flush(catalogo); fixture.detectChanges(); + http.match(() => true); fixture.detectChanges(); + }; + // The KPI and period requests are not what these tests are about. + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + const root = () => fixture.nativeElement as HTMLElement; + const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')] + .map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim()); + + it('los seis tiempos van en su orden; los no publicados quedan como pendientes', () => { + // Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose + // the names of the request. + abrir(CACU); + expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico'); + expect(titulos('.kpi-section .catalog-grid')).toEqual([ + 'catalog-card: Tiempo de toma de muestra a resultado de citología', + 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', + 'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía', + 'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia', + 'catalog-card: Tiempo de toma de muestra a diagnóstico', + 'figura-pendiente: Tiempo de diagnóstico a tratamiento']); + }); + + it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => { + // Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route + // chart's own page spec forbids. + abrir([...CACU, ...RUTA]); + expect(titulos('.kpi-section .catalog-grid')).toEqual([ + 'catalog-card: Tiempo de toma de muestra a resultado de citología', + 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', + 'catalog-card: Tiempo de toma de muestra a diagnóstico', + 'figura-pendiente: Tiempo de diagnóstico a tratamiento']); + 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', + 'figura-pendiente: Progresión por grupo de riesgo']); + }); + + it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => { + // Fails if a published measure of the route stays a pending slot while the chart that would draw it is not there. + abrir([...CACU, ...RUTA.filter(medida => medida.id === 'cacu_dias_toma_colposcopia' || medida.id === 'cacu_dias_toma_biopsia')]); + expect(root().querySelector('app-indicador-screening-route')).toBeNull(); + expect(titulos('.kpi-section .catalog-grid')).toEqual([ + 'catalog-card: Tiempo de toma de muestra a resultado de citología', + 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', + 'catalog-card: Tiempo de toma de muestra a resultado de colposcopía', + 'catalog-card: Tiempo de toma de muestra a resultado de biopsia', + 'catalog-card: Tiempo de toma de muestra a diagnóstico', + 'figura-pendiente: Tiempo de diagnóstico a tratamiento']); + }); + + it('el resultado de laboratorio se llama «Tiempo desde la toma de muestra al resultado»', () => { + // Fails if the opportunity card goes back to «Días de toma a resultado». + abrir(CACU); + const titulosKpi = [...root().querySelectorAll('.kpi-section app-indicador-kpi-card h3')].map(h => h.textContent?.trim()); + expect(titulosKpi).toContain('Tiempo desde la toma de muestra al resultado'); + expect(titulosKpi).not.toContain('Días de toma a resultado'); + }); + + it('los indicadores clínicos son los dos pedidos más «Progresión por grupo de riesgo» pendiente, sin tarjetas vacías', () => { + // Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending + // figure is not drawn as such. + 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', + 'figura-pendiente: Progresión por grupo de riesgo']); + expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')?.textContent).toContain('Integración pendiente'); + }); + + it('Datos y definiciones conserva todo el catálogo', () => { + // Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab. + abrir(CACU); + const definiciones = root().querySelector('#panel-datos')!.textContent!; + for (const titulo of ['Tasa de detección histopatológica', 'Pacientes con citología anómala', 'Tiempo de toma de muestra a diagnóstico']) expect(definiciones).toContain(titulo); + }); +}); diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts index fdd0ae9..184a159 100644 --- a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () => it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => { // Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator. expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied)) - .toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' }); + .toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.', numerador: 0, denominador: 1 }); }); it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => { const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied); diff --git a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts index f4f1c8c..98c70cc 100644 --- a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts @@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => { it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => { // Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia"). const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); - expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' }); + expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.', numerador: 3, denominador: 20 }); }); it('una tasa de cero con denominador es un cero real, no una ausencia', () => { const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index a2d718e..b245b29 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -130,6 +130,24 @@ describe('Indicadores sobre FHIR', () => { expect(figure.status).toBe('supported'); }); + it('la calidad del EEG muestra «No aceptable» en lugar de «Malo» sin cambiar los códigos de la categoría', () => { + // Pins down: the caption is a presentation choice; the rows, the category catalog and the Measure keep MALO, and no + // category is invented for «aceptable». Fails if the caption leaks into the codes, if «Malo» is drawn again or if a + // fourth category appears. + const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre'); + const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1'); + expect(s1.map(f => f['categoria'])).toEqual(['BUENO', 'MALO', 'SIN_ANALIZAR']); + const categorias = datos['categorias'] as Record; + expect(Object.entries(categorias).map(([codigo, c]) => [codigo, c.etiqueta])) + .toEqual([['BUENO', 'Bueno'], ['MALO', 'No aceptable'], ['SIN_ANALIZAR', 'Sin analizar']]); + const unPeriodo = datosDeReportes(measure('M29-calidad-eeg'), [reports(fx.m29Semestres)[0]], 'semestre'); + const figura = c2Figure(unPeriodo, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' }); + expect(figura.status).toBe('supported'); + const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {}); + for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta); + expect(dibujo).not.toContain('Malo'); + }); + it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => { // Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here // instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period. diff --git a/src/app/features/indicadores/indicadores-fhir.ts b/src/app/features/indicadores/indicadores-fhir.ts index 55139bc..cfadcd5 100644 --- a/src/app/features/indicadores/indicadores-fhir.ts +++ b/src/app/features/indicadores/indicadores-fhir.ts @@ -59,12 +59,19 @@ const round1 = (value: number) => Math.round(value * 10) / 10; // A proportion's bounds travel as proportions; the rows hold percentages, like `valor`. const percent = (value: number | null) => value === null ? null : round1(value * 100); +// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data. +// TEA's EEG quality shows its invalid exams as «No aceptable». +const ROTULOS_DE_CATEGORIA: Readonly>>> = { + 'M29-calidad-eeg': { MALO: 'No aceptable' }, +}; + // A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's, // keeps every category ungrouped. export function categorias(measure: Measure): Record { + const rotulos = ROTULOS_DE_CATEGORIA[measure.id ?? ''] ?? {}; return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => { const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString; - return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, + return codigo && etiqueta ? [[codigo, { etiqueta: rotulos[codigo] ?? etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: extension(e, 'grupo')?.valueCode ?? null }]] : []; })); } diff --git a/src/app/features/indicadores/indicadores-format.ts b/src/app/features/indicadores/indicadores-format.ts index dbd30ef..637c69e 100644 --- a/src/app/features/indicadores/indicadores-format.ts +++ b/src/app/features/indicadores/indicadores-format.ts @@ -26,8 +26,13 @@ export function percentText(value: number | null | undefined, fallback = 'No dis return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback; } +/** «12.3» from a count over its denominator. */ +export function shareNumber(k: number, n: number): string { + const value = sharePercent(k, n); + return value > 0 && value < 0.1 ? String(value) : value.toFixed(1); +} + /** «12.3 %» from a count over its denominator. */ export function shareText(k: number, n: number): string { - const value = sharePercent(k, n); - return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`; + return `${shareNumber(k, n)} %`; } diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index 5e59731..fb6c8e5 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -1,4 +1,4 @@ -// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its +// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, and its // panel loads nothing until it is opened. Catalogs are synthetic, shaped like //indicadores. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => { it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); - expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); fixture.componentInstance.changeSection('analisis'); fixture.detectChanges(); @@ -42,17 +42,17 @@ describe('Pestaña Histórico', () => { // Fails if CaCu loses its history tab or gains CaMa's analysis tab. abrir('cama', []); abrir('cacu', [item('cacu_x', 'C2')]); - expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); expect(root().querySelector('#panel-analisis')).toBeNull(); }); it('tea tiene Histórico pero no Análisis epidemiológico', () => { abrir('cama', []); abrir('tea', [item('tea_x', 'C2')]); - expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-analisis')).toBeNull(); }); - it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => { + it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); const panel = () => root().querySelector('#panel-historico') as HTMLElement; expect(panel().hidden).toBe(true); @@ -63,7 +63,7 @@ describe('Pestaña Histórico', () => { fixture.componentInstance.changeSection('resumen'); fixture.detectChanges(); expect(panel().hidden).toBe(true); }); - it('cambiar de dominio vuelve a Resumen', () => { + it('cambiar de dominio vuelve a Indicadores', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); fixture.componentInstance.changeSection('historico'); fixture.detectChanges(); abrir('cacu', [item('cacu_x', 'C2')]); diff --git a/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts index c41e96c..1cdd07d 100644 --- a/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-resultado.spec.ts @@ -126,7 +126,7 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => { http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' }); f.detectChanges(); const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[]; - expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']); + expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']); expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]); expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]); for (const card of cards.slice(3)) { diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index a1f1383..2271fa9 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -73,7 +73,7 @@ it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => { expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.'); const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]); expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0', - info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' }); + info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.', numerador: 3, denominador: 6 }); expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state) .toBe('Selección no consolidable'); }); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index b2c40b6..cd095f5 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -8,10 +8,12 @@ export interface KpiDefinition { c1Info?: (numerador: number, denominador: number) => string; // C3r only: a median over zero observations is no value, not zero days. requiresObservations?: boolean; + // C2 only: replaces the domain's explanatory line when the unit counted is not the domain's usual one. + c2Info?: string; } // Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID. export const CACU_RESULTADO_KPI: KpiDefinition = { - id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true, + id: 'cacu_eu_tiempo_reporte', title: 'Tiempo desde la toma de muestra al resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true, }; export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = { id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, @@ -37,12 +39,34 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { // M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process. export const M28_COMPLETO = 'EEG'; export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA']; -// What only TEA's summary paragraph needs: the children by stage and the time of each screening step. +// M29's category of the EEGs the analysis found valid. +export const M29_BUENO = 'BUENO'; +// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality. export const KPI_RESUMEN_TEA: KpiDefinition[] = [ { id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' }, { id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' }, { id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + { id: 'M29_calidad_eeg', title: 'Estudios de EEG', contrato: 'C2', unit: 'estudios', c2Info: 'Estudios de EEG realizados en el periodo a niños de la cohorte.' }, ]; +// TEA's figures under «Indicadores de oportunidad» and under «Indicadores clínicos», each in display order. Any other +// published TEA indicator follows the clinical ones. +export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; +export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', + 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg']; +// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot +// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure. +export interface FiguraOportunidad { id?: string; titulo: string; } +export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ + { id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' }, + { titulo: 'Tiempo de toma de muestra a resultado de VPH' }, + { id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' }, + { id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' }, + { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' }, + { titulo: 'Tiempo de diagnóstico a tratamiento' }, +]; +// CaCu's clinical figures in display order, and the one still to be implemented. +export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia']; +export const CACU_FIGURA_CLINICA_PENDIENTE = 'Progresión por grupo de riesgo'; export const KPI_BY_DOMAIN: Record = { tea: [ { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, @@ -101,7 +125,8 @@ const C3R_INFO: Record string> = cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`, cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`, }; -export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record; } +// C1 results also carry the counts the percentage comes from; C2 results, the count of each category. +export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record; numerador?: number; denominador?: number; } const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0; const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' }; @@ -137,8 +162,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0); if (!count(value)) return empty; return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])), - info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' - : domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' }; + info: definition.c2Info ?? (domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' + : domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.') }; } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100) return empty; @@ -148,7 +173,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai return { state: 'Error de contrato', info: 'El numerador y el denominador deben ser conteos no negativos compatibles.' }; } if (denominator === 0) return empty; - return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator) }; + return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator), + numerador: numerator, denominador: denominator }; } if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 5c3f592..e5a385d 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -43,7 +43,7 @@

La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.

} @let kpis = kpiCards; - @if (kpis.length && !initialPeriodBlocked) { + @if ((kpis.length || (dominio === 'tea' && oportunidadSlots().length)) && !initialPeriodBlocked) {
@let resumen = teaResumenPeriodo;
@@ -70,6 +70,19 @@ additionalInfo="Este indicador aún no está publicado por el catálogo institucional." /> }
+ @if (oportunidadSlots().length) { + @if (dominio === 'cacu') {

Tiempo de tamizaje a diagnóstico

} +
+ @for (slot of oportunidadSlots(); track slot.item ? cardIdentity(slot.item) : slot.titulo) { + @if (slot.item; as item) { + + } @else { + + } + } +
+ }
} @@ -118,10 +131,11 @@ @if (screeningRouteAvailable) { }
@if (histopatologiaPendiente) { } - @for (item of searchResults().items; track cardIdentity(item)) { + @for (item of clinicosItems(); track cardIdentity(item)) { } + @if (dominio === 'cacu') { }
} diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index 454549e..08aa1ab 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -19,6 +19,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } .graphic-section { margin-top: var(--issste-space-6); } .kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .kpi-section .kpi-grid.kpi-grid-oculto { display: none; } +.kpi-section .catalog-grid { margin-top: var(--issste-space-6); } +.subsection-title { margin: var(--issste-space-6) 0 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; } +.subsection-title + .catalog-grid { margin-top: var(--issste-space-3); } .catalog-grid { align-items: stretch; } .reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } .reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 1f6022b..883d9b3 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,12 +17,13 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { esSocioConteos } from './indicadores-conteos-pareados'; -import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; 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 { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; import { identityElementId, indicatorIdentity } from './indicadores-identities'; import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos'; @@ -39,7 +40,7 @@ import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ - { id: 'resumen', label: 'Resumen' }, + { id: 'resumen', label: 'Indicadores' }, { id: 'seguimiento', label: 'Análisis de riesgos' }, { id: 'datos', label: 'Datos y definiciones' }, ]; @@ -48,6 +49,12 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]]; // Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered. export const CAMA_ANALYSIS_ENABLED = false; +// TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them. +function ordenTea(catalog: Indicador[]): Indicador[] { + const named = [...TEA_FIGURAS_OPORTUNIDAD, ...TEA_FIGURAS_CLINICAS]; + const first = named.flatMap(id => catalog.filter(item => item.id === id)); + return [...first, ...catalog.filter(item => !named.includes(item.id))]; +} const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1], ...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []), @@ -55,7 +62,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorFiguraPendiente, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -174,7 +181,7 @@ export class IndicadoresPage { } if (typeof ResizeObserver !== 'undefined') { this.sizeObserver ??= new ResizeObserver(this.viewportChanged); - const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')] + const targets = [this.document.querySelector('.institutional-header'), ...this.element.nativeElement.querySelectorAll('.catalog-grid')] .filter((target): target is Element => target !== null); for (const target of this.sizeTargets) { if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); } @@ -375,6 +382,7 @@ export class IndicadoresPage { return this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))] : this.dominio === 'cama' ? this.cardsDeCama(catalog) + : this.dominio === 'tea' ? ordenTea(catalog.filter(item => !item.vistas || item.vistas.includes('resumen'))) : catalog.filter(item => !item.vistas || item.vistas.includes('resumen')); }); readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id)); @@ -388,6 +396,31 @@ export class IndicadoresPage { const selected = new Set(this.selectedIndicators()); return { items: this.catalogOrder().filter(item => selected.has(item.id)) }; }); + // The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's six times, each a + // pending slot while the catalog does not publish its indicator. The rest are the clinical ones. + // The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for. + readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => { + const items = this.searchResults().items; + if (this.dominio === 'tea') return items.filter(item => TEA_FIGURAS_OPORTUNIDAD.includes(item.id)).map(item => ({ item, titulo: item.titulo })); + if (this.dominio !== 'cacu' || !this.catalog().length) return []; + // The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while + // it is shown, so those slots are left to the chart instead of drawn twice or as pending. + const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : []; + return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => { + const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined; + return item ? { item, titulo: item.titulo } : { titulo: figura.titulo }; + }); + }); + readonly clinicosItems = computed(() => { + const items = this.searchResults().items; + if (this.dominio === 'cacu') { + // The time figures went to the opportunity section; an indicator with no figure has nothing to draw here. + const clinicos = items.filter(item => item.figuras.length && !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))]; + } + return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items; + }); + readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE; readonly catalogLoading = signal(true); readonly catalogError = signal(''); tema: Tema = 'claro'; @@ -433,8 +466,8 @@ export class IndicadoresPage { private scrollToIndicator(key: string) { if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return; const target = this.document.getElementById(identityElementId(key)); - const grid = this.element.nativeElement.querySelector('.catalog-grid'); - if (!target || !grid?.contains(target)) return; + const grid = target?.closest('.catalog-grid'); + if (!target || !grid) return; const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches; target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' }); target.querySelector('h2')?.focus({ preventScroll: true }); @@ -504,7 +537,9 @@ export class IndicadoresPage { this.catalogLoading.set(false); this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined; this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia' - ? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items); + ? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) + : this.dominio === 'cacu' ? items.map(item => ({ ...item, titulo: CACU_FIGURAS_OPORTUNIDAD.find(figura => figura.id === item.id)?.titulo ?? item.titulo })) + : items); this.filtersEdited(); this.catalogError.set(error); this.availabilityRequests.next(); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index a5bc460..2ad3912 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( - ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts index e80d3a8..c226da3 100644 --- a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts +++ b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts @@ -12,7 +12,8 @@ import { IndicadoresMemory } from './indicadores-memory'; import { Dominio } from './indicadores.models'; import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route'; -const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }); +// Each measure carries the figure of its contract, as the published ones do: the Indicadores tab draws no card for an indicator without figures. +const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [contrato === 'C2' ? 'fig_c2_donas' : 'fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] }); describe('Ruta del tamizaje: página de CaCu', () => { let fixture: ReturnType>, http: HttpTestingController; diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 66cb6a9..7c45c3a 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -33,14 +33,14 @@ describe('Secciones compartidas por dominio', () => { }); afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); }); - it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => { + it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas e Indicadores seleccionado', async domain => { const harness = await RouterTestingHarness.create(); const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); // TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain. - const esperadas = ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; @@ -75,7 +75,7 @@ describe('Secciones compartidas por dominio', () => { http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes. }); - it('cambiar de dominio reinicia Resumen tanto por router como por coordinación de página', async () => { + it('cambiar de dominio reinicia Indicadores tanto por router como por coordinación de página', async () => { const harness = await RouterTestingHarness.create(); for (const domain of DOMINIOS) { const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); diff --git a/src/app/features/indicadores/indicadores-tea-secciones.spec.ts b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts new file mode 100644 index 0000000..e5e282f --- /dev/null +++ b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts @@ -0,0 +1,85 @@ +// Covers how the Indicadores tab arranges TEA's figures: the time figures under «Indicadores de oportunidad», the +// clinical ones under «Indicadores clínicos», each in its order, and the tab's name in the three domains. +// Fixtures: a TEA catalog shaped like /tea/indicadores, published out of order on purpose. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Dominio } from './indicadores.models'; + +const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); +const TEA = [ + item('M30_resultado_eeg', 'Porcentaje de EEG normal y anormal', 'C1', ['fig_c1_barras_alteracion']), + item('M29_calidad_eeg', 'Calidad del EEG', 'C2', ['fig_c2_barras']), + item('M28_casos_por_estado', 'Casos por estatus', 'C2', ['fig_c2_barras']), + item('M27_dias_ados2_diagnostico', 'Días de ADOS-2 a diagnóstico', 'C3r', ['fig_c3r_caja']), + item('M26_dias_mchat_ados2', 'Días de M-CHAT a ADOS-2', 'C3r', ['fig_c3r_caja']), + item('M25_dias_mchat_diagnostico', 'Días de M-CHAT a diagnóstico positivo', 'C3r', ['fig_c3r_caja']), + item('M24_confirmacion_diagnostico', 'Porcentaje de confirmación diagnóstica', 'C1', ['fig_c1_barras_apiladas_edad']), + item('M23_pacientes_evaluados', 'Pacientes evaluados por resultado diagnóstico', 'C2', ['fig_c2_barras']), + item('M22_diagnosticados_sin_eeg', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', 'C1', ['fig_c1_barras_edad']), + item('M21_diagnosticados_con_eeg', 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'C1', ['fig_c1_barras_edad']), +]; + +describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + // The KPI and period requests are not what these tests are about. + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + function open(domain: Dominio, catalog: unknown[]) { + // The page starts in TEA, whose catalog is already answered: leave it first to load it again. + if (domain === fixture.componentInstance.dominio) { + fixture.componentInstance.changeDominio(domain === 'cacu' ? 'cama' : 'cacu'); fixture.detectChanges(); + http.match(() => true); + } + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); + http.match(() => true); fixture.detectChanges(); + } + const root = () => fixture.nativeElement as HTMLElement; + const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); + + it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => { + // Fails if a figure is drawn in both sections, if either order changes, or if M30 (not named by the sections) + // disappears instead of following the clinical ones. + open('tea', TEA); + expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']); + expect(titles('.graphic-section')).toEqual([ + 'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica', + 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', + 'Casos por estatus', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal']); + expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad'); + expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); + }); + + it('un indicador no publicado deja el resto en su orden', () => { + // Fails if the order depends on every figure being published. + open('tea', TEA.filter(entry => entry.id !== 'M27_dias_ados2_diagnostico' && entry.id !== 'M23_pacientes_evaluados')); + expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de M-CHAT a diagnóstico positivo']); + expect(titles('.graphic-section').slice(0, 2)).toEqual(['Porcentaje de confirmación diagnóstica', 'Porcentaje de pacientes con diagnóstico de TEA con EEG']); + }); + + it('CaMa no recibe figuras en oportunidad', () => { + // Fails if TEA's arrangement leaks into CaMa's opportunity strip. + open('cama', [item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja'])]); + expect(root().querySelector('.kpi-section app-indicador-catalog-card')).toBeNull(); + }); + + it('la primera pestaña se llama Indicadores en los tres dominios', () => { + // Fails if the first tab goes back to «Resumen» in any domain, or changes its section id. + for (const domain of ['tea', 'cacu', 'cama'] as const) { + open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]); + const first = root().querySelector('[role="tab"]') as HTMLElement; + expect(first.textContent?.trim()).toBe('Indicadores'); + expect(first.id).toBe('tab-resumen'); + } + }); +}); diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index 5965909..b3f6c90 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -1,13 +1,16 @@ +// Covers TEA's opportunity summary for one period: the sentences read their figures from the KPI panels and name +// the population of each. Fixtures: fake panels holding the result each real panel would publish. import { signal } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; -type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record }; +type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record; numerador?: number; denominador?: number }; function panel(id: string, result: Result) { return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType>; retry: ReturnType }; } const listo = (value: string | number, period = '2025-S2'): Result => ({ state: 'Disponible', value, period }); +const c1 = (value: string, numerador: number, denominador: number): Result => ({ ...listo(value), numerador, denominador }); describe('Resumen TEA por periodo', () => { function render(paneles: IndicadorKpiPanel[]) { @@ -16,33 +19,77 @@ describe('Resumen TEA por periodo', () => { fixture.detectChanges(); return fixture; } - const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }), panel('M24_confirmacion_diagnostico', listo('86.5')), - panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')), - panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))]; + // 100 children in the screening, 60 of them at the EEG stage. 57 have a confirmed diagnosis, 41 with a good EEG. + // 80 EEGs were done in the period: 20 good, 50 invalid, 10 not analysed yet. + const completos = () => [ + panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }), + panel('M24_confirmacion_diagnostico', c1('86.5', 57, 66)), panel('M25_dias_mchat_diagnostico', listo(22.5)), + panel('M21_diagnosticados_con_eeg', c1('71.9', 41, 57)), panel('M22_diagnosticados_sin_eeg', c1('28.1', 16, 57)), + panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14)), + panel('M29_calidad_eeg', { ...listo(80), categorias: { BUENO: 20, MALO: 50, SIN_ANALIZAR: 10 } })]; + const texto = (root: HTMLElement) => root.textContent!.replace(/\s+/g, ' '); - it('redacta el párrafo con cada población y resalta los valores', () => { + it('redacta los dos párrafos con cada población y resalta los valores', () => { + // Fails if a sentence reads another indicator's figure, if the stages stop adding up to the children evaluated + // or if a median is cut (22.5 stays 22.5). const root: HTMLElement = render(completos()).nativeElement; - const text = root.textContent!.replace(/\s+/g, ' '); - expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 niños en el tamizaje, 60 lo completaron con un EEG de buena calidad y 40 siguen en proceso: 15 solo con M-CHAT, 15 hasta la evaluación psicológica y 10 hasta la evaluación neuropediátrica.'); - expect(text).toContain('De los niños con diagnóstico confirmado o en proceso, 86.5 % tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); - expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.'); - expect(text).toContain('De los niños con diagnóstico confirmado, 71.9 % tienen un EEG de buena calidad y 28.1 % todavía no.'); + const text = texto(root); + expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.'); + expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); + expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.'); + expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.'); + expect(text).toContain('*tomando la mediana de los tiempos'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '100', '60', '40', '15', '15', '10', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']); + .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']); expect(root.querySelector('button')).toBeNull(); }); + it('no copia cifras de ejemplo: otros conteos cambian toda la redacción', () => { + // Fails if any figure of the sentences is a constant instead of the contract's value. + const paneles = [ + panel('M28_casos_por_estado', { ...listo(3), categorias: { EEG: 0, SOLO_MCHAT: 1, PSICOLOGIA: 1, NEUROPEDIATRIA: 1 } }), + panel('M24_confirmacion_diagnostico', c1('50.0', 1, 2)), panel('M25_dias_mchat_diagnostico', listo(31)), + panel('M21_diagnosticados_con_eeg', c1('0.0', 0, 1)), panel('M22_diagnosticados_sin_eeg', c1('100.0', 1, 1)), + panel('M26_dias_mchat_ados2', listo(5)), panel('M27_dias_ados2_diagnostico', listo(9)), + panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })]; + const text = texto(render(paneles).nativeElement); + expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan'); + expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.'); + for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo); + }); + + it('un cero publicado es un cero y la ausencia de estudios no inventa un porcentaje', () => { + // Fails if a published 0 turns into «sin dato», or if 0 studies print a percentage of buena calidad. + const paneles = completos(); + paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57)); + paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } }); + const root: HTMLElement = render(paneles).nativeElement; + expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); + expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0'); + }); + it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => { + // Fails if a suppressed, foreign-period or unpublished figure is drawn as a number, or if its reason is lost. const paneles = completos(); paneles[1].result.set({ state: 'Dato oculto por tamaño' }); paneles[2].result.set(listo(30, '2025-S1')); - const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M22_diagnosticados_sin_eeg')).nativeElement; + const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M29_calidad_eeg')).nativeElement; const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato')); expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']); expect(root.textContent).not.toContain('30 días'); }); + it('no muestra los conteos de M21 y M22 si no hablan de los mismos niños', () => { + // Fails if the confirmed children of M21 and of M22 disagree and the summary still prints them as one population. + const paneles = completos(); + paneles[4].result.set(c1('28.1', 16, 58)); + const root: HTMLElement = render(paneles).nativeElement; + expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title'))) + .toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden')); + }); + it('indica la carga y reintenta solo las consultas con error', () => { + // Fails if the summary hides a pending query or retries panels that did not fail. const paneles = completos(); paneles[0].result.set({ state: 'Cargando…', loading: true }); paneles[3].result.set({ state: 'Error de consulta' }); diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index 87dea11..11b47f1 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -2,32 +2,40 @@ import { NgTemplateOutlet } from '@angular/common'; import { Component, Input } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; -import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi'; +import { shareNumber } from './indicadores-format'; +import { M28_COMPLETO, M29_BUENO } from './indicadores-kpi'; interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; } +const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M28 = 'M28_casos_por_estado', M29 = 'M29_calidad_eeg'; + // TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the // requests, contract checks and suppression rules stay those of the cards. Each sentence names -// its own population: M28, M24, M25 and M21/M22 do not count the same patients. +// its own population: M28, M24, M21/M22 and M29 do not count the same patients or exams. @Component({ selector: 'app-tea-resumen-periodo', imports: [MatButtonModule, NgTemplateOutlet], template: `

- Al cierre del periodo {{ periodo }}, de los niños en el tamizaje, - lo completaron con un EEG de buena calidad y - siguen en proceso: - solo con M-CHAT, + Al cierre del periodo {{ periodo }}, se evaluaron niños entre 16 y 36 meses; + únicamente tienen M-CHAT, hasta la evaluación psicológica y - hasta la evaluación neuropediátrica. - De los niños con diagnóstico confirmado o en proceso, - tiene diagnóstico confirmado de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de , de ADOS-2 a diagnóstico, de - , y en total, de M-CHAT a diagnóstico, de + presentan evaluación neuropediátrica. + En este periodo el + de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0). + Las ventanas de tiempo* de tamizaje son: de M-CHAT (psicología) a ADOS-2, + de ADOS-2 a diagnóstico. + El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de . - De los niños con diagnóstico confirmado, - tienen un EEG de buena calidad y todavía no. +
+ De los niños con diagnóstico confirmado en este periodo, + presentan estudio de EEG y faltan + por realizarlo. + De los estudios de EEG, + tienen buena calidad.

+

*tomando la mediana de los tiempos

@if (conError.length) { } @@ -41,6 +49,8 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta .resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; } + p + p { margin-top: var(--issste-space-4); } + p.nota { margin-top: var(--issste-space-2); font-size: .95rem; line-height: 1.5; color: var(--issste-text-secondary); } .dato { display: inline-block; padding: 0 .5em; border-radius: var(--issste-radius); line-height: 1.6; font-weight: 700; white-space: nowrap; background: var(--issste-background); border: 1px dashed var(--issste-border); color: var(--issste-text-secondary); } .dato.listo { background: color-mix(in srgb, var(--issste-accent) 22%, var(--issste-surface)); border: 1px solid var(--issste-accent); color: var(--issste-text); } @@ -54,26 +64,55 @@ export class TeaResumenPeriodo { @Input({ required: true }) paneles: readonly IndicadorKpiPanel[] = []; // Panels render after this paragraph, so on their first pass their inputs are not set yet. private panel(id: string) { return this.paneles.find(p => p.definition?.id === id); } - valor(id: string, sufijo: string): Valor { + // Why a panel has no figure for this period, or undefined when it has one. + private fallo(id: string): Valor | undefined { const result = this.panel(id)?.result(); if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' }; if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' }; // Never show a value from another period in a sentence about this one. if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo) return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state }; - return { texto: result.value + sufijo, estado: 'listo' }; + return undefined; + } + private sinDato(detalle: string): Valor { return { texto: 'sin dato', estado: 'sin_dato', detalle }; } + valor(id: string, sufijo: string): Valor { + return this.fallo(id) ?? { texto: this.panel(id)!.result().value + sufijo, estado: 'listo' }; } - readonly completo = [M28_COMPLETO]; - readonly enProceso = M28_EN_PROCESO; // The children of M28 in some stages, under the same rules as valor(). + readonly conNeuropediatria = ['NEUROPEDIATRIA', M28_COMPLETO]; caso(categorias: readonly string[]): Valor { - const base = this.valor('M28_casos_por_estado', ''); + const base = this.valor(M28, ''); if (base.estado !== 'listo') return base; - const counts = this.panel('M28_casos_por_estado')?.result().categorias; + const counts = this.panel(M28)?.result().categorias; const n = categorias.map(c => counts?.[c]); - return n.some(v => v === undefined) ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Etapa no publicada' } + return n.some(v => v === undefined) ? this.sinDato('Etapa no publicada') : { texto: String(n.reduce((s, v) => s! + v!, 0)), estado: 'listo' }; } + // M21 and M22 split the same confirmed children, so a count of either is only shown while their denominators agree. + private poblacionComun(): boolean { + const a = this.panel(M21)?.result(), b = this.panel(M22)?.result(); + return !(a?.denominador !== undefined && b?.denominador !== undefined && a.denominador !== b.denominador); + } + private conteo(id: string, parte: 'numerador' | 'denominador'): Valor { + const fallo = this.fallo(id); + if (fallo) return fallo; + if (!this.poblacionComun()) return this.sinDato('Las poblaciones de M21 y M22 no coinciden'); + const n = this.panel(id)!.result()[parte]; + return n === undefined ? this.sinDato('Conteo no publicado') : { texto: String(n), estado: 'listo' }; + } + // Children with a confirmed diagnosis at the period's end, the denominator of M21 and M22. + confirmados() { return this.conteo(M21, 'denominador'); } + // Of them, those with a good EEG (M21's numerator) and those without yet (M22's). + conEeg() { return this.conteo(M21, 'numerador'); } + sinEeg() { return this.conteo(M22, 'numerador'); } + // The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid. + buenaCalidad(): Valor { + const base = this.valor(M29, ''); + if (base.estado !== 'listo') return base; + const result = this.panel(M29)!.result(), total = Number(result.value), buenos = result.categorias?.[M29_BUENO]; + if (total === 0) return this.sinDato('Sin estudios de EEG en el periodo'); + return buenos === undefined ? this.sinDato('Categoría no publicada') : { texto: shareNumber(buenos, total) + '%', estado: 'listo' }; + } get cargando() { return this.paneles.some(p => p.result().loading); } get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); } reintentar() { this.conError.forEach(p => p.retry()); } From 6a0c3c9e923aa80677b6e269fa66492c360a6eb8 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 02:49:46 -0600 Subject: [PATCH 04/35] =?UTF-8?q?Hist=C3=B3rico=20CaCu:=20remove=20the=20n?= =?UTF-8?q?otice=20above=20the=20panels?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores-historico-cacu-paneles.spec.ts | 11 +++++------ .../indicadores/indicadores-historico-config.ts | 6 ------ src/app/features/indicadores/indicadores-historico.ts | 4 ---- 3 files changed, 5 insertions(+), 16 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 1447e39..c4c80d1 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -9,7 +9,7 @@ import { By } from '@angular/platform-browser'; import { MatDialog } from '@angular/material/dialog'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistorico } from './indicadores-historico'; -import { AVISO_CACU, HISTORICO_CACU } from './indicadores-historico-config'; +import { HISTORICO_CACU } from './indicadores-historico-config'; import { Indicador } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @@ -113,12 +113,11 @@ describe('Histórico de CaCu', () => { fixture.destroy(); TestBed.resetTestingModule(); } }); - it('el aviso de validación clínica y supresión se ve siempre', () => { + it('no antepone ningún aviso a los paneles', () => { + // Fails if a notice about clinical validation or suppression is shown again above the history's panels. montar(); - const aviso = root().querySelector('[data-aviso="historico"]')!; - expect(aviso.textContent).toBe(AVISO_CACU); - expect(aviso.textContent).toContain('validación clínica'); - expect(aviso.textContent).toContain('supresión'); + expect(root().querySelector('[data-aviso="historico"]')).toBeNull(); + expect(root().textContent).not.toContain('sujetos a validación clínica'); }); it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { // Pins down the first request: the page asks for the latest five months, not the twelve it could. diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 6837fa1..71e313a 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -29,8 +29,6 @@ export interface HistoricoDominio { conciliarC2?: boolean; // A composition period with no units is «sin dato», not a bar of zeros. c2SinPoblacionSinDato?: boolean; - // Shown above the panels. - aviso?: string; } // CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not @@ -45,9 +43,6 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, ]; -export const AVISO_CACU = 'Los resultados de CaCu están sujetos a validación clínica y a la política institucional de supresión estadística. ' - + 'Los conjuntos clínicos, los horizontes y los umbrales son provisionales. No los use para decidir.'; - // CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' }, @@ -73,7 +68,6 @@ const HISTORICOS: Readonly>> = { periodosIniciales: 5, conciliarC2: true, c2SinPoblacionSinDato: true, - aviso: AVISO_CACU, }, }; diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 0f9a0f0..d738c83 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -69,7 +69,6 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P selector: 'app-indicadores-historico', imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], template: ` - @if (aviso(); as texto) {

{{ texto }}

}

Filtros

@@ -141,8 +140,6 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P @use '@angular/material' as mat; :host { display: block; min-width: 0; } - .aviso { margin: 0 0 var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); - border: 1px solid var(--issste-border); border-left-width: 4px; border-radius: var(--issste-radius); font: var(--mat-sys-body-medium); } .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } .controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } @@ -189,7 +186,6 @@ export class IndicadoresHistorico { readonly retryCatalog = output(); // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. private readonly config = computed(() => historicoDeDominio(this.dominio())); - readonly aviso = computed(() => this.config()?.aviso); // The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active; // the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes. private readonly publicados = computed(() => { From f04478e600bf857c50d80303747e896a42d07d7c Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 03:11:12 -0600 Subject: [PATCH 05/35] =?UTF-8?q?CaMa=20Indicadores:=20five=20time=20figur?= =?UTF-8?q?es=20under=20=C2=ABTiempo=20de=20tamizaje=20a=20diagn=C3=B3stic?= =?UTF-8?q?o=C2=BB,=20requested=20clinical=20titles,=20order=20and=20confi?= =?UTF-8?q?rmation=20rate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicador-conteos-pareados.html | 4 +- .../indicadores/indicador-kpi-panel.spec.ts | 2 +- .../indicadores/indicadores-cama-f4c.spec.ts | 11 ++-- .../indicadores-cama-oportunidad.spec.ts | 12 ++-- .../indicadores-cama-resumen-clinico.spec.ts | 23 +++++-- .../indicadores-cama-secciones.spec.ts | 62 +++++++++++++++++++ .../indicadores-conteos-pareados.spec.ts | 4 +- .../features/indicadores/indicadores-kpi.ts | 9 +++ .../indicadores/indicadores-page.html | 15 ++++- .../features/indicadores/indicadores-page.ts | 19 +++++- .../indicadores-tea-secciones.spec.ts | 6 +- 11 files changed, 140 insertions(+), 27 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cama-secciones.spec.ts diff --git a/src/app/features/indicadores/indicador-conteos-pareados.html b/src/app/features/indicadores/indicador-conteos-pareados.html index 2aac49c..6f4d98c 100644 --- a/src/app/features/indicadores/indicador-conteos-pareados.html +++ b/src/app/features/indicadores/indicador-conteos-pareados.html @@ -7,8 +7,8 @@ @case ('incompatible') {

Respuesta incompatible: {{ message }}

} } @if (status() === 'ready' && model; as m) { - @let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo; - @let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo; + @let tituloMastografias = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en ' + m.periodo; + @let tituloPacientes = 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en ' + m.periodo; @if (pages.length > 1) {
@if (oportunidadSlots().length) { - @if (dominio === 'cacu') {

Tiempo de tamizaje a diagnóstico

} + @if (dominio === 'cacu' || dominio === 'cama') {

Tiempo de tamizaje a diagnóstico

}
@for (slot of oportunidadSlots(); track slot.item ? cardIdentity(slot.item) : slot.titulo) { @if (slot.item; as item) { @@ -130,13 +130,24 @@ } @if (screeningRouteAvailable) { }
- @if (histopatologiaPendiente) { } @for (item of clinicosItems(); track cardIdentity(item)) { } + @if (histopatologiaPendiente) { } @if (dominio === 'cacu') { }
+ @if (dominio === 'cama') { +
+ @if (confirmacionCamaPendiente) { + + } @else { + + } +
+ } }
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 883d9b3..8679af3 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,7 +17,7 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { esSocioConteos } from './indicadores-conteos-pareados'; -import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorScreeningRoute } from './indicador-screening-route'; @@ -336,8 +336,8 @@ export class IndicadoresPage { private cardsDeCama(catalog: Indicador[]) { const ids = catalog.map(item => item.id); const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids)); - // The histopathology card keeps its place, first, whether pending or published. - return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)]; + // The exams' and patients' counts come first, then the histopathology card (pending or published); the confirmation rate follows them. + return [...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA)]; } // CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator. get histopatologiaPendiente() { @@ -402,6 +402,16 @@ export class IndicadoresPage { readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => { const items = this.searchResults().items; if (this.dominio === 'tea') return items.filter(item => TEA_FIGURAS_OPORTUNIDAD.includes(item.id)).map(item => ({ item, titulo: item.titulo })); + if (this.dominio === 'cama') { + // CaMa's time indicators have no card in the ordered list (the summary keeps them out), so look in the catalog + // restricted to the selection. The slot names the figure as the request does, whatever title the catalog gives. + if (!this.catalog().length) return []; + const selected = new Set(this.selectedIndicators()); + return CAMA_FIGURAS_OPORTUNIDAD.map(figura => { + const item = figura.id ? this.catalog().find(candidate => candidate.id === figura.id && selected.has(candidate.id)) : undefined; + return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo }; + }); + } if (this.dominio !== 'cacu' || !this.catalog().length) return []; // The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while // it is shown, so those slots are left to the chart instead of drawn twice or as pending. @@ -421,6 +431,9 @@ export class IndicadoresPage { return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items; }); readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE; + // CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it. + readonly confirmacionCama = CAMA_CONFIRMACION_KPI; + get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); } readonly catalogLoading = signal(true); readonly catalogError = signal(''); tema: Tema = 'claro'; diff --git a/src/app/features/indicadores/indicadores-tea-secciones.spec.ts b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts index e5e282f..dedebdf 100644 --- a/src/app/features/indicadores/indicadores-tea-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts @@ -67,10 +67,10 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => { expect(titles('.graphic-section').slice(0, 2)).toEqual(['Porcentaje de confirmación diagnóstica', 'Porcentaje de pacientes con diagnóstico de TEA con EEG']); }); - it('CaMa no recibe figuras en oportunidad', () => { - // Fails if TEA's arrangement leaks into CaMa's opportunity strip. + it('CaMa no recibe el resumen ni el orden de TEA en oportunidad', () => { + // Fails if TEA's summary or its figure order leaks into CaMa's opportunity strip (CaMa has its own time section). open('cama', [item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja'])]); - expect(root().querySelector('.kpi-section app-indicador-catalog-card')).toBeNull(); + expect(root().querySelector('app-tea-resumen-periodo')).toBeNull(); }); it('la primera pestaña se llama Indicadores en los tres dominios', () => { From b5f8e5bfc26f7b980d9c7970595cdc04c0782cf9 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 03:18:19 -0600 Subject: [PATCH 06/35] =?UTF-8?q?Hist=C3=B3rico:=20TEA=20order=20and=20EEG?= =?UTF-8?q?=20normal/abnormal=20lines,=20CaMa=20titles,=20order=20and=20ca?= =?UTF-8?q?ptions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores-historico-cama.spec.ts | 18 ++++---- .../indicadores-historico-config.ts | 11 +++-- .../indicadores-historico-figures.spec.ts | 39 ++++++++++++++++++ .../indicadores-historico-figures.ts | 41 +++++++++++++++++-- .../indicadores/indicadores-historico.spec.ts | 12 +++++- .../indicadores/indicadores-historico.ts | 13 +++++- 6 files changed, 111 insertions(+), 23 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-cama.spec.ts b/src/app/features/indicadores/indicadores-historico-cama.spec.ts index 64a421b..d00d21c 100644 --- a/src/app/features/indicadores/indicadores-historico-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cama.spec.ts @@ -83,10 +83,10 @@ describe('Histórico de CaMa', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo)); const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent); - expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']); + expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']); expect(paneles()).toHaveLength(7); - const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6'; - expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo); + const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6'; + expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo); expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true); expect(graficas()).toHaveLength(5); expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0); @@ -96,7 +96,7 @@ describe('Histórico de CaMa', () => { // closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the // list is open from the start, is cut short, or the figure changes. montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo)); - const panel = paneles()[1]; + const panel = paneles()[4]; const plegable = panel.querySelector('details[data-plegable="sin-dato"]')!; expect(plegable).not.toBeNull(); expect(plegable.open).toBe(false); @@ -117,7 +117,7 @@ describe('Histórico de CaMa', () => { it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => { montar(CATALOGO, true); responder(); expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual'); - expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)'); + expect(paneles()[4].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)'); }); it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => { montar(CATALOGO, true); responder(); @@ -126,7 +126,7 @@ describe('Histórico de CaMa', () => { const semestrales = responder(); expect(semestrales.length).toBeGreaterThan(0); expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true); - expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)'); + expect(paneles()[4].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)'); toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges(); http.expectNone(() => true); }); @@ -135,7 +135,7 @@ describe('Histórico de CaMa', () => { const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } }; expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']); fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); - expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)'); + expect(paneles()[4].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)'); }); it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => { montar(CATALOGO, true); responder(); @@ -144,10 +144,10 @@ describe('Histórico de CaMa', () => { expect(abrirDialogo).toHaveBeenCalledTimes(1); const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] }; expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES); - expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); + expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) }); fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges(); - expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); + expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); }); it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => { // Fails if one failing indicator blanks the others, leaks its body, or cannot be retried. diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 71e313a..6de8005 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -1,5 +1,4 @@ import { Dominio } from './indicadores.models'; -import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; // What each domain's history tab draws, declared as data: the panels and their order, the contract each one is // expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws @@ -34,13 +33,13 @@ export interface HistoricoDominio { // CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not // publish is drawn as a pending panel instead of being left out, so what is missing stays visible. export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ - { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, - { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' }, - { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA }, - { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, - { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, + { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, + { id: 'cama_birads_456_mastografia', titulo: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6' }, + { id: 'cama_birads_456_paciente', titulo: 'Pacientes con resultado BI-RADS 4, 5 ó 6' }, + { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, + { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, ]; // CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. diff --git a/src/app/features/indicadores/indicadores-historico-figures.spec.ts b/src/app/features/indicadores/indicadores-historico-figures.spec.ts index ba439aa..042ac89 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.spec.ts @@ -118,3 +118,42 @@ describe('Histórico: datos inválidos', () => { expect(() => historicoFigura(datos(), 'claro')).toThrow(); }); }); + +describe('Histórico: pies de figura pedidos para CaMa y la gráfica de EEG normal y anormal de TEA', () => { + const med = (id: string) => figura({ ...base('C3r', MESES, [fila('2025-01', { mediana: 10, q1: 9, q3: 12, n: 9 })], { unidad: 'examen' }), id } as IndicadorDatos); + const cats = [{ periodo: '2025-01', categoria: 'A', n: 2, orden: 0, suprimido: 0 }, { periodo: '2025-01', categoria: 'B', n: 3, orden: 1, suprimido: 0 }]; + it('las tres medianas de CaMa usan el pie de la solicitud y las de otros dominios conservan el suyo', () => { + // Fails if a CaMa time figure keeps the general caption, or if the new one leaks into TEA's or CaCu's medians. + for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) { + expect(med(id).comoLeer).toBe('La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'); + } + expect(med('cacu_eu_tiempo_reporte').comoLeer).toContain('la mitad central'); + }); + it('la tasa de confirmación de CaMa dice solo qué representa la línea; otros porcentajes conservan el pie con la banda', () => { + // Fails if the confirmation rate keeps the confidence-band sentence, or if another percentage loses it. + const pct = (id: string) => figura({ ...base('C1', MESES, [fila('2025-01', { valor: 50, numerador: 1, denominador: 2, ic_bajo: 9, ic_alto: 91 })]), id } as IndicadorDatos); + expect(pct('cama_confirmacion_birads45').comoLeer).toBe('La línea representa el porcentaje de confirmación histopatológica.'); + expect(pct('ind1').comoLeer).toContain('su intervalo de confianza'); + }); + it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => { + // Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it. + const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría.'; + for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie); + expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe(''); + expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total'); + }); + it('M30 dibuja dos líneas, normal y anormal, que suman 100 %, con el pie pedido', () => { + // Fails if the chart has one line, if normal is not the rest of the same children (count, percentage and interval) or if the caption changes. + const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }), + fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos); + const f = m30.figure as unknown as Fig; + const lineas = f.data.filter(t => t['mode'] === 'lines+markers'); + expect(lineas.map(t => t['name'])).toEqual(['EEG normal', 'EEG anormal']); + expect(lineas.map(t => (t['y'] as (number | null)[])[0])).toEqual([37.5, 62.5]); + expect(JSON.stringify(lineas[0]['text'])).toContain('3 de 8'); expect(JSON.stringify(lineas[1]['text'])).toContain('5 de 8'); + // The normal band is the anormal one turned around: 100 − 86.3 to 100 − 30.6. + expect(f.data.find(t => t['name'] === 'Intervalo de confianza de eeg normal')!['y']).toEqual([69.4, 13.7]); + expect(m30.comoLeer).toBe('Línea de EEG anormal: se detecta alguna alteración.'); + expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 2878033..9f759d8 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -104,6 +104,15 @@ function colorDeLinea(id: string, tema: Tema) { return { linea, relleno: linea + '40' }; } +// CaMa's captions, as the request words them; the other domains keep the general ones. +const PIE_PORCENTAJE: Readonly> = { + cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.', +}; +const PIE_MEDIANA: Readonly> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id, + 'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'])); +const PIE_CATEGORIAS: Readonly> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id, + 'Cada barra indica el total de pacientes por periodo en cada categoría.'])); + type Trazo = Omit; function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { const periodos = validar(data); @@ -121,10 +130,34 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { }), hovertemplate: '%{x}
%{text}' }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, - comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', + comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', suprimidos, sinDato, }; } +// M30 publishes the share of the children whose first good EEG has some alteration (the TOTAL group). The normal ones are +// the rest of the same children, so their count and their interval are the complement of the published ones. +export const M30_RESULTADO_EEG = 'M30_resultado_eeg'; +function resultadoEeg(data: IndicadorDatos, tema: Tema): Trazo { + const periodos = validar(data); + const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['numerador']) && numero(row['denominador']) && row['denominador'] > 0); + const x = periodos.map(etiquetaPeriodo), layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'); + const redondeo = (v: number) => Math.round(v * 10) / 10; + const lineas = [ + { nombre: 'EEG normal', color: C2_PALETTE.series[0], parte: (r: Record) => (r['denominador'] as number) - (r['numerador'] as number), + valor: (r: Record) => redondeo(100 * ((r['denominador'] as number) - (r['numerador'] as number)) / (r['denominador'] as number)), + bajo: (r: Record) => numero(r['ic_alto']) ? redondeo(100 - r['ic_alto']) : null, alto: (r: Record) => numero(r['ic_bajo']) ? redondeo(100 - r['ic_bajo']) : null }, + { nombre: 'EEG anormal', color: C2_PALETTE.series[2], parte: (r: Record) => r['numerador'] as number, + valor: (r: Record) => r['valor'] as number, + bajo: (r: Record) => numero(r['ic_bajo']) ? r['ic_bajo'] : null, alto: (r: Record) => numero(r['ic_alto']) ? r['ic_alto'] : null }, + ]; + const trazos = lineas.flatMap(l => [ + banda(x, validas.map(r => r ? l.bajo(r) : null), validas.map(r => r ? l.alto(r) : null), 'Intervalo de confianza de ' + l.nombre.toLowerCase(), l.color), + { type: 'scatter', mode: 'lines+markers', name: l.nombre, x, y: validas.map(r => r ? l.valor(r) : null), connectgaps: false, line: { color: l.color, width: 2 }, marker: { color: l.color }, + text: validas.map(r => r ? `${l.valor(r)} %
${l.parte(r)} de ${r['denominador']}` : ''), hovertemplate: '%{x}
%{text}' + l.nombre + '' }, + ]); + return { figure: { data: trazos, layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, + comoLeer: 'Línea de EEG anormal: se detecta alguna alteración.', suprimidos, sinDato }; +} function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { const periodos = validar(data), unidad = unidadDe(data, opciones.unidades); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); @@ -139,7 +172,7 @@ function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena); return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout; })() }, - comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`, + comoLeer: PIE_MEDIANA[data.id] ?? `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`, suprimidos, sinDato, }; } @@ -190,7 +223,7 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}%{fullData.name}' }; }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, comoLeer: data.id === 'cama_birads_456_paciente' ? '' - : CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, + : CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, suprimidos, sinDato, }; } @@ -202,7 +235,7 @@ function etiquetaCategoria(meta: Record, id: string) { // The plot follows from what the contract's numbers mean: counts add up to a total, percentages // and medians do not, so those two are never stacked. export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura { - const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema) + const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? (data.id === M30_RESULTADO_EEG ? resultadoEeg(data, tema) : porcentaje(data, tema)) : data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined; if (!figura) throw new Error('Representación no soportada'); return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts index f84d5b0..fc5b15b 100644 --- a/src/app/features/indicadores/indicadores-historico.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -192,11 +192,19 @@ describe('Pestaña Histórico', () => { } render(); const paneles = fixture.componentInstance.paneles(); - expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']); - const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>; + expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']); + const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>; expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]); expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3); }); + it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => { + // Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped. + const ids = ['M30_resultado_eeg', 'M29_calidad_eeg', 'otro', 'M28_casos_por_estado', 'M22_diagnosticados_sin_eeg', 'M21_diagnosticados_con_eeg', 'M24_confirmacion_diagnostico', 'M23_pacientes_evaluados']; + fixture.componentRef.setInput('catalog', ids.map(id => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['mes'] }))); + render(); + expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', + 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg', 'otro']); + }); it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => { const c = fixture.componentInstance; const cerrar = new Subject(); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index d738c83..4647bfa 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -8,7 +8,7 @@ import { MatSelect, MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { defer, map, Subscription } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; +import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; import { IndicadoresPeriodos } from './indicadores-periodos'; @@ -63,6 +63,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P }); } +// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them. +const ORDEN_TEA = ['tiempos', 'M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg', + CASOS, 'en_proceso', 'M29_calidad_eeg', M30_RESULTADO_EEG]; +function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] { + const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; }; + return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel); +} + // Evolution of each indicator: the granularity and how many of the latest periods to show. // Nothing is requested until the tab is first opened, and each granularity is requested once. @Component({ @@ -295,7 +303,8 @@ export class IndicadoresHistorico { return { ...panelDe(item), item: { ...visible, contrato: item.contrato } }; }); } - return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema); + const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema); + return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles; }); constructor() { From ff4ad2c96404931e2e64e1736f2bdda1d2998dc2 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 03:21:09 -0600 Subject: [PATCH 07/35] =?UTF-8?q?An=C3=A1lisis=20de=20riesgos:=20TEA=20and?= =?UTF-8?q?=20CaCu=20headings=20and=20the=20EEG=20status=20label?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/features/indicadores/cacu-seguimiento.spec.ts | 1 + src/app/features/indicadores/indicadores-tracking.html | 8 ++++---- src/app/features/indicadores/indicadores-tracking.ts | 5 +++++ src/app/features/indicadores/tea-seguimiento.spec.ts | 10 ++++++---- 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index b77f3a9..679d629 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -36,6 +36,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => { const root:HTMLElement=fixture.nativeElement; expect(root.textContent).not.toContain('Datos simulados — uso de demostración'); expect(root.textContent).not.toContain('Las reglas de selección son provisionales'); + expect(root.querySelector('h2')?.textContent).toBe('Modelos de riesgo asociados a cáncer cervicouterino'); expect(root.textContent).toContain('Ventana consultada:'); expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado'); expect(root.textContent).toContain('Insatisfactoria'); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 0b3540a..5eae69c 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -4,7 +4,7 @@ (registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" /> }
-@if (dominio !== 'cama') {

Seguimiento de {{ domainLabel }}

} +@if (dominio !== 'cama') {

{{ titulo }}

} @if (dominio === 'cama') { @@ -22,8 +22,8 @@ - @if (dominio === 'tea') { @@ -82,7 +82,7 @@
- + @for (item of response.items; track item.id_seudonimo) { diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index fcd2197..80366a2 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -25,6 +25,11 @@ import { TeaPacienteResumen } from './tea-paciente-resumen'; export class IndicadoresTracking implements OnChanges { @Input({ required: true }) domainLabel = ''; @Input() dominio: Dominio = 'tea'; + // The section's heading: TEA's follows its EEG, CaCu's names the risk models it will hold; the other domains keep the follow-up one. + get titulo() { + return this.dominio === 'tea' ? 'Alteraciones de EEG relacionadas al TEA' + : this.dominio === 'cacu' ? 'Modelos de riesgo asociados a cáncer cervicouterino' : 'Seguimiento de ' + this.domainLabel; + } @Input() active = false; /** CaMa: the patients of a curve or a cell of the analysis, for its follow-up list. */ @Input() seleccion?: SeleccionSeguimiento; diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 9e91ad6..51125d1 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -62,7 +62,7 @@ describe('Seguimiento TEA', () => { request().flush(data); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual( - ['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']); + ['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Estatus de EEG']); const rows = root.querySelectorAll('tbody tr'); expect(rows).toHaveLength(2); expect(rows[0].textContent).toContain('Anormal'); @@ -70,7 +70,7 @@ describe('Seguimiento TEA', () => { expect(root.textContent).toContain('Página 1 de 1, 2 registros'); http.verify(); }); - it('usa los filtros de CaCu con Alteraciones EEG en lugar del estatus', () => { + it('usa los filtros de CaCu con Estatus de EEG en lugar del estatus, bajo el título de las alteraciones de EEG', () => { const fixture = open(); const first = request(); expect(first.request.params.get('meses')).toBe('3'); @@ -79,8 +79,10 @@ describe('Seguimiento TEA', () => { const root: HTMLElement = fixture.nativeElement; expect(root.querySelector('input[type=date]')).not.toBeNull(); const select = root.querySelector('select[name=estatus]')!; - expect(select.closest('label')?.textContent).toContain('Alteraciones EEG'); - expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal', 'Sin EEG válido']); + // Fails if the section goes back to the «Seguimiento de …» heading or the filter to «Alteraciones EEG». + expect(root.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA'); + expect(select.closest('label')?.textContent).toContain('Estatus de EEG'); + expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todos', 'Normal', 'Anormal', 'Sin EEG válido']); fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 }; fixture.componentInstance.apply(); const filtered = request(); From 6ed87ff3d8a7ba6b7399ce0c0d36ca01044841ee Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 03:28:05 -0600 Subject: [PATCH 08/35] =?UTF-8?q?Fix=20CaMa=20Hist=C3=B3rico=20order=20exp?= =?UTF-8?q?ectation=20in=20the=20f4c=20spec?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/features/indicadores/indicadores-cama-f4c.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts index 2f54eef..9063f4e 100644 --- a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -143,8 +143,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => { const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']); expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica'); expect(titulos.filter(([, estado]) => estado === 'dibujado')) - .toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]); - expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]); + .toEqual([['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Resultado histopatológico', 'dibujado']]); + expect(graficas().map(g => g.figure!.data.length)).toEqual([2, 6]); }); it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => { montar(false); From 999bc4ecf54cf4891bc175c936000ef28b4f2ab8 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 04:03:33 -0600 Subject: [PATCH 09/35] fix(indicadores): distinguish EEG findings and populations --- .../indicadores-historico-figures.spec.ts | 17 +++++----- .../indicadores-historico-figures.ts | 33 ++++--------------- .../indicadores/tea-resumen-periodo.spec.ts | 10 +++--- .../indicadores/tea-resumen-periodo.ts | 8 ++--- 4 files changed, 23 insertions(+), 45 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-figures.spec.ts b/src/app/features/indicadores/indicadores-historico-figures.spec.ts index 042ac89..d05b307 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.spec.ts @@ -119,7 +119,7 @@ describe('Histórico: datos inválidos', () => { }); }); -describe('Histórico: pies de figura pedidos para CaMa y la gráfica de EEG normal y anormal de TEA', () => { +describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en TEA', () => { const med = (id: string) => figura({ ...base('C3r', MESES, [fila('2025-01', { mediana: 10, q1: 9, q3: 12, n: 9 })], { unidad: 'examen' }), id } as IndicadorDatos); const cats = [{ periodo: '2025-01', categoria: 'A', n: 2, orden: 0, suprimido: 0 }, { periodo: '2025-01', categoria: 'B', n: 3, orden: 1, suprimido: 0 }]; it('las tres medianas de CaMa usan el pie de la solicitud y las de otros dominios conservan el suyo', () => { @@ -142,18 +142,17 @@ describe('Histórico: pies de figura pedidos para CaMa y la gráfica de EEG norm expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe(''); expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total'); }); - it('M30 dibuja dos líneas, normal y anormal, que suman 100 %, con el pie pedido', () => { - // Fails if the chart has one line, if normal is not the rest of the same children (count, percentage and interval) or if the caption changes. + it('M30 muestra la proporción publicada de alteraciones y deja pendiente la clasificación de EEG normal', () => { + // Fails if children without an evaluable result are treated as normal through a complement. const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }), fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos); const f = m30.figure as unknown as Fig; const lineas = f.data.filter(t => t['mode'] === 'lines+markers'); - expect(lineas.map(t => t['name'])).toEqual(['EEG normal', 'EEG anormal']); - expect(lineas.map(t => (t['y'] as (number | null)[])[0])).toEqual([37.5, 62.5]); - expect(JSON.stringify(lineas[0]['text'])).toContain('3 de 8'); expect(JSON.stringify(lineas[1]['text'])).toContain('5 de 8'); - // The normal band is the anormal one turned around: 100 − 86.3 to 100 − 30.6. - expect(f.data.find(t => t['name'] === 'Intervalo de confianza de eeg normal')!['y']).toEqual([69.4, 13.7]); - expect(m30.comoLeer).toBe('Línea de EEG anormal: se detecta alguna alteración.'); + expect(lineas.map(t => t['name'])).toEqual(['EEG con alteración detectada']); + expect(lineas[0]['y']).toEqual([62.5, null, null, null]); + expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8'); + expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]); + expect(m30.comoLeer).toContain('La clasificación de EEG normal está pendiente de validación.'); expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']); }); }); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 9f759d8..09fe721 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -104,9 +104,11 @@ function colorDeLinea(id: string, tema: Tema) { return { linea, relleno: linea + '40' }; } -// CaMa's captions, as the request words them; the other domains keep the general ones. +export const M30_RESULTADO_EEG = 'M30_resultado_eeg'; + const PIE_PORCENTAJE: Readonly> = { cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.', + [M30_RESULTADO_EEG]: 'Resultado experimental. La línea muestra EEG con alguna alteración detectada. La clasificación de EEG normal está pendiente de validación.', }; const PIE_MEDIANA: Readonly> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id, 'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'])); @@ -119,10 +121,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { // A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0); const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema); + const nombre = data.id === M30_RESULTADO_EEG ? 'EEG con alteración detectada' : 'Porcentaje'; return { figure: { data: [ banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno), - { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea }, + { type: 'scatter', mode: 'lines+markers', name: nombre, x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea }, text: validas.map(row => { if (!row) return ''; const intervalo = numero(row['ic_bajo']) && numero(row['ic_alto']) ? `
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''; @@ -134,30 +137,6 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { suprimidos, sinDato, }; } -// M30 publishes the share of the children whose first good EEG has some alteration (the TOTAL group). The normal ones are -// the rest of the same children, so their count and their interval are the complement of the published ones. -export const M30_RESULTADO_EEG = 'M30_resultado_eeg'; -function resultadoEeg(data: IndicadorDatos, tema: Tema): Trazo { - const periodos = validar(data); - const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['numerador']) && numero(row['denominador']) && row['denominador'] > 0); - const x = periodos.map(etiquetaPeriodo), layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'); - const redondeo = (v: number) => Math.round(v * 10) / 10; - const lineas = [ - { nombre: 'EEG normal', color: C2_PALETTE.series[0], parte: (r: Record) => (r['denominador'] as number) - (r['numerador'] as number), - valor: (r: Record) => redondeo(100 * ((r['denominador'] as number) - (r['numerador'] as number)) / (r['denominador'] as number)), - bajo: (r: Record) => numero(r['ic_alto']) ? redondeo(100 - r['ic_alto']) : null, alto: (r: Record) => numero(r['ic_bajo']) ? redondeo(100 - r['ic_bajo']) : null }, - { nombre: 'EEG anormal', color: C2_PALETTE.series[2], parte: (r: Record) => r['numerador'] as number, - valor: (r: Record) => r['valor'] as number, - bajo: (r: Record) => numero(r['ic_bajo']) ? r['ic_bajo'] : null, alto: (r: Record) => numero(r['ic_alto']) ? r['ic_alto'] : null }, - ]; - const trazos = lineas.flatMap(l => [ - banda(x, validas.map(r => r ? l.bajo(r) : null), validas.map(r => r ? l.alto(r) : null), 'Intervalo de confianza de ' + l.nombre.toLowerCase(), l.color), - { type: 'scatter', mode: 'lines+markers', name: l.nombre, x, y: validas.map(r => r ? l.valor(r) : null), connectgaps: false, line: { color: l.color, width: 2 }, marker: { color: l.color }, - text: validas.map(r => r ? `${l.valor(r)} %
${l.parte(r)} de ${r['denominador']}` : ''), hovertemplate: '%{x}
%{text}' + l.nombre + '' }, - ]); - return { figure: { data: trazos, layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, - comoLeer: 'Línea de EEG anormal: se detecta alguna alteración.', suprimidos, sinDato }; -} function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { const periodos = validar(data), unidad = unidadDe(data, opciones.unidades); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); @@ -235,7 +214,7 @@ function etiquetaCategoria(meta: Record, id: string) { // The plot follows from what the contract's numbers mean: counts add up to a total, percentages // and medians do not, so those two are never stacked. export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura { - const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? (data.id === M30_RESULTADO_EEG ? resultadoEeg(data, tema) : porcentaje(data, tema)) + const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema) : data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined; if (!figura) throw new Error('Representación no soportada'); return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index b3f6c90..c3cecf6 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -37,10 +37,10 @@ describe('Resumen TEA por periodo', () => { expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.'); expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.'); - expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.'); + expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); expect(text).toContain('*tomando la mediana de los tiempos'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']); + .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']); expect(root.querySelector('button')).toBeNull(); }); @@ -54,7 +54,7 @@ describe('Resumen TEA por periodo', () => { panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })]; const text = texto(render(paneles).nativeElement); expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan'); - expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.'); + expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo); }); @@ -64,7 +64,7 @@ describe('Resumen TEA por periodo', () => { paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57)); paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } }); const root: HTMLElement = render(paneles).nativeElement; - expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); + expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0'); }); @@ -85,7 +85,7 @@ describe('Resumen TEA por periodo', () => { paneles[4].result.set(c1('28.1', 16, 58)); const root: HTMLElement = render(paneles).nativeElement; expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title'))) - .toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden')); + .toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden')); }); it('indica la carga y reintenta solo las consultas con error', () => { diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index 11b47f1..41f5298 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -29,10 +29,10 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2 El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de .
- De los niños con diagnóstico confirmado en este periodo, - presentan estudio de EEG y faltan - por realizarlo. - De los estudios de EEG, + De los niños con diagnóstico confirmado al cierre del periodo, + tienen un EEG de buena calidad y + aún no cuentan con uno de esa calidad. + Del total de estudios de EEG del periodo, tienen buena calidad.

*tomando la mediana de los tiempos

From feaed5ff0e58a35fdfdd79e580b6af9d3c06d045 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 02:48:49 -0600 Subject: [PATCH 10/35] Indicators: a typed page size is brought into 1 to the maximum, one maximum for both lists An input's max only flags the field and still lets a larger number be typed. The follow-up table and the tracking list now clamp the value when it changes and when the query is sent, and both read the single PAGE_SIZE_MAX instead of a literal 200. Co-Authored-By: Claude Sonnet 5.5 (cherry picked from commit 1342b1712dbae9658c47ffe7b8d9ad060eb26eb6) --- .../indicadores/cacu-seguimiento.service.ts | 5 +++-- .../indicadores-seguimiento-tabla.spec.ts | 7 +++---- .../indicadores/indicadores-seguimiento-tabla.ts | 7 ++++--- .../indicadores/indicadores-tracking.html | 2 +- .../features/indicadores/indicadores-tracking.ts | 7 +++++-- .../indicadores/seguimiento-tabla.service.spec.ts | 15 ++++++++++++++- .../indicadores/seguimiento-tabla.service.ts | 5 +++++ 7 files changed, 35 insertions(+), 13 deletions(-) diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index 53cf2da..d073b33 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -3,11 +3,12 @@ import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; import { identidadDe, identidadesDe } from './paciente-identidad'; +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; 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 <= 200; + 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; } export function seguimientoResponse(v: unknown): SeguimientoResponse { // The current authorization covers demonstration records only. Validate this @@ -18,7 +19,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { || !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string') || !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) > 200 || !integer(p['total_items']) || !integer(p['total_pages']) + || !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; const c = item['ultima_citologia'], h = item['ultimo_vph']; diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts index 4d68123..af08327 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts @@ -195,13 +195,12 @@ describe('Seguimiento de CaMa (tabla)', () => { expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.'); expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081'); }); - it('un tamaño de página inválido no sale del navegador', async () => { + it('un tamaño de página mayor al máximo se acota y no sale del navegador sin acotar', async () => { await cargado(); const tam = campo('Registros por página').querySelector('input') as HTMLInputElement; - tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges(); + tam.value = '500'; tam.dispatchEvent(new Event('input')); tam.dispatchEvent(new Event('change')); fixture.detectChanges(); boton('Consultar').click(); fixture.detectChanges(); - http.expectNone(() => true); - expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha'); + expect(parametros(solicitud())).toMatchObject({ page_size: '200' }); }); }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 50164a8..6ee30f7 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { - consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, acotarTamano, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; @@ -76,7 +76,7 @@ const mismosFiltros = (a: Record, b: Record{{ o.etiqueta }} } } - + @switch (estado()) { @@ -163,6 +163,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { private readonly consultas = new Subject(); readonly etiquetaVentana = etiquetaVentana; readonly tamanoMaximo = PAGE_SIZE_MAX; + readonly acotar = acotarTamano; readonly estado = signal('idle'); readonly mensaje = signal(''); readonly data = signal(undefined); @@ -315,7 +316,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.appliedEtiqueta = etiqueta; // Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one. const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; - const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, + const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: acotarTamano(this.draft.page_size), filtros, contexto: otroCorte ? undefined : contexto }; // A new query of the cohort starts from nothing on screen: what was there belongs to the previous one. if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); } diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 5eae69c..0ad6b25 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -48,7 +48,7 @@ @for (t of tiposAlteracion; track t.codigo) { } } - + @if (status === 'loading') {

Cargando seguimiento…

} diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 80366a2..3c6d847 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; +import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service'; import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; import { MatButtonModule } from '@angular/material/button'; import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; @@ -35,6 +36,8 @@ export class IndicadoresTracking implements OnChanges { @Input() seleccion?: SeleccionSeguimiento; /** CaMa: the way back to the analysis the selection came from. */ readonly volverAlAnalisis = output(); + readonly tamanoMaximo = PAGE_SIZE_MAX; + readonly acotar = acotarTamano; private readonly service = inject(CacuSeguimientoService); private readonly indicators = inject(IndicadoresService); private readonly teaService = inject(TeaSeguimientoService); @@ -124,11 +127,11 @@ 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 200).'; 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.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q }; (this.dominio === 'tea' ? this.teaRequests : this.requests).next(q); } - apply() { this.load({ ...this.draft, page: 1 }); } + apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); } retry() { this.load(this.applied); } navigate(page: number) { if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return; diff --git a/src/app/features/indicadores/seguimiento-tabla.service.spec.ts b/src/app/features/indicadores/seguimiento-tabla.service.spec.ts index 834cb34..c9f0dcd 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.spec.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.spec.ts @@ -7,7 +7,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common import fixtureData from './fixtures/cama_seguimiento.json'; import finalResponse from './fixtures/cama_seguimiento-final.json'; import outsideResponse from './fixtures/cama_seguimiento-out-of-range.json'; -import { PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service'; +import { acotarTamano, PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service'; const clonar = () => structuredClone(fixtureData) as unknown as Record; const consulta: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 }; @@ -132,3 +132,16 @@ describe('Seguimiento genérico: petición', () => { }); }); }); + +describe('acotarTamano', () => { + it('brings a typed page size into 1 to the maximum, and falls back when it is not a number', () => { + expect(acotarTamano(500)).toBe(PAGE_SIZE_MAX); + expect(acotarTamano('999')).toBe(PAGE_SIZE_MAX); + expect(acotarTamano(0)).toBe(1); + expect(acotarTamano(-7)).toBe(1); + expect(acotarTamano(25.9)).toBe(25); + expect(acotarTamano('')).toBe(1); + expect(acotarTamano('x')).toBe(50); + expect(acotarTamano(undefined, 20)).toBe(20); + }); +}); diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index 239797c..f0cd94b 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -44,6 +44,11 @@ export type MesesVentana = typeof MESES_VENTANA[number]; /** What the window is called on screen and in the files: the whole cohort or a number of months. */ export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`; export const PAGE_SIZE_MAX = 200; +/** A page size typed in a form, brought into 1..PAGE_SIZE_MAX: an input's `max` only flags the field, it does not stop a larger number. */ +export const acotarTamano = (valor: unknown, defecto = 50) => { + const n = Math.trunc(Number(valor)); + return Number.isFinite(n) ? Math.min(PAGE_SIZE_MAX, Math.max(1, n)) : defecto; +}; const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO]; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); From 7692952ec9a3145a06f261ce7a8bbc4797401e76 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 02:49:34 -0600 Subject: [PATCH 11/35] Risk record: the evaluation instant reads as a day and minute in UTC The index date is a calendar day and the evaluation time was the raw ISO instant, so the two looked inconsistent. The instant now shows as 'YYYY-MM-DD HH:MM UTC' (the full value stays in the
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadEstado del casoÚltimo EEGPuntaje M-CHATCSS ADOS-2Alteraciones EEG
Identificador seudónimoGrupo de edadEstado del casoÚltimo EEGPuntaje M-CHATCSS ADOS-2Estatus de EEG
- + - - + + @@ -37,6 +44,15 @@
Probabilidades por horizonte desde la fecha índice{{ riesgo.estimando?.quantity ?? 'Probabilidades' }} por horizonte desde la fecha índice
Horizonte (años)Probabilidad (%)Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ riesgo.estimando?.quantity ?? 'Probabilidad' }} (%) Intervalo de confianza (%)
+ @if (riesgo.horizontes.length > 1) { +
+ Curva de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo + @if (curvaAbierta()) { + + } +
+ } } @else {

Sin horizontes evaluados en el lote vigente.

} } } 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 90a76f3..99d1396 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -18,3 +18,4 @@ thead th { position: sticky; top: 0; background: var(--issste-background, var(-- tbody th, td { background: var(--issste-surface); } tbody tr:last-child > * { border-bottom: 0; } .percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; } +.risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } 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 4342680..2d4c6d6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,6 +1,9 @@ -import { Component, computed, effect, inject, input } from '@angular/core'; -import { DecimalPipe } from '@angular/common'; -import { DominioRiesgo } from './paciente-riesgo.models'; +import { Component, computed, effect, inject, input, signal } from '@angular/core'; +import { DecimalPipe, LowerCasePipe } from '@angular/common'; +import { PlotlyChart } from '../../../shared/plotly/plotly-chart'; +import { PlotlyFigure } from '../indicadores.models'; +import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; +import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -12,7 +15,7 @@ export const instanteUtc = (iso: string) => { @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [DecimalPipe], + imports: [DecimalPipe, LowerCasePipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -27,6 +30,13 @@ export class PacienteRiesgoTabla { readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; readonly instante = instanteUtc; + /** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */ + readonly curvaAbierta = signal(false); + private figuraDe?: { riesgo: LoteRiesgoCacu; figura: PlotlyFigure }; + figura(riesgo: LoteRiesgoCacu): PlotlyFigure { + if (this.figuraDe?.riesgo !== riesgo) this.figuraDe = { riesgo, figura: figuraRiesgoPaciente(riesgo) }; + return this.figuraDe.figura; + } constructor() { effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); }); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 4acb7cc..c140a2b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -14,6 +14,18 @@ export interface HorizonteRiesgoCacu { ic_alto?: number | null; } +/** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */ +export interface EstimandoRiesgo { + /** e.g. "Riesgo acumulado"; also `method.text`. */ + quantity?: string; + description?: string; + outcome?: string; + index_date?: string; + /** The unit the horizons are counted in, e.g. "años". */ + horizons_unit?: string; + interval?: string; +} + /** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/`). */ export interface LoteRiesgoCacu { /** The resource's id, `-`. */ @@ -28,6 +40,8 @@ export interface LoteRiesgoCacu { desenlace: string; desenlace_texto: string | null; horizontes: HorizonteRiesgoCacu[]; + /** `null` for a model whose scenario doesn't say. */ + estimando: EstimandoRiesgo | null; } /** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index 2344b80..f4332af 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -2,6 +2,7 @@ import { RiesgoPacienteCacu } from './paciente-riesgo.models'; const CS = 'https://isssteleon.org/fhir/CodeSystem'; export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; +export const ESTIMANDO = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; /** A FHIR prediction: probability `p` from `inicio` to `fin`, with its interval when given. */ export function prediccion(p: number, inicio: string, fin: string, ic?: [number, number]): any { @@ -47,6 +48,23 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { { horizonte_anios: 3, probabilidad: 0.21, ic_bajo: 0.15, ic_alto: 0.28 }, { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }, ], + estimando: null, }, }; } + +/** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */ +export function riesgoCacuConEstimando(): any { + const data = riesgoCacuEjemplo(); + const resource = data.entry[0].resource; + resource.method.text = 'Riesgo acumulado'; + resource.extension = [{ url: ESTIMANDO, extension: [ + { url: 'quantity', valueString: 'Riesgo acumulado' }, + { url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' }, + { url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' }, + { url: 'horizons_unit', valueString: 'años' }, + { url: 'interval', valueString: 'IC 95 % por método delta' }, + { url: 'otra', valueString: 'se ignora' }, + ] }]; + return data; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index dbbade0..446263c 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -1,5 +1,5 @@ import { isoDate } from '../cacu-seguimiento.models'; -import { HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); @@ -9,6 +9,8 @@ const probability = (v: unknown): v is number => finite(v) && v >= 0 && v <= 1; const DAYS_PER_YEAR = 365.25; const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; const SIMULATED = 'simulado'; +const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; +const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'interval']; function utcTimestamp(v: unknown): v is string { return typeof v === 'string' @@ -39,6 +41,23 @@ function interval(prediction: Record): { ic_bajo: number | null return { ic_bajo: low, ic_alto: high }; } +/** The resource's `estimando` extension: its known keys with a text value; `null` without one. */ +function estimand(resource: Record): EstimandoRiesgo | null { + const extensions = resource['extension']; + if (extensions === undefined) return null; + if (!Array.isArray(extensions)) invalid(); + const found = extensions.find(e => record(e) && e['url'] === ESTIMAND); + if (found === undefined) return null; + if (!Array.isArray(found['extension'])) invalid(); + const result: EstimandoRiesgo = {}; + for (const item of found['extension']) { + if (!record(item) || !text(item['url'])) invalid(); + const key = item['url'] as keyof EstimandoRiesgo; + if (ESTIMAND_KEYS.includes(key) && text(item['valueString'])) result[key] = item['valueString']; + } + return result; +} + function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } { if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid(); const period = prediction['whenPeriod']; @@ -80,7 +99,7 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null, - horizontes, + horizontes, estimando: estimand(v), }; } From 60c71bfc3dd5a700ce826d067dfea826aed4f142 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 07:48:42 -0600 Subject: [PATCH 15/35] Governance: a version lists only the routines its run recorded Not every model has each of the five routines, and the registry doesn't require them; the dialog showed the missing ones as failures. It now lists the recorded ones and says so when there are none. (cherry picked from commit b5bff7e0c658e0564fc1585ca957894cc1b8d9a2) --- .../model-version-dialog.html | 33 ++++++++++--------- .../model-version-dialog.ts | 5 ++- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.html b/src/app/governance/components/model-version-dialog/model-version-dialog.html index b5f74b6..eed3b70 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.html +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.html @@ -83,24 +83,25 @@

Rutinas del entrenamiento

-

Lo que cada rutina hizo, registrado por la corrida mientras entrenaba (ML-01a).

-
    - @for (routine of routineKinds; track routine.kind) { - @let record = l.routines[routine.kind]; -
  • - - {{ routine.label }} - @if (record) { +

    Lo que cada rutina hizo, registrado por la corrida mientras entrenaba. No todos los modelos + tienen cada rutina; no se piden para promover (ML-01a lo cumple la corrida misma).

    + @let recorded = recordedRoutines(l.routines); + @if (recorded.length) { +
      + @for (routine of recorded; track routine.kind) { +
    • + + {{ routine.label }}
      - {{ record['method'] ?? 'Ver registro' }} -
      {{ record | json }}
      + {{ routine.record['method'] ?? 'Ver registro' }} +
      {{ routine.record | json }}
      - } @else { - La corrida no la registró. - } -
    • - } -
    +
  • + } +
+ } @else { +

La corrida no guardó registros de rutina.

+ }
diff --git a/src/app/governance/components/model-version-dialog/model-version-dialog.ts b/src/app/governance/components/model-version-dialog/model-version-dialog.ts index 1874e32..514b675 100644 --- a/src/app/governance/components/model-version-dialog/model-version-dialog.ts +++ b/src/app/governance/components/model-version-dialog/model-version-dialog.ts @@ -55,7 +55,10 @@ export class ModelVersionDialog { private readonly version = inject(MAT_DIALOG_DATA); private readonly dialog = inject(MatDialog); - readonly routineKinds = ROUTINES; + /** The routines the run recorded, in `ROUTINES`' order; the others aren't listed. */ + recordedRoutines(routines: ModelLineage['routines']) { + return ROUTINES.filter((r) => routines[r.kind]).map((r) => ({ ...r, record: routines[r.kind]! })); + } readonly lineage = signal(null); readonly busy = signal(false); readonly error = signal(null); From 686580af81fbed9e7a0b1cd176b1f8c30d84a770 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 09:35:01 -0600 Subject: [PATCH 16/35] Patient risk: a column per outcome, the index visit's sentence, and the model's details folded The record reads every RiskAssessment of the patient. CaCu's table always has the LIEAG+ and cancer columns, each risk with its interval in parentheses; a column with no current model says "No disponible", and one whose model didn't estimate her says so, with the reason under the table. Another outcome (a survival model's death) shows only when she has its risk, with its own index date in its header. The models' details fold under the table, without the interval's method; the collapsible curves draw one line per outcome with the index date on the x axis, under a sentence that words the index cytology's results and each outcome's risk at the longest common horizon. (cherry picked from commit 73b88de0caf91a64c457eec0d2ac35a3591c64bc) --- .../paciente-riesgo-estimando.spec.ts | 78 ++++++++++-- .../paciente-riesgo-figura.ts | 76 +++++++----- .../paciente-riesgo-tabla.html | 101 ++++++++------- .../paciente-riesgo-tabla.scss | 5 + .../paciente-detalle/paciente-riesgo-tabla.ts | 19 ++- .../paciente-riesgo.models.ts | 18 ++- .../paciente-riesgo.presentacion.ts | 115 ++++++++++++++++++ .../paciente-detalle/paciente-riesgo.spec.ts | 5 +- .../paciente-riesgo.testing.ts | 53 +++++++- .../paciente-riesgo.validation.ts | 69 ++++++++--- 10 files changed, 429 insertions(+), 110 deletions(-) create mode 100644 src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index 30ad7ab..cb6363f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -4,7 +4,8 @@ import { provideHttpClientTesting } from '@angular/common/http/testing'; import { of } from 'rxjs'; import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; -import { riesgoCacuConEstimando, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; +import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; +import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; @@ -24,10 +25,10 @@ describe('Riesgo individual: qué se estima y su curva', () => { return { fixture, root: fixture.nativeElement as HTMLElement }; } - it('lee el estimando conocido e ignora claves que no conoce; sin extensión queda en null', () => { + it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => { expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({ quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.', - outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', interval: 'IC 95 % por método delta' }); + outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' }); expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista()); }); @@ -40,10 +41,12 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => { const { root } = setup(riesgoCacuConEstimando()); expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) - .toEqual(['Horizonte (años)', 'Riesgo acumulado (%)', 'Intervalo de confianza (%)']); - for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma', 'IC 95 % por método delta']) { + .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); + expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo'); + for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) { expect(root.textContent).toContain(value); } + expect(root.textContent).not.toContain('método delta'); }); it('dibuja la curva solo al abrir su sección', async () => { @@ -59,15 +62,76 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('la figura une los horizontes y pone el intervalo como banda, o como barras si falta en alguno', () => { const riesgo = riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo; - const banda = figuraRiesgoPaciente(riesgo); + const banda = figuraRiesgoPaciente([riesgo]); expect(banda.data).toHaveLength(3); expect(banda.data[2]['y']).toEqual([8, 21, 34]); expect(banda.data[1]['y']).toEqual([5, 15, 26]); expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)'); const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) }; - const barras = figuraRiesgoPaciente(parcial); + const barras = figuraRiesgoPaciente([parcial]); expect(barras.data).toHaveLength(1); expect((barras.data[0]['error_y'] as any).array[0]).toBe(0); }); + + it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => { + const { root } = setup(riesgoCacuDosDesenlaces()); + expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); + const fila = [...root.querySelectorAll('tbody tr')][2]; + expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim())) + .toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']); + }); + + it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']); + expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo ' + + 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + + 'respectivamente.'); + expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull(); + }); + + it('dibuja una curva por desenlace, cada una con su banda', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + const figura = figuraRiesgoPaciente(riesgos); + const lineas = figura.data.filter(t => t['mode'] === 'lines+markers'); + expect(lineas.map(t => t['name'])).toEqual(['LIEAG+', 'cáncer']); + expect((lineas[1]['y'] as number[]).map(v => Math.round(v * 10) / 10)).toEqual([0.4, 0.9, 1.5]); + expect(figura.data.filter(t => t['fill'] === 'tonexty')).toHaveLength(2); + expect((figura.layout['xaxis'] as any).title.text).toBe('Horizonte (años desde la fecha índice (2026-06-01))'); + }); + + it('escribe los porcentajes con los decimales que un riesgo pequeño necesita', () => { + expect([0.34, 0.178, 0.015, 0.004, 0.00123, 0, 0.1, 1].map(porcentaje)) + .toEqual(['34', '17.8', '1.5', '0.4', '0.123', '0', '10', '100']); + expect(conIntervalo({ horizonte_anios: 1, probabilidad: 0.2, ic_bajo: null, ic_alto: null })).toBe('20 % (IC no disponible)'); + }); + + it('un desenlace con otra fecha índice la dice en su columna y queda fuera de la frase', () => { + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' }; + expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01'); + expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) ' + + 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); + }); + + it('sin modelo de un desenlace su columna dice No disponible', () => { + const { root } = setup(riesgoCacuConEstimando()); + const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']); + }); + + it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => { + const data = riesgoCacuCancerSinEstimar(); + const { root } = setup(data); + const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']); + expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población'); + const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!; + expect(riesgo.desenlace).toBe('cin2_mas'); + expect(riesgos[1]).toMatchObject({ desenlace: 'cancer', horizontes: [], sin_estimacion: 'queda fuera de su población' }); + expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers')) + .toHaveLength(1); + }); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts index 79797e4..78c08ff 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-figura.ts @@ -1,46 +1,60 @@ import { PlotlyFigure } from '../indicadores.models'; +import { conIntervalo, etiquetaDesenlace } from './paciente-riesgo.presentacion'; import { tieneIntervalo } from './paciente-riesgo.validation'; import { LoteRiesgoCacu } from './paciente-riesgo.models'; -const COLOR = '#6a3d9a'; -const BANDA = 'rgba(106,61,154,.18)'; +/** One color per curve, in the order of the outcomes (CIN2+, cancer, any other). */ +const COLORES = ['#6a3d9a', '#b2182b', '#1f78b4']; +const BANDAS = ['rgba(106,61,154,.18)', 'rgba(178,24,43,.16)', 'rgba(31,120,180,.16)']; /** - * The patient's risk at the model's horizons as a small curve: the points joined by a line, with the interval as a - * band where every horizon has one and as error bars otherwise. In percent; the axis names follow the estimand. + * The patient's risk of each outcome at the model's horizons as small curves on one axis: the points joined by a + * line, with the interval as a band where every horizon has one and as error bars otherwise. In percent; the axis + * names follow the first model's estimand, and the x axis says the index date the horizons count from. */ -export function figuraRiesgoPaciente(riesgo: LoteRiesgoCacu): PlotlyFigure { - const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100); - const cantidad = riesgo.estimando?.quantity ?? 'Probabilidad'; - const unidad = riesgo.estimando?.horizons_unit ?? 'años'; - const conIntervalo = h.map(tieneIntervalo); - const banda = conIntervalo.length > 1 && conIntervalo.every(Boolean); +export function figuraRiesgoPaciente(riesgos: LoteRiesgoCacu[]): PlotlyFigure { const data: Record[] = []; - if (banda) { - data.push( - { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false, hoverinfo: 'skip' }, - { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty', fillcolor: BANDA, line: { width: 0 }, - name: 'Intervalo de confianza', hoverinfo: 'skip' }, - ); - } - const barras = !banda && conIntervalo.some(Boolean) ? { - error_y: { type: 'data', symmetric: false, visible: true, color: COLOR, thickness: 2, width: 6, - array: h.map((p, i) => conIntervalo[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0), - arrayminus: h.map((p, i) => conIntervalo[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) }, - } : {}; - data.push({ - type: 'scatter', mode: 'lines+markers', x, y, name: cantidad, line: { color: COLOR, width: 2 }, - marker: { color: COLOR, size: 9, line: { color: 'white', width: 2 } }, ...barras, - customdata: h.map(p => tieneIntervalo(p) ? `${(p.ic_bajo! * 100).toFixed(2)} % – ${(p.ic_alto! * 100).toFixed(2)} %` : 'sin intervalo'), - hovertemplate: `%{x} ${unidad}: %{y:.2f} %
IC: %{customdata}`, + let maximo = 0; + riesgos.forEach((riesgo, k) => { + const h = riesgo.horizontes, x = h.map(p => p.horizonte_anios), y = h.map(p => p.probabilidad * 100); + const color = COLORES[k % COLORES.length], nombre = etiquetaDesenlace(riesgo); + const conIc = h.map(tieneIntervalo); + const banda = conIc.length > 1 && conIc.every(Boolean); + if (banda) { + data.push( + { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_alto! * 100), line: { width: 0 }, showlegend: false, + hoverinfo: 'skip', legendgroup: nombre }, + { type: 'scatter', mode: 'lines', x, y: h.map(p => p.ic_bajo! * 100), fill: 'tonexty', + fillcolor: BANDAS[k % BANDAS.length], line: { width: 0 }, name: `IC 95 % ${nombre}`, hoverinfo: 'skip', + legendgroup: nombre }, + ); + } + const barras = !banda && conIc.some(Boolean) ? { + error_y: { type: 'data', symmetric: false, visible: true, color, thickness: 2, width: 6, + array: h.map((p, i) => conIc[i] ? (p.ic_alto! - p.probabilidad) * 100 : 0), + arrayminus: h.map((p, i) => conIc[i] ? (p.probabilidad - p.ic_bajo!) * 100 : 0) }, + } : {}; + data.push({ + type: 'scatter', mode: 'lines+markers', x, y, name: nombre, legendgroup: nombre, line: { color, width: 2 }, + marker: { color, size: 9, line: { color: 'white', width: 2 } }, ...barras, + customdata: h.map(conIntervalo), + hovertemplate: `%{x} ${riesgo.estimando?.horizons_unit ?? 'años'}: %{customdata}${nombre}`, + }); + maximo = Math.max(maximo, ...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100)); }); - const maximo = Math.max(...h.map(p => (tieneIntervalo(p) ? p.ic_alto! : p.probabilidad) * 100)); + const primero = riesgos[0]; + const unidad = primero?.estimando?.horizons_unit ?? 'años'; + const fechas = [...new Set(riesgos.map(r => r.fecha_indice))]; + const desde = fechas.length === 1 ? `la fecha índice (${fechas[0]})` + : `la fecha índice de cada desenlace (${riesgos.map(r => `${etiquetaDesenlace(r)}: ${r.fecha_indice}`).join('; ')})`; return { data, layout: { - margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: banda, legend: { orientation: 'h', y: -0.25 }, - xaxis: { title: { text: `Horizonte (${unidad} desde la fecha índice)` }, tickvals: x, zeroline: false }, - yaxis: { title: { text: `${cantidad} (%)` }, rangemode: 'tozero', range: [0, Math.max(maximo * 1.15, 1)], zeroline: false }, + margin: { l: 56, r: 16, t: 16, b: 48 }, showlegend: true, legend: { orientation: 'h', y: -0.25 }, + xaxis: { title: { text: `Horizonte (${unidad} desde ${desde})` }, + tickvals: [...new Set(riesgos.flatMap(r => r.horizontes.map(p => p.horizonte_anios)))], zeroline: false }, + yaxis: { title: { text: `${primero?.estimando?.quantity ?? 'Probabilidad'} (%)` }, rangemode: 'tozero', + range: [0, Math.max(maximo * 1.15, 1)], zeroline: false }, }, }; } 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 40b2e6a..6cbd5f0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -7,53 +7,66 @@ } @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { + @let todos = lectura.datos.riesgos; + @let riesgos = conRiesgo(todos); @let riesgo = lectura.datos.riesgo; -
Modelo y evaluación
- - @if (riesgo.horizontes.length) { -
- - - - - - - - - @for (h of riesgo.horizontes; track h.horizonte_anios) { - - - - - - } - -
{{ riesgo.estimando?.quantity ?? 'Probabilidades' }} por horizonte desde la fecha índice
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ riesgo.estimando?.quantity ?? 'Probabilidad' }} (%)Intervalo de confianza (%)
{{ h.horizonte_anios }}{{ h.probabilidad * 100 | number:'1.0-4' }} %@if (tieneIntervalo(h)) { {{ h.ic_bajo! * 100 | number:'1.0-4' }} % – {{ h.ic_alto! * 100 | number:'1.0-4' }} % } @else { No disponible }
-
- @if (riesgo.horizontes.length > 1) { -
- Curva de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo - @if (curvaAbierta()) { - + @let columnas = columnasDe(todos); + @let filas = filasDe(lotesDe(columnas)); + @if (filas.length) { +
+ + + + + @for (c of columnas; track c.encabezado) { } + + + @for (f of filas; track f.horizonte_anios) { + + + @for (c of f.celdas; track $index; let i = $index) { + + } + } - + +
{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice + ({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ c.encabezado }} (%)
{{ f.horizonte_anios }}@if (columnas[i].vacia; as vacia) {{{ vacia }}} @else if (c) {{{ porcentaje(c.probabilidad) }} %{{ ' ' }}@if (tieneIntervalo(c)) {({{ porcentaje(c.ic_bajo!) }} – {{ porcentaje(c.ic_alto!) }} %)} @else {(IC no disponible)}} @else {—}
+
+ @for (c of columnas; track c.encabezado) { + @if (c.lote?.sin_estimacion; as motivo) {

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

} + } +
+ Detalle del modelo + @for (r of riesgos; track r.id) { + @if (riesgos.length > 1) {
{{ encabezado(r) }}
} + } - } @else {

Sin horizontes evaluados en el lote vigente.

} +
+ @if (filas.length > 1) { +
+ Curva{{ riesgos.length > 1 ? 's' : '' }} de {{ (riesgo.estimando?.quantity ?? 'probabilidad') | lowercase }} con su intervalo + @if (frase(riesgos); as texto) {

{{ texto }}

} + @if (curvaAbierta()) { + + } +
+ } + } @else {

Sin horizontes evaluados en el lote vigente.

} } }

Recomendaciones no disponibles.

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 99d1396..768e31a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -19,3 +19,8 @@ tbody th, td { background: var(--issste-surface); } tbody tr:last-child > * { border-bottom: 0; } .percentage, .interval { font-variant-numeric: tabular-nums; white-space: nowrap; } .risk-curve { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } +.risk-sentence { margin: .25rem 0 .75rem; line-height: 1.5; } +.risk-details { margin-block: .75rem 0; border: 1px solid var(--issste-border); border-radius: .5rem; padding-inline: .75rem; } +.risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; } +.unavailable { color: var(--issste-text-secondary); } +.unavailable-note { color: var(--issste-text-secondary); font-size: .85rem; margin: .5rem 0 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 2d4c6d6..1cb53c2 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,8 +1,9 @@ import { Component, computed, effect, inject, input, signal } from '@angular/core'; -import { DecimalPipe, LowerCasePipe } from '@angular/common'; +import { LowerCasePipe } 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, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -15,7 +16,7 @@ export const instanteUtc = (iso: string) => { @Component({ selector: 'app-paciente-riesgo-tabla', - imports: [DecimalPipe, LowerCasePipe, PlotlyChart], + imports: [LowerCasePipe, PlotlyChart], providers: [PacienteRiesgoState], templateUrl: './paciente-riesgo-tabla.html', styleUrl: './paciente-riesgo-tabla.scss', @@ -32,9 +33,17 @@ export class PacienteRiesgoTabla { readonly instante = instanteUtc; /** The curve is drawn only while its section is open, so Plotly isn't loaded for a closed one. */ readonly curvaAbierta = signal(false); - private figuraDe?: { riesgo: LoteRiesgoCacu; figura: PlotlyFigure }; - figura(riesgo: LoteRiesgoCacu): PlotlyFigure { - if (this.figuraDe?.riesgo !== riesgo) this.figuraDe = { riesgo, figura: figuraRiesgoPaciente(riesgo) }; + readonly porcentaje = porcentaje; + readonly encabezado = encabezado; + readonly etiqueta = etiquetaDesenlace; + readonly frase = fraseRiesgo; + readonly filasDe = filasRiesgo; + readonly conRiesgo = conRiesgo; + columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); } + lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); } + private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure }; + figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure { + if (this.figuraDe?.riesgos !== riesgos) this.figuraDe = { riesgos, figura: figuraRiesgoPaciente(riesgos) }; return this.figuraDe.figura; } constructor() { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index c140a2b..9da4a44 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -23,7 +23,14 @@ export interface EstimandoRiesgo { index_date?: string; /** The unit the horizons are counted in, e.g. "años". */ horizons_unit?: string; - interval?: string; +} + +/** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */ +export interface ResultadosIndice { + escamosas?: string; + glandulares?: string; + /** `POSITIVO`, `NEGATIVO` or `INDETERMINADO`. */ + vph?: string; } /** The view of one FHIR `RiskAssessment` (`GET /cacu/fhir/RiskAssessment?subject=Patient/`). */ @@ -42,12 +49,19 @@ export interface LoteRiesgoCacu { horizontes: HorizonteRiesgoCacu[]; /** `null` for a model whose scenario doesn't say. */ estimando: EstimandoRiesgo | null; + /** `null` when no cytology was sampled on the index date (or the domain doesn't give it). */ + resultados_indice: ResultadosIndice | null; + /** Why a current model of this outcome has no risk for her (extension `sin-estimacion`; then `horizontes` is + * empty and `fecha_indice` too); `null` when it scored her. */ + sin_estimacion: string | null; } -/** DEV-only: the patient's current `RiskAssessment`, from a `searchset` Bundle tagged `simulado`. */ +/** DEV-only: the patient's current `RiskAssessment` of each outcome, from a `searchset` Bundle tagged `simulado`. + * `riesgos` holds them CIN2+ first, then cancer, then any other; `riesgo` is the first. */ export interface RiesgoPacienteCacu { simulado: true; riesgo: LoteRiesgoCacu; + riesgos: LoteRiesgoCacu[]; } /** The raw FHIR answer (a Bundle), or `null` when the patient has no risk data. */ diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts new file mode 100644 index 0000000..f31c557 --- /dev/null +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -0,0 +1,115 @@ +import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models'; +import { tieneIntervalo } from './paciente-riesgo.validation'; + +/** How the record names an outcome in its columns, curves and sentence. */ +export function etiquetaDesenlace(lote: LoteRiesgoCacu): string { + if (lote.desenlace.startsWith('cin2')) return 'LIEAG+'; + if (lote.desenlace === 'cancer') return 'cáncer'; + if (lote.desenlace === 'muerte') return 'muerte'; + return lote.desenlace_texto ?? lote.desenlace; +} + +/** A column's header: "Probabilidad a LIEAG+", "Probabilidad a cáncer"; with its own index date when it isn't + * `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */ +export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string { + const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : ''; + return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`; +} + +/** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8", + * 0.015 -> "1.5", 0.00123 -> "0.123", 0.34 -> "34". */ +export function porcentaje(p: number): string { + const v = p * 100; + const decimales = v === 0 ? 0 : v < 1 ? 3 : v < 10 ? 2 : 1; + const texto = v.toFixed(decimales); + return texto.includes('.') ? texto.replace(/\.?0+$/, '') : texto; +} + +/** The risk with its interval in parentheses, as the table and the sentence write it. */ +export function conIntervalo(h: HorizonteRiesgoCacu): string { + const punto = `${porcentaje(h.probabilidad)} %`; + return tieneIntervalo(h) ? `${punto} (${porcentaje(h.ic_bajo!)} – ${porcentaje(h.ic_alto!)} %)` : `${punto} (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' }], +}; +const esDe = (lote: LoteRiesgoCacu, desenlace: string) => + desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace; + +export interface ColumnaRiesgo { + encabezado: string; + /** Its model's risks; `null` when no model of the outcome is current. */ + lote: LoteRiesgoCacu | null; + /** What the cells say when there's no risk: no model, or a model that doesn't estimate her. */ + vacia: string | null; +} + +/** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any + * other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */ +export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu'): ColumnaRiesgo[] { + const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null; + const fijas = COLUMNAS_FIJAS[dominio] ?? []; + const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => { + const lote = riesgos.find(r => esDe(r, desenlace)) ?? null; + if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' }; + return { encabezado: encabezado(lote, fecha), lote, + vacia: lote.horizontes.length ? null : 'No estimada para su grupo' }; + }); + for (const lote of riesgos) { + if (fijas.some(f => esDe(lote, f.desenlace)) || !lote.horizontes.length) continue; + columnas.push({ encabezado: encabezado(lote, fecha), lote, vacia: null }); + } + return columnas; +} + +/** The risks the record can draw and describe: the ones with horizons. */ +export const conRiesgo = (riesgos: LoteRiesgoCacu[]) => riesgos.filter(r => r.horizontes.length); + +export interface FilaRiesgo { + horizonte_anios: number; + /** One cell per column, in their order; `null` where that column has no risk at this horizon. */ + celdas: (HorizonteRiesgoCacu | null)[]; +} + +/** The table's rows: every horizon any of the columns has, ascending, with each column's risk there. */ +export function filasRiesgo(lotes: (LoteRiesgoCacu | null)[]): FilaRiesgo[] { + const horizontes = [...new Set(lotes.flatMap(r => r?.horizontes.map(h => h.horizonte_anios) ?? []))] + .sort((a, b) => a - b); + return horizontes.map(horizonte_anios => ({ + horizonte_anios, + celdas: lotes.map(r => r?.horizontes.find(h => h.horizonte_anios === horizonte_anios) ?? null), + })); +} + +function resultado(r: ResultadosIndice | null): string | null { + if (!r) return null; + const vph = r.vph === 'POSITIVO' ? 'VPH positivo' : r.vph === 'NEGATIVO' ? 'VPH negativo' + : r.vph ? `VPH ${r.vph.toLowerCase()}` : 'sin resultado de VPH'; + const citologia = [r.escamosas, r.glandulares].filter(Boolean).join(' con '); + return `Un resultado de ${vph} y una citología ${citologia || 'sin resultado'}`; +} + +/** + * The sentence over the curves: the index results and, at the longest horizon the outcomes of the first one's index + * date share, each outcome's + * cumulative risk of being present at the index visit or developing afterwards, "respectivamente" when there are + * several. `null` without the index results. + */ +export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null { + const scored = conRiesgo(todos); + const riesgos = scored.filter(r => r.fecha_indice === scored[0]?.fecha_indice); // the outcomes of the same visit + const inicio = resultado(riesgos.find(r => r.resultados_indice)?.resultados_indice ?? null); + if (!inicio) return null; + const comunes = filasRiesgo(riesgos).filter(f => f.celdas.every(c => c !== null)); + const ultima = comunes[comunes.length - 1]; + if (!ultima) return null; + const fecha = riesgos[0].fecha_indice; + const junta = (xs: string[]) => xs.length > 1 ? `${xs.slice(0, -1).join(', ')} y ${xs[xs.length - 1]}` : xs[0]; + const desenlaces = junta(riesgos.map(etiquetaDesenlace)); + const valores = junta(ultima.celdas.map(c => conIntervalo(c!))); + const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`; + return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} ` + + `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 2b13303..684d4e0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -44,11 +44,12 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const baseline = structuredClone(data); const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); + // horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval expect(root.querySelectorAll('thead th')).toHaveLength(3); expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); - expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %'); + expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)'); expect(root.textContent).toContain('Final (final)'); for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); @@ -86,7 +87,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); - expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['0 % – 0 %', 'No disponible', 'No disponible']); + expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']); expect(root.textContent).toContain('Preliminar (preliminary)'); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index f4332af..c3d0eea 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -1,4 +1,4 @@ -import { RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; const CS = 'https://isssteleon.org/fhir/CodeSystem'; export const INTERVALO = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; @@ -38,9 +38,7 @@ export function riesgoCacuEjemplo(): any { /** TEST ONLY. What the record shows from `riesgoCacuEjemplo()`. */ export function riesgoCacuVista(): RiesgoPacienteCacu { - return { - simulado: true, - riesgo: { + const riesgo: LoteRiesgoCacu = { id: '12-42', modelo_nombre: 'modelo-cacu', modelo_version: '2.1.0', fecha_indice: '2026-06-01', evaluado_en: '2026-10-01T00:00:00Z', estado_lote: 'final', desenlace: 'cin2_mas', desenlace_texto: 'CIN2+ por biopsia', horizontes: [ @@ -49,8 +47,10 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }, ], estimando: null, - }, + resultados_indice: null, + sin_estimacion: null, }; + return { simulado: true, riesgo, riesgos: [riesgo] }; } /** TEST ONLY. `riesgoCacuEjemplo()` from a model whose scenario says what its number is (extension `estimando`). */ @@ -68,3 +68,46 @@ export function riesgoCacuConEstimando(): any { ] }]; return data; } + +export const RESULTADOS_INDICE = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; + +/** TEST ONLY. `riesgoCacuConEstimando()` plus a cancer `RiskAssessment` of the same visit, both with the index + * cytology's results: the Bundle a patient scored by the CIN2+ and the cancer models gets. Cancer comes first, as + * the newer batch would. */ +export function riesgoCacuDosDesenlaces(): any { + const data = riesgoCacuConEstimando(); + const cin2 = data.entry[0].resource; + const resultados = { url: RESULTADOS_INDICE, extension: [ + { url: 'escamosas', valueString: 'LIEBG' }, { url: 'vph', valueString: 'POSITIVO' }] }; + cin2.extension.push(resultados); + const cancer = structuredClone(cin2); + cancer.id = '13-42'; + cancer.method.coding[0].code = 'modelo-cacu-cancer'; + cancer.extension[0].extension = cancer.extension[0].extension.map((e: any) => + e.url === 'outcome' ? { ...e, valueString: 'Cáncer: biopsia de carcinoma' } : e); + cancer.prediction = [ + prediccion(0.004, '2026-06-01', '2027-06-01', [0.002, 0.008]), + prediccion(0.009, '2026-06-01', '2029-06-01', [0.005, 0.016]), + prediccion(0.015, '2026-06-01', '2031-06-01', [0.008, 0.028]), + ].map(p => ({ ...p, outcome: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/desenlace', code: 'cancer', + display: 'Cáncer cervicouterino por biopsia' }] } })); + data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer }); + data.total = 2; + return data; +} + +export const SIN_ESTIMACION = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; + +/** TEST ONLY. `riesgoCacuConEstimando()` plus a current cancer model that didn't score her: a `RiskAssessment` with + * no prediction, marked `sin-estimacion`. */ +export function riesgoCacuCancerSinEstimar(): any { + const data = riesgoCacuConEstimando(); + const cancer = structuredClone(data.entry[0].resource); + cancer.id = '13-42'; + delete cancer.prediction; + cancer.extension = [{ url: SIN_ESTIMACION, extension: [{ url: 'desenlace', valueCode: 'cancer' }, + { url: 'motivo', valueString: 'queda fuera de su población' }] }]; + data.entry.push({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/13-42', resource: cancer }); + data.total = 2; + return data; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index 446263c..932bf4b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -1,5 +1,5 @@ import { isoDate } from '../cacu-seguimiento.models'; -import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, RiesgoPacienteCacu } from './paciente-riesgo.models'; +import { EstimandoRiesgo, HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice, RiesgoPacienteCacu } from './paciente-riesgo.models'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); @@ -10,7 +10,10 @@ const DAYS_PER_YEAR = 365.25; const INTERVAL = 'https://isssteleon.org/fhir/StructureDefinition/intervalo-confianza'; const SIMULATED = 'simulado'; const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; -const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'interval']; +const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; +const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; +const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph']; +const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit']; function utcTimestamp(v: unknown): v is string { return typeof v === 'string' @@ -41,23 +44,40 @@ function interval(prediction: Record): { ic_bajo: number | null return { ic_bajo: low, ic_alto: high }; } -/** The resource's `estimando` extension: its known keys with a text value; `null` without one. */ -function estimand(resource: Record): EstimandoRiesgo | null { +/** The resource's extension `url` as its known `keys` with a text value; `null` without that extension. */ +function stringExtension(resource: Record, url: string, + keys: readonly K[]): Partial> | null { const extensions = resource['extension']; if (extensions === undefined) return null; if (!Array.isArray(extensions)) invalid(); - const found = extensions.find(e => record(e) && e['url'] === ESTIMAND); + const found = extensions.find(e => record(e) && e['url'] === url); if (found === undefined) return null; if (!Array.isArray(found['extension'])) invalid(); - const result: EstimandoRiesgo = {}; + const result: Partial> = {}; for (const item of found['extension']) { if (!record(item) || !text(item['url'])) invalid(); - const key = item['url'] as keyof EstimandoRiesgo; - if (ESTIMAND_KEYS.includes(key) && text(item['valueString'])) result[key] = item['valueString']; + const key = item['url'] as K; + if (keys.includes(key) && text(item['valueString'])) result[key] = item['valueString']; } return result; } +const estimand = (resource: Record): EstimandoRiesgo | null => + stringExtension(resource, ESTIMAND, ESTIMAND_KEYS); + +/** The `sin-estimacion` extension: the outcome of a current model that didn't score her, and why; `null` without it. */ +function notScoredOutcome(resource: Record): { desenlace: string; motivo: string } | null { + const extensions = resource['extension']; + if (!Array.isArray(extensions)) return null; + const found = extensions.find(e => record(e) && e['url'] === NOT_SCORED); + if (found === undefined) return null; + const items = Array.isArray(found['extension']) ? found['extension'].filter(record) : invalid(); + const desenlace = items.find(i => i['url'] === 'desenlace')?.['valueCode']; + const motivo = items.find(i => i['url'] === 'motivo')?.['valueString']; + if (!text(desenlace)) invalid(); + return { desenlace, motivo: text(motivo) ? motivo : 'el modelo no estima a esta paciente' }; +} + function horizon(prediction: unknown, start: string | undefined): { horizonte: HorizonteRiesgoCacu; start: string } { if (!record(prediction) || !probability(prediction['probabilityDecimal'])) invalid(); const period = prediction['whenPeriod']; @@ -81,6 +101,15 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { const method = v['method']; const model = record(method) && Array.isArray(method['coding']) ? method['coding'][0] : undefined; if (!record(model) || !text(model['code']) || !text(model['version'])) invalid(); + const notScored = notScoredOutcome(v); + if (notScored !== null && v['prediction'] === undefined) { + return { + id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, + fecha_indice: '', evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', + desenlace: notScored.desenlace, desenlace_texto: null, horizontes: [], estimando: estimand(v), + resultados_indice: null, sin_estimacion: notScored.motivo, + }; + } const predictions = v['prediction']; if (!Array.isArray(predictions) || predictions.length === 0) invalid(); let start: string | undefined; @@ -99,7 +128,8 @@ function riskAssessment(v: unknown, pacId: string | null): LoteRiesgoCacu { id: v['id'] as string, modelo_nombre: model['code'] as string, modelo_version: model['version'] as string, fecha_indice: start!, evaluado_en: v['occurrenceDateTime'] as string, estado_lote: v['status'] as 'preliminary' | 'final', desenlace: outcome['code'] as string, desenlace_texto: text(outcome['display']) ? outcome['display'] : null, - horizontes, estimando: estimand(v), + horizontes, estimando: estimand(v), resultados_indice: stringExtension(v, INDEX_RESULTS, INDEX_RESULT_KEYS), + sin_estimacion: null, }; } @@ -108,16 +138,27 @@ function simulated(resource: Record): boolean { return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } -/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`, tagged `simulado` (DEV only). - * `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and malformed fields. */ +/** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ +export function ordenDesenlace(desenlace: string): number { + return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2; +} + +/** Validate at the boundary: a `searchset` Bundle of the patient's `RiskAssessment`s, one per outcome, each tagged + * `simulado` (DEV only), and one with no prediction for a current model that didn't score her. `riesgo` is the first + * that has a risk. `null` when the Bundle is empty (no confirmed risk). Rejects real data, coercions and + * malformed fields. */ export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): RiesgoPacienteCacu | null { if (!record(v) || v['resourceType'] !== 'Bundle' || v['type'] !== 'searchset' || !finite(v['total'])) invalid(); const entries = v['entry'] ?? []; if (!Array.isArray(entries)) invalid(); if (entries.length === 0) return null; - const resource = record(entries[0]) ? entries[0]['resource'] : undefined; - if (!record(resource) || !simulated(resource)) invalid(); - return { simulado: true, riesgo: riskAssessment(structuredClone(resource), pacId) }; + const riesgos = entries.map(entry => { + const resource = record(entry) ? entry['resource'] : undefined; + if (!record(resource) || !simulated(resource)) invalid(); + return riskAssessment(structuredClone(resource), pacId); + }); + riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace)); + return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos }; } /** Presentation helper: an incomplete interval must never become a fabricated range. */ From 4e08bb8c4b4c15d6e1f4e56dec59664ae1ad434b Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 09:35:01 -0600 Subject: [PATCH 17/35] Risk batches: one decision at a time, so a double click doesn't send it twice (cherry picked from commit 88c1eb33be973fbbedb69a820793031cd46fb7ed) --- .../risk-batches-panel.spec.ts | 21 +++++++++++++++++-- .../risk-batches-panel/risk-batches-panel.ts | 3 ++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts b/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts index 5fb0ca6..46297c5 100644 --- a/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts +++ b/src/app/governance/components/risk-batches-panel/risk-batches-panel.spec.ts @@ -1,8 +1,8 @@ // Covers the risk batches panel's domain choice: it lists the pending batches of the domain shown (CaCu first, CaMa on -// request) and decides a batch in that domain. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call, +// request) and decides a batch in that domain, one decision at a time. Fixtures: a stub of `RiskBatchesApi` that records the domain of each call, // and an account that reaches every domain. import { TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; +import { of, Subject } from 'rxjs'; import { vi } from 'vitest'; import { AuthService } from '../../../auth/auth.service'; import { RiskBatchesApi } from '../../api/risk-batches.api'; @@ -45,4 +45,21 @@ describe('RiskBatchesPanel domains', () => { expect(api['confirm']).toHaveBeenCalledExactlyOnceWith('cama', 5, 'revisado'); }); + + // Fails if a double click sends the decision twice: the second one finds nothing to decide or collides with the first. + it('sends one decision while another is on its way', () => { + const answer = new Subject<{ lote_id: number; evaluaciones_cambiadas: number }>(); + api['confirm'].mockReturnValue(answer); + const f = TestBed.createComponent(RiskBatchesPanel); + f.detectChanges(); + const batch = f.componentInstance.batches()[0]; + f.componentInstance.reasonFor(batch).setValue('revisado'); + + f.componentInstance.confirm(batch); + f.componentInstance.confirm(batch); + f.componentInstance.void(batch); + + expect(api['confirm']).toHaveBeenCalledTimes(1); + expect(api['void']).not.toHaveBeenCalled(); + }); }); diff --git a/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts b/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts index 8a0a52e..825bb24 100644 --- a/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts +++ b/src/app/governance/components/risk-batches-panel/risk-batches-panel.ts @@ -111,7 +111,8 @@ export class RiskBatchesPanel implements OnInit { verb: string, ): void { const reason = this.reasonFor(batch).value.trim(); - if (!reason) return; + // a double click reaches here before the disabled button is drawn: one decision at a time + if (!reason || this.deciding() !== null) return; this.deciding.set(batch.lote_id); request(reason).subscribe({ next: () => { From 990cab0e373ef8ad4496cec797576475121df65b Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:04:13 -0600 Subject: [PATCH 18/35] Patient risk: probabilities in percent, survival as such, covariates, and one row per model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The table says its probabilities are percentages (0 to 100 %) with their 95 % interval, and its covariates under it. A model whose estimand asks for its complement (survival from a probability of dying) shows 1 − p with its interval swapped. "Riesgo acumulado" reads "probabilidad". The models' details are a table of one row per model, without the version or the batch state. --- .../paciente-riesgo-cama.spec.ts | 2 +- .../paciente-riesgo-estimando.spec.ts | 50 ++++++++++++++----- .../paciente-riesgo-tabla.html | 48 ++++++++++-------- .../paciente-riesgo-tabla.scss | 2 + .../paciente-detalle/paciente-riesgo-tabla.ts | 3 +- .../paciente-riesgo.models.ts | 6 ++- .../paciente-riesgo.presentacion.ts | 16 ++++-- .../paciente-detalle/paciente-riesgo.spec.ts | 17 ++++--- .../paciente-riesgo.testing.ts | 5 +- .../paciente-riesgo.validation.ts | 14 +++++- 10 files changed, 112 insertions(+), 51 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts index 423dc9d..6e3f422 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-cama.spec.ts @@ -84,7 +84,7 @@ describe('Riesgo individual de la paciente CaMa', () => { expect(text).toContain('17.8 %'); expect(text).toContain('25.1 %'); expect(text).not.toMatch(/Información simulada|Entorno DEV|Sin evaluación clínica/); - expect([...(f.nativeElement as HTMLElement).querySelectorAll('tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); + expect([...(f.nativeElement as HTMLElement).querySelectorAll('table.risk tbody th')].map(th => th.textContent!.trim())).toEqual(['0.5', '1', '1.5']); }); // Fails if the CaMa record goes back to showing the individual risk table, which its two analyses replace. diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index cb6363f..a0d0257 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -5,7 +5,7 @@ import { of } from 'rxjs'; import { PLOTLY_LOADER } from '../../../shared/plotly/plotly-runtime'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { riesgoCacuCancerSinEstimar, riesgoCacuConEstimando, riesgoCacuDosDesenlaces, riesgoCacuEjemplo, riesgoCacuVista } from './paciente-riesgo.testing'; -import { conIntervalo, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { conIntervalo, covariables, encabezado, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; import { figuraRiesgoPaciente } from './paciente-riesgo-figura'; import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; @@ -27,8 +27,8 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('lee el estimando conocido e ignora claves que no conoce (también el método del intervalo, que es del reporte); sin extensión queda en null', () => { expect(riesgoPacienteResponse(riesgoCacuConEstimando(), '42')!.riesgo.estimando).toEqual({ - quantity: 'Riesgo acumulado', description: 'Probabilidad de CIN2+ antes de cada horizonte.', - outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años' }); + quantity: 'Probabilidad', description: 'Probabilidad de CIN2+ antes de cada horizonte.', + outcome: 'CIN2+: biopsia LIEAG, CIS o carcinoma', horizons_unit: 'años', covariates: 'VPH y citología índice' }); expect(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')).toEqual(riesgoCacuVista()); }); @@ -40,7 +40,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('nombra el número, su desenlace y la unidad de los horizontes en la ficha', () => { const { root } = setup(riesgoCacuConEstimando()); - expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim())) .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); expect(root.querySelector('details.risk-details summary')!.textContent).toContain('Detalle del modelo'); for (const value of ['Qué se estima', 'CIN2+: biopsia LIEAG, CIS o carcinoma']) { @@ -52,7 +52,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('dibuja la curva solo al abrir su sección', async () => { const { fixture, root } = setup(riesgoCacuConEstimando()); const details = root.querySelector('details.risk-curve') as HTMLDetailsElement; - expect(details.querySelector('summary')!.textContent).toContain('Curva de riesgo acumulado'); + expect(details.querySelector('summary')!.textContent).toContain('Curva de probabilidad'); expect(root.querySelector('app-plotly-chart')).toBeNull(); details.open = true; details.dispatchEvent(new Event('toggle')); @@ -66,7 +66,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { expect(banda.data).toHaveLength(3); expect(banda.data[2]['y']).toEqual([8, 21, 34]); expect(banda.data[1]['y']).toEqual([5, 15, 26]); - expect((banda.layout['yaxis'] as any).title.text).toBe('Riesgo acumulado (%)'); + expect((banda.layout['yaxis'] as any).title.text).toBe('Probabilidad (%)'); const parcial = { ...riesgo, horizontes: riesgo.horizontes.map((h, i) => i === 0 ? { ...h, ic_bajo: null, ic_alto: null } : h) }; const barras = figuraRiesgoPaciente([parcial]); @@ -76,9 +76,9 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('pone una columna por desenlace, LIEAG+ primero, con el IC entre paréntesis', () => { const { root } = setup(riesgoCacuDosDesenlaces()); - expect([...root.querySelectorAll('thead th')].map(th => th.textContent!.trim())) + expect([...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim())) .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); - const fila = [...root.querySelectorAll('tbody tr')][2]; + const fila = [...root.querySelectorAll('table.risk tbody tr')][2]; expect([...fila.querySelectorAll('td')].map(td => td.textContent!.replace(/\s+/g, ' ').trim())) .toEqual(['34 % (26 – 44 %)', '1.5 % (0.8 – 2.8 %)']); }); @@ -86,8 +86,8 @@ describe('Riesgo individual: qué se estima y su curva', () => { it('la frase dice los resultados índice y los dos riesgos al horizonte más largo, respectivamente', () => { const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; expect(riesgos.map(r => r.desenlace)).toEqual(['cin2_mas', 'cancer']); - expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen un riesgo ' - + 'acumulado a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + expect(fraseRiesgo(riesgos)).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) tienen una probabilidad ' + + 'a 5 años de estar presente o de aparecer LIEAG+ y cáncer de 34 % (26 – 44 %) y 1.5 % (0.8 – 2.8 %), ' + 'respectivamente.'); expect(fraseRiesgo(riesgoPacienteResponse(riesgoCacuEjemplo(), '42')!.riesgos)).toBeNull(); }); @@ -113,19 +113,19 @@ describe('Riesgo individual: qué se estima y su curva', () => { const muerte = { ...riesgos[1], desenlace: 'muerte', fecha_indice: '2024-03-01' }; expect(encabezado(muerte, riesgos[0].fecha_indice)).toBe('Probabilidad a muerte desde 2024-03-01'); expect(fraseRiesgo([riesgos[0], muerte])).toBe('Un resultado de VPH positivo y una citología LIEBG (2026-06-01) ' - + 'tienen un riesgo acumulado a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); + + 'tienen una probabilidad a 5 años de estar presente o de aparecer LIEAG+ de 34 % (26 – 44 %).'); }); it('sin modelo de un desenlace su columna dice No disponible', () => { const { root } = setup(riesgoCacuConEstimando()); - const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); expect(celdas).toEqual(['No disponible', 'No disponible', 'No disponible']); }); it('con un modelo que no la estima su columna lo dice, con el motivo, y no entra en la curva ni en la frase', () => { const data = riesgoCacuCancerSinEstimar(); const { root } = setup(data); - const celdas = [...root.querySelectorAll('tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); + const celdas = [...root.querySelectorAll('table.risk tbody tr')].map(tr => tr.querySelectorAll('td')[1].textContent!.trim()); expect(celdas).toEqual(['No estimada para su grupo', 'No estimada para su grupo', 'No estimada para su grupo']); expect(root.querySelector('.unavailable-note')!.textContent).toContain('queda fuera de su población'); const { riesgos, riesgo } = riesgoPacienteResponse(data, '42')!; @@ -134,4 +134,28 @@ describe('Riesgo individual: qué se estima y su curva', () => { expect(figuraRiesgoPaciente(riesgos.filter(r => r.horizontes.length)).data.filter(t => t['mode'] === 'lines+markers')) .toHaveLength(1); }); + + it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido', () => { + const data = riesgoCacuConEstimando(); + const r = data.entry[0].resource; + r.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' }); + r.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; }); + const lote = riesgoPacienteResponse(data, '42')!.riesgo; + expect(lote.horizontes[0]).toMatchObject({ horizonte_anios: 1 }); + expect(lote.horizontes[0].probabilidad).toBeCloseTo(0.92); + expect(lote.horizontes[0].ic_bajo).toBeCloseTo(0.88); + expect(lote.horizontes[0].ic_alto).toBeCloseTo(0.95); + expect(encabezado(lote)).toBe('Probabilidad de supervivencia'); + }); + + it('pone las covariables al pie de la tabla y el detalle en una fila por modelo, sin versión ni estado', () => { + const { root } = setup(riesgoCacuDosDesenlaces()); + expect(root.querySelector('.covariates-note')!.textContent).toBe('Covariables: VPH y citología índice.'); + expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(2); + expect(root.textContent).not.toMatch(/Versión del modelo|Estado del lote/); + expect(root.querySelector('caption')!.textContent).toContain('Probabilidad en porcentaje (0 a 100 %)'); + const { riesgos } = riesgoPacienteResponse(riesgoCacuDosDesenlaces(), '42')!; + riesgos[1].estimando = { ...riesgos[1].estimando, covariates: 'otras' }; + expect(covariables(riesgos)).toBe('Covariables: Probabilidad a LIEAG+: VPH y citología índice; Probabilidad a cáncer: otras.'); + }); }); 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 6cbd5f0..5416dfd 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -14,9 +14,9 @@ @let filas = filasDe(lotesDe(columnas)); @if (filas.length) {
- - +
{{ riesgo.estimando?.quantity ?? 'Probabilidad' }} por horizonte desde la fecha índice - ({{ riesgo.fecha_indice }}), con su intervalo de confianza entre paréntesis
+ @for (c of columnas; track c.encabezado) { } @@ -36,25 +36,31 @@ @for (c of columnas; track c.encabezado) { @if (c.lote?.sin_estimacion; as motivo) {

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

} } + @if (covariables(riesgos); as texto) {

{{ texto }}

}
Detalle del modelo - @for (r of riesgos; track r.id) { - @if (riesgos.length > 1) {
{{ encabezado(r) }}
} - - } +
+
Probabilidad en porcentaje (0 a 100 %) por horizonte desde la fecha índice + ({{ riesgo.fecha_indice }}), con su intervalo de confianza de 95 % entre paréntesis
Horizonte ({{ riesgo.estimando?.horizons_unit ?? 'años' }}){{ c.encabezado }} (%)
+ + + + + + + @for (r of riesgos; track r.id) { + + + + + + + + + + } + +
ProbabilidadModeloQué se estimaDesenlaceDesdeFecha índiceEvaluado en
{{ encabezado(r) }}{{ r.modelo_nombre }}{{ r.estimando?.description ?? '—' }}{{ r.estimando?.outcome ?? r.desenlace_texto ?? r.desenlace }}{{ r.estimando?.index_date ?? '—' }}{{ r.fecha_indice }}
+
@if (filas.length > 1) {
@@ -62,7 +68,7 @@ @if (frase(riesgos); as texto) {

{{ texto }}

} @if (curvaAbierta()) { + [label]="'Curvas de probabilidad individual ' + rotulo() + ' por horizonte'" /> }
} 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 768e31a..5b1677d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.scss @@ -24,3 +24,5 @@ tbody tr:last-child > * { border-bottom: 0; } .risk-details h6 { margin: .75rem 0 .25rem; font-size: .95rem; } .unavailable { color: var(--issste-text-secondary); } .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; } 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 1cb53c2..0fa8ab7 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -3,7 +3,7 @@ import { LowerCasePipe } 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, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { ColumnaRiesgo, columnasRiesgo, conRiesgo, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -39,6 +39,7 @@ export class PacienteRiesgoTabla { readonly frase = fraseRiesgo; readonly filasDe = filasRiesgo; readonly conRiesgo = conRiesgo; + readonly covariables = covariables; columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); } lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); } private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 9da4a44..f2bf13e 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -16,13 +16,17 @@ export interface HorizonteRiesgoCacu { /** What the model's number is (the scenario's `[estimand]`, extension `estimando`); each field may be missing. */ export interface EstimandoRiesgo { - /** e.g. "Riesgo acumulado"; also `method.text`. */ + /** e.g. "Probabilidad"; also `method.text`. */ quantity?: string; description?: string; outcome?: string; index_date?: string; /** The unit the horizons are counted in, e.g. "años". */ horizons_unit?: string; + /** The variables the model uses, in words, as the record writes them under the table. */ + covariates?: string; + /** `supervivencia`: the model gives the probability of the outcome (dying) and the record shows its complement. */ + complement?: string; } /** The results of the cytology sampled on the risk's index date (extension `resultados-indice`), as recorded. */ 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 f31c557..da9a3ee 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -5,7 +5,7 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; export function etiquetaDesenlace(lote: LoteRiesgoCacu): string { if (lote.desenlace.startsWith('cin2')) return 'LIEAG+'; if (lote.desenlace === 'cancer') return 'cáncer'; - if (lote.desenlace === 'muerte') return 'muerte'; + if (lote.desenlace === 'muerte') return lote.estimando?.complement === 'supervivencia' ? 'supervivencia' : 'muerte'; return lote.desenlace_texto ?? lote.desenlace; } @@ -13,7 +13,8 @@ export function etiquetaDesenlace(lote: LoteRiesgoCacu): string { * `fechaComun` (a survival model counts from the invasive biopsy, not from the cytology). */ export function encabezado(lote: LoteRiesgoCacu, fechaComun: string | null = null): string { const desde = fechaComun && lote.fecha_indice !== fechaComun ? ` desde ${lote.fecha_indice}` : ''; - return `Probabilidad a ${etiquetaDesenlace(lote)}${desde}`; + const etiqueta = etiquetaDesenlace(lote); + return `${etiqueta === 'supervivencia' ? 'Probabilidad de supervivencia' : `Probabilidad a ${etiqueta}`}${desde}`; } /** A probability as a percentage with the decimals a small risk needs, without trailing zeros: 0.178 -> "17.8", @@ -110,6 +111,15 @@ export function fraseRiesgo(todos: LoteRiesgoCacu[]): string | null { const desenlaces = junta(riesgos.map(etiquetaDesenlace)); const valores = junta(ultima.celdas.map(c => conIntervalo(c!))); const anios = ultima.horizonte_anios === 1 ? '1 año' : `${ultima.horizonte_anios} años`; - return `${inicio} (${fecha}) tienen un riesgo acumulado a ${anios} de estar presente o de aparecer ${desenlaces} ` + return `${inicio} (${fecha}) tienen una probabilidad a ${anios} de estar presente o de aparecer ${desenlaces} ` + `de ${valores}${riesgos.length > 1 ? ', respectivamente' : ''}.`; } + +/** The covariates under the table: each model's, by its column, or once when every model uses the same ones. */ +export function covariables(riesgos: LoteRiesgoCacu[]): string | null { + const con = riesgos.filter(r => r.estimando?.covariates); + if (!con.length) return null; + const textos = [...new Set(con.map(r => r.estimando!.covariates!))]; + if (textos.length === 1) return `Covariables: ${textos[0]}.`; + return `Covariables: ${con.map(r => `${encabezado(r)}: ${r.estimando!.covariates}`).join('; ')}.`; +} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 684d4e0..f8cb645 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -45,13 +45,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { const f = setup({ obtener }), root: HTMLElement = f.nativeElement; expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); // horizon, CIN2+ (LIEAG+) and cancer (without a model here: "No disponible"), each risk with its interval - expect(root.querySelectorAll('thead th')).toHaveLength(3); - expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); - expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); + expect(root.querySelectorAll('table.risk thead th')).toHaveLength(3); + expect([...root.querySelectorAll('table.risk thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); + expect(root.querySelectorAll('table.risk tbody th[scope="row"]')).toHaveLength(3); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']); expect(root.querySelector('.interval')!.textContent).toContain('(5 – 12 %)'); - expect(root.textContent).toContain('Final (final)'); - for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { + // the record names the model, its index date and outcome, not its version nor the batch's state + expect(root.textContent).not.toMatch(/Final \(final\)|2\.1\.0/); + for (const value of ['modelo-cacu', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) { expect(root.textContent).toContain(value); } // The record no longer shows the cohort's internals (its definition, version or model variables). @@ -73,7 +74,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(getComputedStyle(scroll).overflow).toBe('auto'); expect(getComputedStyle(scroll).maxWidth).toBe('100%'); expect(getComputedStyle(root.querySelector('table')!).minWidth).toBe('36rem'); - expect(getComputedStyle(root.querySelector('thead th')!).position).toBe('sticky'); + expect(getComputedStyle(root.querySelector('table.risk thead th')!).position).toBe('sticky'); }); it('renderiza horizontes parciales/dinámicos y extremos cero y uno con IC opcionales', () => { @@ -85,10 +86,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { prediccion(0.00123, '2026-06-01', '2038-09-01'), ]; const f = setup({ obtener: () => of(data) }), root: HTMLElement = f.nativeElement; - expect([...root.querySelectorAll('tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); + expect([...root.querySelectorAll('table.risk tbody th')].map(c => c.textContent!.trim())).toEqual(['0.5', '8', '12.25']); expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['0 %', '100 %', '0.123 %']); expect([...root.querySelectorAll('.interval')].map(c => c.textContent!.trim())).toEqual(['(0 – 0 %)', '(IC no disponible)', '(IC no disponible)']); - expect(root.textContent).toContain('Preliminar (preliminary)'); + expect(root.textContent).not.toContain('Preliminar (preliminary)'); }); it.each([[[]], [[{ code: 'real' }]], [undefined]])('no expone una respuesta no simulada (%j)', tag => { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts index c3d0eea..e69b7b6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.testing.ts @@ -57,9 +57,10 @@ export function riesgoCacuVista(): RiesgoPacienteCacu { export function riesgoCacuConEstimando(): any { const data = riesgoCacuEjemplo(); const resource = data.entry[0].resource; - resource.method.text = 'Riesgo acumulado'; + resource.method.text = 'Probabilidad'; resource.extension = [{ url: ESTIMANDO, extension: [ - { url: 'quantity', valueString: 'Riesgo acumulado' }, + { url: 'quantity', valueString: 'Probabilidad' }, + { url: 'covariates', valueString: 'VPH y citología índice' }, { url: 'description', valueString: 'Probabilidad de CIN2+ antes de cada horizonte.' }, { url: 'outcome', valueString: 'CIN2+: biopsia LIEAG, CIS o carcinoma' }, { url: 'horizons_unit', valueString: 'años' }, diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index 932bf4b..46e826d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -13,7 +13,7 @@ const ESTIMAND = 'https://isssteleon.org/fhir/StructureDefinition/estimando'; const NOT_SCORED = 'https://isssteleon.org/fhir/StructureDefinition/sin-estimacion'; const INDEX_RESULTS = 'https://isssteleon.org/fhir/StructureDefinition/resultados-indice'; const INDEX_RESULT_KEYS: readonly (keyof ResultadosIndice)[] = ['escamosas', 'glandulares', 'vph']; -const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit']; +const ESTIMAND_KEYS: readonly (keyof EstimandoRiesgo)[] = ['quantity', 'description', 'outcome', 'index_date', 'horizons_unit', 'covariates', 'complement']; function utcTimestamp(v: unknown): v is string { return typeof v === 'string' @@ -138,6 +138,17 @@ function simulated(resource: Record): boolean { return record(meta) && Array.isArray(meta['tag']) && meta['tag'].some(t => record(t) && t['code'] === SIMULATED); } +/** A model whose estimand asks for its complement (survival from a probability of dying): each horizon becomes + * 1 − p, and its interval 1 − high to 1 − low. */ +function complemento(lote: LoteRiesgoCacu): void { + if (lote.estimando?.complement !== 'supervivencia') return; + lote.horizontes = lote.horizontes.map(h => ({ + ...h, probabilidad: 1 - h.probabilidad, + ic_bajo: h.ic_alto == null ? h.ic_alto ?? null : 1 - h.ic_alto, + ic_alto: h.ic_bajo == null ? h.ic_bajo ?? null : 1 - h.ic_bajo, + })); +} + /** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ export function ordenDesenlace(desenlace: string): number { return desenlace.startsWith('cin2') ? 0 : desenlace === 'cancer' ? 1 : 2; @@ -157,6 +168,7 @@ export function riesgoPacienteResponse(v: unknown, pacId: string | null = null): if (!record(resource) || !simulated(resource)) invalid(); return riskAssessment(structuredClone(resource), pacId); }); + riesgos.forEach(complemento); riesgos.sort((a, b) => ordenDesenlace(a.desenlace) - ordenDesenlace(b.desenlace)); return { simulado: true, riesgo: riesgos.find(r => r.horizontes.length) ?? riesgos[0], riesgos }; } From 68b5e927e7833e159edea0fae4ff3503f3d773df Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:04:13 -0600 Subject: [PATCH 19/35] CaCu follow-up table: the latest biopsy, and the probabilities of the status filtered A column with each patient's latest biopsy. The probability columns follow the follow-up status chosen, its scenario's models: a case shows survival, pre-colposcopy LIEAG+ and cancer, post-colposcopy and post-treatment LIEAG+, every patient none. A horizon selector, and an order by the most recent study or one of the columns shown, which the API applies to the whole list. --- .../indicadores/cacu-seguimiento.models.ts | 25 +++++++++- .../indicadores/cacu-seguimiento.service.ts | 15 +++++- .../indicadores/cacu-seguimiento.spec.ts | 48 ++++++++++++++++++- .../indicadores/indicadores-tracking.html | 18 ++++++- .../indicadores/indicadores-tracking.ts | 34 +++++++++++-- 5 files changed, 131 insertions(+), 9 deletions(-) diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index 4fbd27f..40e7fad 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,4 +1,6 @@ -export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } +export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia'; +export type OrdenSeguimiento = 'reciente' | ProbabilidadClave; +export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } // A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`. export interface SeguimientoPaciente { @@ -9,13 +11,20 @@ export interface SeguimientoPaciente { ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null; dias_toma_diagnostico: number | null; + /** CaCu: her latest biopsy reported by the cut-off, with its grade. */ + ultima_biopsia?: { fecha: string; grado: string | null } | null; + /** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */ + probabilidades?: Partial> | null; prioridad: SeguimientoStatus | null; } +export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; } export interface SeguimientoResponse { simulado: boolean; corte: string; ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string }; - filtros: { estatus: string | null }; + filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number }; + /** The horizons the models give, in years, for ordering and showing the probabilities. */ + horizontes_disponibles?: number[]; estatus_disponibles: SeguimientoStatus[]; reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[]; paginacion: { page: number; page_size: number; total_items: number; total_pages: number }; @@ -29,3 +38,15 @@ export function isoDate(value: unknown): value is string { export function latestStudy(item: SeguimientoPaciente): string | null { return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null; } +/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */ +export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined { + return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte); +} +/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival). + * Every patient or an unknown status shows none: each scenario has its own models. */ +export const COLUMNAS_DE_PROBABILIDAD: Readonly> = { + CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'], +}; +export const ETIQUETA_PROBABILIDAD: Readonly> = { + lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia', +}; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index d073b33..a1e68fc 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -7,6 +7,14 @@ import { PAGE_SIZE_MAX } from './seguimiento-tabla.service'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; +const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia']; +const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0; +const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1; +// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates. +const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string'); +const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) => + ['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad']) + && (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto'])))); export function validSeguimientoQuery(q: SeguimientoQuery) { return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX; } @@ -17,6 +25,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const p = v['paginacion'], window = v['ventana'], filters = v['filtros']; if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta']) || !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string') + || (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string)) + || (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios))) || !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status) || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages']) @@ -25,7 +35,8 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { const c = item['ultima_citologia'], h = item['ultimo_vph']; return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) - && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); + && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])) + && biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades']); }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @@ -37,6 +48,8 @@ export class CacuSeguimientoService { let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size); if (query.corte) params = params.set('corte', query.corte); if (query.estatus) params = params.set('estatus', query.estatus); + if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden); + if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte); return this.http.get('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse)); } } diff --git a/src/app/features/indicadores/cacu-seguimiento.spec.ts b/src/app/features/indicadores/cacu-seguimiento.spec.ts index 679d629..e9e24c6 100644 --- a/src/app/features/indicadores/cacu-seguimiento.spec.ts +++ b/src/app/features/indicadores/cacu-seguimiento.spec.ts @@ -42,7 +42,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => { expect(root.textContent).toContain('Insatisfactoria'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte'); expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte'); - expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8); + expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9); expect(root.querySelector('form input[name="corte"]')).not.toBeNull(); expect(root.querySelector('form select[name="meses"]')).not.toBeNull(); expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull(); @@ -97,4 +97,50 @@ describe('Seguimiento CaCu con contrato de demostración', () => { for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow(); http.expectNone(()=>true); }); + // Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the + // horizon stop reaching the API (the list is paginated, so ordering happens there). + it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' }, + probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 }, + { horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }], + cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] }, + } : item); + const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } }; + open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const fila = root.querySelector('tbody tr')!; + expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %'); + expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)'); + expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']); + + fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1'); + req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges(); + expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)'); + }); + + // Fails if the columns stop following the status filtered: each scenario has its own models. + it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => { + const items = fixtureData.items.map((item: any, i: number) => i === 0 ? { + ...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' }, + probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item); + const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } }; + open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim()); + expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)'); + expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false); + expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)'); + expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']); + + fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia'; + fixture.componentInstance.apply(); + const req = http.expectOne(r => r.url === '/cacu/seguimiento'); + expect(req.request.params.has('orden')).toBe(false); + req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges(); + expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false); + expect(root.querySelector('select[name="orden"]')).toBeNull(); + }); }); diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 0ad6b25..0af754a 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -48,6 +48,18 @@ @for (t of tiposAlteracion; track t.codigo) { } } + @if (dominio === 'cacu') { + @if (columnasDelEstatus(draft.estatus).length) { + + } + @if (columnasDelEstatus(draft.estatus).length) { + + } + } @@ -107,16 +119,18 @@
- + @for (c of columnasProbabilidad(); track c) {} @for (item of response.items; track identidad(item).id) { + + @for (c of columnasProbabilidad(); track c) { } - } @empty { } + } @empty { }
Resultados disponibles por paciente
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHÚltima biopsia{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)Estudio más recienteDías de toma a diagnósticoPrioridad
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible }@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}Fecha: {{ b.fecha }} } @else { No disponible }{{ probabilidad(item, c) ?? 'No disponible' }}{{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
No hay registros para los filtros aplicados.
No hay registros para los filtros aplicados.
diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 3c6d847..d49291a 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -5,7 +5,8 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, defer, map, of, Subject, switchMap } from 'rxjs'; import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service'; import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service'; -import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { COLUMNAS_DE_PROBABILIDAD, ETIQUETA_PROBABILIDAD, latestStudy, probabilidadAl, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models'; +import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion'; import { MatButtonModule } from '@angular/material/button'; import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; @@ -64,6 +65,28 @@ export class IndicadoresTracking implements OnChanges { private metadataLoaded = false; categories: Record = {}; draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 }; + /** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */ + horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; } + horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; } + readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD; + /** The probability columns of a follow-up status (its scenario's models); none for every patient. */ + columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] { + return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : []; + } + /** The probability columns of the list shown: those of the status it was filtered by. */ + columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); } + /** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */ + ordenes(): { codigo: string; etiqueta: string }[] { + return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' }, + ...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))]; + } + /** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */ + probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave): string | null { + const h = probabilidadAl(item, clave, this.horizonteMostrado()); + if (!h) return null; + const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : ''; + return `${porcentaje(h.probabilidad)} %${ic}`; + } private applied: SeguimientoQuery = { ...this.draft }; readonly latestStudy = latestStudy; readonly gruposEdad = GRUPOS_EDAD_TEA; @@ -87,7 +110,7 @@ export class IndicadoresTracking implements OnChanges { if (result.data) { const data = result.data; this.statuses = data.estatus_disponibles; - this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size }; + this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size }; this.draft = { ...this.applied }; if (!this.metadataLoaded) { this.metadataLoaded = true; @@ -131,7 +154,12 @@ export class IndicadoresTracking implements OnChanges { this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q }; (this.dominio === 'tea' ? this.teaRequests : this.requests).next(q); } - apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); } + apply() { + this.draft.page_size = acotarTamano(this.draft.page_size); + // an order by a column the chosen status doesn't show goes back to the most recent study + if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente'; + this.load({ ...this.draft, page: 1 }); + } retry() { this.load(this.applied); } navigate(page: number) { if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return; From 396902541deda5d190b9e3d5e9eb4b8960b0d3f3 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:38:12 -0600 Subject: [PATCH 20/35] CaCu history: the screening-to-treatment time panel draws its measure `CACU-DIAS-TOMA-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it, and the panel specs count the active and reserved panels from their lists. --- .../fixtures/cacu_fhir_measures.json | 119 +++++++++++++++++- .../indicadores/indicadores-cacu-fhir.spec.ts | 4 +- .../indicadores-historico-cacu-fhir.spec.ts | 4 +- ...indicadores-historico-cacu-paneles.spec.ts | 31 ++--- .../indicadores-historico-config.ts | 5 +- 5 files changed, 140 insertions(+), 23 deletions(-) diff --git a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json index d4126ee..9684288 100644 --- a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json +++ b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json @@ -1,7 +1,7 @@ { "resourceType": "Bundle", "type": "searchset", - "total": 7, + "total": 8, "link": [ { "relation": "self", @@ -414,6 +414,123 @@ "mode": "match" } }, + { + "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO", + "resource": { + "resourceType": "Measure", + "id": "CACU-DIAS-TOMA-TRATAMIENTO", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/contrato", + "valueCode": "C3r" + }, + { + "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_c3r_caja" + } + ], + "url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO", + "version": "0.1.0", + "name": "cacu_dias_toma_tratamiento", + "title": "Tiempo de tamizaje a tratamiento", + "status": "active", + "subjectCodeableConcept": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/unidad", + "code": "examen" + } + ] + }, + "description": "Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del realizado.", + "scoring": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-scoring", + "code": "continuous-variable" + } + ] + }, + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + }, + "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" + } + ] + }, + "description": "Unidades del periodo", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "description": "Unidades con valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-population-exclusion" + } + ] + }, + "description": "Unidades sin valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_toma_tratamiento" + } + } + ] + } + ] + }, + "search": { + "mode": "match" + } + }, { "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-EU-TIEMPO-REPORTE", "resource": { diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index a4a773b..1a367e7 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -107,13 +107,13 @@ const reporteDe = (m: Measure, conteos: number[]): Report => ({ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => { it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => { - // Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none + // Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none // yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not // checked against the renderer. const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras])); expect(figuras).toEqual({ cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'], - cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], + cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], cacu_riesgo_banda: [], ind1: [], }); }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 7236108..9daec48 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -96,7 +96,8 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { // the page gives it, and with the contract the panel expects. const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); - expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']); + expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', + 'cacu_dias_toma_tratamiento']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); @@ -105,7 +106,6 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'], ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'], ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], ]); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index c4c80d1..0b5330e 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -19,8 +19,9 @@ const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStar const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1']; const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; -const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']; -const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', + 'cacu_dias_toma_tratamiento']; +const RESERVADOS = ['cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); @@ -95,21 +96,21 @@ describe('Histórico de CaCu', () => { expect([...vistos].sort()).toEqual([...ACTIVOS].sort()); for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false); }); - it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => { + it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => { montar(CATALOGO, true); responder(); expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo)); expect(paneles()).toHaveLength(9); - expect(graficas()).toHaveLength(6); - const reservados = paneles().slice(6); + expect(graficas()).toHaveLength(ACTIVOS.length); + const reservados = paneles().slice(ACTIVOS.length); expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true); expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual( - HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo'])); + HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo'])); }); it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => { // Pins down: the state of a reserved panel comes from the config alone. for (const catalogo of [ACTIVOS.map(item), CATALOGO]) { montar(catalogo, true); responder(); - expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo')); + expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo')); fixture.destroy(); TestBed.resetTestingModule(); } }); @@ -122,7 +123,7 @@ describe('Histórico de CaCu', () => { it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => { // Pins down the first request: the page asks for the latest five months, not the twelve it could. montar(CATALOGO, true); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)'); }); @@ -130,7 +131,7 @@ describe('Histórico de CaCu', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7)); expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)'); expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12); @@ -176,7 +177,7 @@ describe('Histórico de CaCu', () => { montar(CATALOGO, true); responder(); pedidos.length = 0; fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder(); - expect(pedidos).toHaveLength(6); + expect(pedidos).toHaveLength(ACTIVOS.length); for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5)); pedidos.length = 0; fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder(); @@ -188,7 +189,7 @@ describe('Histórico de CaCu', () => { const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo'); expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); }); it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => { montar(CATALOGO, true); @@ -196,17 +197,17 @@ describe('Histórico de CaCu', () => { const panel = panelDe(tituloDe('cacu_eu13')); expect(panel.querySelector('[role="alert"]')).not.toBeNull(); expect(panel.textContent).not.toContain('private'); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); const reintentar = panel.querySelector('button') as HTMLButtonElement; reintentar.click(); fixture.detectChanges(); responder(); - expect(graficas()).toHaveLength(6); + expect(graficas()).toHaveLength(ACTIVOS.length); }); it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => { // Pins down the expected contract: the panel does not draw a C1 where it declared a composition. montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} }); const panel = panelDe(tituloDe('cacu_eu7')); expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1'); - expect(graficas()).toHaveLength(5); + expect(graficas()).toHaveLength(ACTIVOS.length - 1); }); it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => { montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} }); @@ -226,7 +227,7 @@ describe('Histórico de CaCu', () => { } }); it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => { - montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true); + montar(RESERVADOS.map(item), true); expect(paneles()).toHaveLength(9); expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 6de8005..3025d8c 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -42,7 +42,7 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, ]; -// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved. +// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask. export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' }, @@ -50,8 +50,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' }, { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', - enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] }, + { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] }, { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', From eada50d2ff92aa7ba07329b62a25290b96313aa5 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:38:55 -0600 Subject: [PATCH 21/35] CaCu history: the diagnosis-to-treatment time panel draws its measure `CACU-DIAS-DIAGNOSTICO-TRATAMIENTO` is published with reports, so its panel reads it like the other active ones instead of showing "Trabajo en desarrollo". The catalog fixture gains the measure as the WebApi serves it. --- .../fixtures/cacu_fhir_measures.json | 119 +++++++++++++++++- .../indicadores/indicadores-cacu-fhir.spec.ts | 3 +- .../indicadores-historico-cacu-fhir.spec.ts | 3 +- ...indicadores-historico-cacu-paneles.spec.ts | 4 +- .../indicadores-historico-config.ts | 3 +- 5 files changed, 124 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json index 9684288..bb879ea 100644 --- a/src/app/features/indicadores/fixtures/cacu_fhir_measures.json +++ b/src/app/features/indicadores/fixtures/cacu_fhir_measures.json @@ -1,7 +1,7 @@ { "resourceType": "Bundle", "type": "searchset", - "total": 8, + "total": 9, "link": [ { "relation": "self", @@ -297,6 +297,123 @@ "mode": "match" } }, + { + "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "resource": { + "resourceType": "Measure", + "id": "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "extension": [ + { + "url": "https://isssteleon.org/fhir/StructureDefinition/contrato", + "valueCode": "C3r" + }, + { + "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_c3r_caja" + } + ], + "url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO", + "version": "0.1.0", + "name": "cacu_dias_diagnostico_tratamiento", + "title": "Tiempo de diagnóstico a tratamiento", + "status": "active", + "subjectCodeableConcept": { + "coding": [ + { + "system": "https://isssteleon.org/fhir/CodeSystem/unidad", + "code": "examen" + } + ] + }, + "description": "Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.", + "scoring": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-scoring", + "code": "continuous-variable" + } + ] + }, + "improvementNotation": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation", + "code": "decrease" + } + ] + }, + "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" + } + ] + }, + "description": "Unidades del periodo", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-observation" + } + ] + }, + "description": "Unidades con valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + }, + { + "code": { + "coding": [ + { + "system": "http://terminology.hl7.org/CodeSystem/measure-population", + "code": "measure-population-exclusion" + } + ] + }, + "description": "Unidades sin valor", + "criteria": { + "language": "text/x-dbt-metric", + "expression": "cacu_dias_diagnostico_tratamiento" + } + } + ] + } + ] + }, + "search": { + "mode": "match" + } + }, { "fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-DIAGNOSTICO", "resource": { diff --git a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts index 1a367e7..1e506b9 100644 --- a/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-fhir.spec.ts @@ -112,7 +112,8 @@ describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas // checked against the renderer. const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras])); expect(figuras).toEqual({ - cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'], + cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'], + cacu_dias_toma_diagnostico: ['fig_c3r_caja'], cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'], cacu_riesgo_banda: [], ind1: [], }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 9daec48..8d04acf 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -97,7 +97,7 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento']); + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); @@ -106,7 +106,6 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'], ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], ]); // The risk bands are in the catalog and stay reserved. diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 0b5330e..43d11fe 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -20,8 +20,8 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025- const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento']; -const RESERVADOS = ['cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']; +const RESERVADOS = ['cacu_riesgo_banda']; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 3025d8c..479f657 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -51,8 +51,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana', - enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] }, + { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] }, ]; From 2a36397fac3574565bef5dff41a06a8597e22cbe Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:39:42 -0600 Subject: [PATCH 22/35] CaCu history: the CIN2+ risk-band panel draws its measure `CACU-RIESGO-BANDA` is published, so its panel reads it like the others; it counts the patients of the confirmed risk batches, and is empty until one is confirmed. No CaCu history panel stays reserved. --- .../indicadores-historico-cacu-fhir.spec.ts | 11 ++++------- .../indicadores-historico-cacu-paneles.spec.ts | 4 ++-- .../indicadores/indicadores-historico-config.ts | 3 +-- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts index 8d04acf..8ad15ca 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-fhir.spec.ts @@ -97,18 +97,15 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => { const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)])); const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo); expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']); + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']); for (const panel of activos) { expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id); expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato); } }); - it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => { - const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo); - expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([ - ['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'], - ]); - // The risk bands are in the catalog and stay reserved. + it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => { + // Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure. + expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]); expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda'); }); }); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 43d11fe..40e88fc 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -20,8 +20,8 @@ const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025- const CONTRATOS: Record = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r', cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' }; const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico', - 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento']; -const RESERVADOS = ['cacu_riesgo_banda']; + 'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']; +const RESERVADOS: string[] = []; const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; // Every measure the catalog could publish, reserved ones included: publishing them must not activate them. const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item); diff --git a/src/app/features/indicadores/indicadores-historico-config.ts b/src/app/features/indicadores/indicadores-historico-config.ts index 479f657..ffce074 100644 --- a/src/app/features/indicadores/indicadores-historico-config.ts +++ b/src/app/features/indicadores/indicadores-historico-config.ts @@ -52,8 +52,7 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [ { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' }, - { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas', - enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] }, + { id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' }, ]; const HISTORICOS: Readonly>> = { From ec5b8fde6b939c8fa7e62a4948ebb831e284266f Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 15:54:54 -0600 Subject: [PATCH 23/35] CaCu treatment time cards: no provisional notice under the value --- .../features/indicadores/indicadores-kpi-tratamiento.spec.ts | 3 ++- src/app/features/indicadores/indicadores-kpi.ts | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts b/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts index a2850a3..f40ff6c 100644 --- a/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-tratamiento.spec.ts @@ -78,7 +78,8 @@ describe('KPI de tratamiento de CaCu', () => { expect(cards[0].querySelector('.value')).toBeNull(); expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75'); expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD); - expect(cards[1].textContent).toContain('El evento de tratamiento se infiere de notas clínicas'); + // the cards carry no provisional notice: what the measure is lives in its technical sheet + expect(cards[1].textContent).not.toContain('Indicador provisional'); expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento'); expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull(); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 86b0443..1278d29 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -22,7 +22,6 @@ const CACU_TRATAMIENTO_C3R = { unit: 'días (mediana)', requiresObservations: true, c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`, - note: 'Indicador provisional. El evento de tratamiento se infiere de notas clínicas, sin confirmación de que se realizó.', } satisfies Omit; export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [ From 253290ed6ae507b62ac622224253d27ea2bde024 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 16:04:04 -0600 Subject: [PATCH 24/35] fix(tea): ajustar indicadores, trazabilidad y etiquetas de riesgo --- .../indicadores/indicadores-fhir.spec.ts | 19 +++++++ .../features/indicadores/indicadores-fhir.ts | 2 +- .../indicadores-historico-figures.spec.ts | 5 +- .../indicadores-historico-figures.ts | 30 ++--------- .../indicadores-historico-pestana.spec.ts | 6 +-- .../indicadores/indicadores-historico.spec.ts | 49 +++++++++++------- .../indicadores/indicadores-historico.ts | 38 +++++++------- .../features/indicadores/indicadores-kpi.ts | 3 +- .../features/indicadores/indicadores-page.ts | 13 +++-- .../indicadores-recorrido-analisis.spec.ts | 3 +- .../indicadores/indicadores-sections.spec.ts | 8 ++- .../indicadores-tea-secciones.spec.ts | 6 +-- .../indicadores/tea-resumen-periodo.spec.ts | 51 +++++++++++++------ .../indicadores/tea-resumen-periodo.ts | 45 +++++++++++----- .../features/indicadores/tea-status-page.html | 16 +++--- .../indicadores/tea-status-page.spec.ts | 11 +++- 16 files changed, 189 insertions(+), 116 deletions(-) diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index b245b29..4623a1a 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -17,6 +17,7 @@ import { import * as fx from './indicadores-fhir.fixtures'; import { c1AlterationFigure } from './indicadores-c1-alteraciones'; import { c2Figure } from './indicadores-c2-adapter'; +import { historicoFigura } from './indicadores-historico-figures'; import { datosValidos } from './indicadores.service'; import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir'; import { IndicadorDatos } from './indicadores.models'; @@ -146,6 +147,24 @@ describe('Indicadores sobre FHIR', () => { const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {}); for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta); expect(dibujo).not.toContain('Malo'); + expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name'])) + .toEqual(['Bueno', 'No aceptable', 'Sin analizar']); + }); + + it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => { + const actual = measure('M29-calidad-eeg'); + const conAceptable: Measure = { + ...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [ + { url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' }, + ] }], + }; + const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre'); + expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 }); + const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' }); + expect(figura.status).toBe('supported'); + expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable'); + expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name'])) + .toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']); }); it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => { diff --git a/src/app/features/indicadores/indicadores-fhir.ts b/src/app/features/indicadores/indicadores-fhir.ts index cfadcd5..0116290 100644 --- a/src/app/features/indicadores/indicadores-fhir.ts +++ b/src/app/features/indicadores/indicadores-fhir.ts @@ -62,7 +62,7 @@ const percent = (value: number | null) => value === null ? null : round1(value * // Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data. // TEA's EEG quality shows its invalid exams as «No aceptable». const ROTULOS_DE_CATEGORIA: Readonly>>> = { - 'M29-calidad-eeg': { MALO: 'No aceptable' }, + 'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' }, }; // A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's, diff --git a/src/app/features/indicadores/indicadores-historico-figures.spec.ts b/src/app/features/indicadores/indicadores-historico-figures.spec.ts index d05b307..490e80f 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.spec.ts @@ -148,11 +148,12 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos); const f = m30.figure as unknown as Fig; const lineas = f.data.filter(t => t['mode'] === 'lines+markers'); - expect(lineas.map(t => t['name'])).toEqual(['EEG con alteración detectada']); + expect(lineas.map(t => t['name'])).toEqual(['EEG anormal']); expect(lineas[0]['y']).toEqual([62.5, null, null, null]); expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8'); expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]); - expect(m30.comoLeer).toContain('La clasificación de EEG normal está pendiente de validación.'); + expect(m30.comoLeer).toBe('Línea de EEG anormal: se detecta alguna alteración.'); + expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.'); expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']); }); }); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 09fe721..c3246cd 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -1,12 +1,12 @@ import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette'; import { sortedPeriods } from './indicadores-periodos'; -import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi'; export interface HistoricoFigura { contrato: string; figure: PlotlyFigure; comoLeer: string; + notaMetodologica?: string; suprimidos: string[]; sinDato: string[]; } @@ -108,7 +108,7 @@ export const M30_RESULTADO_EEG = 'M30_resultado_eeg'; const PIE_PORCENTAJE: Readonly> = { cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.', - [M30_RESULTADO_EEG]: 'Resultado experimental. La línea muestra EEG con alguna alteración detectada. La clasificación de EEG normal está pendiente de validación.', + [M30_RESULTADO_EEG]: 'Línea de EEG anormal: se detecta alguna alteración.', }; const PIE_MEDIANA: Readonly> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id, 'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'])); @@ -121,7 +121,8 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { // A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0); const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema); - const nombre = data.id === M30_RESULTADO_EEG ? 'EEG con alteración detectada' : 'Porcentaje'; + const resultadoEeg = data.id === M30_RESULTADO_EEG; + const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje'; return { figure: { data: [ banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno), @@ -134,6 +135,7 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { hovertemplate: '%{x}
%{text}' }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.', + ...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}), suprimidos, sinDato, }; } @@ -219,25 +221,3 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist if (!figura) throw new Error('Representación no soportada'); return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; } -// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages. -export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura { - const periodos = validar(data); - const n = (periodo: string, categorias: readonly string[]) => { - const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']); - return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null; - }; - const puntos = periodos.map(periodo => { - const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]); - return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo }; - }); - const layout = ejes(data, periodos, [], tema, 'Porcentaje'); - return { - contrato: 'C1', - figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 }, - y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''), - hovertemplate: '%{x}
%{y} % en proceso
%{text}' }], - layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, - comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.', - suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo), - }; -} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index fb6c8e5..744febb 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -1,4 +1,4 @@ -// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, and its +// Covers the history tab in the page: it sits between Indicadores and the risk analysis tab, and its // panel loads nothing until it is opened. Catalogs are synthetic, shaped like //indicadores. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; @@ -46,10 +46,10 @@ describe('Pestaña Histórico', () => { expect(root().querySelector('#panel-historico')).not.toBeNull(); expect(root().querySelector('#panel-analisis')).toBeNull(); }); - it('tea tiene Histórico pero no Análisis epidemiológico', () => { + it('TEA tiene Trazabilidad y Análisis de Riesgo', () => { abrir('cama', []); abrir('tea', [item('tea_x', 'C2')]); - expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']); expect(root().querySelector('#panel-analisis')).toBeNull(); }); it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => { diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts index fc5b15b..17ad486 100644 --- a/src/app/features/indicadores/indicadores-historico.spec.ts +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -7,7 +7,7 @@ import { Subject } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; import { IndicadoresHistorico } from './indicadores-historico'; -import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures'; +import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures'; import { Indicador, IndicadorDatos } from './indicadores.models'; @Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) @@ -86,14 +86,6 @@ describe('Figuras de histórico', () => { expect(etiquetaPeriodo('2024-03')).toBe('mar 2024'); expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2'); }); - it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => { - const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 }); - const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [ - fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10), - fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro'); - expect(figure.data[0]['y']).toEqual([75, 25]); - expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']); - }); it('una escala compartida fija el máximo de las medianas', () => { const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }; expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]); @@ -179,23 +171,42 @@ describe('Pestaña Histórico', () => { expect(c.ventana()).toBe(5); http.expectNone(() => true); }); - it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => { - const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'] - .map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] })); + it('ordena y titula las ocho gráficas de Trazabilidad y agrupa los tres pasos de tiempo', () => { + const items: Indicador[] = [ + { id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1' }, + { id: 'M29_calidad_eeg', titulo: 'Calidad del EEG', contrato: 'C2' }, + { id: 'M28_casos_por_estado', titulo: 'Casos por estatus', contrato: 'C2' }, + { id: 'M27_dias_ados2_diagnostico', titulo: 'Días de ADOS-2 a diagnóstico', contrato: 'C3r' }, + { id: 'M26_dias_mchat_ados2', titulo: 'Días de M-CHAT a ADOS-2', contrato: 'C3r' }, + { id: 'M25_dias_mchat_diagnostico', titulo: 'Días de M-CHAT a diagnóstico positivo', contrato: 'C3r' }, + { id: 'M24_confirmacion_diagnostico', titulo: 'Porcentaje de confirmación diagnóstica', contrato: 'C1' }, + { id: 'M23_pacientes_evaluados', titulo: 'Pacientes evaluados por resultado diagnóstico', contrato: 'C2' }, + { id: 'M22_diagnosticados_sin_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1' }, + { id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1' }, + ].map(item => ({ ...item, figuras: [], tipos_periodo: ['mes'] })); fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render(); + const pasos = ['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']; + const titulos = () => Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel h2'), el => el.textContent?.trim()); + expect(titulos().slice(0, 3)).toEqual(pasos); for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] }); - for (const { id } of items) { - const c2 = id.startsWith('M28'); - http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'], - filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }] - : [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] }); + for (const { id, contrato } of items) { + const periodo = '2024-01'; + const fila = contrato === 'C1' ? c1(periodo, 50) : contrato === 'C2' ? c2(periodo, 'A', 3, 0) + : { periodo, suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }; + http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato, tipo_periodo: 'mes', periodos: [periodo], filas: [fila] }); } render(); const paneles = fixture.componentInstance.paneles(); - expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']); + expect(titulos()).toEqual([ + 'Tiempos del tamizaje', 'Progresión del proceso diagnóstico', 'Porcentaje de confirmación diagnóstica', + 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', + 'Flujo del proceso diagnóstico y estudios de EEG', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal', + ]); const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>; expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]); - expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3); + expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos); + const notas = Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel:last-child p.nota'), el => el.textContent?.trim()); + expect(notas).toEqual(['Línea de EEG anormal: se detecta alguna alteración.', expect.stringContaining('Resultado experimental.')]); }); it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => { // Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped. diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 4647bfa..d154e67 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -8,13 +8,14 @@ import { MatSelect, MatSelectModule } from '@angular/material/select'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { defer, map, Subscription } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures'; +import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures'; import { httpMessage } from './indicadores-http'; import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; import { IndicadoresPeriodos } from './indicadores-periodos'; import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { IndicadoresService } from './indicadores.service'; import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config'; +import { TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD } from './indicadores-kpi'; export { HISTORICO_CAMA }; @@ -31,8 +32,11 @@ type Panel = { item: Pick & { contrato?: Indicador[' { estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] }); class ContratoHistoricoInvalido extends Error {} -const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; -const CASOS = 'M28_casos_por_estado'; +const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD; +const TITULOS_TEA: Readonly> = { + M23_pacientes_evaluados: 'Progresión del proceso diagnóstico', + M28_casos_por_estado: 'Flujo del proceso diagnóstico y estudios de EEG', +}; const PERSONALIZADO = -1; function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos { const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p))); @@ -43,29 +47,25 @@ function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos { ...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) }; } -// The screening steps go together as small charts, and the case counts are followed by their in-process share. -function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] { +// Keep the individual cards available for loading, error and empty states. +function agruparTiempos(paneles: Panel[]): Panel[] { const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id)); const listos = pasos.every(p => p?.estado === 'listo'); return paneles.flatMap((panel): Panel[] => { if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') { const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract).figura })); const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))]; - return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras, + return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos del tamizaje', contrato: 'C3r' }, pasos: figuras, figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.', suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }]; } if (listos && TIEMPOS.includes(panel.item.id)) return []; - if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) { - return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }]; - } return [panel]; }); } // TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them. -const ORDEN_TEA = ['tiempos', 'M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg', - CASOS, 'en_proceso', 'M29_calidad_eeg', M30_RESULTADO_EEG]; +const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG]; function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] { const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; }; return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel); @@ -117,15 +117,16 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
@for (paso of pasos; track paso.titulo) {

{{ paso.titulo }}

- +
}
} @else { + [label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" /> } @if (panel.figura.comoLeer) {

{{ panel.figura.comoLeer }}

} + @if (panel.figura.notaMetodologica) {

{{ panel.figura.notaMetodologica }}

} @if (panel.figura.suprimidos.length) {
Datos suprimidos @@ -192,6 +193,7 @@ export class IndicadoresHistorico { readonly catalogLoading = input(false); readonly catalogError = input(''); readonly retryCatalog = output(); + readonly etiquetaVista = computed(() => this.dominio() === 'tea' ? 'Trazabilidad' : 'Histórico'); // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. private readonly config = computed(() => historicoDeDominio(this.dominio())); // The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active; @@ -260,7 +262,7 @@ export class IndicadoresHistorico { const visibles = this.recortar(carga.datos.periodos); return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0); })) * 1.05; - const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => { + const panelDe = (item: Indicador): Panel => { if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' }; const carga = cargas?.[item.id]; if (!carga) return { item, estado: 'cargando' }; @@ -284,7 +286,7 @@ export class IndicadoresHistorico { if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) { return { item, estado: mensaje ? 'error' : 'vacio', mensaje }; } - return { item, rango, estado: 'listo', figura, datos, mensaje }; + return { item, rango, estado: 'listo', figura, mensaje }; } catch (error) { return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; } @@ -303,8 +305,10 @@ export class IndicadoresHistorico { return { ...panelDe(item), item: { ...visible, contrato: item.contrato } }; }); } - const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema); - return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles; + const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo)); + if (this.dominio() !== 'tea') return items.map(panelDe); + const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo })); + return agruparTiempos(ordenar(paneles, ORDEN_TEA)); }); constructor() { diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 86b0443..213b0f8 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -50,9 +50,8 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { // in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories // (patients), not the distribution. If a TOML title changes, change it here too, until the // cards read the `titulo` that the API already sends. -// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process. +// M28's last stage follows neuropediatrics and requires a good EEG. export const M28_COMPLETO = 'EEG'; -export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA']; // M29's category of the EEGs the analysis found valid. export const M29_BUENO = 'BUENO'; // What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality. diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index ff07dc5..ea07e77 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -37,6 +37,7 @@ import { IndicadoresHistorico } from './indicadores-historico'; import { historicoDeDominio } from './indicadores-historico-config'; import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; +import { M30_RESULTADO_EEG } from './indicadores-historico-figures'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ @@ -44,9 +45,10 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ { id: 'seguimiento', label: 'Análisis de riesgos' }, { id: 'datos', label: 'Datos y definiciones' }, ]; -// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's, -// between its history and its follow-up list. const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]]; +const SECTIONS_TEA: typeof SECTIONS = [ + SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2], +]; // Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered. export const CAMA_ANALYSIS_ENABLED = false; // TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them. @@ -67,7 +69,10 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } + get sections(): typeof SECTIONS { + if (this.dominio === 'tea') return SECTIONS_TEA; + return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; + } get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; } get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; } readonly activeSection = signal('resumen'); @@ -386,7 +391,7 @@ export class IndicadoresPage { return this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))] : this.dominio === 'cama' ? this.cardsDeCama(catalog) - : this.dominio === 'tea' ? ordenTea(catalog.filter(item => !item.vistas || item.vistas.includes('resumen'))) + : this.dominio === 'tea' ? ordenTea(catalog.filter(item => item.id !== M30_RESULTADO_EEG && (!item.vistas || item.vistas.includes('resumen')))) : catalog.filter(item => !item.vistas || item.vistas.includes('resumen')); }); readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id)); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 2ad3912..fe468d3 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -163,7 +163,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( - ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + dominio === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones'] + : ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 7c45c3a..4c61291 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - // TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain. - const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + const esperadas = domain === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones'] + : ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; @@ -58,6 +58,10 @@ describe('Secciones compartidas por dominio', () => { harness.detectChanges(); const tracking = root.querySelector('#panel-seguimiento')!; expect(tracking.hidden).toBe(false); + if (domain === 'tea') { + expect(tracking.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA'); + expect(tracking.querySelector('select[name="estatus"]')?.closest('label')?.firstChild?.textContent?.trim()).toBe('Estatus de EEG'); + } expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible'); if (domain === 'cama') { // An unavailable cohort has no table and offers a retry. diff --git a/src/app/features/indicadores/indicadores-tea-secciones.spec.ts b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts index dedebdf..1c3ef3d 100644 --- a/src/app/features/indicadores/indicadores-tea-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-tea-secciones.spec.ts @@ -48,16 +48,16 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => { const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => { - // Fails if a figure is drawn in both sections, if either order changes, or if M30 (not named by the sections) - // disappears instead of following the clinical ones. + // M30 belongs to Trazabilidad even when the catalog publishes it. open('tea', TEA); expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']); expect(titles('.graphic-section')).toEqual([ 'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica', 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', - 'Casos por estatus', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal']); + 'Casos por estatus', 'Calidad del EEG']); expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad'); expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); + expect(fixture.componentInstance.catalogOrder().map(item => item.id)).not.toContain('M30_resultado_eeg'); }); it('un indicador no publicado deja el resto en su orden', () => { diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index c3cecf6..8001e73 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -13,9 +13,9 @@ const listo = (value: string | number, period = '2025-S2'): Result => ({ state: const c1 = (value: string, numerador: number, denominador: number): Result => ({ ...listo(value), numerador, denominador }); describe('Resumen TEA por periodo', () => { - function render(paneles: IndicadorKpiPanel[]) { + function render(paneles: IndicadorKpiPanel[], periodo = '2025-S2') { const fixture = TestBed.createComponent(TeaResumenPeriodo); - fixture.componentRef.setInput('periodo', '2025-S2'); fixture.componentRef.setInput('paneles', paneles); + fixture.componentRef.setInput('periodo', periodo); fixture.componentRef.setInput('paneles', paneles); fixture.detectChanges(); return fixture; } @@ -27,20 +27,22 @@ describe('Resumen TEA por periodo', () => { panel('M21_diagnosticados_con_eeg', c1('71.9', 41, 57)), panel('M22_diagnosticados_sin_eeg', c1('28.1', 16, 57)), panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14)), panel('M29_calidad_eeg', { ...listo(80), categorias: { BUENO: 20, MALO: 50, SIN_ANALIZAR: 10 } })]; - const texto = (root: HTMLElement) => root.textContent!.replace(/\s+/g, ' '); + const texto = (root: HTMLElement) => Array.from(root.querySelectorAll('p'), p => p.textContent!.replace(/\s+/g, ' ').trim()).join(' '); - it('redacta los dos párrafos con cada población y resalta los valores', () => { + it('identifica el denominador de cada medida y resalta los valores publicados', () => { // Fails if a sentence reads another indicator's figure, if the stages stop adding up to the children evaluated // or if a median is cut (22.5 stays 22.5). const root: HTMLElement = render(completos()).nativeElement; const text = texto(root); - expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.'); - expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); - expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.'); - expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); + expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños de la cohorte de tamizaje; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.'); + expect(text).toContain('La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.'); + expect(text).toContain('En este periodo el 86.5% de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); + expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico positivo fue de 22.5 días.'); + expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad.'); + expect(text).toContain('De los 80 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.'); expect(text).toContain('*tomando la mediana de los tiempos'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']); + .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '80', '25.0%']); expect(root.querySelector('button')).toBeNull(); }); @@ -50,11 +52,15 @@ describe('Resumen TEA por periodo', () => { panel('M28_casos_por_estado', { ...listo(3), categorias: { EEG: 0, SOLO_MCHAT: 1, PSICOLOGIA: 1, NEUROPEDIATRIA: 1 } }), panel('M24_confirmacion_diagnostico', c1('50.0', 1, 2)), panel('M25_dias_mchat_diagnostico', listo(31)), panel('M21_diagnosticados_con_eeg', c1('0.0', 0, 1)), panel('M22_diagnosticados_sin_eeg', c1('100.0', 1, 1)), - panel('M26_dias_mchat_ados2', listo(5)), panel('M27_dias_ados2_diagnostico', listo(9)), + panel('M26_dias_mchat_ados2', listo(54.5)), panel('M27_dias_ados2_diagnostico', listo(9)), panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })]; - const text = texto(render(paneles).nativeElement); - expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan'); - expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); + const periodo = '2026-03'; + for (const p of paneles) p.result.set({ ...p.result(), period: periodo }); + const text = texto(render(paneles, periodo).nativeElement); + expect(text).toContain('Al cierre del periodo 2026-03, se evaluaron 3 niños de la cohorte de tamizaje; 1 únicamente tienen M-CHAT'); + expect(text).toContain('54.5 días de M-CHAT (psicología) a ADOS-2, 9 días de ADOS-2 a diagnóstico.'); + expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad.'); + expect(text).toContain('De los 4 estudios de EEG realizados a niños de la cohorte en el periodo, 25.0% tienen buena calidad.'); for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo); }); @@ -64,10 +70,17 @@ describe('Resumen TEA por periodo', () => { paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57)); paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } }); const root: HTMLElement = render(paneles).nativeElement; - expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); + expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. No se registraron estudios de EEG en el periodo.'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0'); }); + it('incluye los estudios sin analizar en el total de EEG del periodo', () => { + const paneles = completos(); + paneles[7].result.set({ ...listo(6), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 6 } }); + expect(texto(render(paneles).nativeElement)) + .toContain('De los 6 estudios de EEG realizados a niños de la cohorte en el periodo, 0.0% tienen buena calidad.'); + }); + it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => { // Fails if a suppressed, foreign-period or unpublished figure is drawn as a number, or if its reason is lost. const paneles = completos(); @@ -75,10 +88,18 @@ describe('Resumen TEA por periodo', () => { paneles[2].result.set(listo(30, '2025-S1')); const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M29_calidad_eeg')).nativeElement; const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato')); - expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']); + expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Sin datos para el periodo seleccionado', 'Indicador no publicado']); expect(root.textContent).not.toContain('30 días'); }); + it('una respuesta de otro periodo no invalida los conteos vigentes de M21', () => { + const paneles = completos(); + paneles[4].result.set({ ...c1('28.1', 16, 58), period: '2025-S1' }); + const root: HTMLElement = render(paneles).nativeElement; + expect(texto(root)).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad'); + expect(root.querySelector('.dato.sin-dato')?.getAttribute('title')).toBe('Sin datos para el periodo seleccionado'); + }); + it('no muestra los conteos de M21 y M22 si no hablan de los mismos niños', () => { // Fails if the confirmed children of M21 and of M22 disagree and the summary still prints them as one population. const paneles = completos(); diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index 41f5298..ed39c01 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -18,23 +18,40 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2 template: `

- Al cierre del periodo {{ periodo }}, se evaluaron niños entre 16 y 36 meses; + Al cierre del periodo {{ periodo }}, se evaluaron niños de la cohorte de tamizaje; únicamente tienen M-CHAT, hasta la evaluación psicológica y presentan evaluación neuropediátrica. +

+

La cohorte incluye a niños de 16 a 36 meses al primer M-CHAT y a niños sin edad registrada.

+

En este periodo el - de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0). + de los pacientes en tamizaje con diagnóstico confirmado o en proceso tiene diagnóstico confirmado de TEA (CIE-10 F84.0). +

+

Las ventanas de tiempo* de tamizaje son: de M-CHAT (psicología) a ADOS-2, de ADOS-2 a diagnóstico. - El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de - . -
- De los niños con diagnóstico confirmado al cierre del periodo, - tienen un EEG de buena calidad y - aún no cuentan con uno de esa calidad. - Del total de estudios de EEG del periodo, - tienen buena calidad.

+

+ El tiempo* de tamizaje completo de M-CHAT a diagnóstico positivo fue de + . +

+

+ De los niños con diagnóstico confirmado al cierre del periodo, + tienen un EEG de buena calidad y + aún no cuentan con uno de esa calidad. +

+ @let estudios = valor('M29_calidad_eeg', ''); + @if (estudios.estado !== 'listo') { +

Estudios de EEG del periodo: .

+ } @else if (estudios.texto === '0') { +

No se registraron estudios de EEG en el periodo.

+ } @else { +

+ De los estudios de EEG realizados a niños de la cohorte en el periodo, + tienen buena calidad. +

+ }

*tomando la mediana de los tiempos

@if (conError.length) { @@ -70,8 +87,9 @@ export class TeaResumenPeriodo { if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' }; if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' }; // Never show a value from another period in a sentence about this one. - if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo) + if (result.state !== 'Disponible' || result.value === undefined) return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state }; + if (result.period !== this.periodo) return this.sinDato('Sin datos para el periodo seleccionado'); return undefined; } private sinDato(detalle: string): Valor { return { texto: 'sin dato', estado: 'sin_dato', detalle }; } @@ -90,6 +108,7 @@ export class TeaResumenPeriodo { } // M21 and M22 split the same confirmed children, so a count of either is only shown while their denominators agree. private poblacionComun(): boolean { + if (this.fallo(M21) || this.fallo(M22)) return true; const a = this.panel(M21)?.result(), b = this.panel(M22)?.result(); return !(a?.denominador !== undefined && b?.denominador !== undefined && a.denominador !== b.denominador); } @@ -103,8 +122,8 @@ export class TeaResumenPeriodo { // Children with a confirmed diagnosis at the period's end, the denominator of M21 and M22. confirmados() { return this.conteo(M21, 'denominador'); } // Of them, those with a good EEG (M21's numerator) and those without yet (M22's). - conEeg() { return this.conteo(M21, 'numerador'); } - sinEeg() { return this.conteo(M22, 'numerador'); } + conEegBueno() { return this.conteo(M21, 'numerador'); } + sinEegBueno() { return this.conteo(M22, 'numerador'); } // The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid. buenaCalidad(): Valor { const base = this.valor(M29, ''); diff --git a/src/app/features/indicadores/tea-status-page.html b/src/app/features/indicadores/tea-status-page.html index 9ddeced..e867fab 100644 --- a/src/app/features/indicadores/tea-status-page.html +++ b/src/app/features/indicadores/tea-status-page.html @@ -2,13 +2,13 @@

Trastorno del espectro autista

Explora los indicadores de trastorno del espectro autista.

@if (section() !== 'seguimiento') {
-

{{ section() === 'resumen' ? 'Resumen' : 'Histórico' }}

+

{{ section() === 'resumen' ? 'Indicadores' : 'Trazabilidad' }}

@if (section() === 'resumen') { } @else { @@ -30,8 +30,8 @@ }
} -
-

Seguimiento

Consulte los episodios según la fecha de corte y los filtros seleccionados.

+
+

Análisis de Riesgo

Consulte los episodios según la fecha de corte y los filtros seleccionados.

@@ -40,7 +40,7 @@ - + @if (alterationsAvailable() && alterationTypes().length) { } @@ -56,7 +56,7 @@ }
@if (section() === 'seguimiento' && selected()) { -

Ficha del paciente

{{ selected() }}

La ficha muestra la información disponible a la fecha actual.

+

Ficha del paciente

{{ selected() }}

La ficha muestra la información disponible a la fecha actual.

@if (patientState() === 'cargando') {

Consultando ficha…

} @if (patientState() === 'error') {

{{ patientError() }}

} @if (patientState() === 'listo') { diff --git a/src/app/features/indicadores/tea-status-page.spec.ts b/src/app/features/indicadores/tea-status-page.spec.ts index 9f23683..6bd5ebd 100644 --- a/src/app/features/indicadores/tea-status-page.spec.ts +++ b/src/app/features/indicadores/tea-status-page.spec.ts @@ -17,8 +17,17 @@ describe('TEA FHIR journey', () => { const http = TestBed.inject(HttpTestingController); http.expectOne('/tea/fhir/Measure').flush(bundle(measure)); http.expectOne(r => r.url.endsWith('/$evaluate-measure')).flush({ measure: measure.url, period: { start: '2025-01-01', end: '2025-06-30' }, group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 6 }] }] }); - return { c, http }; + return { c, http, fixture }; } + it('presenta las etiquetas de las tres secciones en la vista de estatus', () => { + const { fixture, http } = setup(); + fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + expect(Array.from(root.querySelectorAll('.tabs button'), tab => tab.textContent?.trim())) + .toEqual(['Indicadores', 'Trazabilidad', 'Análisis de Riesgo']); + expect(root.querySelector('section[aria-label="Consulta de indicadores"] h2')?.textContent).toBe('Indicadores'); + http.verify(); + }); it('distinguishes zero, missing and masked values and requests the historical periods', () => { const { c, http } = setup(); expect(c.value({ count: 0 }, 'count')).toBe('0'); From 7f1e43bdc5eff01d162cc41debe6a83522902ffe Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 16:26:55 -0600 Subject: [PATCH 25/35] =?UTF-8?q?CaCu=20indicators:=20no=20=C2=ABTiempo=20?= =?UTF-8?q?de=20tamizaje=20a=20diagn=C3=B3stico=C2=BB=20figures=20next=20t?= =?UTF-8?q?o=20the=20screening=20route=20chart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The route chart draws every time from the sample to each event, the cytology's result and the diagnosis included, so the separate time figures repeated it. They come back only when the chart isn't shown (the catalog lacks one of its measures). --- .../indicadores/indicadores-cacu-secciones.spec.ts | 11 ++++------- src/app/features/indicadores/indicadores-page.ts | 14 +++++++------- .../indicadores-screening-route-page.spec.ts | 10 +++++----- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 11845e3..56638f3 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -53,14 +53,11 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = 'catalog-card: Tiempo de toma de muestra a diagnóstico']); }); - it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => { - // Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route - // chart's own page spec forbids. + it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => { + // Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it. abrir([...CACU, ...RUTA]); - expect(titulos('.kpi-section .catalog-grid')).toEqual([ - 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', - 'catalog-card: Tiempo de toma de muestra a diagnóstico']); + expect(root().querySelector('.subsection-title')).toBeNull(); + 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', diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index ff07dc5..4c19360 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -400,8 +400,9 @@ export class IndicadoresPage { const selected = new Set(this.selectedIndicators()); return { items: this.catalogOrder().filter(item => selected.has(item.id)) }; }); - // The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's five times, each a - // pending slot while the catalog does not publish its indicator. The rest are the clinical ones. + // The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending + // slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The + // rest are the clinical ones. // The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for. readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => { const items = this.searchResults().items; @@ -416,11 +417,10 @@ export class IndicadoresPage { return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo }; }); } - if (this.dominio !== 'cacu' || !this.catalog().length) return []; - // The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while - // it is shown, so those slots are left to the chart instead of drawn twice or as pending. - const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : []; - return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => { + // With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to + // each event. Without it (the catalog lacks one of its measures) the times keep their figures. + if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return []; + return CACU_FIGURAS_OPORTUNIDAD.map(figura => { const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined; return item ? { item, titulo: item.titulo } : { titulo: figura.titulo }; }); diff --git a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts index c226da3..2ae7b88 100644 --- a/src/app/features/indicadores/indicadores-screening-route-page.spec.ts +++ b/src/app/features/indicadores/indicadores-screening-route-page.spec.ts @@ -33,14 +33,14 @@ describe('Ruta del tamizaje: página de CaCu', () => { const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route'); const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id); - it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => { - // Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis' - // keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card. + it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => { + // Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the + // «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as + // a card. abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]); expect(ruta()).not.toBeNull(); const ids = tarjetas(); - for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id); - expect(ids).toContain('cacu_eu_tiempo_reporte'); + for (const id of ROUTE_IDS) expect(ids).not.toContain(id); expect(ids).toContain('cacu_eu7'); }); it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => { From f058f1f476367d5778241ace99ccdde8a5a858a3 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 16:30:01 -0600 Subject: [PATCH 26/35] Screening route chart: it follows the page's period filter, with no filter of its own The chart takes the page's period type and shows the newest of the periods the filter applies that has published boxes (the newest with data when the filter applies every period), so it moves with the other indicators. Its own period selector is gone; the period shown is written over the chart. --- .../indicadores/indicador-screening-route.html | 7 +------ .../indicadores/indicador-screening-route.spec.ts | 4 +++- .../indicadores/indicador-screening-route.ts | 12 +++++------- src/app/features/indicadores/indicadores-page.html | 2 +- src/app/features/indicadores/indicadores-page.ts | 6 ++++++ src/app/features/indicadores/screening-route.spec.ts | 11 +++++++++++ src/app/features/indicadores/screening-route.ts | 10 +++++++--- 7 files changed, 34 insertions(+), 18 deletions(-) diff --git a/src/app/features/indicadores/indicador-screening-route.html b/src/app/features/indicadores/indicador-screening-route.html index fef2e09..72d1bec 100644 --- a/src/app/features/indicadores/indicador-screening-route.html +++ b/src/app/features/indicadores/indicador-screening-route.html @@ -8,12 +8,7 @@ } @if (model(); as m) {
- - Periodo - - @for (period of m.periods; track period) { {{ periodLabel(period) }} } - - + @if (m.period) {

Periodo: {{ periodLabel(m.period) }}

} Acumulado desde la toma Por pasos diff --git a/src/app/features/indicadores/indicador-screening-route.spec.ts b/src/app/features/indicadores/indicador-screening-route.spec.ts index 7a804b5..3b38cf7 100644 --- a/src/app/features/indicadores/indicador-screening-route.spec.ts +++ b/src/app/features/indicadores/indicador-screening-route.spec.ts @@ -64,8 +64,10 @@ describe('Ruta del tamizaje: componente', () => { expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeUndefined(); f.componentInstance.selectView('steps'); f.detectChanges(); expect((f.componentInstance.figure()!.data[0] as Record)['base']).toBeDefined(); - f.componentInstance.selectPeriod('2025-S1'); f.detectChanges(); + // the period follows the page's filter, with no request of its own + f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges(); expect(f.componentInstance.model()!.period).toBe('2025-S1'); + expect(f.nativeElement.querySelector('mat-select')).toBeNull(); f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicador-screening-route.ts b/src/app/features/indicadores/indicador-screening-route.ts index c1d66fe..e2752a2 100644 --- a/src/app/features/indicadores/indicador-screening-route.ts +++ b/src/app/features/indicadores/indicador-screening-route.ts @@ -3,9 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http'; import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatButtonToggleModule } from '@angular/material/button-toggle'; -import { MatFormFieldModule } from '@angular/material/form-field'; import { MatProgressBarModule } from '@angular/material/progress-bar'; -import { MatSelectModule } from '@angular/material/select'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; import { etiquetaPeriodo } from './indicadores-historico-figures'; @@ -16,7 +14,7 @@ import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, ro /** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */ @Component({ selector: 'app-indicador-screening-route', - imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-screening-route.html', styleUrl: './indicador-screening-route.scss', }) @@ -24,17 +22,18 @@ export class IndicadorScreeningRoute { readonly dominio = input.required(); readonly tema = input.required(); readonly tipo = input('semestre'); + /** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */ + readonly periodos = input(undefined); /** The measures load once the region is visible. */ readonly visible = input(true); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); readonly message = signal(''); readonly view = signal('cumulative'); - readonly requestedPeriod = signal(undefined); private readonly payloads = signal | undefined>(undefined); readonly model = computed(() => { const data = this.payloads(); - return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined; + return data ? routeModel(data, this.tipo(), this.periodos()) : undefined; }); readonly figure = computed(() => { const model = this.model(); @@ -56,7 +55,6 @@ export class IndicadorScreeningRoute { } retry() { this.load(this.dominio(), this.tipo()); } - selectPeriod(period: string) { this.requestedPeriod.set(period); } selectView(view: RouteView) { this.view.set(view); } private load(dominio: Dominio, tipo: TipoPeriodo) { @@ -67,7 +65,7 @@ export class IndicadorScreeningRoute { this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({ next: data => { try { - const model = routeModel(data, tipo, this.requestedPeriod()); + const model = routeModel(data, tipo, this.periodos()); this.payloads.set(data); this.status.set(routeHasData(model) ? 'ready' : 'empty'); } catch (error) { this.failure(error); } diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index fed9daa..5b80202 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -126,7 +126,7 @@ Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.
} - @if (screeningRouteAvailable) { } + @if (screeningRouteAvailable) { }
@for (item of clinicosItems(); track cardIdentity(item)) { 0 && !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA); } + /** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening + * route); `undefined` when it applies every period. */ + periodosDelFiltro(): readonly string[] | undefined { + const seleccion = this.filters?.applied.selection; + return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined; + } // CaCu's screening route chart, once the catalog publishes every measure it reads. get screeningRouteAvailable() { return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id)); diff --git a/src/app/features/indicadores/screening-route.spec.ts b/src/app/features/indicadores/screening-route.spec.ts index bd397c0..69f781e 100644 --- a/src/app/features/indicadores/screening-route.spec.ts +++ b/src/app/features/indicadores/screening-route.spec.ts @@ -49,6 +49,17 @@ describe('Ruta del tamizaje: modelo', () => { expect(routeModel(data, 'semestre').period).toBe('2025-S2'); expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1'); }); + it('con los periodos del filtro de la página se usa el más reciente de ellos con cajas publicadas', () => { + // Fails if the chart, which has no period filter of its own, ignores the page's periods or opens on an empty one of + // them while an earlier one it was given has data. + const vacio = (id: string) => payload(id, [row('2025-S1', [10, 1, 2, 3]), row('2025-S2', S2[id]), + row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S1', '2025-S2', '2026-S1']); + const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)])); + expect(routeModel(data, 'semestre', ['2025-S1', '2026-S1', '2025-S2']).period).toBe('2025-S2'); + expect(routeModel(data, 'semestre', ['2025-S1']).period).toBe('2025-S1'); + expect(routeModel(data, 'semestre', ['2026-S1']).period).toBe('2026-S1'); + expect(routeModel(data, 'semestre', ['2023-S1']).period).toBe('2025-S2'); + }); it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => { // Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box // becomes a bar or leaves a gap in the chain. diff --git a/src/app/features/indicadores/screening-route.ts b/src/app/features/indicadores/screening-route.ts index 0f8f768..77fd39e 100644 --- a/src/app/features/indicadores/screening-route.ts +++ b/src/app/features/indicadores/screening-route.ts @@ -47,7 +47,8 @@ const fail = (message: string): never => { throw new RouteIncompatible(message); const NOT_AVAILABLE: Caja = { estado: 'No disponible' }; /** The seven C3r /datos payloads -> one row per event for a period, newest period first when none is requested. */ -export function routeModel(data: Record, tipo: TipoPeriodo, requested?: string): RouteModel { +export function routeModel(data: Record, tipo: TipoPeriodo, + requested?: string | readonly string[]): RouteModel { const boxes: Record> = {}; for (const id of ROUTE_IDS) { const d = data[id]; @@ -66,9 +67,12 @@ export function routeModel(data: Record, tipo: TipoPerio } } const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse(); - // Without a valid request the newest period that has a published box: a semester that has just begun is empty. + // The newest of the requested periods (the page's filter) that has a published box, else the newest requested one; + // without a valid request, the newest period that has a published box: a semester that has just begun is empty. const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado'); - const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0]; + const pedidos = (typeof requested === 'string' ? [requested] : [...(requested ?? [])]) + .filter(p => periods.includes(p)).sort().reverse(); + const period = pedidos.length ? pedidos.find(hasData) ?? pedidos[0] : periods.find(hasData) ?? periods[0]; let cursor = 0; const rows = ROUTE_STEPS.map((step): RouteRow => { const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE; From 26285a87fa83a335295fb57b47f0f63c04297dba Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 16:55:16 -0600 Subject: [PATCH 27/35] =?UTF-8?q?fix(cacu):=20ajustar=20trazabilidad=20y?= =?UTF-8?q?=20figuras=20cl=C3=ADnicas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores/indicadores-cacu-secciones.spec.ts | 10 ++++------ .../indicadores-historico-cacu-paneles.spec.ts | 2 +- .../indicadores/indicadores-historico-pestana.spec.ts | 2 +- src/app/features/indicadores/indicadores-historico.ts | 2 +- src/app/features/indicadores/indicadores-kpi.ts | 3 +-- src/app/features/indicadores/indicadores-page.html | 1 - src/app/features/indicadores/indicadores-page.ts | 5 +++-- .../indicadores/indicadores-recorrido-analisis.spec.ts | 2 +- .../features/indicadores/indicadores-sections.spec.ts | 2 +- 9 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 11845e3..95501cd 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -63,8 +63,7 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = 'catalog-card: Tiempo de toma de muestra a diagnóstico']); 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', - 'figura-pendiente: Progresión por grupo de riesgo']); + 'catalog-card: Distribución de resultados citológicos', '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', () => { @@ -87,14 +86,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(titulosKpi).not.toContain('Días de toma a resultado'); }); - it('los indicadores clínicos son los dos pedidos más «Progresión por grupo de riesgo» pendiente, sin tarjetas vacías', () => { + it('los indicadores clínicos son los dos pedidos, sin una reserva de progresión sin datos', () => { // Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending // figure is not drawn as such. 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', - 'figura-pendiente: Progresión por grupo de riesgo']); - expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')?.textContent).toContain('Integración pendiente'); + 'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']); + expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull(); }); it('Datos y definiciones conserva todo el catálogo', () => { diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index c4c80d1..02681ee 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -75,7 +75,7 @@ describe('Histórico de CaCu', () => { const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!; const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo; const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); - const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!; + const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!; it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => { // Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it. diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index 744febb..ec5dde0 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -42,7 +42,7 @@ describe('Pestaña Histórico', () => { // Fails if CaCu loses its history tab or gains CaMa's analysis tab. abrir('cama', []); abrir('cacu', [item('cacu_x', 'C2')]); - expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); expect(root().querySelector('#panel-analisis')).toBeNull(); }); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index d154e67..abe6832 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -193,7 +193,7 @@ export class IndicadoresHistorico { readonly catalogLoading = input(false); readonly catalogError = input(''); readonly retryCatalog = output(); - readonly etiquetaVista = computed(() => this.dominio() === 'tea' ? 'Trazabilidad' : 'Histórico'); + readonly etiquetaVista = computed(() => this.dominio() === 'cama' ? 'Histórico' : 'Trazabilidad'); // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. private readonly config = computed(() => historicoDeDominio(this.dominio())); // The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active; diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 213b0f8..c4b44dd 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -85,9 +85,8 @@ export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { titulo: 'Tiempo de diagnóstico a tratamiento' }, { id: 'cama_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' }, ]; -// CaCu's clinical figures in display order, and the one still to be implemented. +// CaCu's clinical figures in display order. export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia']; -export const CACU_FIGURA_CLINICA_PENDIENTE = 'Progresión por grupo de riesgo'; export const KPI_BY_DOMAIN: Record = { tea: [ { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index fed9daa..05d30e8 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -133,7 +133,6 @@ [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> } @if (histopatologiaPendiente) { } - @if (dominio === 'cacu') { }
@if (dominio === 'cama') {
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index ea07e77..89e1751 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,7 +17,7 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { esSocioConteos } from './indicadores-conteos-pareados'; -import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorScreeningRoute } from './indicador-screening-route'; @@ -49,6 +49,7 @@ const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] const SECTIONS_TEA: typeof SECTIONS = [ SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2], ]; +const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]]; // Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered. export const CAMA_ANALYSIS_ENABLED = false; // TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them. @@ -71,6 +72,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ export class IndicadoresPage { get sections(): typeof SECTIONS { if (this.dominio === 'tea') return SECTIONS_TEA; + if (this.dominio === 'cacu') return SECTIONS_CACU; return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; } @@ -440,7 +442,6 @@ export class IndicadoresPage { } return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items; }); - readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE; // CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it. readonly confirmacionCama = CAMA_CONFIRMACION_KPI; get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); } diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index fe468d3..b5ea420 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -164,7 +164,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( dominio === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones'] - : ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + : ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 4c61291..752780e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -40,7 +40,7 @@ describe('Secciones compartidas por dominio', () => { const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); const esperadas = domain === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones'] - : ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + : ['Indicadores', domain === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; From b1ff6cadb2ad735a8c3f1bbe5fa996fac7e85312 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 17:21:15 -0600 Subject: [PATCH 28/35] =?UTF-8?q?fix(cama):=20ajustar=20t=C3=ADtulos=20y?= =?UTF-8?q?=20pies=20de=20trazabilidad?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores-cama-resumen-clinico.spec.ts | 2 +- .../indicadores/indicadores-conteos-pareados.spec.ts | 2 +- .../indicadores/indicadores-figure-labels.ts | 2 +- .../indicadores/indicadores-historico-cama.spec.ts | 12 ++++++++++-- .../indicadores-historico-figures.spec.ts | 2 +- .../indicadores/indicadores-historico-figures.ts | 2 +- .../indicadores-historico-pestana.spec.ts | 2 +- .../features/indicadores/indicadores-historico.ts | 2 +- src/app/features/indicadores/indicadores-page.ts | 2 +- .../indicadores/indicadores-sections.spec.ts | 2 +- 10 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts index 141af69..514fcdc 100644 --- a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => { open('cama', CAMA); const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim()); - expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6'); + expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6'); expect(nombres).not.toContain(CAMA[1].titulo); }); it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => { diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts index 0d3db7b..7d79476 100644 --- a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts +++ b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts @@ -217,7 +217,7 @@ describe('Tarjeta pareada de CaMa en la página', () => { 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2', ]); expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe( - 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía'); + 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía'); const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); expect(graficas).toHaveLength(2); expect(graficas.map(g => g.label)).toEqual(h3); diff --git a/src/app/features/indicadores/indicadores-figure-labels.ts b/src/app/features/indicadores/indicadores-figure-labels.ts index aaa1402..c90a76c 100644 --- a/src/app/features/indicadores/indicadores-figure-labels.ts +++ b/src/app/features/indicadores/indicadores-figure-labels.ts @@ -1,7 +1,7 @@ // Presentation labels for representations confirmed in the published catalog. // Exact IDs remain the option values and HTTP identities; never infer a type // from a prefix. Unknown options keep a neutral label in publication order. -export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6'; +export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6'; const FIGURE_LABELS: Readonly> = { fig_c1_barras_alteracion: 'Barras por alteración', diff --git a/src/app/features/indicadores/indicadores-historico-cama.spec.ts b/src/app/features/indicadores/indicadores-historico-cama.spec.ts index d00d21c..3970d03 100644 --- a/src/app/features/indicadores/indicadores-historico-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cama.spec.ts @@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => { }); it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => { montar(CATALOGO, true); responder(); - expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo)); + expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([ + 'Días de la toma de la mastografía a su resultado', + 'Días del resultado de la mastografía al diagnóstico', + 'Días de tamizaje a diagnóstico', + 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6', + 'Pacientes con resultado BI-RADS 4, 5 ó 6', + 'Resultado histopatológico', + 'Tasa de confirmación histopatológica', + ]); const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent); expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']); expect(paneles()).toHaveLength(7); const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6'; expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo); - expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true); + expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true); expect(graficas()).toHaveLength(5); expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0); }); diff --git a/src/app/features/indicadores/indicadores-historico-figures.spec.ts b/src/app/features/indicadores/indicadores-historico-figures.spec.ts index 490e80f..c7aa4a2 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.spec.ts @@ -137,7 +137,7 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en }); it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => { // Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it. - const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría.'; + const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría'; for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie); expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe(''); expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total'); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index c3246cd..423eded 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -113,7 +113,7 @@ const PIE_PORCENTAJE: Readonly> = { const PIE_MEDIANA: Readonly> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id, 'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.'])); const PIE_CATEGORIAS: Readonly> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id, - 'Cada barra indica el total de pacientes por periodo en cada categoría.'])); + 'Cada barra indica el total de pacientes por periodo en cada categoría'])); type Trazo = Omit; function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index ec5dde0..6212dc7 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => { it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); - expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); fixture.componentInstance.changeSection('analisis'); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index abe6832..5e18bed 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -193,7 +193,7 @@ export class IndicadoresHistorico { readonly catalogLoading = input(false); readonly catalogError = input(''); readonly retryCatalog = output(); - readonly etiquetaVista = computed(() => this.dominio() === 'cama' ? 'Histórico' : 'Trazabilidad'); + readonly etiquetaVista = computed(() => 'Trazabilidad'); // What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog. private readonly config = computed(() => historicoDeDominio(this.dominio())); // The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active; diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 89e1751..048c830 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -59,7 +59,7 @@ function ordenTea(catalog: Indicador[]): Indicador[] { return [...first, ...catalog.filter(item => !named.includes(item.id))]; } const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ - SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1], + SECTIONS_WITH_HISTORY[0], { id: 'historico', label: 'Trazabilidad' }, ...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []), SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]]; diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 752780e..bd96dad 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -40,7 +40,7 @@ describe('Secciones compartidas por dominio', () => { const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); const esperadas = domain === 'tea' ? ['Indicadores', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones'] - : ['Indicadores', domain === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + : ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; From 8bca0fbcdf7d6831d599c4e1d17db1517a437722 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 18:39:22 -0600 Subject: [PATCH 29/35] =?UTF-8?q?CaCu=20indicators:=20=C2=ABProgresi=C3=B3?= =?UTF-8?q?n=20por=20grupo=20de=20riesgo=C2=BB=20withdrawn=20from=20the=20?= =?UTF-8?q?clinical=20figures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores-cacu-secciones.spec.ts | 17 +++++++---------- src/app/features/indicadores/indicadores-kpi.ts | 3 +-- .../features/indicadores/indicadores-page.html | 1 - .../features/indicadores/indicadores-page.ts | 3 +-- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 56638f3..521e7e6 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -1,6 +1,5 @@ // Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under -// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures with the -// pending «Progresión por grupo de riesgo». Fixtures: a CaCu catalog shaped like /cacu/indicadores. +// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; @@ -60,8 +59,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', - 'figura-pendiente: Progresión por grupo de riesgo']); + 'catalog-card: Distribución de resultados citológicos', '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', () => { @@ -84,14 +82,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(titulosKpi).not.toContain('Días de toma a resultado'); }); - it('los indicadores clínicos son los dos pedidos más «Progresión por grupo de riesgo» pendiente, sin tarjetas vacías', () => { - // Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending - // figure is not drawn as such. + it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => { + // Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending + // 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', - 'figura-pendiente: Progresión por grupo de riesgo']); - expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')?.textContent).toContain('Integración pendiente'); + 'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica']); + expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull(); }); it('Datos y definiciones conserva todo el catálogo', () => { diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 1278d29..d8a7bf3 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -85,9 +85,8 @@ export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { titulo: 'Tiempo de diagnóstico a tratamiento' }, { id: 'cama_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' }, ]; -// CaCu's clinical figures in display order, and the one still to be implemented. +// CaCu's clinical figures in display order. export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia']; -export const CACU_FIGURA_CLINICA_PENDIENTE = 'Progresión por grupo de riesgo'; export const KPI_BY_DOMAIN: Record = { tea: [ { id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' }, diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 5b80202..58a084f 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -133,7 +133,6 @@ [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> } @if (histopatologiaPendiente) { } - @if (dominio === 'cacu') { }
@if (dominio === 'cama') {
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index d62cce3..5d1db51 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,7 +17,7 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { esSocioConteos } from './indicadores-conteos-pareados'; -import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi'; import { TeaResumenPeriodo } from './tea-resumen-periodo'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorScreeningRoute } from './indicador-screening-route'; @@ -441,7 +441,6 @@ export class IndicadoresPage { } return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items; }); - readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE; // CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it. readonly confirmacionCama = CAMA_CONFIRMACION_KPI; get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); } From 61867ff973839986ceace2c6a3f9d271feef832c Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 18:40:34 -0600 Subject: [PATCH 30/35] Patient risk: survival is 1 at 0 years, at the index date --- .../paciente-riesgo-estimando.spec.ts | 12 +++++++----- .../paciente-detalle/paciente-riesgo.validation.ts | 9 +++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index a0d0257..06052bc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -135,16 +135,18 @@ describe('Riesgo individual: qué se estima y su curva', () => { .toHaveLength(1); }); - it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido', () => { + it('una supervivencia se muestra como 1 − la probabilidad de morir, con el IC invertido, y es 1 a los 0 años', () => { const data = riesgoCacuConEstimando(); const r = data.entry[0].resource; r.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' }); r.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; }); const lote = riesgoPacienteResponse(data, '42')!.riesgo; - expect(lote.horizontes[0]).toMatchObject({ horizonte_anios: 1 }); - expect(lote.horizontes[0].probabilidad).toBeCloseTo(0.92); - expect(lote.horizontes[0].ic_bajo).toBeCloseTo(0.88); - expect(lote.horizontes[0].ic_alto).toBeCloseTo(0.95); + // at the index date every patient is alive + expect(lote.horizontes[0]).toEqual({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 }); + expect(lote.horizontes[1]).toMatchObject({ horizonte_anios: 1 }); + expect(lote.horizontes[1].probabilidad).toBeCloseTo(0.92); + expect(lote.horizontes[1].ic_bajo).toBeCloseTo(0.88); + expect(lote.horizontes[1].ic_alto).toBeCloseTo(0.95); expect(encabezado(lote)).toBe('Probabilidad de supervivencia'); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts index 46e826d..e3b246f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.validation.ts @@ -139,14 +139,19 @@ function simulated(resource: Record): boolean { } /** A model whose estimand asks for its complement (survival from a probability of dying): each horizon becomes - * 1 − p, and its interval 1 − high to 1 − low. */ + * 1 − p, and its interval 1 − high to 1 − low; survival at 0 years is 1. */ function complemento(lote: LoteRiesgoCacu): void { if (lote.estimando?.complement !== 'supervivencia') return; - lote.horizontes = lote.horizontes.map(h => ({ + const horizontes = lote.horizontes.map(h => ({ ...h, probabilidad: 1 - h.probabilidad, ic_bajo: h.ic_alto == null ? h.ic_alto ?? null : 1 - h.ic_alto, ic_alto: h.ic_bajo == null ? h.ic_bajo ?? null : 1 - h.ic_bajo, })); + // At its index date every patient is alive: survival at 0 years is 1, whether or not the model gives it. + if (horizontes.length && !horizontes.some(h => h.horizonte_anios === 0)) { + horizontes.unshift({ horizonte_anios: 0, probabilidad: 1, ic_bajo: 1, ic_alto: 1 }); + } + lote.horizontes = horizontes; } /** Where an outcome goes among the patient's risks: CIN2+ first, then cancer, then any other. */ From f82ce8cc389589e9740513bde0d45a86788f4930 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 19:41:34 -0600 Subject: [PATCH 31/35] Patient record: probability columns by follow-up status The risk table shows only what the patient's follow-up status follows, as the follow-up table does: a case, her survival; before colposcopy, LIEAG+ and cancer; after colposcopy or treatment, LIEAG+. Without a status every column stays. --- .../paciente-detalle/paciente-detalle.html | 2 +- .../paciente-detalle.models.ts | 2 ++ .../paciente-detalle.state.ts | 1 + .../paciente-detalle/paciente-detalle.ts | 1 + .../paciente-riesgo-estimando.spec.ts | 34 ++++++++++++++++++- .../paciente-riesgo-tabla.html | 4 +-- .../paciente-detalle/paciente-riesgo-tabla.ts | 7 ++-- .../paciente-riesgo.presentacion.ts | 21 ++++++++++-- 8 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html index 18d3a53..e540175 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html @@ -79,7 +79,7 @@

Riesgos y recomendaciones

- +
} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts index bbbde94..254f2f4 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts @@ -6,6 +6,8 @@ export interface PacienteResumen { identidad: IdentidadPaciente; grupoEdad: string | null; estatus: string | null; + /** The follow-up status code (`CASO`, `PRE_COLPOSCOPIA`…): it decides which probabilities the record shows. */ + estatusCodigo: string | null; corte: string; origen: 'seguimiento-demostracion'; citologia: { fecha: string; resultado: string | null; calidad: string | null } | null; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts index b323aa1..58006e3 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts @@ -45,6 +45,7 @@ export class PacienteDetalleState { identidad, grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad, estatus: paciente.estatus.etiqueta, + estatusCodigo: paciente.estatus.codigo, corte, origen: 'seguimiento-demostracion', citologia: paciente.ultima_citologia ? { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts index d9b38c3..1361ce5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts @@ -34,6 +34,7 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy { get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; } /** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */ + get estatusCodigo() { return this.estado.tipo !== 'cerrado' ? this.estado.resumen.estatusCodigo : null; } get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; } temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts index 06052bc..a40fe00 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-estimando.spec.ts @@ -12,7 +12,7 @@ import { PacienteRiesgoTabla } from './paciente-riesgo-tabla'; // What the patient's risk says about its number (the model's `[estimand]`) and the curve of its horizons. describe('Riesgo individual: qué se estima y su curva', () => { - function setup(data: unknown) { + function setup(data: unknown, estatus: string | null = null) { const react = vi.fn(() => Promise.resolve()); TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), { provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(data) } }, @@ -20,6 +20,7 @@ describe('Riesgo individual: qué se estima y su curva', () => { addFrames: vi.fn(), deleteFrames: vi.fn() }) }] }); const fixture = TestBed.createComponent(PacienteRiesgoTabla); fixture.componentRef.setInput('pacId', '42'); + fixture.componentRef.setInput('estatus', estatus); fixture.detectChanges(); fixture.detectChanges(); return { fixture, root: fixture.nativeElement as HTMLElement }; @@ -160,4 +161,35 @@ describe('Riesgo individual: qué se estima y su curva', () => { riesgos[1].estimando = { ...riesgos[1].estimando, covariates: 'otras' }; expect(covariables(riesgos)).toBe('Covariables: Probabilidad a LIEAG+: VPH y citología índice; Probabilidad a cáncer: otras.'); }); + + /** The Bundle of a patient scored by the CIN2+, cancer and survival models (survival first). */ + function conSupervivencia() { + const data = riesgoCacuDosDesenlaces(); + const muerte = structuredClone(data.entry[1].resource); + muerte.id = '14-42'; + muerte.extension[0].extension.push({ url: 'complement', valueString: 'supervivencia' }); + muerte.prediction.forEach((p: any) => { p.outcome.coding[0].code = 'muerte'; }); + data.entry.unshift({ fullUrl: 'http://localhost/cacu/fhir/RiskAssessment/14-42', resource: muerte }); + data.total = 3; + return data; + } + const encabezados = (root: HTMLElement) => [...root.querySelectorAll('table.risk thead th')].map(th => th.textContent!.trim()); + + it('a un caso solo le muestra su supervivencia, sin LIEAG+ ni cáncer, también en el detalle', () => { + // Fails if the record stops following the follow-up status, or shows a case the risk of a disease she already has. + const { root } = setup(conSupervivencia(), 'CASO'); + expect(encabezados(root)).toEqual(['Horizonte (años)', 'Probabilidad de supervivencia (%)']); + expect(root.querySelectorAll('table.models tbody tr')).toHaveLength(1); + }); + + it('antes de la colposcopia muestra LIEAG+ y cáncer; después, solo LIEAG+; sin estatus, todo', () => { + // Fails if a status shows another set of columns than the follow-up table's, or no status hides a column. + expect(encabezados(setup(conSupervivencia(), 'PRE_COLPOSCOPIA').root)) + .toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)']); + TestBed.resetTestingModule(); + expect(encabezados(setup(conSupervivencia(), 'POST_COLPOSCOPIA').root)).toEqual(['Horizonte (años)', 'Probabilidad a LIEAG+ (%)']); + TestBed.resetTestingModule(); + expect(encabezados(setup(conSupervivencia()).root)).toEqual( + ['Horizonte (años)', 'Probabilidad a LIEAG+ (%)', 'Probabilidad a cáncer (%)', 'Probabilidad de supervivencia (%)']); + }); }); 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 5416dfd..38d81bc 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -8,8 +8,8 @@ @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { @let todos = lectura.datos.riesgos; - @let riesgos = conRiesgo(todos); - @let riesgo = lectura.datos.riesgo; + @let riesgos = conRiesgo(delEstatus(todos)); + @let riesgo = riesgos[0] ?? lectura.datos.riesgo; @let columnas = columnasDe(todos); @let filas = filasDe(lotesDe(columnas)); @if (filas.length) { 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 0fa8ab7..215d641 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -3,7 +3,7 @@ import { LowerCasePipe } 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, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; +import { ColumnaRiesgo, columnasRiesgo, conRiesgo, delEstatus, covariables, encabezado, etiquetaDesenlace, filasRiesgo, fraseRiesgo, porcentaje } from './paciente-riesgo.presentacion'; import { DominioRiesgo, LoteRiesgoCacu } from './paciente-riesgo.models'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -26,6 +26,8 @@ export class PacienteRiesgoTabla { readonly pacId = input.required(); /** The domain whose model scored her: CaCu unless said otherwise. */ readonly dominio = input('cacu'); + /** Her follow-up status code: the table shows only the probabilities that status follows (a case, her survival). */ + readonly estatus = input(null); readonly rotulo = computed(() => this.dominio() === 'cama' ? 'CaMa' : 'CaCu'); private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; @@ -40,7 +42,8 @@ export class PacienteRiesgoTabla { readonly filasDe = filasRiesgo; readonly conRiesgo = conRiesgo; readonly covariables = covariables; - columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio()); } + columnasDe(riesgos: LoteRiesgoCacu[]): ColumnaRiesgo[] { return columnasRiesgo(riesgos, this.dominio(), this.estatus()); } + delEstatus(riesgos: LoteRiesgoCacu[]): LoteRiesgoCacu[] { return delEstatus(riesgos, this.estatus()); } lotesDe(columnas: ColumnaRiesgo[]) { return columnas.map(c => (c.lote?.horizontes.length ? c.lote : null)); } private figuraDe?: { riesgos: LoteRiesgoCacu[]; figura: PlotlyFigure }; figura(riesgos: LoteRiesgoCacu[]): PlotlyFigure { 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 da9a3ee..98b6fa7 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.presentacion.ts @@ -1,3 +1,4 @@ +import { COLUMNAS_DE_PROBABILIDAD, ProbabilidadClave } from '../cacu-seguimiento.models'; import { HorizonteRiesgoCacu, LoteRiesgoCacu, ResultadosIndice } from './paciente-riesgo.models'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -39,6 +40,20 @@ const COLUMNAS_FIJAS: Record const esDe = (lote: LoteRiesgoCacu, desenlace: string) => desenlace === 'cin2' ? lote.desenlace.startsWith('cin2') : lote.desenlace === desenlace; +/** The outcomes the record shows for each follow-up status, the same as the follow-up table's columns: a case + * already has the disease, so only her survival; a patient before colposcopy, LIEAG+ and cancer; after it, LIEAG+. */ +const DESENLACE_DE_LA_COLUMNA: Record = { lieag: 'cin2', cancer: 'cancer', supervivencia: 'muerte' }; +export function desenlacesDelEstatus(estatus: string | null | undefined): string[] | null { + const columnas = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] : undefined; + return columnas ? columnas.map(c => DESENLACE_DE_LA_COLUMNA[c]) : null; +} + +/** The risks of the outcomes her follow-up status shows; all of them when the status names none. */ +export function delEstatus(riesgos: LoteRiesgoCacu[], estatus: string | null | undefined): LoteRiesgoCacu[] { + const desenlaces = desenlacesDelEstatus(estatus); + return desenlaces ? riesgos.filter(r => desenlaces.some(d => esDe(r, d))) : riesgos; +} + export interface ColumnaRiesgo { encabezado: string; /** Its model's risks; `null` when no model of the outcome is current. */ @@ -49,9 +64,11 @@ export interface ColumnaRiesgo { /** The table's columns: the domain's fixed outcomes (CaCu: LIEAG+ and cancer), with or without a model, then any * other outcome she has a risk of. A column's index date shows when it isn't the first risk's. */ -export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu'): ColumnaRiesgo[] { +export function columnasRiesgo(riesgos: LoteRiesgoCacu[], dominio = 'cacu', estatus: string | null = null): ColumnaRiesgo[] { + riesgos = delEstatus(riesgos, estatus); const fecha = riesgos.find(r => r.horizontes.length)?.fecha_indice ?? null; - const fijas = COLUMNAS_FIJAS[dominio] ?? []; + const desenlaces = desenlacesDelEstatus(estatus); + const fijas = (COLUMNAS_FIJAS[dominio] ?? []).filter(f => !desenlaces || desenlaces.includes(f.desenlace)); const columnas: ColumnaRiesgo[] = fijas.map(({ desenlace, etiqueta }) => { const lote = riesgos.find(r => esDe(r, desenlace)) ?? null; if (!lote) return { encabezado: `Probabilidad a ${etiqueta}`, lote: null, vacia: 'No disponible' }; From 14d6875d9b3059259a48ab96d9f164296e8e3335 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 19:48:41 -0600 Subject: [PATCH 32/35] =?UTF-8?q?Screening=20route:=20the=20reading=20note?= =?UTF-8?q?,=20condensed,=20folds=20into=20=C2=ABC=C3=B3mo=20leer=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicador-screening-route.html | 20 ++++++++++--------- .../indicador-screening-route.scss | 1 + .../indicador-screening-route.spec.ts | 11 ++++++++++ 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/app/features/indicadores/indicador-screening-route.html b/src/app/features/indicadores/indicador-screening-route.html index 72d1bec..e6e0f1b 100644 --- a/src/app/features/indicadores/indicador-screening-route.html +++ b/src/app/features/indicadores/indicador-screening-route.html @@ -17,15 +17,17 @@ @if (status() === 'empty') {

No hay tiempos publicados para esta ruta.

} @else if (figure(); as figure) { -

- @if (view() === 'cumulative') { - Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento. - El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia. - } @else { - Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos. - Las medianas de los tramos no tienen que sumar el tiempo acumulado. - } -

+
Cómo leer +

+ @if (view() === 'cumulative') { + Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él. + El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia. + } @else { + Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos, + y las medianas de los tramos no suman el acumulado. + } +

+
}
Valores publicados
diff --git a/src/app/features/indicadores/indicador-screening-route.scss b/src/app/features/indicadores/indicador-screening-route.scss index d4a1da2..f0ac5a5 100644 --- a/src/app/features/indicadores/indicador-screening-route.scss +++ b/src/app/features/indicadores/indicador-screening-route.scss @@ -3,6 +3,7 @@ p, h3, summary { overflow-wrap: anywhere; } h3 { font-size: 1rem; line-height: 1.5; } .controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; } +.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); } .note { color: var(--issste-text-secondary); max-width: 70ch; } app-plotly-chart { --plot-height: 360px; } summary { cursor: pointer; padding-block: .75rem; } diff --git a/src/app/features/indicadores/indicador-screening-route.spec.ts b/src/app/features/indicadores/indicador-screening-route.spec.ts index 3b38cf7..d69f512 100644 --- a/src/app/features/indicadores/indicador-screening-route.spec.ts +++ b/src/app/features/indicadores/indicador-screening-route.spec.ts @@ -81,6 +81,17 @@ describe('Ruta del tamizaje: componente', () => { expect(text).toContain('mediana 35.7'); expect(text).toContain('Suprimido'); }); + it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => { + // Fails if the reading note goes back to an open paragraph under the chart. + f.detectChanges(); + responder(id => payload(id)); + const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement; + expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer'); + expect(guia.open).toBe(false); + expect(guia.textContent).toContain('bigote: Q1 a Q3'); + expect(f.nativeElement.querySelector('section > p.note')).toBeNull(); + }); + it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => { // Fails if an empty route draws a chart or hides the reason. f.detectChanges(); From 34c6f2af3ae7cc38eec8afe0d3871b3bccf9cedc Mon Sep 17 00:00:00 2001 From: ulises Date: Sat, 21 Nov 2026 23:18:39 -0600 Subject: [PATCH 33/35] TEA seguimiento: the ADOS-2 relation panel reads the association's rows --- .../features/indicadores/indicadores-fhir.spec.ts | 15 ++++++++++++--- .../features/indicadores/tea-seguimiento-fhir.ts | 6 ++++-- .../features/indicadores/tea-seguimiento.spec.ts | 4 ++-- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/app/features/indicadores/indicadores-fhir.spec.ts b/src/app/features/indicadores/indicadores-fhir.spec.ts index b245b29..c23a7a9 100644 --- a/src/app/features/indicadores/indicadores-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-fhir.spec.ts @@ -35,12 +35,12 @@ const curva = { ], }; const prediccion = (zona: string, z: number | null) => ({ - outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] }, + outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] }, probabilityDecimal: 0.41, extension: [ { url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } }, { url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } }, - { url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' }, + { url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' }, ...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]), { url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 }, { url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 }, @@ -329,7 +329,7 @@ describe('Seguimiento de TEA sobre FHIR', () => { expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 }); expect(relacion.filas).toEqual([{ biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item', - resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01, + resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01, probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]); }); @@ -356,4 +356,13 @@ describe('Seguimiento de TEA sobre FHIR', () => { expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']); expect(mapa.regiones[0].valor_z).toBe(-2.6); }); + + it('las regiones del mapa son las zonas del análisis del EEG', () => { + // Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the + // EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes + // back into the central average or the frontal media region disappears. + const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 }); + expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([ + ['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]); + }); }); diff --git a/src/app/features/indicadores/tea-seguimiento-fhir.ts b/src/app/features/indicadores/tea-seguimiento-fhir.ts index 4c3c61f..b41e26f 100644 --- a/src/app/features/indicadores/tea-seguimiento-fhir.ts +++ b/src/app/features/indicadores/tea-seguimiento-fhir.ts @@ -35,7 +35,8 @@ const CRITERIOS = 'urn:tea:validation'; const FILTRO_EEG: Record = { sin_eeg_valido: 'sin-eeg-valido' }; const INTERPRETACION: Record = { H: 'aumentado', L: 'disminuido', N: 'normal' }; -// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average. +// The 10-20 electrodes on the page's head (x left to right, y back to front, radius 1) and the regions they average, +// the scalp zones of the EEG analysis (`tea.contracts.ZONES`). export const ELECTRODOS: Record = { Fp1: [-.25, .77], Fp2: [.25, .77], F7: [-.65, .47], F3: [-.33, .4], Fz: [0, .38], F4: [.33, .4], F8: [.65, .47], T3: [-.8, 0], C3: [-.4, 0], Cz: [0, 0], C4: [.4, 0], T4: [.8, 0], @@ -43,7 +44,8 @@ export const ELECTRODOS: Record = { }; const REGIONES: [string, string, string[]][] = [ ['frontal_izq', 'Frontal izquierda', ['Fp1', 'F3', 'F7']], ['frontal_der', 'Frontal derecha', ['Fp2', 'F4', 'F8']], - ['central', 'Central', ['Fz', 'C3', 'Cz', 'C4']], ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']], + ['frontal_media', 'Frontal media', ['Fz']], ['central', 'Central', ['C3', 'Cz', 'C4']], + ['temporal_izq', 'Temporal izquierda', ['T3', 'T5']], ['temporal_der', 'Temporal derecha', ['T4', 'T6']], ['parietal', 'Parietal', ['P3', 'Pz', 'P4']], ['occipital', 'Occipital', ['O1', 'O2']], ]; const EJE = Array.from({ length: 41 }, (_, i) => Math.round((-1 + i * .05) * 100) / 100); diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index 51125d1..fb039d7 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -381,8 +381,8 @@ describe('Seguimiento TEA', () => { }); // The association model's panel (prototype, simulated data): the field is optional and checked when present. it('valida la relación con el ADOS-2 y solo muestra las zonas alteradas del paciente', () => { - const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'css_sa', - resultado_etiqueta: 'CSS afecto social', evento: 'Severidad alta (CSS ≥ 8)', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, + const fila = { biomarcador: 'husos', zona: 'central', zona_etiqueta: 'Central', valor_z: -2.5, tipo: 'dominio', resultado: 'CSS', + resultado_etiqueta: 'Puntaje de severidad calibrado (CSS)', evento: '>=8', or: 0.2, ic_inf: 0.13, ic_sup: 0.3, q: 0.0002, probabilidad: 0.93, probabilidad_referencia: 0.18, observado: 10 }; const otra = { ...fila, zona: 'parietal', zona_etiqueta: 'Parietal', valor_z: 0.4, q: 0.01 }; const rel = (filas: object[]) => ({ ...detalle, relacion_ados2: { validado: false, nivel: 'item', n_cohorte: 46, version: 'v', filas } }); From 329c0891aec59f57df47e5df914d6206094d8311 Mon Sep 17 00:00:00 2001 From: ulises Date: Sun, 22 Nov 2026 22:01:50 -0600 Subject: [PATCH 34/35] TEA indicators: Resumen and Trazabilidad tabs, round help buttons, series chips, shared colours, summary box, three-per-row grid and three-significant-digit EEG values --- .../indicadores/indicador-ayuda.spec.ts | 50 ++++ .../features/indicadores/indicador-ayuda.ts | 39 ++++ .../indicadores/indicador-catalog-card.ts | 12 +- .../indicadores/indicador-figure-card.html | 19 +- .../indicadores/indicador-figure-card.scss | 5 + .../indicadores/indicador-figure-card.spec.ts | 10 + .../indicadores/indicador-figure-card.ts | 5 +- .../indicador-figure-panel.spec.ts | 3 + .../indicadores/indicador-figure-panel.ts | 11 +- .../indicadores/indicadores-c1-donut.spec.ts | 4 +- .../indicadores/indicadores-c2-palette.ts | 4 +- .../indicadores/indicadores-c2-panel.spec.ts | 2 +- .../indicadores-historico-figures.spec.ts | 12 +- .../indicadores-historico-figures.ts | 28 ++- .../indicadores-historico-pestana.spec.ts | 3 +- .../indicadores-historico-series.spec.ts | 26 +++ .../indicadores/indicadores-historico.spec.ts | 5 +- .../indicadores/indicadores-historico.ts | 83 ++++++- .../indicadores/indicadores-page.html | 2 +- .../indicadores/indicadores-page.scss | 3 + .../indicadores/indicadores-page.spec.ts | 5 +- .../features/indicadores/indicadores-page.ts | 7 +- .../indicadores-recorrido-analisis.spec.ts | 3 +- .../indicadores/indicadores-sections.spec.ts | 3 +- .../indicadores-tea-secciones.spec.ts | 6 +- .../indicadores/indicadores-tracking.html | 14 +- .../indicadores/indicadores-tracking.scss | 3 +- .../indicadores/indicadores-tracking.ts | 17 ++ .../indicadores/tea-paciente-resumen.html | 220 ++++++++++++------ .../indicadores/tea-paciente-resumen.scss | 46 ++-- .../indicadores/tea-paciente-resumen.ts | 22 +- .../indicadores/tea-resumen-periodo.spec.ts | 11 +- .../indicadores/tea-resumen-periodo.ts | 12 +- .../indicadores/tea-seguimiento.spec.ts | 156 ++++++++----- 34 files changed, 625 insertions(+), 226 deletions(-) create mode 100644 src/app/features/indicadores/indicador-ayuda.spec.ts create mode 100644 src/app/features/indicadores/indicador-ayuda.ts create mode 100644 src/app/features/indicadores/indicadores-historico-series.spec.ts diff --git a/src/app/features/indicadores/indicador-ayuda.spec.ts b/src/app/features/indicadores/indicador-ayuda.spec.ts new file mode 100644 index 0000000..e177c77 --- /dev/null +++ b/src/app/features/indicadores/indicador-ayuda.spec.ts @@ -0,0 +1,50 @@ +// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click. +// Fixture: a host component that projects one line of text into the button. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { IndicadorAyuda } from './indicador-ayuda'; + +@Component({ imports: [IndicadorAyuda], template: `Texto de ayuda` }) +class Host { aperturas = 0; } + +describe('Ayuda redonda', () => { + function crear() { + const fixture = TestBed.createComponent(Host); + fixture.detectChanges(); + const root: HTMLElement = fixture.nativeElement; + const boton = () => root.querySelector('.ayuda-boton')!; + const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim(); + const ayuda = root.querySelector('.ayuda')!; + return { fixture, boton, texto, ayuda }; + } + + it('muestra el texto al pasar el cursor y lo oculta al salir', () => { + // Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned. + const { fixture, texto, ayuda } = crear(); + expect(texto()).toBeUndefined(); + ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges(); + expect(texto()).toBe('Texto de ayuda'); + ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges(); + expect(texto()).toBeUndefined(); + }); + + it('un clic fija el texto hasta el siguiente clic', () => { + // Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it. + const { fixture, boton, texto, ayuda } = crear(); + ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges(); + ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges(); + expect(texto()).toBe('Texto de ayuda'); + expect(boton().getAttribute('aria-expanded')).toBe('true'); + boton().click(); fixture.detectChanges(); + expect(texto()).toBeUndefined(); + expect(boton().getAttribute('aria-expanded')).toBe('false'); + }); + + it('avisa solo al abrirse con un clic y nombra el botón', () => { + // Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost. + const { fixture, boton } = crear(); + boton().click(); boton().click(); boton().click(); fixture.detectChanges(); + expect(fixture.componentInstance.aperturas).toBe(2); + expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba'); + }); +}); diff --git a/src/app/features/indicadores/indicador-ayuda.ts b/src/app/features/indicadores/indicador-ayuda.ts new file mode 100644 index 0000000..ffeb980 --- /dev/null +++ b/src/app/features/indicadores/indicador-ayuda.ts @@ -0,0 +1,39 @@ +import { Component, input, output, signal } from '@angular/core'; + +// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click. +@Component({ + selector: 'app-indicador-ayuda', + template: ` +
+ + @if (visible()) { + + } +
+ `, + styles: ` + :host { position: absolute; top: .5rem; right: .5rem; z-index: 2; } + .ayuda { position: relative; } + .ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0; + border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; } + .ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + .ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4); + background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent); + border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; } + `, +}) +export class IndicadorAyuda { + readonly etiqueta = input('Cómo leer'); + readonly opened = output(); + readonly sobre = signal(false); + readonly fijo = signal(false); + private static contador = 0; + readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador; + visible() { return this.sobre() || this.fijo(); } + alternar() { + const abre = !this.fijo(); + this.fijo.set(abre); + if (abre) this.opened.emit(); + } +} diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index d175696..2e21b53 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados'; import { IndicadorConteosPareados } from './indicador-conteos-pareados'; import { parConteos } from './indicadores-conteos-pareados'; +const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados']; + @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' }, + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' }, imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], template: ` @if (!conteos) {
-

{{ indicador.titulo }}

+

{{ indicador.titulo }}

} @@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados'; `, styles: ` :host { display: flex; min-width: 0; margin: 0; } - mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); + mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); } .catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; } .graphic-region { flex: 1; min-width: 0; } :host(.dual-card) { grid-column: 1 / -1; } + :host(.doble) { grid-column: span 2; } .graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); } .representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); } .representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; } @@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados'; .card-identity { min-width: 0; } h2, p { overflow-wrap: anywhere; } h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; } + h2.con-ayuda { padding-right: 2.5rem; } .pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto; min-width: 48px; min-height: 48px; color: var(--issste-text); } .pin-toggle mat-icon { flex-shrink: 0; } @@ -137,6 +141,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { } // Every domain follows CaMa's mockup: no pin, representation selector or figure count. get sobrio() { return true; } + // 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); } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } diff --git a/src/app/features/indicadores/indicador-figure-card.html b/src/app/features/indicadores/indicador-figure-card.html index 406c5c4..58e55a3 100644 --- a/src/app/features/indicadores/indicador-figure-card.html +++ b/src/app/features/indicadores/indicador-figure-card.html @@ -1,5 +1,12 @@ - -@if (selected) { + +@if (selected && ayudaRedonda) { + +
    @for (line of interpretation; track $index) {
  • {{ line }}
  • }
+ @if (state.status === 'ready' && state.footnotes?.length) { + @for (note of state.footnotes; track $index) {

{{ note }}

} + } +
+} @else if (selected) {
} @if (state.status === 'ready' && state.highlight; as h) { -
+

Selección: {{ highlightStatus }}

@for (row of highlightRows(h); track row.group?.id ?? '') { diff --git a/src/app/features/indicadores/indicador-figure-card.scss b/src/app/features/indicadores/indicador-figure-card.scss index 3fe56b0..8f2c09f 100644 --- a/src/app/features/indicadores/indicador-figure-card.scss +++ b/src/app/features/indicadores/indicador-figure-card.scss @@ -22,6 +22,7 @@ .methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } .figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto; overflow: visible; min-width: 0; border: 1px solid var(--issste-border); } +.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; } .figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; } .interpretation { grid-row: 1; } .figure-legend { grid-row: 3; min-width: 0; } @@ -117,6 +118,7 @@ .highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); } .dark .highlight-legend { color: #eef1f7; } .highlight-status { margin: 0; font-weight: 600; } +.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } .highlight-back { justify-self: start; } .highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; } .highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start; @@ -126,3 +128,6 @@ .highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } .highlight-legend .legend-swatch { border-radius: 50%; } .highlight-legend .highlight-group { font-weight: 600; } + +.ayuda-lista { margin: 0; padding-left: 1.1rem; } +.ayuda-nota { margin: .5rem 0 0; } diff --git a/src/app/features/indicadores/indicador-figure-card.spec.ts b/src/app/features/indicadores/indicador-figure-card.spec.ts index d7b6cd9..be6bde9 100644 --- a/src/app/features/indicadores/indicador-figure-card.spec.ts +++ b/src/app/features/indicadores/indicador-figure-card.spec.ts @@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => { expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot); }); + it('con la ayuda redonda no repite el título ni el nombre de la figura', () => { + // Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title. + fixture.componentRef.setInput('ayudaRedonda', true); + ready({ data: [{ y: [1] }], layout: {} }); + const root: HTMLElement = fixture.nativeElement; + expect(root.querySelector('.figure-title')).toBeNull(); + expect(root.querySelector('.figure-id')).toBeNull(); + expect(root.querySelector('.ayuda-boton')).not.toBeNull(); + expect(root.querySelector('.interpretation')).toBeNull(); + }); }); diff --git a/src/app/features/indicadores/indicador-figure-card.ts b/src/app/features/indicadores/indicador-figure-card.ts index dc6f8cc..3e56541 100644 --- a/src/app/features/indicadores/indicador-figure-card.ts +++ b/src/app/features/indicadores/indicador-figure-card.ts @@ -10,6 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels'; import { CategoryLabel } from './indicadores-axis-labels'; import { figureIdentity, identityElementId } from './indicadores-identities'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadorAyuda } from './indicador-ayuda'; import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology'; import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown'; import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight'; @@ -41,7 +42,7 @@ export interface FigureState { selector: 'app-indicador-figure-card', standalone: true, host: { '[class.methodology-expanded]': 'methodologyExpanded()' }, - imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart], + imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda], templateUrl: './indicador-figure-card.html', styleUrl: './indicador-figure-card.scss', }) @@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges { if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label); else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label); } + // A round "?" button with the reading guide instead of the «Cómo leer» box. + @Input() ayudaRedonda = false; @Input() selected?: Indicador; @Input() metadata?: IndicadorMetadatos; @Input({ required: true }) figuraId!: string; diff --git a/src/app/features/indicadores/indicador-figure-panel.spec.ts b/src/app/features/indicadores/indicador-figure-panel.spec.ts index e34ec83..d858e65 100644 --- a/src/app/features/indicadores/indicador-figure-panel.spec.ts +++ b/src/app/features/indicadores/indicador-figure-panel.spec.ts @@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => { fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]); fixture.componentRef.setInput('figuraId', 'f1'); + // These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec. + fixture.componentRef.setInput('ayudaRedonda', false); fixture.componentRef.setInput('tema', 'claro'); state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']); fixture.componentRef.setInput('applied', state.applied); @@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => { fixture = TestBed.createComponent(IndicadorFigurePanel); fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]); fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro'); + fixture.componentRef.setInput('ayudaRedonda', false); fixture.componentRef.setInput('applied', state.applied); page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} }); expect(JSON.stringify(state)).toBe(snapshot); diff --git a/src/app/features/indicadores/indicador-figure-panel.ts b/src/app/features/indicadores/indicador-figure-panel.ts index 0213b44..711c4c4 100644 --- a/src/app/features/indicadores/indicador-figure-panel.ts +++ b/src/app/features/indicadores/indicador-figure-panel.ts @@ -23,9 +23,10 @@ import { MatTooltipModule } from '@angular/material/tooltip'; @Component({ selector: 'app-indicador-figure-panel', + host: { '[class.ayuda-externa]': 'conAyudaRedonda' }, imports: [IndicadorFigureCard, MatTooltipModule], template: ` -
+

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

@if (sidebar) {
- @if (d.eeg; as e) { -
-
-

Alteraciones del EEG Datos de ejemplo

-

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

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

Sin alteraciones en las métricas evaluadas.

} -
    - @for (m of e.alteraciones; track m.codigo) { -
  • -
    - - {{ estado[m.estado] }} -
    - @if (m.referencia; as r) { -

    {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}

    - } @else { -

    @if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}

    + @if (d.eeg; as e) { +
    +

    Alteraciones del EEG Datos de ejemplo

    +

    Referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}). Elige una alteración para ver sus zonas y la norma.

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

    Sin alteraciones en las métricas evaluadas.

    } +
    +
      + @for (m of e.alteraciones; track m.codigo) { +
    • +
      + + {{ estado[m.estado] }} +
      + @if (m.referencia; as r) { +

      {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ cifras(r.min) }}–{{ cifras(r.max) }}@if (r.mediana !== null) { (mediana {{ cifras(r.mediana) }}) } · z = {{ cifras(m.valor_z) }}

      + } @else { +

      @if (m.valor !== null) { {{ cifras(m.valor) }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}

      + } + @if (m.efectos.length) { +

      Posibles efectos asociados

      +
        + @for (efecto of m.efectos; track efecto) {
      • {{ efecto }}
      • } +
      + } +
    • } - @if (m.efectos.length) { -

      Posibles efectos asociados

      -
        - @for (efecto of m.efectos; track efecto) {
      • {{ efecto }}
      • } -
      +
    +
    + @if (!abierto(e)) {

    La métrica elegida no tiene mapa ni norma por edad para mostrar.

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

    Zonas más afectadas

    +

    {{ mapa.metrica }} · mapa ilustrativo

    +

    Azul: menos actividad Rojo: más actividad

    + @if (figura) { + + } +
      + @for (r of mapa.regiones; track r.codigo) { +
    1. {{ r.etiqueta }}z = {{ cifras(r.valor_z) }}
    2. + } +
    +
    } -
  • - } -
-
- - @if (abierto(e)) { -
- @if (mapaActual(e) && normaActual(e)) { -
- - + @if (normaActual(e); as m) { +
+

Norma por edad

+

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

+ @if (figuraNorma) { + + } +

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

+
+ } +
- } - @if (vista === 'norma' && normaActual(e); as m) { -

Norma por edad

-

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

- @if (figuraNorma) { - - } -

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

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

Zonas más afectadas

-

{{ mapa.metrica }} · mapa ilustrativo

-

Azul: menos actividad Rojo: más actividad

- @if (figura) { - - } -
    - @for (r of mapa.regiones; track r.codigo) { -
  1. {{ r.etiqueta }}z = {{ r.valor_z }}
  2. - } -
- } -
+ } -
- } - @if (d.relacion_ados2; as rel) { -
-

Relación con el ADOS-2 Datos de ejemplo

+ @if (d.relacion_ados2; as rel) { +
+

Relación con el ADOS-2 Datos de ejemplo

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

@@ -144,9 +211,9 @@ @for (f of filasRelacion(rel); track f.biomarcador + f.zona + f.resultado) { - {{ f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ f.valor_z }}@if (zonaAlterada(f)) { · alterada} + {{ f.biomarcador }}{{ f.zona_etiqueta }} · z = {{ cifras(f.valor_z) }}@if (zonaAlterada(f)) { · alterada} {{ f.resultado_etiqueta }}{{ f.tipo === 'item' ? 'Reactivo' : 'Dominio' }} - OR {{ f.or }}IC 95 % {{ f.ic_inf }}–{{ f.ic_sup }} · q {{ qTexto(f.q) }}{{ direccion(f) }} + OR {{ cifras(f.or) }}IC 95 % {{ cifras(f.ic_inf) }}–{{ cifras(f.ic_sup) }} · q {{ qTexto(f.q) }}{{ direccion(f) }} {{ porcentaje(f.probabilidad) }} %
- } -
+ + } +
+ } } diff --git a/src/app/features/indicadores/tea-paciente-resumen.scss b/src/app/features/indicadores/tea-paciente-resumen.scss index f81cf4d..e0c20cd 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.scss +++ b/src/app/features/indicadores/tea-paciente-resumen.scss @@ -1,5 +1,23 @@ :host { display: block; container: host / inline-size; } -.resumen { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: .75rem; } +// The four cards side by side in one row; two by two and then stacked as the row narrows. +.tarjetas { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: .75rem; } +@container host (max-width: 64rem) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@container host (max-width: 36rem) { .tarjetas { grid-template-columns: minmax(0, 1fr); } } +.cifras { margin: 0; font-size: .85rem; } +.alteradas { margin: 0; padding: 0; list-style: none; font-size: .85rem; } +.alteradas li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; padding: .25rem 0; border-top: 1px solid var(--issste-border); font-weight: 600; } +.alteradas .estado { color: #B3261E; font-weight: 400; } +.principal { margin: 0; font-size: .85rem; } +button.completo { margin-top: .75rem; padding: .35rem .75rem; color: var(--issste-accent); font-weight: 600; } +// The full record: one collapsible section after another, no cards. +.documento { max-width: 64rem; } +.seccion { margin: 0; padding: .25rem 0 .75rem; border-bottom: 1px solid var(--issste-border); } +.seccion > summary { margin: 0; } +.seccion > summary h2 { margin: 0; font-size: 1.15rem; } +.seccion > :not(summary) { margin-inline-start: 1.25rem; } +.documento .metricas { grid-template-columns: minmax(0, 1fr); gap: 0; } +.documento .metricas > li { border: 0; border-top: 1px solid var(--issste-border); border-radius: 0; padding: .5rem 0 .5rem .6rem; } +.documento .metricas > li[data-estado=aumentado], .documento .metricas > li[data-estado=disminuido] { border-inline-start: 4px solid #B3261E; } .panel { min-width: 0; padding: .75rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); } h3 { margin: 0 0 .15rem; font-size: 1rem; } .meta { margin: 0 0 .5rem; font-size: .8rem; color: var(--issste-text-secondary); } @@ -47,17 +65,12 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re font-size: .75rem; font-weight: 400; color: var(--issste-text-secondary); vertical-align: middle; } .sin-alteraciones { margin: 0 0 .75rem; font-weight: 600; } .metricas, .efectos { margin: 0; padding: 0; list-style: none; } -// The map has its final width from the start, because Plotly draws at the width it finds: its column only reveals it. -.alteraciones-zona { container: zona / inline-size; grid-column: 1 / -1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 0fr); align-items: start; transition: grid-template-columns 300ms ease; } -.alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 1rem; } -.marco-mapa { min-width: 0; overflow: hidden; } -.mapa { box-sizing: border-box; width: calc(50cqw - .5rem); padding-top: .75rem; animation: aparecer 300ms ease; } -.mapa h3 { margin-top: 0; } -@keyframes aparecer { from { opacity: 0; } } -@container (min-width: 68rem) { .alteraciones-zona { grid-column: span 2; } } -@container host (max-width: 42rem) { .mapa { width: 100cqw; } } -@container (max-width: 42rem) { .alteraciones-zona.abierta { grid-template-columns: minmax(0, 1fr); } } -@media (prefers-reduced-motion: reduce) { .alteraciones-zona { transition: none; } .mapa { animation: none; } } +// The full summary: the metric list on the left, the plots of the chosen metric on the right, always in view. +.alteraciones-lado { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 1.5rem; align-items: start } +@container host (max-width: 52rem) { .alteraciones-lado { grid-template-columns: minmax(0, 1fr); } } +.graficos { min-width: 0; display: grid; gap: 1rem; } +.grafico h3 { margin-top: 0; } +.sin-grafico { margin: 0; font-size: .9rem; color: var(--issste-text-secondary); } .metricas { display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: .5rem; align-items: start; } .metricas > li { position: relative; padding: .5rem .6rem; border: 1px solid var(--issste-border); border-inline-start-width: 4px; border-radius: var(--issste-radius); transition: background-color 120ms ease; } .metricas > li:has(button:not(:disabled)):hover { background: color-mix(in srgb, var(--issste-accent) 8%, transparent); } @@ -65,7 +78,9 @@ h3 .mock { display: inline-block; white-space: nowrap; margin-inline-start: .5re .metricas > li[data-estado=aumentado], .metricas > li[data-estado=disminuido] { border-inline-start-color: #B3261E; } .metrica { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .1rem 1rem; font-size: .9rem; font-weight: 600; } li[data-estado=aumentado] .estado, li[data-estado=disminuido] .estado { color: #B3261E; } -li[data-estado=normal] .estado { color: var(--issste-text-secondary); font-weight: 400; } +li[data-estado=normal] .estado { color: #1B7F3B; font-weight: 600; } +:host-context([data-theme=dark]) li[data-estado=normal] .estado { color: #6FD38A; } +@media (prefers-color-scheme: dark) { :host-context(:root:not([data-theme=light])) li[data-estado=normal] .estado { color: #6FD38A; } } li[data-estado=no_evaluable] .estado { color: var(--issste-text-secondary); font-weight: 400; font-style: italic; } .valor { margin: .1rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); font-variant-numeric: tabular-nums; } .efectos-titulo { margin: .3rem 0 .1rem; font-size: .8rem; font-weight: 600; } @@ -88,9 +103,4 @@ button { min-height: 44px; padding: .6rem; border: 1px solid var(--issste-border .barra .paciente { position: absolute; inset-block: 0; inset-inline-start: 0; border-radius: 999px; background: var(--issste-accent); } .barra .referencia { position: absolute; top: -.15rem; bottom: -.15rem; width: 2px; background: var(--issste-text-secondary); } .nota { margin: .5rem 0 0; font-size: .75rem; color: var(--issste-text-secondary); } -// The switch between the head map and the age norm, when the metric has both. -.vistas { display: inline-flex; margin-bottom: .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); overflow: hidden; } -.vistas button { margin: 0; min-height: 0; padding: .3rem .75rem; border: 0; background: none; color: inherit; font: inherit; font-size: .8rem; cursor: pointer; } -.vistas button + button { border-inline-start: 1px solid var(--issste-border); } -.vistas button[aria-pressed=true] { background: color-mix(in srgb, var(--issste-accent) 14%, transparent); font-weight: 600; } .leyenda-norma { margin: .25rem 0 0; font-size: .8rem; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-paciente-resumen.ts b/src/app/features/indicadores/tea-paciente-resumen.ts index 1f99f7a..80936dd 100644 --- a/src/app/features/indicadores/tea-paciente-resumen.ts +++ b/src/app/features/indicadores/tea-paciente-resumen.ts @@ -1,4 +1,4 @@ -import { Component, DestroyRef, ElementRef, inject, Input, OnInit, signal } from '@angular/core'; +import { Component, DestroyRef, ElementRef, inject, Input, OnInit, output, signal } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyFigure } from './indicadores.models'; @@ -86,6 +86,10 @@ export function normaFigure(m: TeaEegAlteracion, edad: number): PlotlyFigure { }) export class TeaPacienteResumen implements OnInit { @Input({ required: true }) id = ''; + /** `tarjetas`: four summary cards for a table row. `resumen`: the whole record as a summary with collapsible headers. */ + @Input() modo: 'tarjetas' | 'resumen' = 'tarjetas'; + /** The cards' button: the host shows the whole record in its own section. */ + readonly completo = output(); private readonly service = inject(TeaSeguimientoService); private readonly destroy = inject(DestroyRef); readonly status = signal<'loading' | 'ready' | 'error'>('loading'); @@ -101,8 +105,7 @@ export class TeaPacienteResumen implements OnInit { } return '#FFFFFF'; } - // The side panel shows the chosen metric's head map, its age norm, or both with a switch between them. - vista: 'zonas' | 'norma' = 'zonas'; + // The chosen metric's head map and its age norm, whichever it has. figuraNorma?: PlotlyFigure; mapaActual(eeg: TeaEeg) { return eeg.mapas.find(m => m.codigo === this.mapaElegido); } // The age norm can only be drawn with the curve, the patient's value and their age. @@ -115,15 +118,13 @@ export class TeaPacienteResumen implements OnInit { private mostrar(eeg: TeaEeg, codigo: string | undefined) { const mapa = eeg.mapas.find(m => m.codigo === codigo), norma = this.conNorma(eeg, codigo); this.mapaElegido = mapa || norma ? codigo : undefined; - this.vista = mapa ? 'zonas' : 'norma'; this.figura = mapa && mapaFigure(eeg, mapa, this.fondo()); this.figuraNorma = norma && normaFigure(norma, eeg.edad_meses as number); } elegirMapa(eeg: TeaEeg, codigo: string) { - // The chosen card closes the panel again, and the cards take the whole space back. - this.mostrar(eeg, codigo === this.mapaElegido ? undefined : codigo); + // In the cards' accordion the chosen metric closes its panel again; in the full summary the plots stay in view. + this.mostrar(eeg, this.modo === 'tarjetas' && codigo === this.mapaElegido ? undefined : codigo); } - verVista(vista: 'zonas' | 'norma') { this.vista = vista; } readonly clasificacion = CLASIFICACIONES_ADOS2; readonly nivelCss = NIVEL_CSS; readonly calidad = CALIDAD; @@ -146,6 +147,8 @@ export class TeaPacienteResumen implements OnInit { } // The study-wide checks, then each bad channel. delEstudio(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo === null); } + // Three significant digits, without trailing zeros. + cifras(n: number | null | undefined) { return typeof n === 'number' ? String(Number(n.toPrecision(3))) : ''; } canalesMalos(eeg: TeaEeg) { return eeg.criterios_calidad.filter(c => c.electrodo !== null); } valorDe(c: TeaCriterioCalidad) { return c.valor === null ? '' : typeof c.valor === 'number' ? `${Math.round(c.valor * 100) / 100}${c.unidad ? ' ' + c.unidad : ''}` : c.valor; @@ -155,6 +158,9 @@ export class TeaPacienteResumen implements OnInit { return m.sin_evaluar === 'sin_valor' ? 'No se pudo medir en el estudio.' : 'Sin referencia para la edad del niño.'; } clasificacionDe(a: TeaAdos2) { return a.clasificacion ? this.clasificacion[a.clasificacion] : 'Sin clasificación'; } + // How many of the study-wide checks are out of range, and how many metrics could be judged against the age norm. + reglasFuera(eeg: TeaEeg) { return this.delEstudio(eeg).filter(c => c.nivel === 'malo').length; } + evaluables(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado !== 'no_evaluable').length; } alteradas(eeg: TeaEeg) { return eeg.alteraciones.filter(m => m.estado === 'aumentado' || m.estado === 'disminuido'); } pct(value: number, max: number) { return max > 0 ? Math.round(100 * value / max) : 0; } @@ -165,7 +171,7 @@ export class TeaPacienteResumen implements OnInit { return f.or >= 1 ? 'A mayor z, mayor probabilidad' : 'A menor z, mayor probabilidad'; } porcentaje(p: number) { return Math.round(100 * p); } - qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${q.toFixed(3)}`; } + qTexto(q: number) { return q < 0.001 ? '< 0.001' : `= ${this.cifras(q)}`; } observado(f: TeaRelacionAdos2) { if (f.observado === null) return 'Sin dato'; if (f.tipo === 'item') return f.observado >= 1 ? `Alterado (${f.observado})` : 'Sin anormalidad (0)'; diff --git a/src/app/features/indicadores/tea-resumen-periodo.spec.ts b/src/app/features/indicadores/tea-resumen-periodo.spec.ts index c3cecf6..f5a0c27 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.spec.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.spec.ts @@ -37,11 +37,12 @@ describe('Resumen TEA por periodo', () => { expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.'); expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).'); expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.'); - expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); + expect(text).toContain('De los 57 niños con diagnóstico confirmado en este periodo, 41 presentan estudio de EEG y faltan 16 por realizarlo. De los 41 estudios de EEG, 25.0% tienen buena calidad.'); expect(text).toContain('*tomando la mediana de los tiempos'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())) - .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']); + .toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '41', '25.0%']); expect(root.querySelector('button')).toBeNull(); + expect(root.querySelector('h2')!.textContent).toBe('Resumen'); }); it('no copia cifras de ejemplo: otros conteos cambian toda la redacción', () => { @@ -54,7 +55,7 @@ describe('Resumen TEA por periodo', () => { panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })]; const text = texto(render(paneles).nativeElement); expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan'); - expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.'); + expect(text).toContain('De los 1 niños con diagnóstico confirmado en este periodo, 0 presentan estudio de EEG y faltan 1 por realizarlo. De los 0 estudios de EEG, 25.0% tienen buena calidad.'); for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo); }); @@ -64,7 +65,7 @@ describe('Resumen TEA por periodo', () => { paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57)); paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } }); const root: HTMLElement = render(paneles).nativeElement; - expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); + expect(texto(root)).toContain('0 presentan estudio de EEG y faltan 57 por realizarlo. De los 0 estudios de EEG, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.'); expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0'); }); @@ -85,7 +86,7 @@ describe('Resumen TEA por periodo', () => { paneles[4].result.set(c1('28.1', 16, 58)); const root: HTMLElement = render(paneles).nativeElement; expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title'))) - .toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden')); + .toEqual(Array(4).fill('Las poblaciones de M21 y M22 no coinciden')); }); it('indica la carga y reintenta solo las consultas con error', () => { diff --git a/src/app/features/indicadores/tea-resumen-periodo.ts b/src/app/features/indicadores/tea-resumen-periodo.ts index 41f5298..5604f6b 100644 --- a/src/app/features/indicadores/tea-resumen-periodo.ts +++ b/src/app/features/indicadores/tea-resumen-periodo.ts @@ -16,7 +16,8 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2 selector: 'app-tea-resumen-periodo', imports: [MatButtonModule, NgTemplateOutlet], template: ` -
+
+

Resumen

Al cierre del periodo {{ periodo }}, se evaluaron niños entre 16 y 36 meses; únicamente tienen M-CHAT, @@ -29,10 +30,10 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2 El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de .
- De los niños con diagnóstico confirmado al cierre del periodo, - tienen un EEG de buena calidad y - aún no cuentan con uno de esa calidad. - Del total de estudios de EEG del periodo, + De los niños con diagnóstico confirmado en este periodo, + presentan estudio de EEG y faltan + por realizarlo. + De los estudios de EEG, tienen buena calidad.

*tomando la mediana de los tiempos

@@ -48,6 +49,7 @@ const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M2 :host { display: block; min-width: 0; } .resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + h2 { margin: 0 0 var(--issste-space-3); font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; } p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; } p + p { margin-top: var(--issste-space-4); } p.nota { margin-top: var(--issste-space-2); font-size: .95rem; line-height: 1.5; color: var(--issste-text-secondary); } diff --git a/src/app/features/indicadores/tea-seguimiento.spec.ts b/src/app/features/indicadores/tea-seguimiento.spec.ts index fb039d7..5ddd57a 100644 --- a/src/app/features/indicadores/tea-seguimiento.spec.ts +++ b/src/app/features/indicadores/tea-seguimiento.spec.ts @@ -2,7 +2,7 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { teaPacienteDetalle, teaSeguimientoResponse, TeaEeg, TeaEegMapa } from './tea-seguimiento.service'; -import { mapaFigure } from './tea-paciente-resumen'; +import { mapaFigure, TeaPacienteResumen } from './tea-paciente-resumen'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; import { IndicadoresTracking } from './indicadores-tracking'; @@ -57,6 +57,16 @@ describe('Seguimiento TEA', () => { return fixture; } const request = () => http.expectOne(r => r.url === '/tea/seguimiento'); + // The patient's whole record, as the window opened from the patient id shows it. + function resumen(d: object, id = 'T-0001') { + const fixture = TestBed.createComponent(TeaPacienteResumen); + fixture.componentRef.setInput('id', id); fixture.componentRef.setInput('modo', 'resumen'); + fixture.detectChanges(); + http.expectOne(`/tea/seguimiento/${id}`).flush(d); fixture.detectChanges(); + return fixture; + } + const seccion = (root: HTMLElement, titulo: string) => + Array.from(root.querySelectorAll('details.seccion')).find(d => d.querySelector('summary h2')!.textContent!.trim().startsWith(titulo))!; it('muestra las siete columnas y los valores ausentes como No disponible', () => { const fixture = open(); request().flush(data); fixture.detectChanges(); @@ -146,17 +156,15 @@ describe('Seguimiento TEA', () => { expect(c.draft).toMatchObject({ estado_caso: 'completo', alteracion: 'picos_paroxisticos' }); http.verify(); }); - it('abre con las zonas de la primera alteración, cambia al elegir otra y se cierra al repetirla', () => { - const fixture = open(); - request().flush(data); fixture.detectChanges(); + it('el resumen muestra las alteraciones y sus gráficas lado a lado, siempre a la vista: elegir otra las cambia y repetirla las deja', () => { + const fixture = resumen(detalle); const root: HTMLElement = fixture.nativeElement; - root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); - http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); + const lado = root.querySelector('.alteraciones-lado')!; + expect(lado.querySelector('ul.metricas')).not.toBeNull(); + expect(lado.querySelector('section.graficos')).not.toBeNull(); const tarjetas = root.querySelectorAll('button.nombre'); - expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(true); - expect(tarjetas[0].getAttribute('aria-expanded')).toBe('true'); - const panel = () => root.querySelector('section.mapa')!; - expect(panel().classList.contains('panel')).toBe(false); + const panel = () => root.querySelector('section.graficos')!; + expect(tarjetas[0].getAttribute('aria-pressed')).toBe('true'); expect(panel().textContent).toContain('Azul: menos actividad'); expect(panel().textContent).toContain('Rojo: más actividad'); expect(panel().querySelector('.meta')!.textContent).toContain('Ritmo posterior'); @@ -164,45 +172,38 @@ describe('Seguimiento TEA', () => { tarjetas[3].click(); fixture.detectChanges(); expect(panel().querySelector('.meta')!.textContent).toContain('Picos paroxísticos'); expect(panel().querySelector('.regiones')!.textContent).toContain('Occipital'); - expect(tarjetas[0].getAttribute('aria-expanded')).toBe('false'); + expect(tarjetas[0].getAttribute('aria-pressed')).toBe('false'); expect(tarjetas[1].disabled).toBe(true); - expect(tarjetas[1].hasAttribute('aria-expanded')).toBe(false); + expect(tarjetas[1].hasAttribute('aria-pressed')).toBe(false); + // Choosing the same metric again keeps its plots in view. tarjetas[3].click(); fixture.detectChanges(); - expect(root.querySelector('section.mapa')).toBeNull(); - expect(root.querySelector('.alteraciones-zona')!.classList.contains('abierta')).toBe(false); - tarjetas[0].click(); fixture.detectChanges(); - expect(root.querySelector('section.mapa')).not.toBeNull(); + expect(panel().querySelector('.regiones')).not.toBeNull(); + expect(tarjetas[3].getAttribute('aria-pressed')).toBe('true'); http.verify(); }); - it('muestra la norma por edad con el paciente, con o sin mapa, y rechaza una curva cuyos percentiles se cruzan', () => { + it('muestra el mapa y la norma por edad juntos cuando la métrica tiene los dos, o solo la norma si no tiene mapa, y rechaza una curva cuyos percentiles se cruzan', () => { const curva = { fuente: 'Helsinki (HK1K, base pública)', estado: 'vigilia', edad_meses: [12, 24, 48], p5: [0.5, 0.6, 0.7], p25: [0.8, 1, 1.1], mediana: [1.2, 1.5, 1.6], p75: [1.6, 1.8, 2], p95: [2, 2.2, 2.4] }; const conCurva = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' || m.codigo === 'gradiente_anteroposterior' ? { ...m, curva_referencia: curva } : m); const conNorma = { ...detalle, eeg: { ...detalle.eeg, edad_meses: 20.5, alteraciones: conCurva } }; - const fixture = open(); - request().flush(data); fixture.detectChanges(); + const fixture = resumen(conNorma); const root: HTMLElement = fixture.nativeElement; - root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); - http.expectOne('/tea/seguimiento/T-0001').flush(conNorma); fixture.detectChanges(); - const panel = () => root.querySelector('section.mapa')!; - const vistas = () => panel().querySelectorAll('.vistas button'); - // Ritmo has both: it opens on the map, and the switch moves to the norm with the patient's value and age. - expect(Array.from(vistas()).map(b => b.textContent)).toEqual(['Zonas de la cabeza', 'Norma por edad']); - expect(panel().textContent).toContain('Zonas más afectadas'); - vistas()[1].click(); fixture.detectChanges(); - expect(vistas()[1].getAttribute('aria-pressed')).toBe('true'); - expect(panel().querySelector('h3')!.textContent).toBe('Norma por edad'); + const panel = () => root.querySelector('section.graficos')!; + const titulos = () => Array.from(panel().querySelectorAll('h3')).map(h => h.textContent); + // Ritmo has both: the map and the norm show together, with the patient's value and age, and no switch between them. + expect(titulos()).toEqual(['Zonas más afectadas', 'Norma por edad']); + expect(panel().querySelector('.vistas')).toBeNull(); expect(panel().textContent).toContain('0.9 a los 20.5 meses (z = -2.4)'); - expect(panel().querySelector('.regiones')).toBeNull(); - // Gradiente has no map: its card opens the norm alone, without the switch. + expect(panel().querySelector('.regiones')).not.toBeNull(); + // Gradiente has no map: its norm shows alone. const tarjetas = root.querySelectorAll('button.nombre'); tarjetas[4].click(); fixture.detectChanges(); - expect(tarjetas[4].getAttribute('aria-expanded')).toBe('true'); - expect(vistas().length).toBe(0); + expect(tarjetas[4].getAttribute('aria-pressed')).toBe('true'); + expect(titulos()).toEqual(['Norma por edad']); expect(panel().textContent).toContain('Gradiente anteroposterior'); - const c = fixture.debugElement.query(d => d.name === 'app-tea-paciente-resumen').componentInstance; - const trazas = c.figuraNorma.data as { name: string; x: number[]; y: number[] }[]; + const c = fixture.componentInstance; + const trazas = c.figuraNorma!.data as { name: string; x: number[]; y: number[] }[]; expect(trazas.map(t => t.name)).toEqual(['Del 5 al 95 %', 'Del 25 al 75 %', 'Mediana', 'Este paciente']); expect([trazas[3].x[0], trazas[3].y[0]]).toEqual([20.5, 1.2]); const cruzada = conCurva.map(m => m.codigo === 'ritmo_posterior' ? { ...m, curva_referencia: { ...curva, p25: [0.8, 3, 1.1] } } : m); @@ -215,14 +216,55 @@ describe('Seguimiento TEA', () => { expect(marco('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)'); expect(marco()).toBe('#FFFFFF'); }); + it('redondea a tres cifras significativas', () => { + // Fails if the alterations show more than three significant digits or keep trailing zeros. + const c = TestBed.createComponent(TeaPacienteResumen).componentInstance; + expect([c.cifras(0.123456), c.cifras(12.3456), c.cifras(1234.5), c.cifras(2), c.cifras(null)]).toEqual(['0.123', '12.3', '1230', '2', '']); + }); + it('sin alteraciones abre con la primera métrica evaluable', () => { + const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m); + const fixture = resumen({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); + const root: HTMLElement = fixture.nativeElement; + expect(root.querySelector('section.graficos .meta')!.textContent).toContain('Ritmo posterior'); + http.verify(); + }); + it('el identificador abre el resumen completo en su propia sección, sin desplegar la fila, y Volver regresa a la lista', () => { const fixture = open(); + const ficha = vi.fn(); fixture.componentInstance.fichaPacienteAbierta.subscribe(ficha); request().flush(data); fixture.detectChanges(); const root: HTMLElement = fixture.nativeElement; - root.querySelector('button.row-toggle')!.click(); fixture.detectChanges(); - const normales = detalle.eeg.alteraciones.map(m => m.codigo === 'ritmo_posterior' ? { ...m, estado: 'normal', efectos: [] } : m); - http.expectOne('/tea/seguimiento/T-0001').flush({ ...detalle, eeg: { ...detalle.eeg, alteraciones: normales } }); fixture.detectChanges(); - expect(root.querySelector('section.mapa .meta')!.textContent).toContain('Ritmo posterior'); + const id = root.querySelector('tbody tr.tea-row button.patient-link')!; + expect(id.textContent!.trim()).toBe('T-0001'); + id.click(); fixture.detectChanges(); + http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); + expect(ficha).toHaveBeenLastCalledWith(true); + expect(root.querySelector('tr.tea-detalle')).toBeNull(); + const seccionFicha = root.querySelector('section.ficha-tea')!; + expect(seccionFicha.querySelector('h2')!.textContent).toContain('T-0001'); + expect(seccionFicha.querySelectorAll('details.seccion').length).toBeGreaterThanOrEqual(4); + expect(root.querySelector('form')!.closest('[hidden]')).not.toBeNull(); + Array.from(seccionFicha.querySelectorAll('button')).find(b => b.textContent!.includes('Volver a Seguimiento'))!.click(); fixture.detectChanges(); + expect(ficha).toHaveBeenLastCalledWith(false); + expect(root.querySelector('section.ficha-tea')).toBeNull(); + expect(root.querySelector('form')!.closest('[hidden]')).toBeNull(); + expect(root.querySelectorAll('tbody tr.tea-row')).toHaveLength(2); + http.verify(); + }); + it('el resumen completo son secciones con encabezado plegable, abiertas, y los reactivos van plegados dentro del ADOS-2', () => { + const root: HTMLElement = resumen(detalle).nativeElement; + const secciones = Array.from(root.querySelectorAll('details.seccion')); + expect(secciones.map(d => d.querySelector('summary h2')!.textContent!.replace('Datos de ejemplo', '').trim())).toEqual( + ['Datos del paciente', 'ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG']); + expect(secciones.every(d => d.open)).toBe(true); + expect(root.querySelector('.tarjetas, .panel')).toBeNull(); + expect(seccion(root, 'Datos del paciente').textContent).toContain('T-0001'); + expect(seccion(root, 'Datos del paciente').textContent).toContain('16-23 meses'); + const reactivos = seccion(root, 'ADOS-2').querySelector('details:not(.seccion)')!; + expect(reactivos.open).toBe(false); + expect(reactivos.textContent).toContain('A2 · Reactivo A2'); + secciones[1].open = false; + expect(secciones[1].open).toBe(false); http.verify(); }); it('sin filtros no envía sus parámetros', () => { @@ -258,22 +300,24 @@ describe('Seguimiento TEA', () => { expect(toggles[1].getAttribute('aria-expanded')).toBe('true'); http.expectOne('/tea/seguimiento/T-0002').flush({ ...detalle, id_seudonimo: 'T-0002' }); fixture.detectChanges(); const panel = root.querySelector('#tea-detalle-T-0002')!; + // Four summary cards, two by two, with the verdicts and no maps or item tables. + expect(Array.from(panel.querySelectorAll('.tarjetas > section')).map(c => c.getAttribute('aria-label'))).toEqual([ + 'Resumen ADOS-2', 'Calidad del EEG', 'Alteraciones del EEG', 'Relación de las alteraciones del EEG con el ADOS-2']); expect(panel.textContent).toContain('CSS 3'); expect(panel.textContent).toContain('Afecto social (AS)'); expect(panel.textContent).toContain('Válido'); - // Opens with the map of the first altered metric. - expect(panel.querySelector('app-plotly-chart')).not.toBeNull(); - // Item scores start collapsed. - expect(panel.querySelector('details')!.open).toBe(false); + expect(panel.querySelector('app-plotly-chart')).toBeNull(); + expect(panel.querySelector('details')).toBeNull(); const metricas = panel.querySelector('[aria-label="Alteraciones del EEG"]')!; expect(metricas.textContent).toContain('Datos de ejemplo'); + expect(metricas.textContent).toContain('1 de 4 métricas evaluadas fuera de la referencia'); + expect(metricas.textContent).toContain('Ritmo posterior'); expect(metricas.textContent).toContain('Disminuido'); - expect(metricas.textContent).toContain('Posibles efectos asociados'); - expect(metricas.textContent).toContain('Ritmo más lento de lo esperado para la edad.'); - expect(metricas.textContent).toContain('No se pudo medir en el estudio.'); - expect(Array.from(metricas.querySelectorAll('.nombre')).map(n => n.textContent)).toEqual( - ['Ritmo posterior', 'Husos de sueño N2', 'Husos de sueño N3', 'Picos paroxísticos', 'Gradiente anteroposterior']); - expect(metricas.textContent).not.toContain('Sin alteraciones en las métricas evaluadas.'); + expect(metricas.textContent).not.toContain('Husos de sueño N3'); + expect(panel.querySelector('[aria-label="Calidad del EEG"]')!.textContent).toContain('1 de 2 reglas del estudio fuera de rango · 1 canal descartado'); + // The whole record opens in its own section from the patient id and from the cards' button. + const enlace = panel.querySelector('button.completo')!; + expect(enlace.textContent).toContain('resumen completo'); (root.querySelectorAll('tbody tr.tea-row')[2] as HTMLElement).click(); fixture.detectChanges(); expect(root.querySelector('#tea-detalle-T-0002')).toBeNull(); http.expectOne('/tea/seguimiento/T-0004').flush({ ...detalle, id_seudonimo: 'T-0004', ados2: null, eeg: null }); fixture.detectChanges(); @@ -345,12 +389,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle({ ...detalle, eeg: { ...detalle.eeg, calidad: 'regular' } }, 'T-0001')).toThrow(); }); it('la calidad es el veredicto del análisis, con sus reglas y los canales descartados, y se valida', () => { - const fixture = open(); - request().flush(tres); fixture.detectChanges(); - const root: HTMLElement = fixture.nativeElement; - root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); - http.expectOne('/tea/seguimiento/T-0001').flush(detalle); fixture.detectChanges(); - const panel = root.querySelector('section.calidad')!; + const panel = seccion(resumen(detalle).nativeElement, 'Calidad del EEG'); const texto = (n: Element) => n.textContent!.replace(/\s+/g, ' ').trim(); expect(texto(panel.querySelector('.css')!)).toBe('Válido'); expect(Array.from(panel.querySelectorAll('dt, dd')).map(texto)).toEqual(['Ventanas limpias (decisiva)', '95 %', 'Ruido de la línea eléctrica', '48 dB']); @@ -392,12 +431,7 @@ describe('Seguimiento TEA', () => { expect(() => teaPacienteDetalle(rel([{ ...fila, probabilidad: 1.2 }]), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(rel([{ ...fila, ic_inf: 0.5 }]), 'T-0001')).toThrow(); expect(() => teaPacienteDetalle(rel([{ ...fila, tipo: 'zona' }]), 'T-0001')).toThrow(); - const fixture = open(); - request().flush(tres); fixture.detectChanges(); - const root: HTMLElement = fixture.nativeElement; - root.querySelectorAll('button.row-toggle')[0].click(); fixture.detectChanges(); - http.expectOne('/tea/seguimiento/T-0001').flush(rel([otra, fila])); fixture.detectChanges(); - const filas = Array.from(root.querySelectorAll('section.relacion tbody tr')); + const filas = Array.from(seccion(resumen(rel([otra, fila])).nativeElement, 'Relación con el ADOS-2').querySelectorAll('tbody tr')); expect(filas.length).toBe(1); expect(filas[0].classList.contains('alterada')).toBe(true); expect(filas[0].textContent).toContain('q < 0.001'); From ff1f6758ba67f0286b292b4321ea9f2169fa043f Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sun, 22 Nov 2026 22:27:49 -0600 Subject: [PATCH 35/35] fix(cacu): ajustar trazabilidad y figuras disponibles --- .../indicadores-cacu-secciones.spec.ts | 20 ++++++++++++++----- ...indicadores-historico-cacu-paneles.spec.ts | 2 +- .../indicadores-historico-pestana.spec.ts | 2 +- .../indicadores/indicadores-historico.ts | 4 ++-- .../features/indicadores/indicadores-kpi.ts | 7 +++---- .../features/indicadores/indicadores-page.ts | 15 +++++++------- .../indicadores-recorrido-analisis.spec.ts | 2 +- .../indicadores/indicadores-sections.spec.ts | 2 +- 8 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts index 521e7e6..145e33d 100644 --- a/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts +++ b/src/app/features/indicadores/indicadores-cacu-secciones.spec.ts @@ -39,16 +39,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')] .map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim()); - it('las cinco figuras conservan su orden y las ausentes quedan como pendientes', () => { + it('las figuras disponibles conservan su orden sin reservas vacías', () => { // Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose // the names of the request. abrir(CACU); expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico'); expect(titulos('.kpi-section .catalog-grid')).toEqual([ 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', - 'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía', - 'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia', 'catalog-card: Tiempo de toma de muestra a diagnóstico']); }); @@ -68,7 +65,6 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(root().querySelector('app-indicador-screening-route')).toBeNull(); expect(titulos('.kpi-section .catalog-grid')).toEqual([ 'catalog-card: Tiempo de toma de muestra a resultado de citología', - 'figura-pendiente: Tiempo de toma de muestra a resultado de VPH', 'catalog-card: Tiempo de toma de muestra a resultado de colposcopía', 'catalog-card: Tiempo de toma de muestra a resultado de biopsia', 'catalog-card: Tiempo de toma de muestra a diagnóstico']); @@ -91,6 +87,20 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () = expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull(); }); + it('agrega la gráfica publicada de diagnóstico a tratamiento al final', () => { + abrir([...CACU, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]); + expect(titulos('.kpi-section .catalog-grid')).toEqual([ + 'catalog-card: Tiempo de toma de muestra a resultado de citología', + 'catalog-card: Tiempo de toma de muestra a diagnóstico', + 'catalog-card: Tiempo de diagnóstico a tratamiento']); + }); + + it('conserva la ruta y muestra la gráfica publicada de diagnóstico a tratamiento', () => { + abrir([...CACU, ...RUTA, item('cacu_dias_diagnostico_tratamiento', 'Tiempo de diagnóstico a tratamiento', 'C3r', ['fig_c3r_caja'])]); + expect(root().querySelector('app-indicador-screening-route')).not.toBeNull(); + expect(titulos('.kpi-section .catalog-grid')).toEqual(['catalog-card: Tiempo de diagnóstico a tratamiento']); + }); + it('Datos y definiciones conserva todo el catálogo', () => { // Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab. abrir(CACU); diff --git a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts index 40e88fc..04426a7 100644 --- a/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-cacu-paneles.spec.ts @@ -76,7 +76,7 @@ describe('Histórico de CaCu', () => { const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!; const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo; const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); - const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!; + const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!; it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => { // Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it. diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index fb6c8e5..f0ea485 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -42,7 +42,7 @@ describe('Pestaña Histórico', () => { // Fails if CaCu loses its history tab or gains CaMa's analysis tab. abrir('cama', []); abrir('cacu', [item('cacu_x', 'C2')]); - expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); expect(root().querySelector('#panel-analisis')).toBeNull(); }); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts index 4647bfa..fe1f47c 100644 --- a/src/app/features/indicadores/indicadores-historico.ts +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -117,13 +117,13 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
@for (paso of pasos; track paso.titulo) {

{{ paso.titulo }}

- +
}
} @else { + [label]="(dominio() === 'cacu' ? 'Trazabilidad de ' : 'Histórico de ') + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" /> } @if (panel.figura.comoLeer) {

{{ panel.figura.comoLeer }}

} @if (panel.figura.suprimidos.length) { diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index d8a7bf3..f719d9a 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -66,17 +66,16 @@ export const KPI_RESUMEN_TEA: KpiDefinition[] = [ export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']; export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg']; -// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot -// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure. +// CaCu's available figures in display order; titles are assigned when the catalog publishes them. export interface FiguraOportunidad { id?: string; titulo: string; } export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' }, - { titulo: 'Tiempo de toma de muestra a resultado de VPH' }, { id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' }, { id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' }, { id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' }, + { id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento' }, ]; -// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. Same rules as CaCu's: an entry +// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry // with no `id` has no published indicator yet and draws as pending. export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [ { id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' }, diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 5d1db51..43c5468 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -47,6 +47,7 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [ // TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's, // between its history and its follow-up list. const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]]; +const SECTIONS_CACU: typeof SECTIONS_WITH_HISTORY = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]]; // Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered. export const CAMA_ANALYSIS_ENABLED = false; // TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them. @@ -67,7 +68,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } + get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.dominio === 'cacu' ? SECTIONS_CACU : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; } get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; } get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; } readonly activeSection = signal('resumen'); @@ -423,12 +424,12 @@ export class IndicadoresPage { return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo }; }); } - // With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to - // each event. Without it (the catalog lacks one of its measures) the times keep their figures. - if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return []; - return CACU_FIGURAS_OPORTUNIDAD.map(figura => { - const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined; - return item ? { item, titulo: item.titulo } : { titulo: figura.titulo }; + // Preserve the route chart; individual figures require a published figure contract. + if (this.dominio !== 'cacu' || !this.catalog().length) return []; + return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => { + if (this.screeningRouteAvailable && figura.id !== 'cacu_dias_diagnostico_tratamiento') return []; + const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0); + return item ? [{ item, titulo: item.titulo }] : []; }); }); readonly clinicosItems = computed(() => { diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 2ad3912..2612c1c 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -163,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); expect(e.page.seleccionSeguimiento()).toBeUndefined(); expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual( - ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); + ['Indicadores', dominio === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']); expect(e.root.querySelector('#panel-analisis')).toBeNull(); } e.page.changeDominio('cama'); e.harness.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 7c45c3a..f35e0a3 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -40,7 +40,7 @@ describe('Secciones compartidas por dominio', () => { const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); // TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain. - const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; + const esperadas = ['Indicadores', domain === 'cacu' ? 'Trazabilidad' : 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;