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/13] =?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)!; -- 2.53.0 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/13] =?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]; -- 2.53.0 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/13] =?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()); } -- 2.53.0 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/13] =?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(() => { -- 2.53.0 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/13] =?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', () => { -- 2.53.0 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/13] =?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() { -- 2.53.0 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/13] =?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(); -- 2.53.0 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/13] =?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); -- 2.53.0 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/13] 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

-- 2.53.0 From feaed5ff0e58a35fdfdd79e580b6af9d3c06d045 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 02:48:49 -0600 Subject: [PATCH 10/13] 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); -- 2.53.0 From 7692952ec9a3145a06f261ce7a8bbc4797401e76 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 22 Nov 2026 02:49:34 -0600 Subject: [PATCH 11/13] 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