Feature/cama audit histopathology demo #12
@@ -14,3 +14,30 @@ npx ng build # compilación de producción en dist/WebApp
|
||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||
|
||||
## Fuente de histopatología BI-RADS
|
||||
|
||||
La compilación estándar incorpora la fuente sintética de la tarjeta de
|
||||
histopatología en **CaMa → Resumen**. La dona y las barras usan el mismo
|
||||
fixture. El catálogo, los filtros generales y los demás indicadores siguen
|
||||
usando WebApi. Si el catálogo carga sin la medida de histopatología, Resumen
|
||||
incluye la tarjeta con su fuente local.
|
||||
|
||||
El archivo
|
||||
`src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json`
|
||||
contiene conteos inventados, sin validez clínica. Define los 12 subtipos en orden
|
||||
con sus identificadores y colores. Cada mes remite a un perfil de conteos por
|
||||
estrato BI-RADS que incluye resultados benignos, subtipos, casos sin biopsia
|
||||
reportada y casos sin dato. Abarca enero de 2025 a diciembre de 2026. Los semestres
|
||||
suman esos mismos meses. Un periodo fuera de cobertura queda sin resultados.
|
||||
|
||||
El anillo interior usa el total con resultado de biopsia. El exterior reparte
|
||||
el grupo «Riesgo a carcinoma» entre sus 12 subtipos. Las barras y el centro
|
||||
muestran el subconjunto elegido sobre el total con resultado, por BI-RADS y del
|
||||
periodo completo, respectivamente. La leyenda permite elegir subtipos incluso
|
||||
cuando el sector es demasiado pequeño.
|
||||
|
||||
Cuando se valide la matriz clínica de subtipos, el adaptador FHIR podrá construir
|
||||
el mismo modelo de presentación con los conteos, estratos, denominadores y
|
||||
reglas de supresión aprobados. Los componentes de visualización ya consumen
|
||||
ese modelo tanto para las tasas como para los anillos.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
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 };
|
||||
});
|
||||
}
|
||||
@@ -33,13 +33,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ tituloVisible }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@if (!sobrio) {
|
||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + tituloVisible"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
@@ -56,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
</div>
|
||||
} @else if (isHistopatologia) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
@@ -64,7 +64,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
</div>
|
||||
} @else if (conteos; as par) {
|
||||
<div #visibilityRegion class="conteos-region">
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [metadataAttempt]="metadataAttempt" (metadataRequested)="loadMetadata()" />
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@@ -128,7 +128,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
metadata?: IndicadorMetadatos;
|
||||
metadataAttempt = 0;
|
||||
private activatedKey = '';
|
||||
constructor() {
|
||||
effect(() => {
|
||||
@@ -138,11 +137,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
|
||||
get sobrio() { return this.dominio === 'cama'; }
|
||||
// The published title keeps «individual»; the card does not. The paired BI-RADS card has no card title:
|
||||
// each donut carries its own («Mastografías por categoría, <periodo>», «Pacientes por categoría, <periodo>»).
|
||||
get tituloVisible() {
|
||||
return this.indicador.id === 'cama_birads_456_mastografia' ? this.indicador.titulo.replace(' individual', '') : this.indicador.titulo;
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
@@ -228,7 +222,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.metadata = value;
|
||||
this.metadataAttempt++;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
@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) {
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
@@ -17,45 +19,33 @@
|
||||
<div class="figures">
|
||||
<section class="figure">
|
||||
<div class="figure-head">
|
||||
<h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
<h3>{{ tituloMastografias }}</h3>
|
||||
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
|
||||
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
|
||||
@if (helpWhich === 'examenes') {
|
||||
<div class="methodology" role="tooltip">
|
||||
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
|
||||
<h3>Dona por categoría</h3>
|
||||
@if (donutGuide; as guide) {
|
||||
@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> }
|
||||
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
|
||||
</section>
|
||||
</div>
|
||||
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (total) {
|
||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
|
||||
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
|
||||
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
|
||||
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||
</section>
|
||||
<section class="figure">
|
||||
<div class="figure-head">
|
||||
<h3>{{ par.unidades.pacientes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
<h3>{{ tituloPacientes }}</h3>
|
||||
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
|
||||
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
|
||||
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
|
||||
@if (helpWhich === 'pacientes') {
|
||||
<div class="methodology" role="tooltip">
|
||||
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
|
||||
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
|
||||
<p>Cada paciente cuenta una vez en el periodo, en la categoría más alta de sus mastografías. Cada mastografía cuenta en su propia categoría. Cada dona muestra uno de esos conteos; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
|
||||
</section>
|
||||
</div>
|
||||
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@if (totalPacientes) {
|
||||
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="indicador.titulo + ', dona de pacientes por categoría BI-RADS, ' + m.periodo" />
|
||||
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
|
||||
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
|
||||
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
|
||||
</section>
|
||||
|
||||
@@ -3,14 +3,11 @@
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
.figure-head { display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||
.figure-head h3 { margin: 0; }
|
||||
.help { position: relative; display: flex; flex: none; justify-content: flex-end; }
|
||||
.help .methodology { position: absolute; z-index: 8; top: calc(100% + .35rem); right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||
.help { display: flex; flex: none; justify-content: flex-end; }
|
||||
.help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
|
||||
box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
|
||||
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
||||
.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { TitleCasePipe } from '@angular/common';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
@@ -25,10 +25,6 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
// Bumps when a metadata request finishes, including a failure that leaves metadata empty.
|
||||
@Input() metadataAttempt = 0;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
periodIndex = 0;
|
||||
@@ -50,16 +46,6 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||
helpWhich: 'examenes' | 'pacientes' | null = null;
|
||||
private helpPinned: 'examenes' | 'pacientes' | null = null;
|
||||
// True only while a metadata request is outstanding. A failure leaves metadata empty, so the next
|
||||
// hover may ask again; the catalog card ignores a second ask until that request finishes.
|
||||
private helpAsked = false;
|
||||
// "Cómo leer": what the kit publishes for the exams' donut. Both donuts use the same categories.
|
||||
get donutGuide() {
|
||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
||||
}
|
||||
toggleHelp(which: 'examenes' | 'pacientes') {
|
||||
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
|
||||
this.helpPinned = which;
|
||||
@@ -67,12 +53,6 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
}
|
||||
openHelp(which: 'examenes' | 'pacientes') {
|
||||
this.helpWhich = which;
|
||||
this.showHelp();
|
||||
}
|
||||
showHelp() {
|
||||
if (this.metadata || this.helpAsked) return;
|
||||
this.helpAsked = true;
|
||||
this.metadataRequested.emit();
|
||||
}
|
||||
hideHelp(which: 'examenes' | 'pacientes') {
|
||||
if (this.helpPinned === which) return;
|
||||
@@ -86,11 +66,9 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (changes['metadata'] && this.metadata) this.helpAsked = false;
|
||||
else if (changes['metadataAttempt'] && !this.metadata) this.helpAsked = false;
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.helpAsked = false; this.clear();
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
|
||||
@@ -8,27 +8,20 @@
|
||||
<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) {
|
||||
<div class="methodology" id="histo-como-leer" role="tooltip">
|
||||
<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>
|
||||
@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>
|
||||
}
|
||||
}
|
||||
<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>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>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</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> }
|
||||
@case ('incompatible') { <p role="alert">{{ message }}</p> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (status() === 'empty') {
|
||||
<p role="status">No hay resultados de biopsia para el periodo seleccionado.</p>
|
||||
}
|
||||
@if (status() === 'ready') {
|
||||
@if (periods.length > 1) {
|
||||
<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>
|
||||
@@ -37,8 +30,6 @@
|
||||
</nav>
|
||||
}
|
||||
@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="tab-bar">
|
||||
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
|
||||
@@ -50,7 +41,7 @@
|
||||
<div class="child-groups">
|
||||
@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">
|
||||
@for (c of m.categorias; track c.id; let ci = $index) {
|
||||
@for (c of categoriasExteriores(m); track c.id; let ci = $index) {
|
||||
@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>
|
||||
}
|
||||
@@ -71,9 +62,8 @@
|
||||
} @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>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<details class="published-values"><summary>Ver valores</summary>
|
||||
<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>
|
||||
<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,28 +1,15 @@
|
||||
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 { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { snapshotKey } from './indicadores-snapshots';
|
||||
import { Celda } from './indicadores-confirmacion-citologia';
|
||||
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
|
||||
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
|
||||
|
||||
/**
|
||||
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
|
||||
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
|
||||
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
|
||||
*/
|
||||
import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA,
|
||||
ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama';
|
||||
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
|
||||
@Component({
|
||||
selector: 'app-indicador-histopatologia-cama',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
imports: [PlotlyChart],
|
||||
templateUrl: './indicador-histopatologia-cama.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
@@ -32,9 +19,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection?: SeleccionHistopatologia;
|
||||
periods: string[] = [];
|
||||
@@ -43,10 +28,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
readonly categoriasExteriores = categoriasExteriores;
|
||||
private helpPinned = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloHistopatologia[] = [];
|
||||
@@ -61,21 +45,8 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
|
||||
}
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() {
|
||||
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||
this.helpPinned = true;
|
||||
@@ -84,7 +55,6 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
showHelp() {
|
||||
if (this.helpOpen) return;
|
||||
this.helpOpen = true;
|
||||
this.metadataRequested.emit();
|
||||
}
|
||||
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
|
||||
onHelpFocusOut(event: FocusEvent) {
|
||||
@@ -95,53 +65,32 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied)
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
|
||||
// The most recent period first; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
const { tipo, selection } = this.applied;
|
||||
this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined);
|
||||
this.periods = this.pages.map(modelo => modelo.periodo);
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1);
|
||||
this.activatePeriod();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
@@ -166,5 +115,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -113,9 +113,10 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
||||
const respuestas: Record<string, unknown> = visibles
|
||||
? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture }
|
||||
: { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture };
|
||||
const respuestas: Record<string, unknown> = {
|
||||
cama_dias_resultado_diagnostico: visibles ? diasVisible : diasSuprimido,
|
||||
cama_histopatologia_birads: generalFixture,
|
||||
};
|
||||
const pedidos: string[] = [];
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
@@ -132,28 +133,29 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
|
||||
it('los tres indicadores publicados se piden y se dibujan; los cinco restantes de la lista siguen pendientes', () => {
|
||||
it('omite el panel y las consultas de detección aunque la medida figure en el catálogo', () => {
|
||||
const pedidos = montar(true);
|
||||
expect(REALES.map(i => i.id)).toContain('cama_tasa_deteccion_histopatologica');
|
||||
expect(pedidos.some(p => p.includes('cama_tasa_deteccion_histopatologica'))).toBe(false);
|
||||
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
|
||||
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
|
||||
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
|
||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
|
||||
expect(graficas()).toHaveLength(3);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]);
|
||||
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
|
||||
});
|
||||
it('con el umbral normal los dos paneles C1 y C3r avisan el periodo suprimido, y la matriz CAM-03 sigue visible', () => {
|
||||
it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
|
||||
montar(false);
|
||||
const texto = paneles().map(p => p.textContent!);
|
||||
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
|
||||
expect(graficas()).toHaveLength(3);
|
||||
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(1);
|
||||
expect(graficas()).toHaveLength(2);
|
||||
});
|
||||
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
|
||||
montar(false);
|
||||
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
|
||||
expect(notas).toHaveLength(2);
|
||||
expect(notas).toHaveLength(1);
|
||||
for (const nota of notas) {
|
||||
expect(nota.open).toBe(false);
|
||||
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
|
||||
@@ -161,7 +163,6 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
}
|
||||
notas[0].open = true;
|
||||
expect(notas[0].open).toBe(true);
|
||||
expect(notas[1].open).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -204,9 +205,11 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
|
||||
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||
cargar(completo());
|
||||
const pedidos = cargar(completo());
|
||||
expect(kpis()).toHaveLength(5);
|
||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
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].textContent).toContain('0 de 1 biopsias con resultado maligno.');
|
||||
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');
|
||||
@@ -214,7 +217,6 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
});
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
const pedidos = cargar(completo());
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
const primera = tarjetas()[0];
|
||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
@@ -228,13 +230,10 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
|
||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
|
||||
});
|
||||
it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
|
||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull();
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
});
|
||||
it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => {
|
||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(kpis()).toHaveLength(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
|
||||
it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => {
|
||||
const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||
expect(kpis()).toHaveLength(5);
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(pedidos).not.toContain('cama_histopatologia_birads');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -53,8 +53,8 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect(titles()).not.toContain('Distribución de resultados de biopsia');
|
||||
// The patients' counts go on the exams' card, so the partner indicator has no card of its own.
|
||||
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
|
||||
// The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
|
||||
expect(titles()).toEqual([]);
|
||||
// The paired card has no card title; each donut names itself.
|
||||
expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||
expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull();
|
||||
expect(section().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
|
||||
expect(root().textContent).not.toContain('indicador publicado');
|
||||
@@ -67,26 +67,27 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||
}
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||
open('cama', CAMA);
|
||||
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
|
||||
expect(tarjeta).not.toBeNull();
|
||||
expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||
expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente');
|
||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||
it('CaMa: la tarjeta de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => {
|
||||
open('cama', CAMA);
|
||||
const primera = root().querySelector('.catalog-grid')!.firstElementChild!;
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||
expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads');
|
||||
});
|
||||
it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => {
|
||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1);
|
||||
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
|
||||
});
|
||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => {
|
||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => {
|
||||
open(domain, OTRO(domain));
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||
});
|
||||
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
|
||||
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
|
||||
|
||||
@@ -203,8 +203,8 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
// Fails if the patients' indicator keeps a card of its own beside the pair.
|
||||
const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
|
||||
// The pair has no card title; each donut carries «Mastografías/Pacientes por categoría, <periodo>».
|
||||
expect(titulos).toEqual([]);
|
||||
// The pair has no card title; each donut has its own heading.
|
||||
expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||
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');
|
||||
});
|
||||
@@ -212,9 +212,15 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
abrir();
|
||||
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());
|
||||
expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes por categoría, 2025-S2']);
|
||||
expect(h3).toEqual([
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 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(
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]);
|
||||
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
|
||||
@@ -223,6 +229,27 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
expect([...root().querySelectorAll('.help-icon')].map(b => b.getAttribute('aria-label'))).toEqual(['Cómo leer, mastografías por categoría', 'Cómo leer, pacientes por categoría']);
|
||||
expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato');
|
||||
});
|
||||
it('cada ayuda muestra su explicación exacta sin depender de metadatos de FHIR', () => {
|
||||
abrir();
|
||||
const [mastografias, pacientes] = [...root().querySelectorAll<HTMLButtonElement>('.help-icon')];
|
||||
const ayuda = () => root().querySelector('[role=tooltip]');
|
||||
|
||||
mastografias.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(ayuda()?.textContent?.trim()).toBe('Cada mastografía cuenta en su propia categoría.');
|
||||
expect(mastografias.getAttribute('aria-describedby')).toBe(ayuda()?.id);
|
||||
|
||||
pacientes.click();
|
||||
fixture.detectChanges();
|
||||
expect(ayuda()?.textContent?.trim()).toBe('La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.');
|
||||
expect(pacientes.getAttribute('aria-describedby')).toBe(ayuda()?.id);
|
||||
expect(mastografias.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(root().querySelectorAll('[role=tooltip]')).toHaveLength(1);
|
||||
pacientes.click();
|
||||
fixture.detectChanges();
|
||||
expect(ayuda()).toBeNull();
|
||||
http.expectNone(r => r.url.endsWith('/metadatos'));
|
||||
});
|
||||
it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => {
|
||||
abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' }));
|
||||
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||
@@ -252,50 +279,3 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
expect(pedidos().length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Cómo leer de conteos pareados: reintento tras un fallo', () => {
|
||||
it('vuelve a pedir los metadatos después de un fallo, sin duplicar la consulta abierta ni la ya recibida', () => {
|
||||
TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
const fixture = TestBed.createComponent(IndicadorCatalogCard);
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cama');
|
||||
fixture.componentRef.setInput('indicador', {
|
||||
id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías', contrato: 'C2',
|
||||
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'],
|
||||
});
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 });
|
||||
fixture.detectChanges();
|
||||
fixture.componentInstance.setVisible(true);
|
||||
fixture.detectChanges();
|
||||
const conteos = fixture.debugElement.query(By.directive(IndicadorConteosPareados)).componentInstance as IndicadorConteosPareados;
|
||||
const meta = () => http.match(r => r.url.endsWith('/metadatos'));
|
||||
conteos.showHelp();
|
||||
fixture.detectChanges();
|
||||
const primero = meta();
|
||||
expect(primero).toHaveLength(1);
|
||||
conteos.showHelp();
|
||||
fixture.detectChanges();
|
||||
expect(meta()).toHaveLength(0);
|
||||
primero[0].flush('no', { status: 500, statusText: 'Error' });
|
||||
fixture.detectChanges();
|
||||
conteos.showHelp();
|
||||
fixture.detectChanges();
|
||||
const segundo = meta();
|
||||
expect(segundo).toHaveLength(1);
|
||||
segundo[0].flush({ descripcion: 'Lectura de la dona', figuras_detalle: [{ figura: 'fig_c2_donas', descripcion: 'Lectura de la dona', como_leer: [] }] });
|
||||
for (const q of http.match(r => r.url.endsWith('/datos'))) q.flush(q.request.url.includes('paciente') ? pacientes(LAB_P) : examenes(LAB_E));
|
||||
fixture.detectChanges();
|
||||
(fixture.nativeElement.querySelectorAll('.help-icon')[1] as HTMLButtonElement).dispatchEvent(new MouseEvent('mouseenter', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('en la categoría más alta de sus mastografías');
|
||||
expect(fixture.nativeElement.textContent).toContain('Cada dona muestra uno de esos conteos');
|
||||
conteos.showHelp();
|
||||
fixture.detectChanges();
|
||||
expect(meta()).toHaveLength(0);
|
||||
fixture.destroy();
|
||||
http.match(() => true);
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Presentation labels for representations confirmed in the published catalog.
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows,
|
||||
// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic
|
||||
// rates and figures, and the catalog wiring of the local view. The fixtures are what WebApi publishes for the synthetic
|
||||
// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per
|
||||
// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator).
|
||||
import { Component, input, output } from '@angular/core';
|
||||
@@ -235,124 +235,32 @@ describe('Histopatología por BI-RADS: componente', () => {
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos');
|
||||
function flush(body: unknown = estratoFixture) {
|
||||
const r = solicitud();
|
||||
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
|
||||
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
expect([...f.nativeElement.querySelectorAll('.tabs button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['No maligno', 'Maligno']);
|
||||
expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno');
|
||||
expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim()))
|
||||
.toEqual(['Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']);
|
||||
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
|
||||
const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement;
|
||||
const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement;
|
||||
expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
|
||||
expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado');
|
||||
expect(f.nativeElement.querySelector('.selection-status')).toBeNull();
|
||||
expect(f.nativeElement.querySelector('.rate-states')).toBeNull();
|
||||
expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia');
|
||||
expect(contexto.textContent).toContain('Intervalo semestral');
|
||||
expect(contexto.textContent).toContain('Periodo 2025-S1');
|
||||
expect(f.componentInstance.selectionLabel).toBe('Maligno');
|
||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(
|
||||
['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']);
|
||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([
|
||||
['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'],
|
||||
['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'],
|
||||
['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]);
|
||||
expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;');
|
||||
});
|
||||
it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => {
|
||||
f.detectChanges(); flush();
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
expect(f.nativeElement.textContent).not.toContain('Volver');
|
||||
boton('No maligno').click(); f.detectChanges();
|
||||
const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
||||
expect(b3.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)');
|
||||
b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' });
|
||||
boton('Maligno').click(); f.detectChanges();
|
||||
boton('Carcinoma invasor').click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' });
|
||||
boton('Maligno').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
||||
it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => {
|
||||
f.componentRef.setInput('visible', false);
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred');
|
||||
f.componentRef.setInput('visible', true);
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
|
||||
expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma');
|
||||
f.componentRef.setInput('tema', 'oscuro');
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
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', () => {
|
||||
const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 });
|
||||
f.detectChanges(); flush(d);
|
||||
|
||||
it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => {
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.contextPeriod).toBe('2025-02');
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
|
||||
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('Suprimido');
|
||||
const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent));
|
||||
expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4');
|
||||
});
|
||||
it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => {
|
||||
const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6');
|
||||
d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6');
|
||||
f.detectChanges(); flush(d);
|
||||
const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement;
|
||||
expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]);
|
||||
expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('No disponible');
|
||||
});
|
||||
it('sin filas en el periodo lo dice y conserva la tabla vacía', () => {
|
||||
const d = estrato(); d.filas = []; d.totales_estrato = [];
|
||||
f.detectChanges(); flush(d);
|
||||
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 });
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
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.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
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);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
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
|
||||
// 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;
|
||||
const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
|
||||
export const ETIQUETA_ESTRATO: Readonly<Record<typeof ESTRATOS_BIRADS[number], 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',
|
||||
};
|
||||
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
|
||||
@@ -41,19 +41,21 @@ export interface Categoria { id: string; etiqueta: string; color: string; grupo:
|
||||
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
|
||||
export interface FilaBirads {
|
||||
id: string; etiqueta: string;
|
||||
// The four categories with a result.
|
||||
// Categories with a biopsy result.
|
||||
celdas: Record<string, Celda>;
|
||||
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
|
||||
aparte: Record<string, Celda>;
|
||||
// Patients of the stratum, as the response publishes them.
|
||||
total: Celda;
|
||||
// Patients with a biopsy result: the denominator. Null while any of the four cells is unknown.
|
||||
// Patients with a biopsy result: the denominator. Null while any result cell is unknown.
|
||||
den: number | null; estado: Celda['estado'];
|
||||
}
|
||||
export interface ModeloHistopatologia {
|
||||
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
|
||||
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||
// When set, the outer ring shows the subtype distribution within this group.
|
||||
grupoAnilloExterior?: string;
|
||||
}
|
||||
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
@@ -66,7 +68,7 @@ const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').re
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
|
||||
const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1);
|
||||
const enFrase = (v: string) => v === v.toUpperCase() ? v : v.charAt(0).toLowerCase() + v.slice(1);
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
|
||||
@@ -183,6 +185,9 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
|
||||
export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] {
|
||||
return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias;
|
||||
}
|
||||
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
|
||||
}
|
||||
@@ -194,12 +199,15 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
if (traza === 'centro') return seleccionBase(m);
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.categorias[indice];
|
||||
const c = categoriasExteriores(m)[indice];
|
||||
if (!c) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
||||
if (m.grupoAnilloExterior) {
|
||||
return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia';
|
||||
}
|
||||
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
|
||||
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
|
||||
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
|
||||
@@ -229,16 +237,19 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
|
||||
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const barras = !!m.grupoAnilloExterior;
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const tono = tonoDe(sel.categoria ?? sel.grupo);
|
||||
const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color];
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||
const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||
const rango = rangoTasas(valores);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color: colores }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6,
|
||||
...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }),
|
||||
uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
@@ -248,8 +259,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
|
||||
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
|
||||
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||||
title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||||
xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||||
title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : 'Porcentaje con resultado ') + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: estrecho ? 11 : 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
@@ -262,17 +273,27 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
|
||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.categorias.map(c => m.totales[c.id]!);
|
||||
const categorias = categoriasExteriores(m);
|
||||
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 hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
const custom = (values: number[]) => {
|
||||
const subtotal = values.reduce((s, n) => s + n, 0);
|
||||
return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]);
|
||||
};
|
||||
const hoverExterior = m.grupoAnilloExterior
|
||||
? { hovertemplate: '%{label}<br>%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)<extra></extra>' }
|
||||
: hover;
|
||||
const zoomGrupo = (id: string, hijos: readonly string[]) =>
|
||||
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1;
|
||||
const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1;
|
||||
const zoomDe = (values: number[]) => Math.max(1, ...values);
|
||||
const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)');
|
||||
const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias));
|
||||
const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id));
|
||||
const categoriasZoom = categorias.map(c => zoomCategoria(c.id));
|
||||
const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({
|
||||
...comun, ...hover, name, values, labels, hole, customdata: custom(values),
|
||||
domain: caja(base, zoomDe(zoom)),
|
||||
@@ -280,16 +301,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
||||
});
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text },
|
||||
text: [centro], 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>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: caja(CAJA_GRUPO, 1),
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||
labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } },
|
||||
anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)),
|
||||
anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)),
|
||||
{ ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior },
|
||||
], 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 } };
|
||||
}
|
||||
|
||||
@@ -79,11 +79,15 @@ describe('Histórico de CaMa', () => {
|
||||
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
|
||||
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
|
||||
});
|
||||
it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => {
|
||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
|
||||
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
|
||||
expect(paneles()).toHaveLength(7);
|
||||
const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
|
||||
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
||||
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||
@@ -28,12 +29,11 @@ const PERSONALIZADO = -1;
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
|
||||
];
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
|
||||
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { pending } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@@ -64,7 +64,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||
function cards() {
|
||||
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||
// The shared request queue runs four at a time: flushing a batch starts the next.
|
||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@@ -36,7 +37,9 @@ describe('UX-04 navegación Angular', () => {
|
||||
harness.detectChanges();
|
||||
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||
const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
||||
// CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one.
|
||||
const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!;
|
||||
if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
|
||||
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||
|
||||
@@ -117,7 +117,6 @@
|
||||
</div>
|
||||
}
|
||||
<div class="catalog-grid">
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@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)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
|
||||
@@ -15,6 +15,7 @@ import { MatSelect } from '@angular/material/select';
|
||||
import { NgModel } from '@angular/forms';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||
|
||||
@@ -37,7 +38,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
}
|
||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
||||
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||
function cards() {
|
||||
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
|
||||
function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
|
||||
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
|
||||
|
||||
@@ -31,7 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
@@ -51,7 +51,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||
templateUrl: './indicadores-page.html',
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
@@ -314,14 +314,15 @@ export class IndicadoresPage {
|
||||
private cardsDeCama(catalog: Indicador[]) {
|
||||
const ids = catalog.map(item => item.id);
|
||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
// The histopathology card keeps its place, first, whether pending or published.
|
||||
if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) {
|
||||
cards.unshift({
|
||||
id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS',
|
||||
contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'],
|
||||
});
|
||||
}
|
||||
// The histopathology card comes first, including when only the local source is available.
|
||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
||||
}
|
||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
||||
get histopatologiaPendiente() {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
||||
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
|
||||
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||
@@ -364,8 +365,8 @@ export class IndicadoresPage {
|
||||
return selected.length + ' indicadores';
|
||||
});
|
||||
readonly searchResults = computed(() => {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
const items = this.catalogOrder().filter(item => selected.has(item.id));
|
||||
const selected = this.indicatorSelection();
|
||||
const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id));
|
||||
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
||||
});
|
||||
readonly catalogLoading = signal(true);
|
||||
@@ -483,7 +484,8 @@ export class IndicadoresPage {
|
||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
||||
this.catalogLoading.set(false);
|
||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
||||
this.catalog.set(items);
|
||||
this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
|
||||
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
|
||||
this.filtersEdited();
|
||||
this.catalogError.set(error);
|
||||
this.availabilityRequests.next();
|
||||
|
||||
@@ -8,6 +8,7 @@ import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||
import { Indicador } from './indicadores.models';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||
@@ -83,7 +84,8 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
||||
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
||||
// Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned.
|
||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]);
|
||||
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
||||
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
||||
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
||||
|
||||
Reference in New Issue
Block a user