20261119 CaMa: donas de BI-RADS y etiquetas del resumen
La oportunidad dice confirmación histopatológica, la tarjeta de mastografías muestra dos donas y Cómo leer puede reintentar los metadatos. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -32,12 +32,12 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
<mat-card>
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1">{{ tituloVisible }}</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') + ', ' + indicador.titulo"
|
||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + tituloVisible"
|
||||
(click)="pinChanged.emit()">
|
||||
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||
</button>
|
||||
@@ -62,7 +62,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" (metadataRequested)="loadMetadata()" />
|
||||
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [metadataAttempt]="metadataAttempt" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||
@@ -126,6 +126,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
metadata?: IndicadorMetadatos;
|
||||
metadataAttempt = 0;
|
||||
private activatedKey = '';
|
||||
constructor() {
|
||||
effect(() => {
|
||||
@@ -135,6 +136,10 @@ 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.
|
||||
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; }
|
||||
@@ -220,6 +225,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.metadata = value;
|
||||
this.metadataAttempt++;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -24,8 +24,10 @@
|
||||
} @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"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} por categoría, {{ m.periodo }}</h3>
|
||||
@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" />
|
||||
} @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>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './in
|
||||
import { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
|
||||
import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-conteos-pareados',
|
||||
@@ -27,27 +27,32 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
@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;
|
||||
pages: ModeloConteos[] = [];
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
patientsFigure?: PlotlyFigure;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private anchoDona = 390;
|
||||
private anchoPacientes = 390;
|
||||
|
||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
||||
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
|
||||
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
|
||||
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||
// 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. The bars combine two indicators, so the kit's
|
||||
// description of its own bars does not apply to them and is not used.
|
||||
// "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() ?? '';
|
||||
@@ -62,22 +67,28 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
const pacientes = this.par.unidades.pacientes;
|
||||
const examenes = this.par.unidades.examenes;
|
||||
return [...dona, `${pacientes[0].toUpperCase()}${pacientes.slice(1)} y ${examenes}`,
|
||||
`Cada ${pacientes.slice(0, -1)} cuenta una vez en el periodo, en la categoría más grave de sus ${examenes}. Cada ${examenes.slice(0, -1)} cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas ${examenes} tiene cada ${pacientes.slice(0, -1)}, porque no son las mismas poblaciones.`,
|
||||
`Cada ${pacientes.slice(0, -1)} cuenta una vez en el periodo, en la categoría más grave de sus ${examenes}. Cada ${examenes.slice(0, -1)} cuenta en su propia categoría. Cada dona muestra uno de esos conteos; no se calcula cuántas ${examenes} tiene cada ${pacientes.slice(0, -1)}, porque no son las mismas poblaciones.`,
|
||||
].join('\n');
|
||||
}
|
||||
showHelp() { if (!this.helpAsked) { this.helpAsked = true; this.metadataRequested.emit(); } }
|
||||
showHelp() {
|
||||
if (this.metadata || this.helpAsked) return;
|
||||
this.helpAsked = true;
|
||||
this.metadataRequested.emit();
|
||||
}
|
||||
|
||||
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.clear();
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.helpAsked = 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.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; }
|
||||
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
@@ -123,11 +134,17 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
||||
const m = this.model;
|
||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
||||
}
|
||||
ajustarAnchoPacientes(ancho: number) {
|
||||
if (ancho === this.anchoPacientes) return;
|
||||
this.anchoPacientes = ancho;
|
||||
const m = this.model;
|
||||
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
|
||||
}
|
||||
private draw() {
|
||||
const m = this.model;
|
||||
if (!m) return;
|
||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
||||
this.barsFigure = barrasConteos(m, this.par, this.tema);
|
||||
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
|
||||
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
||||
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
||||
]);
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
||||
});
|
||||
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
||||
@@ -215,7 +215,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false);
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]);
|
||||
expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
||||
expect(cards()[1].textContent).toContain('aún no está publicado');
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
// 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');
|
||||
// Only the paired card is a published indicator the summary draws; the other three are in Histórico.
|
||||
expect(titles()).toEqual(['Porcentaje individual de mastografías']);
|
||||
expect(titles()).toEqual(['Porcentaje de mastografías']);
|
||||
expect(root().textContent).not.toContain('indicador publicado');
|
||||
});
|
||||
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
||||
|
||||
@@ -14,7 +14,7 @@ import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes } from './indicadores-conteos-pareados';
|
||||
import { barrasConteos, ConteosIncompatibles, donaConteos, donaPacientes, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
|
||||
|
||||
const PAR = parConteos('cama', 'cama_birads_456_mastografia')!;
|
||||
const CATEGORIAS = {
|
||||
@@ -89,6 +89,16 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
|
||||
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]);
|
||||
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
|
||||
});
|
||||
it('la dona de pacientes usa la categoría más grave de cada paciente, con ceros y sin razón', () => {
|
||||
const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P));
|
||||
expect(totalPacientes(m)).toBe(31);
|
||||
const dona = donaPacientes(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } };
|
||||
expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
|
||||
expect(dona.data[0].values).toEqual([13, 0, 0, 0, 18, 0]);
|
||||
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>31</b>', 'pacientes']);
|
||||
expect(JSON.stringify(dona)).not.toMatch(/≈|por paciente|razón/i);
|
||||
expect(donaPacientes(modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })), PAR, 'claro').data).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
|
||||
@@ -192,17 +202,17 @@ 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.
|
||||
expect(titulos).toEqual(['Porcentaje individual de mastografías']);
|
||||
expect(titulos).toEqual(['Porcentaje de mastografías']);
|
||||
expect(root().textContent).not.toContain('indicador publicado');
|
||||
});
|
||||
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
|
||||
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 y mastografías, 2025-S2']);
|
||||
expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes por categoría, 2025-S2']);
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 2]);
|
||||
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']]);
|
||||
expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente');
|
||||
@@ -214,7 +224,8 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
|
||||
expect(root().textContent).toContain('Pacientes pendientes');
|
||||
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
|
||||
expect(root().textContent).toContain('Dona de pacientes no disponible');
|
||||
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
|
||||
});
|
||||
it('una respuesta incompatible no dibuja cifras y lo dice', () => {
|
||||
// Fails if a pair of responses that are not the two indicators is drawn as if it were.
|
||||
@@ -237,3 +248,45 @@ 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' });
|
||||
fixture.detectChanges();
|
||||
conteos.showHelp();
|
||||
fixture.detectChanges();
|
||||
expect(meta()).toHaveLength(0);
|
||||
fixture.destroy();
|
||||
http.match(() => true);
|
||||
http.verify();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -50,7 +50,7 @@ const COLOR_NEUTRO = '#8A9199';
|
||||
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
|
||||
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||
export interface ModeloConteos {
|
||||
periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
|
||||
periodo: string; examenes: CategoriaConteo[]; pacientes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
|
||||
// False when the patients' version is not one whose definition was checked: their cells stay unknown.
|
||||
pacientesVerificados: boolean; notas: string[];
|
||||
}
|
||||
@@ -97,6 +97,8 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
return periodos.map(periodo => ({
|
||||
periodo,
|
||||
examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })),
|
||||
// The same published cells the family rows add up, kept by category for the patients' donut.
|
||||
pacientes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catPacientes, id), color: color(id, index), n: verificados ? de(filasP, catPacientes, periodo, id) : null })),
|
||||
// Only the exams the response reports apart; an indicator that lists no such category has none.
|
||||
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||
filas: par.grupos.map(g => ({
|
||||
@@ -109,14 +111,15 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
|
||||
}));
|
||||
}
|
||||
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
|
||||
export const totalPacientes = (m: ModeloConteos) => m.pacientesVerificados ? sumar(m.pacientes.map(c => c.n)) : null;
|
||||
|
||||
const ALTO_DONA = 400, MARGEN_DONA = 8;
|
||||
const DIAMETRO_MAXIMO_DONA = 270;
|
||||
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
||||
const total = totalExamenes(m);
|
||||
function donaDe(categorias: CategoriaConteo[], unidad: string, tema: Tema, ancho: number): PlotlyFigure {
|
||||
const total = sumar(categorias.map(c => c.n));
|
||||
if (!total) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
|
||||
const p = c2Theme(tema), n = categorias.map(c => c.n!);
|
||||
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
|
||||
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
|
||||
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
|
||||
@@ -125,7 +128,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
|
||||
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
|
||||
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
|
||||
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
|
||||
const etiquetas = m.examenes.map(c => escapar(c.etiqueta));
|
||||
const etiquetas = categorias.map(c => escapar(c.etiqueta));
|
||||
const porcentajes = n.map(v => percentNumber(100 * v / total));
|
||||
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
|
||||
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
|
||||
@@ -154,7 +157,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
|
||||
});
|
||||
});
|
||||
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
|
||||
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
|
||||
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
|
||||
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
|
||||
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
|
||||
hovertemplate: '%{value}<extra></extra>' }],
|
||||
@@ -163,11 +166,20 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
|
||||
shapes: llamadas.map(({ shape }) => shape),
|
||||
annotations: [
|
||||
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
|
||||
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: par.unidades.examenes },
|
||||
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: unidad },
|
||||
...llamadas.map(({ annotation }) => annotation),
|
||||
] }, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
||||
return donaDe(m.examenes, par.unidades.examenes, tema, ancho);
|
||||
}
|
||||
|
||||
/** Patients in the most severe BI-RADS category of the period. Same slices as the exams' donut; no ratio. */
|
||||
export function donaPacientes(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
||||
return donaDe(m.pacientes, par.unidades.pacientes, tema, ancho);
|
||||
}
|
||||
|
||||
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
|
||||
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
||||
|
||||
@@ -99,7 +99,8 @@ describe('Histórico de CaMa', () => {
|
||||
expect(plegable.querySelector('summary')!.textContent!.trim()).toBe('Periodos sin dato (5)');
|
||||
expect(plegable.querySelector('p')!.textContent).toMatch(/Sin dato: .*mar 2025.*abr 2025.*may 2025.*jun 2025.*jul 2025./);
|
||||
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
|
||||
expect(panel.querySelector('.nota')!.textContent!.length).toBeGreaterThan(0);
|
||||
expect(panel.querySelector('.nota')).toBeNull();
|
||||
expect(panel.textContent).not.toContain('Cada barra es el total de pacientes');
|
||||
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||
fixture.detectChanges();
|
||||
expect(plegable.open).toBe(true);
|
||||
|
||||
@@ -87,6 +87,12 @@ describe('Histórico: C2 (conteos por categoría)', () => {
|
||||
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
|
||||
expect(r.comoLeer).toContain('mastografías');
|
||||
});
|
||||
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => {
|
||||
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
|
||||
expect(pacientes.comoLeer).toBe('');
|
||||
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
|
||||
expect(figura(d(completo)).comoLeer).toContain('Cada barra es el total de pacientes');
|
||||
});
|
||||
it('un periodo con una celda suprimida se sombrea completo y sus barras no se dibujan como cero', () => {
|
||||
// Fails if the known cells of a partly suppressed period pass for its total.
|
||||
const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f);
|
||||
|
||||
@@ -161,7 +161,8 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
comoLeer: data.id === 'cama_birads_456_paciente' ? ''
|
||||
: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -107,7 +107,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
<p class="nota">{{ panel.figura.comoLeer }}</p>
|
||||
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
|
||||
@@ -24,7 +24,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)',
|
||||
};
|
||||
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
|
||||
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
|
||||
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
||||
};
|
||||
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
|
||||
Reference in New Issue
Block a user