fix(cama): restore published histopathology and mammography counts

This commit is contained in:
Angel Capetillo Zavala
2026-11-20 09:07:38 -06:00
parent 241631b884
commit 366591f247
25 changed files with 339 additions and 461 deletions
-27
View File
@@ -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` `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 (`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`. 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.
@@ -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);
});
});
@@ -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 = <T extends Record<string, unknown>>(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<string, unknown>[]).map(doble) } : {}),
};
}
@@ -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 }
}
}
}
@@ -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();
});
});
@@ -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<string, Celda> = 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 };
});
}
@@ -56,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</div> </div>
} @else if (isHistopatologia) { } @else if (isHistopatologia) {
<div #visibilityRegion class="confirmacion-region"> <div #visibilityRegion class="confirmacion-region">
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" /> <app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div> </div>
} @else if (tiempos; as par) { } @else if (tiempos; as par) {
<div #visibilityRegion class="tiempos-region"> <div #visibilityRegion class="tiempos-region">
@@ -8,20 +8,27 @@
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button> <button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
@if (helpOpen) { @if (helpOpen) {
<div class="methodology" id="histo-como-leer" role="tooltip"> <div class="methodology" id="histo-como-leer" role="tooltip">
<p>Cada barra muestra el porcentaje de pacientes con resultado de biopsia en la categoría BI-RADS que corresponde a la selección. La línea indica el intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» se muestran aparte en la tabla.</p> <p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
<p>El anillo interior compara los grupos entre todas las pacientes con resultado. El exterior muestra solo la distribución de los subtipos dentro de «Riesgo a carcinoma». Selecciona un sector o su etiqueta para actualizar las barras.</p> @if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
}
</div> </div>
} }
</div> </div>
</div> </div>
@switch (status()) { @switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> } @case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('incompatible') { <p role="alert">{{ message }}</p> } @case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
} }
@if (status() === 'empty') { @if (status() === 'ready' || status() === 'empty') {
<p role="status">No hay resultados de biopsia para el periodo seleccionado.</p>
}
@if (status() === 'ready') {
@if (periods.length > 1) { @if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS"> <nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button> <button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
@@ -30,6 +37,8 @@
</nav> </nav>
} }
@if (model; as m) { @if (model; as m) {
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend"> <div class="legend">
<div class="tab-bar"> <div class="tab-bar">
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia"> <div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
@@ -41,7 +50,7 @@
<div class="child-groups"> <div class="child-groups">
@for (g of m.grupos; track g.id) { @for (g of m.grupos; track g.id) {
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id"> <div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + 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) { @if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button> <button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
} }
@@ -62,8 +71,9 @@
} @else { <p role="status">{{ 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.' }}</p> } } @else { <p role="status">{{ 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.' }}</p> }
</section> </section>
</div> </div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> } @for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Ver valores</summary> <details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0"> <div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption> <table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead> <thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
@@ -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 { 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 { 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 { Celda } from './indicadores-confirmacion-citologia';
import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA, import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama'; lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
// 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({ @Component({
selector: 'app-indicador-histopatologia-cama', selector: 'app-indicador-histopatologia-cama',
imports: [PlotlyChart], imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-histopatologia-cama.html', templateUrl: './indicador-histopatologia-cama.html',
styleUrl: './indicador-confirmacion-citologia.scss', styleUrl: './indicador-confirmacion-citologia.scss',
}) })
@@ -19,7 +32,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
@Input({ required: true }) tema!: Tema; @Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied; @Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true; @Input() visible = true;
readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred'); @Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = ''; message = '';
selection?: SeleccionHistopatologia; selection?: SeleccionHistopatologia;
periods: string[] = []; periods: string[] = [];
@@ -28,9 +43,10 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
donutFigure?: PlotlyFigure; donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure; ratesFigure?: PlotlyFigure;
helpOpen = false; helpOpen = false;
readonly categoriasExteriores = categoriasExteriores;
private helpPinned = false; private helpPinned = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef); private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = ''; private key = '';
private loaded = false; private loaded = false;
private pages: ModeloHistopatologia[] = []; 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] : ''); ?? (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 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'); } 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'); } 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() { toggleHelp() {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; } if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
this.helpPinned = true; this.helpPinned = true;
@@ -55,6 +84,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
showHelp() { showHelp() {
if (this.helpOpen) return; if (this.helpOpen) return;
this.helpOpen = true; this.helpOpen = true;
this.metadataRequested.emit();
} }
hideHelp() { if (!this.helpPinned) this.helpOpen = false; } hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
onHelpFocusOut(event: FocusEvent) { onHelpFocusOut(event: FocusEvent) {
@@ -65,32 +95,53 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied) const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]); + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
if (key !== this.key) { if (key !== this.key) {
this.key = key; this.loaded = false; this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.clear(); this.clear();
if (!this.visible) { this.status.set('deferred'); return; } if (!this.visible) { this.status.set('deferred'); return; }
this.load(); this.load();
} else if (this.visible && !this.loaded) this.load(); } else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw(); else if (this.model && changes['tema']) this.draw();
} }
retry() { if (this.visible) this.load(); }
private clear() { private clear() {
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
this.donutFigure = undefined; this.ratesFigure = undefined; this.donutFigure = undefined; this.ratesFigure = undefined;
} }
private load() { private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear(); this.loaded = true; this.clear();
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) { 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.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
this.status.set('incompatible'); return; this.status.set('incompatible'); return;
} }
const { tipo, selection } = this.applied; const key = this.key;
this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined); const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.periods = this.pages.map(modelo => modelo.periodo); this.status.set('loading');
this.periodIndex = Math.max(0, this.periods.length - 1); this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
this.activatePeriod(); { 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() { private activatePeriod() {
this.model = this.pages[this.periodIndex]; 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.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
} }
ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); } ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
} }
@@ -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: `
<mat-card>
<h2>Resultado histopatológico por categoría BI-RADS</h2>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
@if (ayuda()) {
<div class="methodology">
<p>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.</p>
</div>
}
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
<div class="figures">
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
</div>
</mat-card>
`,
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);
}
@@ -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', () => { 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()); const pedidos = cargar(completo());
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
const primera = tarjetas()[0]; const primera = tarjetas()[0];
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD'); expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); 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_tasa_deteccion_histopatologica');
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico'); 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', () => { it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); 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')).not.toBeNull();
expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
expect(pedidos).not.toContain('cama_histopatologia_birads'); });
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');
}); });
}); });
@@ -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; let http: HttpTestingController;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] }); 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 })) }); http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer; return answer;
} }
it('las mastografías llegan a la tarjeta con el doble de cada conteo, exactamente una vez', async () => { it('las mastografías llegan a la tarjeta con los conteos publicados', 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).
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS); const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA'); 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 pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre'); const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(78); expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.examenes)).toEqual([32, 42, 4]); expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]); expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
}); });
it('los conteos de pacientes llegan sin el factor', async () => { it('los pacientes conservan sus conteos publicados', async () => {
// Fails if the factor leaks to the patients' indicator, which shares the card and the history with the mastographies.
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS); const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE'); const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas); expect(pacientes.filas).toEqual(publicado.filas);
@@ -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'); 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. // 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'); 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. // The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']); expect(titles()).toEqual([]);
expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull(); 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(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'); 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).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); 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); open('cama', CAMA);
const primera = root().querySelector('.catalog-grid')!.firstElementChild!; const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); expect(tarjeta).not.toBeNull();
expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS'); expect(tarjeta.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'); 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'])]); 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'); 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)); 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', () => { 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. // Fails if any of the controls the mockup does not have comes back to CaMa's summary.
@@ -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()); 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. // 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. // 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('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
expect(root().textContent).not.toContain('indicador publicado'); 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.label)).toEqual(h3);
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]); 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())); 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', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
expect(filas).toEqual([['BI-RADS 4', '13', '30'], ['BI-RADS 5', '18', '36'], ['BI-RADS 6', '0', '0']]);
expect(root().querySelector('.published-values caption')?.textContent).toContain('su categoría más alta'); 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(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']); 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', () => { 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' })); 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())); 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('Pacientes pendientes');
expect(root().textContent).toContain('Dona de pacientes no disponible'); expect(root().textContent).toContain('Dona de pacientes no disponible');
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1); expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
@@ -6,7 +6,6 @@ import { periodLabel } from './measure-report';
import { import {
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo, DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
} from './indicadores.models'; } from './indicadores.models';
import { ajustarMastografiasDemo } from './ajuste-mastografias-demo';
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service'; import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos'; import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests'; 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); params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
return this.measures.one(dominio, indicador).pipe( return this.measures.one(dominio, indicador).pipe(
switchMap(measure => this.measures.reports(dominio, measure, params).pipe( switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
map(bundle => ajustarMastografiasDemo(dominio, indicador, map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope))))));
} }
override figura(selection: FigureSelection) { override figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea'); const dominio = requireDominio(selection.dominio ?? 'tea');
@@ -1,5 +1,5 @@
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows, // 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 // 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). // 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'; 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); f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
}); });
afterEach(() => { f.destroy(); http.verify(); }); afterEach(() => { f.destroy(); http.verify(); });
it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => { const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos');
f.componentRef.setInput('visible', false); function flush(body: unknown = estratoFixture) {
f.detectChanges(); const r = solicitud();
expect(f.componentInstance.status()).toBe('deferred'); expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
f.componentRef.setInput('visible', true); r.flush(body as Record<string, unknown>); f.detectChanges();
f.detectChanges(); }
expect(f.componentInstance.status()).toBe('ready'); const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma'); it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
f.componentRef.setInput('tema', 'oscuro'); f.componentRef.setInput('visible', false); f.detectChanges();
f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); 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); http.expectNone(() => true);
}); });
it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => {
it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => { const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 });
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 }); f.detectChanges(); flush(d);
f.detectChanges();
expect(f.componentInstance.contextPeriod).toBe('2025-02');
expect(f.componentInstance.status()).toBe('ready'); expect(f.componentInstance.status()).toBe('ready');
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 }); expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
f.detectChanges(); 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.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); 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', () => { it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => {
@@ -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 // 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. // 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 ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
export const ETIQUETA_ESTRATO: Readonly<Record<typeof ESTRATOS_BIRADS[number], string>> = { const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
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', 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 // 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 GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
export interface FilaBirads { export interface FilaBirads {
id: string; etiqueta: string; id: string; etiqueta: string;
// Categories with a biopsy result. // The four categories with a result.
celdas: Record<string, Celda>; celdas: Record<string, Celda>;
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them. // SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
aparte: Record<string, Celda>; aparte: Record<string, Celda>;
// Patients of the stratum, as the response publishes them. // Patients of the stratum, as the response publishes them.
total: Celda; 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']; den: number | null; estado: Celda['estado'];
} }
export interface ModeloHistopatologia { export interface ModeloHistopatologia {
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string; periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null; filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; 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 SeleccionHistopatologia { grupo: string; categoria?: string; }
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } 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, '&amp;').replace(/</g, '&lt;').re
const miles = (v: number) => v.toLocaleString('es-MX'); const miles = (v: number) => v.toLocaleString('es-MX');
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; 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. // 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; 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. // 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 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[] { export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? []; 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 === 'centro') return seleccionBase(m);
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; } if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
if (traza !== 'categorias') return sel; if (traza !== 'categorias') return sel;
const c = categoriasExteriores(m)[indice]; const c = m.categorias[indice];
if (!c) return sel; if (!c) return sel;
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id }; return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
} }
/** The axis title says what the rate reads. */ /** The axis title says what the rate reads. */
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { 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 && 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'; 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)); 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. // `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 { export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
const p = c2Theme(tema); const p = c2Theme(tema);
const barras = !!m.grupoAnilloExterior;
const valores = tasas(m, sel); 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 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 tono = tonoDe(sel.categoria ?? sel.grupo);
const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color]; const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color];
const y = valores.map(t => t.fila.etiqueta); const y = valores.map(t => t.fila.etiqueta);
const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
const rango = rangoTasas(valores);
return { data: [{ return { data: [{
...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }), type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), marker: { size: 12, color: colores }, cliponaxis: false,
marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false, error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6,
error_x: { type: 'data', symmetric: false, color: barras ? p.text : 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!) }, 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!)]), 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}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>', hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
@@ -259,8 +248,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 }, margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true, 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', '<br>sin subtipo')) } : {}) }, ...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true, xaxis: { range: rangoTasas(valores), 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 } }, 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', 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 }, font: { size: estrecho ? 11 : 12, color: p.text },
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })), text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${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 p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0); 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 interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
const categorias = categoriasExteriores(m); const exterior = m.categorias.map(c => m.totales[c.id]!);
const exterior = categorias.map(c => m.totales[c.id]!);
const centro = m.grupoAnilloExterior
? `<b>${miles(k)}</b><br>de ${miles(total)}<br>con resultado`
: `<b>${miles(k)}</b><br>de ${miles(total)} con resultado`;
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' }; const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
const custom = (values: number[]) => { const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
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}<br>%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)<extra></extra>' }
: hover;
const zoomGrupo = (id: string, hijos: readonly string[]) => const zoomGrupo = (id: string, hijos: readonly string[]) =>
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1; 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 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 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 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 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[]) => ({ 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), ...comun, ...hover, name, values, labels, hole, customdata: custom(values),
domain: caja(base, zoomDe(zoom)), domain: caja(base, zoomDe(zoom)),
@@ -301,16 +280,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
}); });
return { data: [ return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside', { ...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: [`<b>${miles(k)}</b><br>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) + '<extra></extra>' }, marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1), { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1),
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), 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 } } }, 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), { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), labels: m.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 } } }, 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('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 } }, ], 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 } }; config: { displayModeBar: false } };
} }
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; 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 { pending } from './indicadores-memory';
import { Indicador } from './indicadores.models'; 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')); 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); } 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); }
function cards() {
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
}
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } 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. // The shared request queue runs four at a time: flushing a batch starts the next.
function flushPanels(period: string, expected = definitions.length - 1) { function flushPanels(period: string, expected = definitions.length - 1) {
@@ -15,7 +15,6 @@ import { IndicadoresPage } from './indicadores-page';
import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorFigureCard } from './indicador-figure-card';
import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorPeriodFilters } from './indicador-period-filters';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { PlotlyFigure } from './indicadores.models'; import { PlotlyFigure } from './indicadores.models';
import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
@@ -37,9 +36,7 @@ describe('UX-04 navegación Angular', () => {
harness.detectChanges(); harness.detectChanges();
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); 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!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!;
if (!card.visible) { card.setVisible(true); harness.detectChanges(); } if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
const req = http.expectOne(r => r.url.includes('/figuras/')); const req = http.expectOne(r => r.url.includes('/figuras/'));
req.flush({ data: [{ y: [0, null] }], layout: {} }); req.flush({ data: [{ y: [0, null] }], layout: {} });
@@ -117,6 +117,7 @@
</div> </div>
} }
<div class="catalog-grid"> <div class="catalog-grid">
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
@for (item of searchResults().items; track cardIdentity(item)) { @for (item of searchResults().items; track cardIdentity(item)) {
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)" <app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" /> [pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
@@ -15,7 +15,6 @@ import { MatSelect } from '@angular/material/select';
import { NgModel } from '@angular/forms'; import { NgModel } from '@angular/forms';
import { IndicadoresMemory } from './indicadores-memory'; import { IndicadoresMemory } from './indicadores-memory';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { Indicador, PlotlyFigure } from './indicadores.models'; import { Indicador, PlotlyFigure } from './indicadores.models';
import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; 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') { function load(items: Indicador[] = [item, second], domain = 'tea') {
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); 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); }
function cards() {
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
}
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } 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 toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
@@ -31,6 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking';
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico'; import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
@@ -51,7 +52,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
@Component({ @Component({
selector: 'app-indicadores-page', 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', templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss', styleUrl: './indicadores-page.scss',
}) })
@@ -314,15 +315,14 @@ export class IndicadoresPage {
private cardsDeCama(catalog: Indicador[]) { private cardsDeCama(catalog: Indicador[]) {
const ids = catalog.map(item => item.id); 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)); const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) { // The histopathology card keeps its place, first, whether pending or published.
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.
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)]; 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. // 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)); } 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. // 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'; return selected.length + ' indicadores';
}); });
readonly searchResults = computed(() => { readonly searchResults = computed(() => {
const selected = this.indicatorSelection(); const selected = new Set(this.selectedIndicators());
const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id)); const items = this.catalogOrder().filter(item => selected.has(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] }; return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
}); });
readonly catalogLoading = signal(true); readonly catalogLoading = signal(true);
@@ -8,7 +8,6 @@ import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadoresMemory } from './indicadores-memory'; import { IndicadoresMemory } from './indicadores-memory';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
import { Indicador } from './indicadores.models'; import { Indicador } from './indicadores.models';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; 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 () => { 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)); 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. // 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(items.map(i => i.id));
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]);
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
@@ -142,6 +142,23 @@ describe('UX-04 validación defensiva HTTP', () => {
describe('contrato datos exclusivo de KPI', () => { describe('contrato datos exclusivo de KPI', () => {
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] })); 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', () => { 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; const http = TestBed.inject(HttpTestingController); let result: unknown;
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v); TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
@@ -1,7 +1,6 @@
import { inject, Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'; import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs'; import { map } from 'rxjs';
import { ajustarMastografiasDemo } from './ajuste-mastografias-demo';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models'; import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> { function record(value: unknown): value is Record<string, unknown> {
@@ -21,7 +20,7 @@ export class IndicadoresService {
const domain = requireDominio(dominio); const domain = requireDominio(dominio);
const params = datosParams(tipo, periodos, scope); const params = datosParams(tipo, periodos, scope);
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params }) return this.http.get<unknown>(`/${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) { figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea'); const dominio = requireDominio(selection.dominio ?? 'tea');