From 366591f247e9855b3e83bab637771aca88ddd12e Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 20 Nov 2026 09:07:38 -0600 Subject: [PATCH] fix(cama): restore published histopathology and mammography counts --- README.md | 27 ---- .../ajuste-mastografias-demo.spec.ts | 32 ----- .../indicadores/ajuste-mastografias-demo.ts | 19 --- ..._histopatologia_birads_demo_sintetica.json | 41 ------ .../histopatologia-cama-demo.spec.ts | 136 ------------------ .../indicadores/histopatologia-cama-demo.ts | 53 ------- .../indicadores/indicador-catalog-card.ts | 2 +- .../indicador-histopatologia-cama.html | 28 ++-- .../indicador-histopatologia-cama.ts | 87 ++++++++--- .../indicador-histopatologia-pendiente.ts | 48 +++++++ .../indicadores/indicadores-cama-f4c.spec.ts | 14 +- .../indicadores/indicadores-cama-fhir.spec.ts | 15 +- .../indicadores-cama-resumen-clinico.spec.ts | 27 ++-- .../indicadores-conteos-pareados.spec.ts | 7 +- .../features/indicadores/indicadores-fhir.ts | 4 +- .../indicadores-histopatologia-cama.spec.ts | 136 +++++++++++++++--- .../indicadores-histopatologia-cama.ts | 59 +++----- .../indicadores-initial-integration.spec.ts | 8 +- .../indicadores-navigation.spec.ts | 5 +- .../indicadores/indicadores-page.html | 1 + .../indicadores/indicadores-page.spec.ts | 7 +- .../features/indicadores/indicadores-page.ts | 20 +-- .../indicadores/indicadores-pinning.spec.ts | 4 +- .../indicadores/indicadores.service.spec.ts | 17 +++ .../indicadores/indicadores.service.ts | 3 +- 25 files changed, 339 insertions(+), 461 deletions(-) delete mode 100644 src/app/features/indicadores/ajuste-mastografias-demo.spec.ts delete mode 100644 src/app/features/indicadores/ajuste-mastografias-demo.ts delete mode 100644 src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json delete mode 100644 src/app/features/indicadores/histopatologia-cama-demo.spec.ts delete mode 100644 src/app/features/indicadores/histopatologia-cama-demo.ts create mode 100644 src/app/features/indicadores/indicador-histopatologia-pendiente.ts diff --git a/README.md b/README.md index b8caaf4..e5540b3 100644 --- a/README.md +++ b/README.md @@ -14,30 +14,3 @@ npx ng build # compilación de producción en dist/WebApp `ng serve` envía las rutas de la API a WebApi en `localhost:5050` (`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`. - -## Fuente de histopatología BI-RADS - -La compilación estándar incorpora la fuente sintética de la tarjeta de -histopatología en **CaMa → Resumen**. La dona y las barras usan el mismo -fixture. El catálogo, los filtros generales y los demás indicadores siguen -usando WebApi. Si el catálogo carga sin la medida de histopatología, Resumen -incluye la tarjeta con su fuente local. - -El archivo -`src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json` -contiene conteos inventados, sin validez clínica. Define los 12 subtipos en orden -con sus identificadores y colores. Cada mes remite a un perfil de conteos por -estrato BI-RADS que incluye resultados benignos, subtipos, casos sin biopsia -reportada y casos sin dato. Abarca enero de 2025 a diciembre de 2026. Los semestres -suman esos mismos meses. Un periodo fuera de cobertura queda sin resultados. - -El anillo interior usa el total con resultado de biopsia. El exterior reparte -el grupo «Riesgo a carcinoma» entre sus 12 subtipos. Las barras y el centro -muestran el subconjunto elegido sobre el total con resultado, por BI-RADS y del -periodo completo, respectivamente. La leyenda permite elegir subtipos incluso -cuando el sector es demasiado pequeño. - -Cuando se valide la matriz clínica de subtipos, el adaptador FHIR podrá construir -el mismo modelo de presentación con los conteos, estratos, denominadores y -reglas de supresión aprobados. Los componentes de visualización ya consumen -ese modelo tanto para las tasas como para los anillos. diff --git a/src/app/features/indicadores/ajuste-mastografias-demo.spec.ts b/src/app/features/indicadores/ajuste-mastografias-demo.spec.ts deleted file mode 100644 index 115d59b..0000000 --- a/src/app/features/indicadores/ajuste-mastografias-demo.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Covers the x2 shown for CaMa's mastographies in the demonstration build, on hand-made C2 rows. -import { ajustarMastografiasDemo } from './ajuste-mastografias-demo'; -import { IndicadorDatos } from './indicadores.models'; - -const datos = (): IndicadorDatos => ({ - id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], - filas: [ - { periodo: '2025-S1', categoria: 'BIRADS_4', n: 10, suprimido: 0 }, - { periodo: '2025-S2', categoria: 'BIRADS_4', n: 10, suprimido: 0 }, - { periodo: '2025-S2', categoria: 'BIRADS_5', n: null, suprimido: 1 }, - ], -}); - -describe('Mastografías en la demostración', () => { - it('duplica el conteo de todos los periodos y deja intactas las celdas suprimidas', () => { - // Fails if a period is left out (the factor must not depend on the filter), a suppressed cell becomes a number, or the factor changes. - const r = ajustarMastografiasDemo('cama', 'cama_birads_456_mastografia', datos()); - expect(r.filas.map(f => f['n'])).toEqual([20, 20, null]); - }); - it('no modifica los datos recibidos', () => { - // Fails if the cached API payload is mutated, which would double again on every read. - const original = datos(); - ajustarMastografiasDemo('cama', 'cama_birads_456_mastografia', original); - expect(original.filas.map(f => f['n'])).toEqual([10, 10, null]); - }); - it('no afecta a otros indicadores ni a otros dominios', () => { - // Fails if the factor leaks to the patients' count or to another domain with the same indicator id. - const d = datos(); - expect(ajustarMastografiasDemo('cama', 'cama_birads_456_paciente', d)).toBe(d); - expect(ajustarMastografiasDemo('cacu', 'cama_birads_456_mastografia', d)).toBe(d); - }); -}); diff --git a/src/app/features/indicadores/ajuste-mastografias-demo.ts b/src/app/features/indicadores/ajuste-mastografias-demo.ts deleted file mode 100644 index 315e892..0000000 --- a/src/app/features/indicadores/ajuste-mastografias-demo.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { IndicadorDatos } from './indicadores.models'; - -// The demonstration build shows twice the mastographies the API reports, in every period, for CaMa's BI-RADS 4, 5 -// or 6 indicator. Resumen and Histórico read it through the same service call, so both show the same counts. -const INDICADOR = 'cama_birads_456_mastografia'; -export const FACTOR_MASTOGRAFIAS = 2; - -const doble = >(fila: T): T => - typeof fila['n'] === 'number' && Number.isFinite(fila['n']) ? { ...fila, n: fila['n'] * FACTOR_MASTOGRAFIAS } : fila; - -/** The data with each published count `n`, and each stratum total, multiplied; suppressed or missing cells stay as they are. */ -export function ajustarMastografiasDemo(dominio: string, indicador: string, datos: IndicadorDatos): IndicadorDatos { - if (dominio !== 'cama' || indicador !== INDICADOR) return datos; - return { - ...datos, - filas: datos.filas.map(doble), - ...(Array.isArray(datos['totales_estrato']) ? { totales_estrato: (datos['totales_estrato'] as Record[]).map(doble) } : {}), - }; -} diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json deleted file mode 100644 index 03ec214..0000000 --- a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "origen": "Sintético (WebApp). Conteos inventados para demostrar la visualización; sin significado clínico.", - "categorias": [ - { "id": "DUCTAL_NST", "etiqueta": "Ductal (NST)", "color": "#AD386D" }, - { "id": "LOBULILLAR", "etiqueta": "Lobulillar", "color": "#5C55BB" }, - { "id": "OTROS", "etiqueta": "Otros", "color": "#007F86" }, - { "id": "DUCTAL_LOBULILLAR", "etiqueta": "Ductal-lobulillar mixto", "color": "#8767C9" }, - { "id": "MUCINOSO", "etiqueta": "Mucinoso", "color": "#3274BF" }, - { "id": "PAGET", "etiqueta": "Paget", "color": "#D35C91" }, - { "id": "PAPILAR", "etiqueta": "Papilar", "color": "#537723" }, - { "id": "TUBULAR_CRIBIFORME", "etiqueta": "Tubular / cribiforme", "color": "#9454AA" }, - { "id": "MICROPAPILAR", "etiqueta": "Micropapilar", "color": "#C24938" }, - { "id": "SIN_MAPEAR", "etiqueta": "SIN MAPEAR", "color": "#68778B" }, - { "id": "INFLAMATORIO", "etiqueta": "Inflamatorio", "color": "#A4932A" }, - { "id": "MEDULAR", "etiqueta": "Medular", "color": "#438573" } - ], - "meses": { - "2025-01": "A", "2025-02": "B", "2025-03": "A", "2025-04": "B", "2025-05": "B", "2025-06": "A", - "2025-07": "B", "2025-08": "A", "2025-09": "B", "2025-10": "A", "2025-11": "B", "2025-12": "B", - "2026-01": "A", "2026-02": "B", "2026-03": "A", "2026-04": "A", "2026-05": "B", "2026-06": "A", - "2026-07": "A", "2026-08": "B", "2026-09": "B", "2026-10": "B", "2026-11": "A", "2026-12": "B" - }, - "perfiles": { - "A": { - "BIRADS_4": { "benignos": 54, "subtipos": [8, 3, 2, 1, 1, 0, 1, 0, 0, 1, 0, 0], "sinBiopsia": 5, "sinDato": 1 }, - "BIRADS_4A": { "benignos": 93, "subtipos": [5, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0], "sinBiopsia": 9, "sinDato": 2 }, - "BIRADS_4B": { "benignos": 67, "subtipos": [19, 5, 3, 2, 1, 1, 1, 1, 0, 1, 0, 1], "sinBiopsia": 6, "sinDato": 2 }, - "BIRADS_4C": { "benignos": 30, "subtipos": [33, 9, 5, 4, 3, 1, 2, 2, 1, 2, 1, 1], "sinBiopsia": 4, "sinDato": 1 }, - "BIRADS_5": { "benignos": 10, "subtipos": [48, 12, 8, 6, 4, 3, 3, 2, 2, 2, 2, 1], "sinBiopsia": 3, "sinDato": 1 }, - "BIRADS_6": { "benignos": 0, "subtipos": [15, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0], "sinBiopsia": 0, "sinDato": 1 } - }, - "B": { - "BIRADS_4": { "benignos": 49, "subtipos": [7, 2, 2, 1, 0, 0, 1, 0, 0, 2, 0, 1], "sinBiopsia": 6, "sinDato": 2 }, - "BIRADS_4A": { "benignos": 86, "subtipos": [6, 2, 0, 1, 0, 0, 1, 1, 0, 2, 0, 0], "sinBiopsia": 7, "sinDato": 1 }, - "BIRADS_4B": { "benignos": 66, "subtipos": [15, 4, 4, 2, 2, 0, 1, 1, 1, 1, 0, 0], "sinBiopsia": 4, "sinDato": 1 }, - "BIRADS_4C": { "benignos": 35, "subtipos": [31, 8, 5, 3, 2, 1, 3, 2, 1, 1, 1, 1], "sinBiopsia": 5, "sinDato": 2 }, - "BIRADS_5": { "benignos": 9, "subtipos": [44, 14, 7, 7, 5, 4, 3, 2, 2, 1, 2, 1], "sinBiopsia": 2, "sinDato": 2 }, - "BIRADS_6": { "benignos": 0, "subtipos": [17, 5, 3, 1, 2, 1, 0, 1, 1, 2, 1, 1], "sinBiopsia": 0, "sinDato": 0 } - } - } -} diff --git a/src/app/features/indicadores/histopatologia-cama-demo.spec.ts b/src/app/features/indicadores/histopatologia-cama-demo.spec.ts deleted file mode 100644 index 6f9357f..0000000 --- a/src/app/features/indicadores/histopatologia-cama-demo.spec.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { provideHttpClient } from '@angular/common/http'; -import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; -import { TestBed } from '@angular/core/testing'; -import { By } from '@angular/platform-browser'; -import { provideRouter } from '@angular/router'; -import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; -import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama'; -import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { modelosHistopatologiaDemo } from './histopatologia-cama-demo'; -import { recolorFigure } from './indicadores-c2-palette'; -import { categoriasExteriores, donaHistopatologia, figuraTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama'; -import { IndicadoresMemory } from './indicadores-memory'; -import { IndicadoresPage } from './indicadores-page'; - -const nombres = [ - 'Ductal (NST)', 'Lobulillar', 'Otros', 'Ductal-lobulillar mixto', 'Mucinoso', 'Paget', 'Papilar', - 'Tubular / cribiforme', 'Micropapilar', 'SIN MAPEAR', 'Inflamatorio', 'Medular', -]; -const [modelo] = modelosHistopatologiaDemo('mes', ['2025-02']); -const suma = (valores: number[]) => valores.reduce((a, b) => a + b, 0); - -describe('Fuente sintética de histopatología CaMa', () => { - it('dibuja los 12 subtipos en orden, con colores distintos y con el subtotal del grupo exterior', () => { - const seleccion = seleccionBase(modelo); - const [, interior, exterior] = recolorFigure(donaHistopatologia(modelo, seleccion, 'claro')).data; - expect(exterior['labels']).toEqual(nombres); - expect(categoriasExteriores(modelo).map(c => c.etiqueta)).toEqual(nombres); - const colores = categoriasExteriores(modelo).map(c => c.color); - expect(new Set(colores).size).toBe(12); - expect(exterior['marker']).toMatchObject({ colors: colores }); - expect(interior['labels']).toEqual(['No maligno', 'Riesgo a carcinoma']); - expect(suma(exterior['values'] as number[])).toBe((interior['values'] as number[])[1]); - expect(suma(interior['values'] as number[])).toBe(modelo.conResultado); - expect((exterior['values'] as number[]).every(n => n > 0)).toBe(true); - }); - - it('mantiene SIN MAPEAR en mayúsculas y evita porcentajes indefinidos en un anillo sin casos', () => { - const figura = figuraTasas(modelo, { grupo: modelo.base, categoria: 'SIN_MAPEAR' }, 'claro'); - expect(figura.layout['xaxis']).toMatchObject({ title: { text: 'Porcentaje con SIN MAPEAR' } }); - const benignos = modelo.totales['BENIGNO']; - const totales = { ...modelo.totales, ...Object.fromEntries(categoriasExteriores(modelo).map(c => [c.id, 0])) }; - const sinCasos = { ...modelo, totales, conResultado: benignos }; - const exterior = donaHistopatologia(sinCasos, seleccionBase(sinCasos), 'claro').data[2]; - expect(exterior['customdata']).toEqual(nombres.map(() => ['0', '—'])); - }); - - it('reconcilia barras, anillos y tabla para cada selección, incluidos los ceros', () => { - for (const { id, grupo } of modelo.categorias) { - const seleccion = { grupo, categoria: id }; - const valores = tasas(modelo, seleccion); - expect(suma(valores.map(t => t.k!))).toBe(modelo.totales[id]); - for (const { fila, k, valor, bajo, alto } of valores) { - expect(k).toBe(fila.celdas[id].n); - expect(valor).toBe(100 * k! / fila.den!); - expect(bajo).toBeGreaterThanOrEqual(0); - expect(alto).toBeLessThanOrEqual(100); - expect(fila.total.n).toBe(fila.den! + fila.aparte['SIN_BIOPSIA'].n! + fila.aparte['SIN_DATO'].n!); - } - const [barra] = figuraTasas(modelo, seleccion, 'oscuro', true).data; - expect(barra['type']).toBe('bar'); - expect(barra['x']).toEqual(valores.map(t => t.valor)); - } - expect(tasas(modelo, { grupo: modelo.base, categoria: 'MICROPAPILAR' })[0].valor).toBe(0); - }); - - it('agrega los mismos meses en cada semestre y devuelve vacío fuera de cobertura', () => { - const semestres = modelosHistopatologiaDemo('semestre'); - expect(semestres.map(m => m.periodo)).toEqual(['2025-S1', '2025-S2', '2026-S1', '2026-S2']); - const primerSemestre = modelosHistopatologiaDemo('mes').filter(m => m.periodo <= '2025-06'); - for (const { id } of modelo.categorias) { - expect(semestres[0].totales[id]).toBe(suma(primerSemestre.map(m => m.totales[id]!))); - } - expect(modelosHistopatologiaDemo('mes', ['2025-03', '2025-02']).map(m => m.periodo)).toEqual(['2025-03', '2025-02']); - expect(modelosHistopatologiaDemo('mes', ['2024-10'])).toEqual([]); - }); - - it.each([true, false])('Resumen usa los datos incorporados con medida publicada = %s', publicada => { - TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [ - provideRouter([]), provideHttpClient(), provideHttpClientTesting(), - { provide: PLOTLY_LOADER, useValue: () => new Promise(() => {}) }, - ] }); - const http = TestBed.inject(HttpTestingController); - const memory = TestBed.inject(IndicadoresMemory); - for (const dominio of ['cama', 'cacu', 'tea'] as const) memory.finishInitialKpiPresentation(dominio); - const f = TestBed.createComponent(IndicadoresPage); - const catalogo = (id: string) => [{ id, titulo: 'Indicador publicado', contrato: 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] }]; - http.expectOne('/tea/indicadores').flush(catalogo('tea_prueba')); - f.componentInstance.changeDominio('cama'); - const idsCama = ['cama_birads_456_mastografia', 'cama_birads_456_paciente']; - if (publicada) idsCama.push('cama_histopatologia_birads'); - http.expectOne('/cama/indicadores').flush(idsCama.flatMap(catalogo)); - f.detectChanges(); - const tarjeta = f.debugElement.query(node => node.componentInstance instanceof IndicadorHistopatologiaCama); - expect(tarjeta).toBeTruthy(); - const histo = tarjeta.componentInstance as IndicadorHistopatologiaCama; - const card = f.debugElement.queryAll(By.directive(IndicadorCatalogCard)) - .map(node => node.componentInstance as IndicadorCatalogCard) - .find(item => item.indicador.id === 'cama_histopatologia_birads')!; - card.setVisible(true); - f.detectChanges(); - expect(histo.status()).toBe('ready'); - expect(histo.contextPeriod).toBe('2026-S2'); - expect(f.nativeElement.textContent).toContain('Tiempo de diagnóstico a tratamiento'); - expect(f.componentInstance.catalog().map(item => item.id)).toEqual(idsCama); - expect(f.nativeElement.querySelector('app-indicador-conteos-pareados')).not.toBeNull(); - expect([...tarjeta.nativeElement.querySelectorAll('.child')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(nombres); - expect(histo.selectionLabel).toBe('Riesgo a carcinoma'); - - histo.plotClicked({ points: [{ data: { name: 'categorias' }, pointNumber: 9 }] }); - f.detectChanges(); - expect(histo.selectionLabel).toBe('SIN MAPEAR'); - expect(histo.ratesFigure!.data[0]['x']).toEqual(tasas(histo.model!, histo.selection!).map(t => t.valor)); - expect(tarjeta.nativeElement.querySelector('.child[aria-pressed=true]').textContent.trim()).toBe('SIN MAPEAR'); - histo.plotClicked({ points: [{ data: { name: 'grupos' }, pointNumber: 0 }] }); - expect(histo.selectionLabel).toBe('No maligno'); - histo.plotClicked({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); - expect(histo.selectionLabel).toBe('Riesgo a carcinoma'); - histo.changePeriod(-1); - expect(histo.contextPeriod).toBe('2026-S1'); - histo.showHelp(); - f.detectChanges(); - expect(tarjeta.nativeElement.querySelector('.methodology').textContent).toContain('El exterior muestra solo la distribución de los subtipos'); - http.expectNone(req => /cama_histopatologia_birads\/(datos|metadatos)$/.test(req.url)); - - for (const dominio of ['cacu', 'tea'] as const) { - f.componentInstance.changeDominio(dominio); - http.expectOne('/' + dominio + '/indicadores').flush(catalogo(dominio + '_prueba')); - f.detectChanges(); - expect(f.nativeElement.querySelector('app-indicador-histopatologia-cama')).toBeNull(); - expect(f.nativeElement.querySelector('.catalog-grid').textContent).toContain('Indicador publicado'); - } - f.destroy(); - http.match(() => true); - http.verify(); - }); -}); diff --git a/src/app/features/indicadores/histopatologia-cama-demo.ts b/src/app/features/indicadores/histopatologia-cama-demo.ts deleted file mode 100644 index 8f7decd..0000000 --- a/src/app/features/indicadores/histopatologia-cama-demo.ts +++ /dev/null @@ -1,53 +0,0 @@ -import fixture from './fixtures/cama_histopatologia_birads_demo_sintetica.json'; -import { C2_PALETTE } from './indicadores-c2-palette'; -import { Celda } from './indicadores-confirmacion-citologia'; -import { - APARTE, ESTRATOS_BIRADS, ETIQUETA_ESTRATO, FilaBirads, ModeloHistopatologia, -} from './indicadores-histopatologia-cama'; -import { TipoPeriodo } from './indicadores.models'; - -const RIESGO = 'RIESGO_CARCINOMA'; -const NO_MALIGNO = 'NO_MALIGNO'; -const BENIGNO = 'BENIGNO'; -const subtipos = fixture.categorias.map(c => ({ ...c, grupo: RIESGO })); -const categorias = [ - ...subtipos, - { id: BENIGNO, etiqueta: 'Benigno', color: C2_PALETTE.frios[0], grupo: NO_MALIGNO }, -]; -const grupos = [ - { id: NO_MALIGNO, etiqueta: 'No maligno', color: C2_PALETTE.frios[3], categorias: [BENIGNO] }, - { id: RIESGO, etiqueta: 'Riesgo a carcinoma', color: C2_PALETTE.calidos[0], categorias: subtipos.map(c => c.id) }, -]; - -const meses = Object.entries(fixture.meses).map(([mes, perfil]) => ({ - mes, - semestre: mes.slice(0, 4) + (mes.slice(5) <= '06' ? '-S1' : '-S2'), - perfil: fixture.perfiles[perfil as keyof typeof fixture.perfiles], -})); -const sumar = (valores: number[]) => valores.reduce((total, n) => total + n, 0); -const publicada = (n: number) => ({ n, estado: 'Publicado' as const }); - -export function modelosHistopatologiaDemo(tipo: TipoPeriodo, solicitados?: readonly string[]): ModeloHistopatologia[] { - const disponibles = [...new Set(meses.map(mes => mes[tipo]))].sort(); - const periodos = solicitados ? solicitados.filter(p => disponibles.includes(p)) : disponibles; - return periodos.map(periodo => { - const enPeriodo = meses.filter(mes => mes[tipo] === periodo); - const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => { - const datos = enPeriodo.map(mes => mes.perfil[id]); - const celdas: Record = Object.fromEntries(subtipos.map((subtipo, i) => - [subtipo.id, publicada(sumar(datos.map(d => d.subtipos[i])))] - )); - celdas[BENIGNO] = publicada(sumar(datos.map(d => d.benignos))); - const den = sumar(Object.values(celdas).map(celda => celda.n!)); - const sinBiopsia = sumar(datos.map(d => d.sinBiopsia)); - const sinDato = sumar(datos.map(d => d.sinDato)); - return { id, etiqueta: ETIQUETA_ESTRATO[id], celdas, den, estado: 'Publicado', - aparte: { SIN_BIOPSIA: publicada(sinBiopsia), SIN_DATO: publicada(sinDato) }, - total: publicada(den + sinBiopsia + sinDato) }; - }); - const totales = Object.fromEntries(categorias.map(c => [c.id, sumar(filas.map(fila => fila.celdas[c.id].n!))])); - return { periodo, categorias, grupos, base: RIESGO, filas, totales, - conResultado: sumar(Object.values(totales)), aparte: [...APARTE], vacio: false, notas: [], - grupoAnilloExterior: RIESGO }; - }); -} diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index e176e41..3a22177 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -56,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados'; } @else if (isHistopatologia) {
- +
} @else if (tiempos; as par) {
diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.html b/src/app/features/indicadores/indicador-histopatologia-cama.html index eae765b..7211fc3 100644 --- a/src/app/features/indicadores/indicador-histopatologia-cama.html +++ b/src/app/features/indicadores/indicador-histopatologia-cama.html @@ -8,20 +8,27 @@ @if (helpOpen) { }
@switch (status()) { @case ('deferred') {

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

} - @case ('incompatible') {

{{ message }}

} + @case ('loading') {

Cargando el mismo periodo para tasas y dona…

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} } - @if (status() === 'empty') { -

No hay resultados de biopsia para el periodo seleccionado.

- } - @if (status() === 'ready') { + @if (status() === 'ready' || status() === 'empty') { @if (periods.length > 1) { } @if (model; as m) { + @if (status() === 'empty') {

No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.

} + @else {
@@ -41,7 +50,7 @@
@for (g of m.grupos; track g.id) {
- @for (c of categoriasExteriores(m); track c.id; let ci = $index) { + @for (c of m.categorias; track c.id; let ci = $index) { @if (c.grupo === g.id) { } @@ -62,8 +71,9 @@ } @else {

{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}

}
+ } @for (note of m.notas; track $index) {

{{ note }}

} -
Ver valores +
Valores publicados
@for (c of m.categorias; track c.id) { }@for (a of m.aparte; track a.id) { } diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.ts b/src/app/features/indicadores/indicador-histopatologia-cama.ts index e52dba6..d6cd68c 100644 --- a/src/app/features/indicadores/indicador-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicador-histopatologia-cama.ts @@ -1,15 +1,28 @@ -import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core'; +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { filterCompatibility, GlobalApplied } from './indicadores-memory'; -import { snapshotKey } from './indicadores-snapshots'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; import { Celda } from './indicadores-confirmacion-citologia'; -import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA, - ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama'; -import { modelosHistopatologiaDemo } from './histopatologia-cama-demo'; +import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA, + lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama'; + +// Figures of the kit whose "Cómo leer" describes this coordinated view. +const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const; + +/** + * CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the + * result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service + * for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`. + */ @Component({ selector: 'app-indicador-histopatologia-cama', - imports: [PlotlyChart], + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-histopatologia-cama.html', styleUrl: './indicador-confirmacion-citologia.scss', }) @@ -19,7 +32,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; - readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred'); + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); message = ''; selection?: SeleccionHistopatologia; periods: string[] = []; @@ -28,9 +43,10 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { donutFigure?: PlotlyFigure; ratesFigure?: PlotlyFigure; helpOpen = false; - readonly categoriasExteriores = categoriasExteriores; private helpPinned = false; + private readonly snapshots = inject(IndicadoresSnapshots); private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; private key = ''; private loaded = false; private pages: ModeloHistopatologia[] = []; @@ -45,8 +61,21 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { ?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : ''); } get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } + get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } + get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } + get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } + readonly estadoTasa = estadoTasa; cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); } + get readingGuide() { + const details = this.metadata?.figuras_detalle ?? []; + return FIGURAS.flatMap(([figura, nombre]) => { + const detail = details.find(item => item.figura === figura); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; + }); + } toggleHelp() { if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; } this.helpPinned = true; @@ -55,6 +84,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { showHelp() { if (this.helpOpen) return; this.helpOpen = true; + this.metadataRequested.emit(); } hideHelp() { if (!this.helpPinned) this.helpOpen = false; } onHelpFocusOut(event: FocusEvent) { @@ -65,32 +95,53 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { } ngOnChanges(changes: SimpleChanges) { - const key = snapshotKey(this.dominio, this.indicador, this.applied) - + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]); + const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS }) + + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]); if (key !== this.key) { - this.key = key; this.loaded = false; + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); if (!this.visible) { this.status.set('deferred'); return; } this.load(); } else if (this.visible && !this.loaded) this.load(); else if (this.model && changes['tema']) this.draw(); } + retry() { if (this.visible) this.load(); } private clear() { this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; this.donutFigure = undefined; this.ratesFigure = undefined; } private load() { + this.subscription?.unsubscribe(); this.loaded = true; this.clear(); const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) { this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.'; this.status.set('incompatible'); return; } - const { tipo, selection } = this.applied; - this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined); - this.periods = this.pages.map(modelo => modelo.periodo); - this.periodIndex = Math.max(0, this.periods.length - 1); - this.activatePeriod(); + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, + { estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({ + next: datos => { + if (key !== this.key) return; + try { + this.periods = periodosHistopatologia(datos, this.applied.tipo, periods); + this.pages = this.periods.map(p => modeloHistopatologia(datos, p)); + // The most recent period first; navigation goes back. + this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod(); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error); + this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); } private activatePeriod() { this.model = this.pages[this.periodIndex]; @@ -115,5 +166,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches); this.changeDetector.markForCheck(); } - ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); } + ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); } } diff --git a/src/app/features/indicadores/indicador-histopatologia-pendiente.ts b/src/app/features/indicadores/indicador-histopatologia-pendiente.ts new file mode 100644 index 0000000..d7b7d9f --- /dev/null +++ b/src/app/features/indicadores/indicador-histopatologia-pendiente.ts @@ -0,0 +1,48 @@ +import { Component, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; + +/** + * CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator + * (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number. + */ +@Component({ + selector: 'app-indicador-histopatologia-pendiente', + host: { class: 'dual-card' }, + imports: [MatButtonModule, MatCardModule], + template: ` + +

Resultado histopatológico por categoría BI-RADS

+ + @if (ayuda()) { +
+

Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.

+
+ } +

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

+
+

Por categoría BI-RADS

Sin datos publicados
+

Resultado de la biopsia

Sin datos publicados
+
+
+ `, + styles: ` + :host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; } + 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; } + h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; } + p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } + .estado { color: var(--issste-text-secondary); } + .methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + .methodology p { margin: 0; } + .figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); } + @media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + .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); } + button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } + `, +}) +export class IndicadorHistopatologiaPendiente { + readonly ayuda = signal(false); +} diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts index ee6420c..fdd0ae9 100644 --- a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -217,6 +217,7 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { }); it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => { const pedidos = cargar(completo()); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); const primera = tarjetas()[0]; expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD'); expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); @@ -230,10 +231,13 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica'); expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico'); }); - it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => { - const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); - expect(kpis()).toHaveLength(5); - expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); - expect(pedidos).not.toContain('cama_histopatologia_birads'); + it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => { + cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull(); + expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull(); + }); + it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => { + cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); + expect(kpis()).toHaveLength(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente'); }); }); diff --git a/src/app/features/indicadores/indicadores-cama-fhir.spec.ts b/src/app/features/indicadores/indicadores-cama-fhir.spec.ts index d927600..7f7c406 100644 --- a/src/app/features/indicadores/indicadores-cama-fhir.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-fhir.spec.ts @@ -309,7 +309,7 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => }); }); -describe('Ajuste x2 de mastografías en la ruta FHIR', () => { +describe('Conteos publicados de CaMa en la ruta FHIR', () => { let http: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] }); @@ -322,20 +322,17 @@ describe('Ajuste x2 de mastografías en la ruta FHIR', () => { http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) }); return answer; } - it('las mastografías llegan a la tarjeta con el doble de cada conteo, exactamente una vez', async () => { - // Pins down: the page reads through FhirIndicadoresService, which does not call the base service, so the factor is - // applied there. Fails if the factor is missing (counts equal the published ones) or applied twice (four times). + it('las mastografías llegan a la tarjeta con los conteos publicados', async () => { const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS); const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA'); - expect(mostrado.filas.map(f => f['n'])).toEqual(publicado.filas.map(f => (f['n'] as number) * 2)); + expect(mostrado.filas).toEqual(publicado.filas); const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS); const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre'); - expect(totalExamenes(model)).toBe(78); - expect(model.filas.map(f => f.examenes)).toEqual([32, 42, 4]); + expect(totalExamenes(model)).toBe(39); + expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]); expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]); }); - it('los conteos de pacientes llegan sin el factor', async () => { - // Fails if the factor leaks to the patients' indicator, which shares the card and the history with the mastographies. + it('los pacientes conservan sus conteos publicados', async () => { const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS); const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE'); expect(pacientes.filas).toEqual(publicado.filas); diff --git a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts index 84fa065..46cc2ba 100644 --- a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -53,8 +53,8 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { expect(titles()).not.toContain('Distribución de resultados de biopsia'); // The patients' counts go on the exams' card, so the partner indicator has no card of its own. expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6'); - // The paired card has no card title; each donut names itself. - expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']); + // The paired card has no card title; each donut names itself. The other three indicators are in Histórico. + expect(titles()).toEqual([]); expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull(); expect(section().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6'); expect(root().textContent).not.toContain('indicador publicado'); @@ -73,21 +73,26 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6'); expect(nombres).not.toContain(CAMA[1].titulo); }); - it('CaMa: la tarjeta de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => { + it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => { open('cama', CAMA); - const primera = root().querySelector('.catalog-grid')!.firstElementChild!; - expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); - expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS'); - expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads'); + const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement; + expect(tarjeta).not.toBeNull(); + expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS'); + expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente'); + expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']); + expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull(); + expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false); + // It comes first, as in the reference, and is not counted as a published indicator. + expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta); }); - it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => { + it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => { open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]); - expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS'); }); - it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => { + it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => { open(domain, OTRO(domain)); - expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull(); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); }); it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => { // Fails if any of the controls the mockup does not have comes back to CaMa's summary. diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts index d7fe2c1..3189d54 100644 --- a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts +++ b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts @@ -204,7 +204,7 @@ describe('Tarjeta pareada de CaMa en la página', () => { const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); // Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary. // The pair has no card title; each donut has its own heading. - expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']); + expect(titulos).toEqual([]); expect(root().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6'); expect(root().textContent).not.toContain('indicador publicado'); }); @@ -223,8 +223,7 @@ describe('Tarjeta pareada de CaMa en la página', () => { expect(graficas.map(g => g.label)).toEqual(h3); expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); - // The mastographies column shows twice the published counts (15 and 18) in the demonstration build. - expect(filas).toEqual([['BI-RADS 4', '13', '30'], ['BI-RADS 5', '18', '36'], ['BI-RADS 6', '0', '0']]); + expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]); expect(root().querySelector('.published-values caption')?.textContent).toContain('su categoría más alta'); expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente'); expect([...root().querySelectorAll('.help-icon')].map(b => b.getAttribute('aria-label'))).toEqual(['Cómo leer, mastografías por categoría', 'Cómo leer, pacientes por categoría']); @@ -254,7 +253,7 @@ describe('Tarjeta pareada de CaMa en la página', () => { it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => { abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); - expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '30'], ['BI-RADS 5', 'Pendiente', '36'], ['BI-RADS 6', 'Pendiente', '0']]); + expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]); expect(root().textContent).toContain('Pacientes pendientes'); expect(root().textContent).toContain('Dona de pacientes no disponible'); expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1); diff --git a/src/app/features/indicadores/indicadores-fhir.ts b/src/app/features/indicadores/indicadores-fhir.ts index 1c066b6..5b85c77 100644 --- a/src/app/features/indicadores/indicadores-fhir.ts +++ b/src/app/features/indicadores/indicadores-fhir.ts @@ -6,7 +6,6 @@ import { periodLabel } from './measure-report'; import { DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo, } from './indicadores.models'; -import { ajustarMastografiasDemo } from './ajuste-mastografias-demo'; import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service'; import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos'; import { IndicadoresRequests } from './indicadores-requests'; @@ -368,8 +367,7 @@ export class FhirIndicadoresService extends IndicadoresService { 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 => ajustarMastografiasDemo(dominio, indicador, - datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))))); + map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope))))); } override figura(selection: FigureSelection) { const dominio = requireDominio(selection.dominio ?? 'tea'); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts index 6b9988c..2073295 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -1,5 +1,5 @@ // Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows, -// rates and figures, and the catalog wiring of the local view. The fixtures are what WebApi publishes for the synthetic +// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic // demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per // period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator). import { Component, input, output } from '@angular/core'; @@ -235,32 +235,124 @@ describe('Histopatología por BI-RADS: componente', () => { f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); }); afterEach(() => { f.destroy(); http.verify(); }); - it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => { - f.componentRef.setInput('visible', false); - f.detectChanges(); - expect(f.componentInstance.status()).toBe('deferred'); - f.componentRef.setInput('visible', true); - f.detectChanges(); - expect(f.componentInstance.status()).toBe('ready'); - expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2); - expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma'); - f.componentRef.setInput('tema', 'oscuro'); - f.detectChanges(); - expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); + const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos'); + function flush(body: unknown = estratoFixture) { + const r = solicitud(); + expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO); + r.flush(body as Record); f.detectChanges(); + } + const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement; + + it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); + f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); + flush(); expect(f.componentInstance.status()).toBe('ready'); + const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[]; + expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']); + expect([...f.nativeElement.querySelectorAll('.tabs button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['No maligno', 'Maligno']); + expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno'); + expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']); + const grafica = f.nativeElement.querySelector('.figures') as HTMLElement; + const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement; + const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement; + expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING); + expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado'); + expect(f.nativeElement.querySelector('.selection-status')).toBeNull(); + expect(f.nativeElement.querySelector('.rate-states')).toBeNull(); + expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia'); + expect(contexto.textContent).toContain('Intervalo semestral'); + expect(contexto.textContent).toContain('Periodo 2025-S1'); + expect(f.componentInstance.selectionLabel).toBe('Maligno'); + const table = f.nativeElement.querySelector('table') as HTMLTableElement; + expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual( + ['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']); + expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([ + ['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'], + ['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'], + ['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]); + expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;'); + }); + it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => { + f.detectChanges(); flush(); + const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub); + expect(f.nativeElement.textContent).not.toContain('Volver'); + boton('No maligno').click(); f.detectChanges(); + const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + expect(b3.getAttribute('aria-pressed')).toBe('true'); + expect(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)'); + b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); + boton('Maligno').click(); f.detectChanges(); + boton('Carcinoma invasor').click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); + boton('Maligno').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); http.expectNone(() => true); }); - - it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => { - f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 }); - f.detectChanges(); - expect(f.componentInstance.contextPeriod).toBe('2025-02'); + it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => { + const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 }); + f.detectChanges(); flush(d); expect(f.componentInstance.status()).toBe('ready'); - f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 }); - f.detectChanges(); + expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos'); + expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('Suprimido'); + const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent)); + expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4'); + }); + it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => { + const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6'); + d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6'); + f.detectChanges(); flush(d); + const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement; + expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]); + expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('No disponible'); + }); + it('sin filas en el periodo lo dice y conserva la tabla vacía', () => { + const d = estrato(); d.filas = []; d.totales_estrato = []; + f.detectChanges(); flush(d); expect(f.componentInstance.status()).toBe('empty'); - expect(f.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.'); + expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); - http.expectNone(() => true); + }); + it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => { + f.detectChanges(); + solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); + f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' }); + expect(f.componentInstance.status()).toBe('incompatible'); + expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => { + f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + }); + it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => { + f.detectChanges(); flush(); + f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); + expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); + }); + it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido); + (f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges(); + expect(pedido).toHaveBeenCalledTimes(1); + expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador'); + f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [ + { figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); + f.detectChanges(); + const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement; + expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']); + for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente); }); it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => { diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts index 83bc7eb..35d1e92 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -15,7 +15,7 @@ export const ESTRATO_BIRADS = 'birads'; // The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never // split among 4A/4B/4C nor added to them. export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const; -export const ETIQUETA_ESTRATO: Readonly> = { +const ETIQUETA_ESTRATO: Readonly> = { BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6', }; // The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two @@ -41,21 +41,19 @@ export interface Categoria { id: string; etiqueta: string; color: string; grupo: export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; } export interface FilaBirads { id: string; etiqueta: string; - // Categories with a biopsy result. + // The four categories with a result. celdas: Record; // SIN_BIOPSIA and SIN_DATO, when the catalog publishes them. aparte: Record; // Patients of the stratum, as the response publishes them. total: Celda; - // Patients with a biopsy result: the denominator. Null while any result cell is unknown. + // Patients with a biopsy result: the denominator. Null while any of the four cells is unknown. den: number | null; estado: Celda['estado']; } export interface ModeloHistopatologia { periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string; filas: FilaBirads[]; totales: Record; conResultado: number | null; aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; - // When set, the outer ring shows the subtype distribution within this group. - grupoAnilloExterior?: string; } export interface SeleccionHistopatologia { grupo: string; categoria?: string; } export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } @@ -68,7 +66,7 @@ const escapar = (v: string) => v.replace(/&/g, '&').replace(/ v.toLocaleString('es-MX'); const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; // A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals. -const enFrase = (v: string) => v === v.toUpperCase() ? v : v.charAt(0).toLowerCase() + v.slice(1); +const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1); const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined; // 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available. @@ -185,9 +183,6 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo } export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; } -export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] { - return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias; -} export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] { return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? []; } @@ -199,15 +194,12 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop if (traza === 'centro') return seleccionBase(m); if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; } if (traza !== 'categorias') return sel; - const c = categoriasExteriores(m)[indice]; + const c = m.categorias[indice]; if (!c) return sel; return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id }; } /** The axis title says what the rate reads. */ export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { - if (m.grupoAnilloExterior) { - return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia'; - } if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia'; if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia'; return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel)); @@ -237,19 +229,16 @@ export function rangoTasas(valores: Tasa[]): [number, number] { // `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits. export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure { const p = c2Theme(tema); - const barras = !!m.grupoAnilloExterior; const valores = tasas(m, sel); const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color; const tono = tonoDe(sel.categoria ?? sel.grupo); const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color]; const y = valores.map(t => t.fila.etiqueta); - const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); - const rango = rangoTasas(valores); + const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); return { data: [{ - ...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }), - uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), - marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false, - error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, thickness: 2, width: 6, + type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), + marker: { size: 12, color: colores }, cliponaxis: false, + error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6, array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) }, customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), hovertemplate: '%{y}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', @@ -259,8 +248,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 }, yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true, ...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '
sin subtipo')) } : {}) }, - xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true, - title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : 'Porcentaje con resultado ') + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } }, + xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true, + title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } }, annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left', font: { size: estrecho ? 11 : 12, color: p.text }, text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), @@ -273,27 +262,17 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado; const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0); const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0)); - const categorias = categoriasExteriores(m); - const exterior = categorias.map(c => m.totales[c.id]!); - const centro = m.grupoAnilloExterior - ? `${miles(k)}
de ${miles(total)}
con resultado` - : `${miles(k)}
de ${miles(total)} con resultado`; + const exterior = m.categorias.map(c => m.totales[c.id]!); const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes con resultado, %{customdata[1]}' }; - const custom = (values: number[]) => { - const subtotal = values.reduce((s, n) => s + n, 0); - return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]); - }; - const hoverExterior = m.grupoAnilloExterior - ? { hovertemplate: '%{label}
%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)' } - : hover; + const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]); const zoomGrupo = (id: string, hijos: readonly string[]) => sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1; const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1; const zoomDe = (values: number[]) => Math.max(1, ...values); const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)'); const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias)); - const categoriasZoom = categorias.map(c => zoomCategoria(c.id)); + const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id)); const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({ ...comun, ...hover, name, values, labels, hole, customdata: custom(values), domain: caja(base, zoomDe(zoom)), @@ -301,16 +280,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop }); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside', - text: [centro], textfont: { size: 16, color: p.text }, + text: [`${miles(k)}
de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text }, marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1), labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } }, - { ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1), - labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), - marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } }, + { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1), + labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), + marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } }, anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)), - { ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior }, + anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)), ], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 91a8301..61b0a4c 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; import { pending } from './indicadores-memory'; import { Indicador } from './indicadores.models'; @@ -64,11 +64,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos')); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); } - // CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards. - function cards() { - return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) - .filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA); - } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } // The shared request queue runs four at a time: flushing a batch starts the next. function flushPanels(period: string, expected = definitions.length - 1) { diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index 7efe6df..49eec65 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -15,7 +15,6 @@ import { IndicadoresPage } from './indicadores-page'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { PlotlyFigure } from './indicadores.models'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; @@ -37,9 +36,7 @@ describe('UX-04 navegación Angular', () => { harness.detectChanges(); const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); - // CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one. - const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) - .find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!; + const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; if (!card.visible) { card.setVisible(true); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 59905a6..a7c3ed6 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -117,6 +117,7 @@ }
+ @if (histopatologiaPendiente) { } @for (item of searchResults().items; track cardIdentity(item)) { diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index d737559..eac148d 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -15,7 +15,6 @@ import { MatSelect } from '@angular/material/select'; import { NgModel } from '@angular/forms'; import { IndicadoresMemory } from './indicadores-memory'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { Indicador, PlotlyFigure } from './indicadores.models'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; @@ -38,11 +37,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { function load(items: Indicador[] = [item, second], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } - // CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards. - function cards() { - return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) - .filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA); - } + function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index f26d910..0f4327c 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -31,6 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking'; import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresHistorico } from './indicadores-historico'; +import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; @@ -51,7 +52,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, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -314,15 +315,14 @@ 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)); - if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) { - cards.unshift({ - id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS', - contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'], - }); - } - // The histopathology card comes first, including when only the local source is available. + // 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)]; } + // CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator. + get histopatologiaPendiente() { + return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0 + && !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA); + } // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } // TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period. @@ -365,8 +365,8 @@ export class IndicadoresPage { return selected.length + ' indicadores'; }); readonly searchResults = computed(() => { - const selected = this.indicatorSelection(); - const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id)); + const selected = new Set(this.selectedIndicators()); + const items = this.catalogOrder().filter(item => selected.has(item.id)); return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] }; }); readonly catalogLoading = signal(true); diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index f9fc8ca..8bf182a 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -8,7 +8,6 @@ import { IndicadoresPage } from './indicadores-page'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresMemory } from './indicadores-memory'; -import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { Indicador } from './indicadores.models'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; @@ -84,8 +83,7 @@ describe('UX-06E.D.3.B fijación temporal', () => { it('memoria independiente por dominio y persistente al recrear la página', async () => { await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); // CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins. - // Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned. - await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]); + await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id)); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); diff --git a/src/app/features/indicadores/indicadores.service.spec.ts b/src/app/features/indicadores/indicadores.service.spec.ts index 790a960..88a99a7 100644 --- a/src/app/features/indicadores/indicadores.service.spec.ts +++ b/src/app/features/indicadores/indicadores.service.spec.ts @@ -142,6 +142,23 @@ describe('UX-04 validación defensiva HTTP', () => { describe('contrato datos exclusivo de KPI', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); + it('conserva los conteos, totales y celdas suprimidas que publica WebApi para mastografías de CaMa', () => { + const http = TestBed.inject(HttpTestingController); + const payload = { + id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'], + filas: [ + { periodo: '2025-S1', categoria: 'BIRADS_4', n: 15, suprimido: 0 }, + { periodo: '2025-S1', categoria: 'BIRADS_5', n: 0, suprimido: 0 }, + { periodo: '2025-S2', categoria: 'BIRADS_4', n: null, suprimido: 1 }, + ], + totales_estrato: [{ periodo: '2025-S1', estrato: 'BIRADS_4', n: 15, suprimido: 0 }], + }; + let result: unknown; + TestBed.inject(IndicadoresService).datos('cama', payload.id, 'semestre', payload.periodos).subscribe(value => result = value); + http.expectOne(req => req.url === `/cama/indicadores/${payload.id}/datos`).flush(payload); + expect(result).toEqual(payload); + http.verify(); + }); it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => { const http = TestBed.inject(HttpTestingController); let result: unknown; TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index a28ad69..b43773f 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -1,7 +1,6 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; -import { ajustarMastografiasDemo } from './ajuste-mastografias-demo'; import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models'; function record(value: unknown): value is Record { @@ -21,7 +20,7 @@ export class IndicadoresService { const domain = requireDominio(dominio); const params = datosParams(tipo, periodos, scope); return this.http.get(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }) - .pipe(map(value => ajustarMastografiasDemo(domain, indicador, datosValidos(value, indicador, tipo, periodos, scope)))); + .pipe(map(value => datosValidos(value, indicador, tipo, periodos, scope))); } figura(selection: FigureSelection) { const dominio = requireDominio(selection.dominio ?? 'tea'); -- 2.53.0
Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}
Categoría BI-RADS{{ c.etiqueta }}Con resultado{{ a.etiqueta }}Total de pacientes