Compare commits

..

6 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 3385df4ba3 Merge current WebApp dev into the CaMa selective rollback 2026-11-20 09:57:32 -06:00
Manuel Aurrecoechea Castillo 96b1cabb5a feat(cama): space the opportunity strip, share its period and unify history lines
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:49:32 -06:00
Angel Capetillo Zavala 366591f247 fix(cama): restore published histopathology and mammography counts 2026-11-20 09:07:38 -06:00
angel 241631b884 Merge pull request 'Finalize CaMa wording, demo mammography counts and histologic classification' (#13) from feature/cama-clasificacion-histologica into dev 2026-11-20 00:52:29 -06:00
Angel Capetillo Zavala 6c063344a3 feat(cama): adjust summary wording, double mastography counts and classify histologic types
Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
2026-11-20 00:32:27 -06:00
angel 2f5b1ce1f2 Merge pull request 'Feature/cama audit histopathology demo' (#12) from feature/cama-audit-histopathology-demo into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/12
2026-11-19 19:45:53 -06:00
39 changed files with 572 additions and 439 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,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">
@@ -7,7 +7,7 @@
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ 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() === 'ready' && model; as m) { @if (status() === 'ready' && model; as m) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo; @let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo; @let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
@if (pages.length > 1) { @if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo"> <nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
@@ -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);
}
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p> <p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
} }
<div class="kpi-foot"> <div class="kpi-foot">
@if (temporalReference) { @if (showPeriod && temporalReference) {
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p> <p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
} }
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p> <p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@@ -40,6 +40,7 @@ import { MatCardModule } from '@angular/material/card';
// CaMa's cards are as tall as their grid row. // CaMa's cards are as tall as their grid row.
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; } :host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; } :host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section[data-domain='cama']) .value { font-size: 1.65rem; }
`, `,
}) })
export class IndicadorKpiCard { export class IndicadorKpiCard {
@@ -47,6 +48,8 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null; @Input() value?: string | number | null;
@Input() unit?: string; @Input() unit?: string;
@Input() temporalReference?: string; @Input() temporalReference?: string;
// CaMa's opportunity strip shares one period, shown by the parent instead of on every card.
@Input() showPeriod = true;
@Input() loading = false; @Input() loading = false;
@Input() notes: string[] = []; @Input() notes: string[] = [];
@Input() state = 'Pendiente de definición'; @Input() state = 'Pendiente de definición';
@@ -190,9 +190,14 @@ describe('KPI integración con autoridad global', () => {
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']); : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
expect.stringContaining('2025-S1'),
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
])); ]));
if (domain === 'cama') {
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
} else {
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('2025-S1')]));
}
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions. // CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false); expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
@@ -19,7 +19,8 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule], imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit" template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference" [state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" /> [loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'"
[showPeriod]="dominio !== 'cama'" />
@if (result().state === 'Error de consulta') { @if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button> <button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`, }`,
@@ -38,7 +38,7 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0;
.remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); } .remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); }
.remove button { min-height: 44px; } .remove button { min-height: 44px; }
.apply-button { min-height: 44px; margin-top: var(--issste-space-2); } .apply-button { min-height: 44px; margin-top: var(--issste-space-2); }
.fields.compact { align-items: center; } .fields.compact { align-items: end; }
.fields.compact mat-form-field { flex: 0 1 14rem; } .fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; } .fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) { @media (max-width: 550px) {
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => { it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator. // Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied)) expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con resultado maligno.' }); .toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
}); });
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => { it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied); const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -210,13 +210,14 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente'); expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1); expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica'); expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.'); expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.'); expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible'); expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
expect(kpis()[4].querySelector('.value')).toBeNull(); expect(kpis()[4].querySelector('.value')).toBeNull();
}); });
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');
}); });
}); });
@@ -308,3 +308,33 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () =>
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]); expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
}); });
}); });
describe('Conteos publicados de CaMa en la ruta FHIR', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
function pedir(id: string, fhirId: string) {
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer;
}
it('las mastografías llegan a la tarjeta con los conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
expect(mostrado.filas).toEqual(publicado.filas);
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
});
it('los pacientes conservan sus conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas);
});
});
@@ -73,7 +73,7 @@ describe('Tasa de detección histopatológica (C1)', () => {
expect(d['grupos']).toEqual({ total: 'Total' }); expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]); expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({ expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` }); state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
}); });
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => { it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'], ['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]); ]);
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([ expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']); 'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]); expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
}); });
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => { it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => { it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia"). // Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' }); expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
}); });
it('una tasa de cero con denominador es un cero real, no una ausencia', () => { it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -213,8 +213,10 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) }); const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort()); expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad'); expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
expect(cards().map(card => text(card, 'h3'))).toEqual([ expect(cards().map(card => text(card, 'h3'))).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']); 'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]); expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([ expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
@@ -234,7 +236,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible'); expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
expect(text(cards()[4], '.value')).toBeUndefined(); expect(text(cards()[4], '.value')).toBeUndefined();
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false); expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.'); expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
}); });
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => { it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
@@ -254,7 +256,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined(); expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
expect(text(cards()[0], '.value')).toBe('5pacientes'); expect(text(cards()[0], '.value')).toBe('5pacientes');
expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.textContent).not.toContain('private');
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía interpretación radiológica"]')).not.toBeNull(); expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
}); });
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => { it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators. // Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
@@ -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');
}); });
@@ -213,7 +213,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim(); const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim()); const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
expect(h3).toEqual([ expect(h3).toEqual([
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, 2025-S2', 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
]); ]);
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe( expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
@@ -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 } };
} }
@@ -87,7 +87,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } }); expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías'); expect(r.comoLeer).toContain('mastografías');
}); });
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => { it('Pacientes evaluadas con BI-RADS 4, 5 o 6 conserva la gráfica y omite la explicación de la barra', () => {
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' })); const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
expect(pacientes.comoLeer).toBe(''); expect(pacientes.comoLeer).toBe('');
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']); expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
@@ -14,12 +14,9 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette. // The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] }; const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose. // CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = { const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' }, const FONDO_AZUL = '#9DBFE380';
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
};
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right. // sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
@@ -92,17 +89,24 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
return { validas, suprimidos, sinDato }; return { validas, suprimidos, sinDato };
} }
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
function colorDeLinea(id: string, tema: Tema) {
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
const linea = c2Theme(tema).line;
return { linea, relleno: linea + '40' };
}
type Trazo = Omit<HistoricoFigura, 'contrato'>; type Trazo = Omit<HistoricoFigura, 'contrato'>;
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
const periodos = validar(data); const periodos = validar(data);
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. // A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = LINEAS[data.id] ?? c2Theme(tema).line; const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
return { return {
figure: { data: [ figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea), banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 }, { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' }, hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
@@ -113,13 +117,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data); const periodos = validar(data), unidad = unidadDe(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const propio = DIAS[data.id]; const trazo = colorDeLinea(data.id, tema);
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
return { return {
figure: { data: [ figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, relleno), banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, marker: { color: linea }, { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''), text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' }, hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => { ], layout: (() => {
@@ -63,15 +63,19 @@ describe('Figuras de histórico', () => {
expect(traza(data, 0).y).toEqual([30, 10]); expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]); expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
}); });
it('las líneas de días de CaMa usan el azul, el morado y el rosa de la histopatología', () => { it('las líneas de CaMa comparten el morado y, si hay banda, el fondo azul', () => {
const color = (id: string, tema: 'claro' | 'oscuro') => { const dias = (id: string, tema: 'claro' | 'oscuro') => {
const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure; const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure;
return { linea: (figure.data[1]['line'] as { color: string }).color, banda: figure.data[0]['fillcolor'] }; return { linea: (figure.data[1]['line'] as { color: string }).color, puntos: (figure.data[1]['marker'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
}; };
expect(color('cama_dias_toma_diagnostico', 'claro')).toEqual({ linea: '#2F6DB3', banda: '#9DBFE380' }); for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' }); expect(dias(id, 'claro')).toEqual({ linea: '#9C42C2', puntos: '#9C42C2', banda: '#9DBFE380' });
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' }); }
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3'); expect(dias('cama_dias_toma_diagnostico', 'oscuro')).toEqual({ linea: '#D2A4EA', puntos: '#D2A4EA', banda: '#9DBFE380' });
const tasa = historicoFigura({ ...base, id: 'cama_confirmacion_birads45', contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure;
expect((tasa.data[1]['line'] as { color: string }).color).toBe('#9C42C2');
expect((tasa.data[1]['marker'] as { color: string }).color).toBe('#9C42C2');
expect(tasa.data[0]['fillcolor']).toBe('#9DBFE380');
}); });
it('las líneas usan el verde legible en cada tema', () => { it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }; const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
@@ -28,7 +28,7 @@ const PERSONALIZADO = -1;
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible. // publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' }, { id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' }, { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA }, { id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
@@ -62,7 +62,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico', selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: ` template: `
<div class="controles"> <div class="controles" [class.compacto]="dominio() === 'cama'">
<h2>Filtros</h2> <h2>Filtros</h2>
<div class="controles-fila"> <div class="controles-fila">
<div class="interval"> <div class="interval">
@@ -127,10 +127,22 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
</div> </div>
`, `,
styles: ` styles: `
@use '@angular/material' as mat;
:host { display: block; min-width: 0; } :host { display: block; min-width: 0; }
.controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } .controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
// Same field height as the summary filters. The theme also rewrites corners, which would turn the switch into a pill.
.controles.compacto {
@include mat.theme((density: -4));
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
.controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); } .controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; } .interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; } .interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; }
@@ -151,7 +163,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); } .pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } } @container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); } h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { flex: 0 1 14rem; width: 14rem; min-width: 14rem; max-width: 24rem; } mat-form-field { flex: 0 1 14rem; min-width: 0; max-width: 24rem; }
`, `,
}) })
export class IndicadoresHistorico { export class IndicadoresHistorico {
@@ -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) {
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => { it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
if (domain === 'cama') { if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente'); expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6'); expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']); expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
} else expect(anchor.id).toBe('cacu_eu7'); } else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true, id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
}; };
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = { export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
}; };
// Institutional definitions retained for consumers outside the opportunity strip. // Institutional definitions retained for consumers outside the opportunity strip.
export const CAMA_CONFIRMACION_KPI: KpiDefinition = { export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
@@ -25,7 +25,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
}; };
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = { export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%', id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`, c1Info: (n, d) => `${n} de ${d} biopsias con riesgo a carcinoma.`,
}; };
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
@@ -58,7 +58,7 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, { id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
], ],
cama: [ cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI,
], ],
}; };
@@ -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: {} });
@@ -50,7 +50,10 @@
@if (kpis.length && !initialPeriodBlocked) { @if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio"> <section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@let resumen = teaResumenPeriodo; @let resumen = teaResumenPeriodo;
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2> <div class="kpi-heading">
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
@if (periodoCompartido) { <p class="kpi-period">Periodo {{ periodoCompartido }}</p> }
</div>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> } @if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. --> <!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)"> <div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
@@ -117,6 +120,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)" />
@@ -16,7 +16,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2); .kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2);
padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border); padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); background: var(--issste-surface); } border-radius: var(--issste-radius); background: var(--issste-surface); }
.kpi-section > .section-title { margin-bottom: var(--issste-space-4); } .kpi-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--issste-space-3); }
.kpi-section > .kpi-heading { margin-bottom: var(--issste-space-4); }
.kpi-period { margin: .15rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; white-space: nowrap; }
.graphic-section { margin-top: var(--issste-space-6); } .graphic-section { margin-top: var(--issste-space-6); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; } .kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
@@ -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',
}) })
@@ -101,6 +102,15 @@ export class IndicadoresPage {
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect'); private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard); private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel); readonly kpiPanels = viewChildren(IndicadorKpiPanel);
// The opportunity cards share the period their own query already resolved.
get periodoCompartido(): string {
if (this.dominio !== 'cama') return '';
const deConsulta = this.kpiPanels().map(panel => panel.temporalReference.trim())
.find(text => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(text));
if (deConsulta) return deConsulta;
const applied = this.filters?.applied;
return applied?.selection.mode === 'explicit' && applied.selection.periodos.length === 1 ? applied.selection.periodos[0] : '';
}
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>(); private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = []; private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver; private visibilityObserver?: IntersectionObserver;
@@ -314,15 +324,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 +374,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);
@@ -0,0 +1,76 @@
// Covers the histologic-type classification and its column in the follow-up table. It uses the CaMa follow-up
// fixture (fixtures/cama_seguimiento.json), to which each test adds a synthetic `tipo_histologico` per row.
import fixtureData from './fixtures/cama_seguimiento.json';
import { clasificacionHistologica, MAPEO_HISTOLOGICO, SIN_CLASIFICAR } from './mapeo-histologico';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
const respuesta = () => structuredClone(fixtureData) as unknown as { columnas: { clave: string; etiqueta: string }[]; items: Record<string, string | number | null>[] };
describe('Clasificación histológica', () => {
it.each([
['Ductal (NST)', 'Carcinoma invasor'], ['Lobulillar', 'Carcinoma invasor'], ['Ductal-lobulillar mixto', 'Carcinoma invasor'],
['Mucinoso', 'Carcinoma invasor'], ['Paget', 'Carcinoma in situ'], ['Papilar', 'Revisar (Benigno / In situ / Invasor)'],
['Tubular', 'Carcinoma invasor'], ['cribiforme', 'Revisar (In situ / Invasor)'], ['Micropapilar', 'Revisar (In situ / Invasor)'],
['Inflamatorio', 'Carcinoma invasor'], ['Medular', 'Carcinoma invasor'], ['Otros', 'Revisar (Benigno / In situ / Invasor)'],
['SIN MAPEAR', 'Sin clasificar'],
])('asigna a «%s» la clasificación «%s»', (tipo, clasificacion) => {
// Fails if a type is moved to another group or dropped from the mapping.
expect(clasificacionHistologica(tipo)).toBe(clasificacion);
});
it('la categoría combinada «Tubular / cribiforme» del gráfico es carcinoma invasor', () => {
// Fails if the chart's merged category stops being classified, which would leave its patients unclassified.
expect(clasificacionHistologica('Tubular / cribiforme')).toBe('Carcinoma invasor');
});
it('un tipo fuera del mapeo, incluido uno heredado del prototipo de objeto, es «Sin clasificar»', () => {
// Fails if the lookup returns inherited properties such as «constructor» instead of the fallback.
for (const tipo of ['Desconocido', '', 'constructor', 'toString']) expect(clasificacionHistologica(tipo)).toBe(SIN_CLASIFICAR);
});
it('el mapeo conserva sus trece tipos y sus cuatro clasificaciones directas', () => {
// Fails if a type is added or removed without reviewing its classification.
expect(Object.keys(MAPEO_HISTOLOGICO)).toHaveLength(14);
expect(new Set(Object.values(MAPEO_HISTOLOGICO))).toEqual(new Set([
'Carcinoma invasor', 'Carcinoma in situ', 'Revisar (Benigno / In situ / Invasor)', 'Revisar (In situ / Invasor)', 'Sin clasificar']));
});
});
describe('Seguimiento: columna de clasificación histológica', () => {
const tipos = ['Ductal (NST)', 'Paget', 'Otros', 'SIN MAPEAR', 'Zzz'];
it('cada paciente recibe la clasificación de su propio tipo, en una columna tras el tipo o tras el resultado de la biopsia', () => {
// Fails if the classification is computed from another row or placed away from the biopsy columns.
const datos = respuesta();
const conBiopsia = datos.items.filter(item => item['biopsia'] !== null);
conBiopsia.forEach((item, i) => { item['tipo_histologico'] = tipos[i % tipos.length]; });
const r = seguimientoTablaResponse(datos);
const claves = r.columnas.map(c => c.clave);
expect(claves[claves.indexOf('biopsia') + 1]).toBe('clasificacion_histologica');
expect(r.columnas.find(c => c.clave === 'clasificacion_histologica')!.etiqueta).toBe('Clasificación histológica');
for (const item of r.items.filter(item => typeof item['tipo_histologico'] === 'string')) {
expect(item['clasificacion_histologica']).toBe(clasificacionHistologica(item['tipo_histologico'] as string));
}
});
it('con una columna de tipo, la clasificación va justo después de ella', () => {
// Fails if the derived column ignores the type's own column and lands elsewhere.
const datos = respuesta();
datos.columnas.splice(datos.columnas.findIndex(c => c.clave === 'biopsia') + 1, 0, { clave: 'tipo_histologico', etiqueta: 'Tipo histológico' });
datos.items.forEach(item => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Lobulillar'; });
const claves = seguimientoTablaResponse(datos).columnas.map(c => c.clave);
expect(claves.slice(claves.indexOf('tipo_histologico'), claves.indexOf('tipo_histologico') + 2)).toEqual(['tipo_histologico', 'clasificacion_histologica']);
});
it('un paciente sin tipo no recibe clasificación y los demás campos quedan como llegaron', () => {
// Fails if a patient without biopsy is shown as «Sin clasificar», or if other row values are altered.
const datos = respuesta();
datos.items.forEach((item, i) => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Medular'; });
const original = structuredClone(datos.items);
const r = seguimientoTablaResponse(datos);
r.items.forEach((item, i) => {
if (original[i]['tipo_histologico'] === null) expect('clasificacion_histologica' in item).toBe(false);
expect({ ...item, clasificacion_histologica: undefined }).toEqual({ ...original[i], clasificacion_histologica: undefined });
});
});
it('una lista sin tipo histológico no cambia', () => {
// Fails if the column appears while the API does not send the field.
const r = seguimientoTablaResponse(respuesta());
expect(r.columnas.map(c => c.clave)).not.toContain('clasificacion_histologica');
expect(r.items.some(item => 'clasificacion_histologica' in item)).toBe(false);
});
});
@@ -0,0 +1,23 @@
// Groups the histologic type of a biopsy into the classification shown beside it.
export const SIN_CLASIFICAR = 'Sin clasificar';
export const MAPEO_HISTOLOGICO: Readonly<Record<string, string>> = {
'Ductal (NST)': 'Carcinoma invasor',
'Lobulillar': 'Carcinoma invasor',
'Ductal-lobulillar mixto': 'Carcinoma invasor',
'Mucinoso': 'Carcinoma invasor',
'Paget': 'Carcinoma in situ',
'Papilar': 'Revisar (Benigno / In situ / Invasor)',
'Tubular': 'Carcinoma invasor',
'Tubular / cribiforme': 'Carcinoma invasor',
'cribiforme': 'Revisar (In situ / Invasor)',
'Micropapilar': 'Revisar (In situ / Invasor)',
'Inflamatorio': 'Carcinoma invasor',
'Medular': 'Carcinoma invasor',
'Otros': 'Revisar (Benigno / In situ / Invasor)',
'SIN MAPEAR': SIN_CLASIFICAR,
};
/** The classification of a histologic type; a type outside the mapping is «Sin clasificar». */
export const clasificacionHistologica = (tipo: string) =>
Object.hasOwn(MAPEO_HISTOLOGICO, tipo) ? MAPEO_HISTOLOGICO[tipo] : SIN_CLASIFICAR;
@@ -4,6 +4,7 @@ import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models'; import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad'; import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte'; import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { clasificacionHistologica } from './mapeo-histologico';
import { Dominio, requireDominio } from './indicadores.models'; import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per // A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -96,10 +97,33 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) { || !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
} }
const respuesta = v as unknown as SeguimientoTablaResponse; const respuesta = clasificarHistologia(v as unknown as SeguimientoTablaResponse);
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta; return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
} }
const TIPO_HISTOLOGICO = 'tipo_histologico';
const CLASIFICACION_HISTOLOGICA = 'clasificacion_histologica';
/**
* A list that carries the histologic type of each patient (`tipo_histologico`) also shows its classification, computed
* from that same value in the same row, in a column placed after the type's (or after the biopsy result when the type
* has no column). Rows without a type, and lists without the field, are left as received.
*/
export function clasificarHistologia(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
if (!r.items.some(item => typeof item[TIPO_HISTOLOGICO] === 'string') || r.columnas.some(c => c.clave === CLASIFICACION_HISTOLOGICA)) return r;
const columnas = [...r.columnas];
const despuesDe = [TIPO_HISTOLOGICO, 'biopsia'].map(k => columnas.findIndex(c => c.clave === k)).find(i => i >= 0) ?? columnas.length - 1;
columnas.splice(despuesDe + 1, 0, { clave: CLASIFICACION_HISTOLOGICA, etiqueta: 'Clasificación histológica' });
return {
...r,
columnas,
items: r.items.map(item => {
const tipo = item[TIPO_HISTOLOGICO];
return typeof tipo === 'string' ? { ...item, [CLASIFICACION_HISTOLOGICA]: clasificacionHistologica(tipo) } : item;
}),
};
}
/** /**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is * A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays * rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
+1
View File
@@ -43,6 +43,7 @@
--issste-space-2: var(--space-2); --issste-space-2: var(--space-2);
--issste-space-3: var(--space-3); --issste-space-3: var(--space-3);
--issste-space-4: var(--space-4); --issste-space-4: var(--space-4);
--issste-space-5: var(--space-5);
--issste-space-6: var(--space-6); --issste-space-6: var(--space-6);
--issste-radius: var(--mat-sys-corner-medium); --issste-radius: var(--mat-sys-corner-medium);
} }