diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 39c133b..bb25c5b 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -21,11 +21,13 @@ import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; import { parTiempos } from './indicadores-tiempos-pareados'; +import { IndicadorConteosPareados } from './indicador-conteos-pareados'; +import { parConteos } from './indicadores-conteos-pareados'; @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados], template: `
@@ -54,6 +56,10 @@ import { parTiempos } from './indicadores-tiempos-pareados';
+ } @else if (conteos; as par) { +
+ +
} @else if (selectedFigure) { @if (!sobrio && (!pair.length || otherFigures.length)) { @@ -140,6 +146,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } // Connected time pairs replace the diagnosis card with one coordinated box plot. get tiempos() { return parTiempos(this.dominio, this.indicador.id); } + // Exams and patients of the same finding, drawn together on the exams' card. + get conteos() { return parConteos(this.dominio, this.indicador.id); } get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.html b/src/app/features/indicadores/indicador-conteos-pareados.html new file mode 100644 index 0000000..22e0deb --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.html @@ -0,0 +1,57 @@ +
+ + @if (helpOpen) { +
+
+

Dona por categoría

+ @if (donutGuide; as guide) { + @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} + } @else if (!metadata) {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

} + @else {

El servicio no publica instrucciones de lectura para esta figura.

} +
+
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}

+

Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.

+
+
+ } + @switch (status()) { + @case ('deferred') {

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

} + @case ('loading') {

Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…

} + @case ('empty') {

No hay periodos publicados por los dos conteos.

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' && model; as m) { + @if (pages.length > 1) { + + } +
+

{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}

+ @if (total) { + + } @else {

{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}

} + @if (m.sinDato) {

Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.

} +
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}

+ + @if (!m.pacientesVerificados) {

Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.

} +
+
+

Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.

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

{{ note }}

} +
Valores publicados +
+ + + @for (f of m.filas; track f.id) { } +
{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}
Familia de BI-RADS{{ par.unidades.pacientes | titlecase }}{{ par.unidades.examenes | titlecase }}
{{ f.etiqueta }}{{ textoPacientes(f.pacientes) }}{{ texto(f.examenes) }}
+
+
+ } +
diff --git a/src/app/features/indicadores/indicador-conteos-pareados.scss b/src/app/features/indicadores/indicador-conteos-pareados.scss new file mode 100644 index 0000000..632a2a3 --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.scss @@ -0,0 +1,22 @@ +:host { display: block; min-width: 0; } +.conteos { min-width: 0; padding-top: var(--issste-space-3); } +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; } +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); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; } +.periods button:disabled { opacity: .5; cursor: default; } +// The two figures share the card in equal halves; one above the other on a narrow card. +.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } +@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +app-plotly-chart { --plot-height: 400px; } +summary { cursor: pointer; padding-block: .75rem; } +summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.table-scroll { overflow: auto; } +table { border-collapse: collapse; width: 100%; margin-block: 1rem; } +th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } +caption { text-align: start; font-weight: 600; } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.ts b/src/app/features/indicadores/indicador-conteos-pareados.ts new file mode 100644 index 0000000..3ae0ebf --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.ts @@ -0,0 +1,115 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, 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 { 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'; + +@Component({ + selector: 'app-indicador-conteos-pareados', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe], + templateUrl: './indicador-conteos-pareados.html', + styleUrl: './indicador-conteos-pareados.scss', +}) +export class IndicadorConteosPareados implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) par!: ParConteos; + // The card's indicator (the exams); its partner (the patients) has no card and is requested by id. + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + periodIndex = 0; + pages: ModeloConteos[] = []; + donutFigure?: PlotlyFigure; + barsFigure?: PlotlyFigure; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + + get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; } + get total() { return this.model ? totalExamenes(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); } + helpOpen = 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. + 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() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + 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(); + 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 load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.clear(); + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario 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 = combineLatest([ + this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version), + this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods), + ]).pipe(timeout({ first: 40000 })).subscribe({ + next: ([examenes, pacientes]) => { + if (key !== this.key) return; + try { + this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo); + // The most recent period first; navigation goes back. + this.periodIndex = Math.max(0, this.pages.length - 1); + this.draw(); this.status.set(this.model ? 'ready' : 'empty'); + } 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 ConteosIncompatibles ? error.message : httpMessage(error); + this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.draw(); + } + private draw() { + const m = this.model; + if (!m) return; + this.donutFigure = donaConteos(m, this.par, this.tema); + this.barsFigure = barrasConteos(m, this.par, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts index 76deebd..d14f322 100644 --- a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -51,6 +51,9 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { open('cama', CAMA); expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); 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'); + expect(titles()).toHaveLength(4); expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe(titles().length + ' indicadores publicados'); }); it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => { diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts new file mode 100644 index 0000000..410ca73 --- /dev/null +++ b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts @@ -0,0 +1,220 @@ +// Covers CaMa's paired card (mammograms by BI-RADS category and patients by their most severe one): what the model +// is allowed to add up, what it refuses to compute, and the card drawing it. Fixtures are shaped like the +// /cama/indicadores//datos responses of cama_birads_456_mastografia and cama_birads_456_paciente (version 0.2.0) +// served by WebApi for 2025-S2; the counts are synthetic. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +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'; + +const PAR = parConteos('cama', 'cama_birads_456_mastografia')!; +const CATEGORIAS = { + B4A: { etiqueta: 'BI-RADS 4A', color: '#E0A060', grupo: null, gravedad: 6 }, B4B: { etiqueta: 'BI-RADS 4B', color: '#CF7D3C', grupo: null, gravedad: 7 }, + B4C: { etiqueta: 'BI-RADS 4C', color: '#C26A2B', grupo: null, gravedad: 8 }, B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null, gravedad: 9 }, + B6: { etiqueta: 'BI-RADS 6', color: '#7A2E0E', grupo: null, gravedad: 10 }, SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: null, gravedad: null }, + B4: { etiqueta: 'B4', color: null, grupo: null, gravedad: 5 }, +}; +type Conteos = Partial>; +function respuesta(id: string, unidad: string, conteos: Conteos, extra: Partial & Record = {}, suprimidas: string[] = []): IndicadorDatos { + return { + id, titulo: id, version: '0.2.0', contrato: 'C2', unidad, tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, grupos: { TOTAL: 'Total' }, + categorias: CATEGORIAS, notas: [unidad === 'paciente' ? 'Pacientes cuyo BI-RADS más grave entre sus mastografías del semestre es 4, 5 o 6.' : 'Mastografías tomadas en el semestre con BI-RADS 4, 5 o 6, cada una con su categoría.'], + filas: Object.keys(CATEGORIAS).map((categoria, orden) => ({ + periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: conteos[categoria as keyof Conteos] ?? 0, orden, suprimido: suprimidas.includes(categoria) ? 1 : 0 })), + ...extra } as unknown as IndicadorDatos; +} +const examenes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_mastografia', 'examen', c, extra, suprimidas); +const pacientes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_paciente', 'paciente', c, extra, suprimidas); +// The 2025-S2 counts of the laboratory instance. +const LAB_E: Conteos = { B5: 18, B4: 15 }, LAB_P: Conteos = { B5: 18, B4: 13 }; +const modelo = (e: IndicadorDatos, p: IndicadorDatos) => modelosConteos(PAR, e, p, 'semestre')[0]; + +describe('Conteos pareados de CaMa: lo que se puede sumar', () => { + it('con los datos del laboratorio: BI-RADS 4 suma sus subcategorías en ambas unidades', () => { + // Fails if the family rows stop adding the categories of each indicator (B4 without subcategory included). + const m = modelo(examenes(LAB_E), pacientes(LAB_P)); + expect(m.filas.map(f => [f.etiqueta, f.pacientes, f.examenes])).toEqual([['BI-RADS 4', 13, 15], ['BI-RADS 5', 18, 18], ['BI-RADS 6', 0, 0]]); + expect(totalExamenes(m)).toBe(33); + expect(m.pacientesVerificados).toBe(true); + }); + it('las subcategorías se suman dentro de cada indicador y los pacientes no se derivan de las mastografías', () => { + // Fails if patients are taken from the exams' counts: here 10 exams belong to 7 patients. + const m = modelo(examenes({ B4: 1, B4A: 2, B4B: 3, B4C: 4, B5: 5 }), pacientes({ B4: 1, B4A: 1, B4B: 2, B4C: 3, B5: 5 })); + expect(m.filas[0]).toMatchObject({ pacientes: 7, examenes: 10 }); + expect(m.filas[1]).toMatchObject({ pacientes: 5, examenes: 5 }); + }); + it('una celda suprimida o sin fila deja desconocida la familia que la contiene, no en cero', () => { + // Fails if an unknown cell is added as zero. + const suprimida = modelo(examenes(LAB_E), pacientes({ B4: 13, B4B: 2, B5: 18 }, {}, ['B4B'])); + expect(suprimida.filas.map(f => f.pacientes)).toEqual([null, 18, 0]); + const sinFila = pacientes(LAB_P); sinFila.filas = sinFila.filas.filter(f => f['categoria'] !== 'B4C'); + expect(modelo(examenes(LAB_E), sinFila).filas.map(f => f.pacientes)).toEqual([null, 18, 0]); + const examenSuprimido = modelo(examenes(LAB_E, {}, ['B6']), pacientes(LAB_P)); + expect(examenSuprimido.filas.map(f => f.examenes)).toEqual([15, 18, null]); + expect(totalExamenes(examenSuprimido)).toBeNull(); + expect(donaConteos(examenSuprimido, PAR, 'claro').data).toEqual([]); + }); + it('una versión del indicador de pacientes que no se verificó no se suma', () => { + // Fails if another version of the patients' indicator is added up without its definition being checked again. + const m = modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })); + expect(m.pacientesVerificados).toBe(false); + expect(m.filas.map(f => f.pacientes)).toEqual([null, null, null]); + expect(m.filas.map(f => f.examenes)).toEqual([15, 18, 0]); + const texto = JSON.stringify(barrasConteos(m, PAR, 'claro').data[0]); + expect(texto).toContain('Pendiente'); expect(texto).not.toContain('Sin dato'); + }); + it('la mastografía sin categoría solo cuenta si el indicador la publica', () => { + expect(modelo(examenes({ ...LAB_E, SIN_DATO: 3 }), pacientes(LAB_P)).sinDato).toBe(3); + const sin = examenes(LAB_E); delete (sin as unknown as Record>)['categorias']['SIN_DATO']; + expect(modelo(sin, pacientes(LAB_P)).sinDato).toBe(0); + }); + it('solo hay modelo para los periodos que publican los dos conteos, en orden cronológico', () => { + const e = examenes(LAB_E), p = pacientes(LAB_P); + e.periodos = ['2025-S2', '2025-S1', '2024-S2']; p.periodos = ['2025-S1', '2025-S2']; + expect(modelosConteos(PAR, e, p, 'semestre').map(m => m.periodo)).toEqual(['2025-S1', '2025-S2']); + }); + it('la dona muestra las categorías de las mastografías con la etiqueta publicada y un nombre claro para el 4 sin subcategoría', () => { + const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P)); + const dona = donaConteos(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([15, 2, 0, 0, 18, 0]); + expect(dona.layout.annotations[0].text).toBe('35
mastografías'); + }); +}); + +describe('Conteos pareados de CaMa: lo que no se calcula', () => { + it('no hay razón de mastografías por paciente en la figura ni en el modelo', () => { + // Fails if a "≈ x por paciente" annotation comes back: exams of a category include those of patients whose + // most severe category is another one, so the quotient mixes populations. + const m = modelo(examenes(LAB_E), pacientes(LAB_P)); + const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record }; + expect(barras.layout['annotations']).toBeUndefined(); + expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i); + expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']); + }); + it.each([ + ['unidades cambiadas', () => [examenes(LAB_E, { unidad: 'paciente' }), pacientes(LAB_P)]], + ['indicador que no es el esperado', () => [examenes(LAB_E, { id: 'otro' }), pacientes(LAB_P)]], + ['contrato que no es C2', () => [examenes(LAB_E, { contrato: 'C1' }), pacientes(LAB_P)]], + ['categorías de pacientes de otro catálogo (BIRADS_4, 5 y 6)', () => [examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } })]], + ])('respuesta incompatible: %s', (_nombre, datos) => { + // Fails if a response that is not the pair of indicators is drawn as if it were. + const [e, p] = datos(); + expect(() => modelosConteos(PAR, e, p, 'semestre')).toThrow(ConteosIncompatibles); + }); + it('el par solo existe en CaMa y su socio no tiene tarjeta propia mientras la tarjeta de mastografías esté publicada', () => { + expect(PARES_CONTEOS.map(p => p.dominio)).toEqual(['cama']); + expect(parConteos('cacu', 'cama_birads_456_mastografia')).toBeUndefined(); + expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true); + // Without the exams' indicator in the catalog, the patients' one keeps its own card. + expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false); + expect(esSocioConteos('cacu', 'cama_birads_456_paciente', ['cama_birads_456_mastografia'])).toBe(false); + }); +}); + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: { data: unknown[] }; label?: string; } + +describe('Tarjeta pareada de CaMa en la página', () => { + let fixture: ReturnType>, http: HttpTestingController; + const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); + const CATALOGO = [ + item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']), + ]; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama'); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush(CATALOGO); fixture.detectChanges(); + // Only the card's own requests matter here. The period inventory is answered and the KPI requests are + // closed, because unanswered requests would hold the shared request queue. + const responder = () => { + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + if (r.request.url.endsWith('/periodos')) r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: '2025-S2', tipo: 'semestre' }] }); + else r.flush(null, { status: 404, statusText: 'Missing' }); + } + fixture.detectChanges(); + } + }; + responder(); + fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + responder(); + }); + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + const root = () => fixture.nativeElement as HTMLElement; + const tarjeta = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => d.componentInstance as IndicadorCatalogCard) + .find(c => c.indicador.id === 'cama_birads_456_mastografia')!; + const pedidos = () => http.match(r => /cama_birads_456_(mastografia|paciente)\/datos$/.test(r.url)); + function abrir(e: IndicadorDatos = examenes(LAB_E), p: IndicadorDatos = pacientes(LAB_P)) { + tarjeta().setVisible(true); fixture.detectChanges(); + const r = pedidos(); + expect(r.map(q => q.request.url).sort()).toEqual(['/cama/indicadores/cama_birads_456_mastografia/datos', '/cama/indicadores/cama_birads_456_paciente/datos']); + expect(r.every(q => q.request.params.get('periodos') === '2025-S2')).toBe(true); + for (const q of r) q.flush(q.request.url.includes('mastografia') ? e : p); + fixture.detectChanges(); + } + + it('el resumen dibuja una sola tarjeta para mastografías y pacientes, y no dibuja el socio ni biopsias', () => { + // 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()); + expect(titulos).toEqual(['Porcentaje individual de mastografías', 'Tasa de confirmación histopatológica']); + expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('2 indicadores publicados'); + }); + 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']); + 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]); + 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')).toContain('no se calcula la razón de mastografías por paciente'); + expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato'); + }); + it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => { + abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })); + const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); + expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '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); + }); + 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. + abrir(examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } })); + expect(root().querySelector('app-indicador-conteos-pareados [role=alert]')?.textContent).toContain('Respuesta incompatible'); + expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(root().querySelector('.published-values')).toBeNull(); + }); + it('un error de red no filtra su cuerpo, no dibuja cifras y el reintento vuelve a pedir los dos conteos', () => { + tarjeta().setVisible(true); fixture.detectChanges(); + for (const q of pedidos()) { + if (q.request.url.includes('paciente')) q.flush('private', { status: 500, statusText: 'Error' }); + else q.flush(examenes(LAB_E)); + } + fixture.detectChanges(); + const alerta = root().querySelector('app-indicador-conteos-pareados [role=alert]'); + expect(alerta).not.toBeNull(); expect(alerta!.textContent).not.toContain('private'); + expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + (alerta!.querySelector('button') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(pedidos().length).toBeGreaterThan(0); + }); +}); diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.ts b/src/app/features/indicadores/indicadores-conteos-pareados.ts new file mode 100644 index 0000000..c531203 --- /dev/null +++ b/src/app/features/indicadores/indicadores-conteos-pareados.ts @@ -0,0 +1,136 @@ +import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Theme } from './indicadores-c2-palette'; +import { percentNumber } from './indicadores-format'; + +// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one. +// +// What the kit publishes (indicadores_kit, cama/familias/birads, version 0.2.0 of both): +// - exams: each exam counts once, in its own category; +// - patients: each patient counts once per period, in the category of the most severe exam of that period, +// so the patient categories are mutually exclusive and their sum is a number of different patients. +// Adding categories inside one indicator is therefore a count of the same unit. What is not allowed is mixing +// the two: the exams of a category include those of patients whose most severe exam is another category, so +// no ratio of exams to patients is computed, and patients are never derived from exams. +export interface GrupoConteo { id: string; etiqueta: string; categorias: readonly string[]; } +export interface ParConteos { + dominio: Dominio; + examenes: string; + pacientes: string; + // Exam categories in severity order, as the donut draws them. + categoriasExamen: readonly string[]; + // Rows of the bars: a BI-RADS family and the categories of both indicators that add up to it. + grupos: readonly GrupoConteo[]; + // Versions of the patient indicator whose definition was checked as above; another version is not added up. + versionesPacientes: readonly string[]; + unidades: { examenes: string; pacientes: string }; +} +export const PARES_CONTEOS: readonly ParConteos[] = [ + { dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente', + categoriasExamen: ['B4', 'B4A', 'B4B', 'B4C', 'B5', 'B6'], + grupos: [ + { id: 'BIRADS_4', etiqueta: 'BI-RADS 4', categorias: ['B4', 'B4A', 'B4B', 'B4C'] }, + { id: 'BIRADS_5', etiqueta: 'BI-RADS 5', categorias: ['B5'] }, + { id: 'BIRADS_6', etiqueta: 'BI-RADS 6', categorias: ['B6'] }, + ], + versionesPacientes: ['0.2.0'], + unidades: { examenes: 'mastografías', pacientes: 'pacientes' } }, +]; +// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own. +export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id); +export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) => + PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes)); + +// The kit publishes a 4 without subcategory as «B4», with no colour. +const ETIQUETA_RESPALDO: Readonly> = { B4: 'BI-RADS 4 (sin subcategoría)' }; +const COLOR_RESPALDO: Readonly> = { B4: '#E9C08C' }; +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[]; + // False when the patients' version is not one whose definition was checked: their cells stay unknown. + pacientesVerificados: boolean; notas: string[]; +} +export class ConteosIncompatibles extends Error {} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const fail = (message: string): never => { throw new ConteosIncompatibles(message); }; +const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const miles = (v: number) => v.toLocaleString('es-MX'); +// A suppressed, unpublished or invalid cell is unknown, never zero. +function cuenta(filas: Record[], periodo: string, categoria: string): number | null { + const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria && f['grupo'] === 'TOTAL' && (f['estrato'] ?? null) === null); + return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null; +} +const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce((s, v) => s + v!, 0); + +/** One model per period both responses publish, in chronological order. */ +export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] { + for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) { + if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) { + fail('Los datos no corresponden a los conteos por mastografía y por paciente.'); + } + } + if (examenes['unidad'] !== 'examen' || pacientes['unidad'] !== 'paciente') fail('Las unidades publicadas no son mastografías y pacientes.'); + const catExamenes = examenes['categorias'] as Record, catPacientes = pacientes['categorias'] as Record; + const etiqueta = (cat: Record, id: string) => { + const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : ''; + return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id; + }; + const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO; + const todas = par.grupos.flatMap(g => g.categorias); + if (par.categoriasExamen.some(id => !Object.hasOwn(catExamenes, id)) || todas.some(id => !Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id))) { + fail('Las categorías de mastografías y pacientes no coinciden.'); + } + const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? '')); + const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort(); + const filasE = examenes.filas as Record[], filasP = pacientes.filas as Record[]; + return periodos.map(periodo => ({ + periodo, + examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })), + // 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 => ({ + id: g.id, etiqueta: g.etiqueta, + pacientes: verificados ? sumar(g.categorias.map(id => cuenta(filasP, periodo, id))) : null, + examenes: sumar(g.categorias.map(id => cuenta(filasE, periodo, id))), + })), + pacientesVerificados: verificados, + notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])], + })); +} +export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n)); + +/** Exams by category around their total; nothing is drawn when a cell is unknown. */ +export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure { + const total = totalExamenes(m); + if (!total) return { data: [], layout: {} }; + const p = c2Theme(tema), n = m.examenes.map(c => c.n!); + return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)), + marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside', + text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '
' + percentNumber(100 * v / total) + ' %'), + customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]), + hovertemplate: `%{label}
%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %` }], + layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text }, + annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text }, + text: `${miles(total)}
${par.unidades.examenes}` }] }, config: { displayModeBar: false } }; +} + +/** 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)); + const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más grave)`, examenes: par.unidades.examenes }; + const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') => + v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato'; + const traza = (clave: 'pacientes' | 'examenes', color: string) => ({ + type: 'bar', orientation: 'h', name: nombres[clave], y, x: m.filas.map(f => f[clave]), marker: { color }, + text: m.filas.map(f => textoDe(f[clave], clave)), textposition: 'outside', cliponaxis: false, + hovertemplate: `%{y}: %{x} ${nombres[clave]}` }); + const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0)); + return { data: [traza('pacientes', '#7A8794'), traza('examenes', '#C26A2B')], + layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { t: 16, l: 96, r: 70, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false }, + yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true }, + xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true } }, config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index d209a54..42b462a 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,6 +17,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { esSocioConteos } from './indicadores-conteos-pareados'; import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; @@ -289,6 +290,11 @@ export class IndicadoresPage { } return undefined; } + // CaMa's summary: without the indicators it does not draw, and with the patients' counts on the exams' card. + private cardsDeCama(catalog: Indicador[]) { + const ids = catalog.map(item => item.id); + return catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids)); + } // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. get shownIndicators() { return this.dominio === 'cama' ? this.searchResults().items.length : this.catalog().length; } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } @@ -315,7 +321,7 @@ export class IndicadoresPage { // Stable presentation priority; search matches and pins still take precedence. const items = this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] - : this.dominio === 'cama' ? catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id)) : catalog; + : this.dominio === 'cama' ? this.cardsDeCama(catalog) : catalog; if (this.dominio === 'cama') return { items, active: false, count: 0 }; const query = this.normalizeSearch(this.searchQuery()); const prioritize = (group: Indicador[]) => [