diff --git a/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json new file mode 100644 index 0000000..72d19a0 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json @@ -0,0 +1,56 @@ +[ + { + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "sentido": "decrease", + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c3r_caja" + ], + "estratos": [], + "filtros": [] + }, + { + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS (demostración sintética)", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "sentido": null, + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c2_barras", + "fig_c2_donas" + ], + "estratos": [ + "birads" + ], + "filtros": [] + }, + { + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica (demostración sintética)", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "sentido": null, + "tipos_periodo": [ + "semestre", + "mes" + ], + "figuras": [ + "fig_c1_puntos" + ], + "estratos": [], + "filtros": [] + } +] \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json new file mode 100644 index 0000000..ef5a9eb --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json @@ -0,0 +1,477 @@ +{ + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS (demostración sintética)", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": "birads", + "valores_estrato": [ + "BIRADS_4", + "BIRADS_4A", + "BIRADS_4B", + "BIRADS_4C", + "BIRADS_5", + "BIRADS_6" + ], + "etiquetas_estrato": { + "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" + }, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "BENIGNO": { + "etiqueta": "Benigno", + "color": "#9DBFE3", + "grupo": "NO_MALIGNO", + "gravedad": 1 + }, + "RIESGO_B3": { + "etiqueta": "Lesión de riesgo (B3)", + "color": "#2F6DB3", + "grupo": "NO_MALIGNO", + "gravedad": 2 + }, + "IN_SITU": { + "etiqueta": "Carcinoma in situ", + "color": "#D9822B", + "grupo": "MALIGNO", + "gravedad": 3 + }, + "INVASOR": { + "etiqueta": "Carcinoma invasor", + "color": "#B5482E", + "grupo": "MALIGNO", + "gravedad": 4 + }, + "SIN_BIOPSIA": { + "etiqueta": "Sin biopsia reportada", + "color": "#C9CDD2", + "grupo": null, + "gravedad": null + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_MALIGNO": "No maligno", + "MALIGNO": "Maligno", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 141, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2025-12-31", + "generado_en": "2026-11-12T16:33:37.621606+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe", + "parametros": { + "sql": { + "_catalogo": [ + "BENIGNO", + "RIESGO_B3", + "IN_SITU", + "INVASOR" + ], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2025-12-31", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "BENIGNO", + "n": 2, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "RIESGO_B3", + "n": 0, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "INVASOR", + "n": 2, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "BENIGNO", + "n": 1, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "RIESGO_B3", + "n": 1, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "IN_SITU", + "n": 1, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "INVASOR", + "n": 1, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "SIN_BIOPSIA", + "n": 1, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "categoria": "SIN_DATO", + "n": 1, + "orden": 5, + "suprimido": 0 + } + ], + "totales_estrato": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4A", + "n": 7, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4B", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_4C", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_5", + "n": 6, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": "BIRADS_6", + "n": 6, + "suprimido": 0 + } + ] +} diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json new file mode 100644 index 0000000..8b409f0 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json @@ -0,0 +1,150 @@ +{ + "id": "cama_histopatologia_birads", + "titulo": "Histopatología por BI-RADS (demostración sintética)", + "version": "0.1.0", + "contrato": "C2", + "unidad": "paciente", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Total" + }, + "categorias": { + "BENIGNO": { + "etiqueta": "Benigno", + "color": "#9DBFE3", + "grupo": "NO_MALIGNO", + "gravedad": 1 + }, + "RIESGO_B3": { + "etiqueta": "Lesión de riesgo (B3)", + "color": "#2F6DB3", + "grupo": "NO_MALIGNO", + "gravedad": 2 + }, + "IN_SITU": { + "etiqueta": "Carcinoma in situ", + "color": "#D9822B", + "grupo": "MALIGNO", + "gravedad": 3 + }, + "INVASOR": { + "etiqueta": "Carcinoma invasor", + "color": "#B5482E", + "grupo": "MALIGNO", + "gravedad": 4 + }, + "SIN_BIOPSIA": { + "etiqueta": "Sin biopsia reportada", + "color": "#C9CDD2", + "grupo": null, + "gravedad": null + }, + "SIN_DATO": { + "etiqueta": "Sin dato", + "color": "#C9CDD2", + "grupo": "SIN_DATO", + "gravedad": null + } + }, + "grupos_de_categoria": { + "NO_MALIGNO": "No maligno", + "MALIGNO": "Maligno", + "SIN_DATO": "Sin dato" + }, + "notas": [ + "Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 141, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2025-12-31", + "generado_en": "2026-11-12T16:33:37.621606+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "75706ce35dbdd4440f22f71220400666e6a14eeb2922353960c1d66878bbf6fe", + "parametros": { + "sql": { + "_catalogo": [ + "BENIGNO", + "RIESGO_B3", + "IN_SITU", + "INVASOR" + ], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2025-12-31", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "BENIGNO", + "n": 7, + "orden": 0, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "RIESGO_B3", + "n": 5, + "orden": 1, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "IN_SITU", + "n": 6, + "orden": 2, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "INVASOR", + "n": 7, + "orden": 3, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_BIOPSIA", + "n": 6, + "orden": 4, + "suprimido": 0 + }, + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "categoria": "SIN_DATO", + "n": 6, + "orden": 5, + "suprimido": 0 + } + ], + "totales_estrato": [] +} diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 61e276f..cf2337c 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -20,14 +20,16 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario'; import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; +import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama'; +import { ID_HISTOPATOLOGIA } from './indicadores-histopatologia-cama'; 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 || !!conteos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados], + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados], template: `
@@ -52,6 +54,10 @@ import { parConteos } from './indicadores-conteos-pareados';
+ } @else if (isHistopatologia) { +
+ +
} @else if (tiempos; as par) {
@@ -144,6 +150,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { 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; } + // CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu. + get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; } // 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. diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.html b/src/app/features/indicadores/indicador-histopatologia-cama.html new file mode 100644 index 0000000..0b7b077 --- /dev/null +++ b/src/app/features/indicadores/indicador-histopatologia-cama.html @@ -0,0 +1,78 @@ +
+

Filtro general aplicado: {{ appliedSummary }}

+ + @if (helpOpen) { +
+

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.

+ @if (metadata) { + @for (guide of readingGuide; track guide.figura) { +
+

{{ guide.nombre }}

+ @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} +
+ } + } +
+ } + @switch (status()) { + @case ('deferred') {

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

} + @case ('loading') {

Cargando el mismo periodo para tasas y dona…

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' || status() === 'empty') { + @if (periods.length > 1) { + + } + @if (model; as m) { +

{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}

+ @if (status() === 'empty') {

No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.

} + @else { +
+ +
+ @for (g of m.grupos; track g.id; let i = $index) { + + } +
+
+ @for (c of m.categorias; track c.id; let i = $index) { + + } +
+
+
+

Por categoría BI-RADS, {{ m.periodo }}

+ @if (ratesFigure) { + + } +
    + @for (t of rates; track t.fila.id) { @if (t.k === null) {
  • {{ t.fila.etiqueta }}: {{ estadoTasa(t) }}
  • } } +
+
+

Resultado de la biopsia, {{ m.periodo }}

+ @if (m.conResultado !== null && m.conResultado > 0 && donutFigure) { + + } @else {

{{ 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.' }}

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

{{ note }}

} +
Valores publicados +
+ + @for (c of m.categorias; track c.id) { }@for (a of m.aparte; track a.id) { } + @for (fila of m.filas; track fila.id) { + @for (c of m.categorias; track c.id) { }@for (a of m.aparte; track a.id) { } + } +
Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}
Categoría BI-RADS{{ c.etiqueta }}Con resultado{{ a.etiqueta }}Total de pacientes
{{ fila.etiqueta }}{{ cellText(fila.celdas[c.id]) }}{{ denText(fila.den, fila.estado) }}{{ cellText(fila.aparte[a.id]) }}{{ cellText(fila.total) }}
+
+
+ } + } +
diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.ts b/src/app/features/indicadores/indicador-histopatologia-cama.ts new file mode 100644 index 0000000..c78083d --- /dev/null +++ b/src/app/features/indicadores/indicador-histopatologia-cama.ts @@ -0,0 +1,145 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +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`. + */ +@Component({ + selector: 'app-indicador-histopatologia-cama', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-histopatologia-cama.html', + styleUrl: './indicador-confirmacion-citologia.scss', +}) +export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @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 = ''; + selection?: SeleccionHistopatologia; + periods: string[] = []; + periodIndex = 0; + model?: ModeloHistopatologia; + donutFigure?: PlotlyFigure; + ratesFigure?: PlotlyFigure; + helpOpen = false; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + private pages: ModeloHistopatologia[] = []; + + get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } + get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } + get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } + get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } + get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } + readonly estadoTasa = estadoTasa; + cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } + 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() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + 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]); + 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.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(); + } + private activatePeriod() { + this.model = this.pages[this.periodIndex]; + this.selection = this.model ? seleccionBase(this.model) : undefined; + this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty'); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.activatePeriod(); + } + select(trace: string, index = 0) { + if (!this.model || !this.selection || this.status() !== 'ready') return; + this.selection = clicHistopatologia(this.model, this.selection, trace, index); this.draw(); + } + plotClicked(event: unknown) { + const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; + if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); + } + private draw() { + if (!this.model || !this.selection) return; + this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema); + this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts new file mode 100644 index 0000000..48a7535 --- /dev/null +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -0,0 +1,338 @@ +// 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 +// 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'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import estratoFixture from './fixtures/cama_histopatologia_birads_estrato.json'; +import generalFixture from './fixtures/cama_histopatologia_birads_general.json'; +import catalogoFixture from './fixtures/cama_catalogo_f4c.json'; +import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { GlobalApplied } from './indicadores-memory'; +import { Indicador, IndicadorDatos } from './indicadores.models'; +import { wilson } from './indicadores-confirmacion-citologia'; +import { clicHistopatologia, donaHistopatologia, estadoTasa, figuraTasas, HistopatologiaIncompatible, lectura, modeloHistopatologia, + periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); showNotes = input(); plotClick = output(); } + +const estrato = () => structuredClone(estratoFixture) as unknown as IndicadorDatos & { filas: Record[]; totales_estrato: Record[]; valores_estrato: string[]; categorias: Record }; +const fila = (d: { filas: Record[] }, e: string, c: string) => d.filas.find(f => f['estrato'] === e && f['categoria'] === c)!; +const PERIODO = '2025-S1'; +const base = (d = estrato()) => modeloHistopatologia(d, PERIODO); + +describe('Histopatología por BI-RADS: modelo', () => { + it('lee la matriz completa: seis estratos, cuatro categorías con resultado y dos aparte', () => { + const m = base(); + expect(m.filas.map(f => f.id)).toEqual(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']); + expect(m.filas.map(f => f.etiqueta)).toEqual(['BI-RADS 4 sin subtipo', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); + expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']); + expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E']); + expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([ + ['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]); + expect(m.base).toBe('MALIGNO'); + expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]); + expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n, f.total.n])).toEqual([[1, 1, 6], [1, 1, 7], [1, 1, 6], [1, 1, 6], [1, 1, 6], [1, 1, 6]]); + expect(m.notas[0]).toContain('BI-RADS 4 sin subtipo es una fila propia'); + }); + it('el denominador de cada estrato son las cuatro categorías con resultado: Sin biopsia y Sin dato quedan fuera', () => { + const m = base(); + expect(m.filas.map(f => f.den)).toEqual([4, 5, 4, 4, 4, 4]); + expect(m.totales).toEqual({ BENIGNO: 7, RIESGO_B3: 5, IN_SITU: 6, INVASOR: 7 }); + expect(m.conResultado).toBe(25); + }); + it('BI-RADS 4 es una fila independiente: no se reparte entre 4A, 4B y 4C ni se suma a ellos', () => { + // Fails if the 4 without subtype is merged into a subtype: 4A has 5 patients with a result, the 4 has 4. + const m = base(); + expect([m.filas[0].den, m.filas[1].den]).toEqual([4, 5]); + expect(m.filas[0].celdas['BENIGNO'].n).toBe(2); expect(m.filas[1].celdas['BENIGNO'].n).toBe(1); + expect(m.filas.slice(1, 4).reduce((s, f) => s + f.den!, 0)).toBe(13); + }); + it('un cero publicado es un cero válido: cuenta en el denominador y no bloquea la fila', () => { + // BIRADS_4 / RIESGO_B3 is published with n: 0 in the example. + const m = base(); + expect(fila(estrato(), 'BIRADS_4', 'RIESGO_B3')['n']).toBe(0); + expect(m.filas[0].celdas['RIESGO_B3']).toEqual({ n: 0, estado: 'Publicado' }); + expect([m.filas[0].den, m.filas[0].estado]).toEqual([4, 'Publicado']); + }); + it('una celda que la respuesta no trae es «No disponible», no cero: la fila no da tasa y la dona no suma un total parcial', () => { + const d = estrato(); d.filas = d.filas.filter(f => !(f['estrato'] === 'BIRADS_4B' && f['categoria'] === 'INVASOR')); + const m = base(d), sel = seleccionBase(m); + expect(m.filas[2].celdas['INVASOR']).toEqual({ n: null, estado: 'No disponible' }); + expect([m.filas[2].den, m.filas[2].estado]).toEqual([null, 'No disponible']); + expect(tasas(m, sel).map(t => t.k)).toEqual([2, 3, null, 2, 2, 2]); + expect(tasas(m, sel).map(estadoTasa)).toEqual(['', '', 'No disponible', '', '', '']); + expect(m.conResultado).toBeNull(); expect(m.totales['INVASOR']).toBeNull(); + expect(donaHistopatologia(m, sel, 'claro').data).toHaveLength(0); + expect(JSON.stringify(figuraTasas(m, sel, 'claro').layout['annotations'])).not.toContain('0/'); + }); + it('una celda suprimida es «Suprimido»; un total suprimido suprime la fila aunque sus celdas se publiquen', () => { + const d = estrato(); Object.assign(fila(d, 'BIRADS_5', 'IN_SITU'), { n: null, suprimido: 1 }); + const m = base(d); + expect(m.filas[4].celdas['IN_SITU']).toEqual({ n: null, estado: 'Suprimido' }); + expect([m.filas[4].den, m.filas[4].estado]).toEqual([null, 'Suprimido']); + expect(m.conResultado).toBeNull(); + const t = estrato(); Object.assign(t.totales_estrato.find(x => x['estrato'] === 'BIRADS_6')!, { n: null, suprimido: 1 }); + const s = base(t); + expect([s.filas[5].den, s.filas[5].estado, s.filas[5].total]).toEqual([null, 'Suprimido', { n: null, estado: 'Suprimido' }]); + expect(s.filas[0].den).toBe(4); expect(s.conResultado).toBeNull(); + }); + it('un estrato que no se publica no se lee como cero pacientes: sus celdas, tasa y dona no están disponibles', () => { + const d = estrato(); + d.filas = d.filas.filter(f => f['estrato'] !== 'BIRADS_4A'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_4A'); + d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_4A'); + const m = base(d); + expect(m.filas[1].etiqueta).toBe('BI-RADS 4A'); + expect(Object.values(m.filas[1].celdas).every(c => c.n === null && c.estado === 'No disponible')).toBe(true); + expect([m.filas[1].den, m.filas[1].total.estado]).toEqual([null, 'No disponible']); + expect(m.conResultado).toBeNull(); + expect(tasas(m, seleccionBase(m))[1].k).toBeNull(); + }); + it('sin ninguna fila del periodo el modelo está vacío', () => { + const d = estrato(); d.filas = []; d.totales_estrato = []; + expect(base(d).vacio).toBe(true); expect(base().vacio).toBe(false); + }); + it('rechaza lo que no es de esta medida: otro indicador, otro estrato, el C2 general, periodos no pedidos', () => { + expect(() => periodosHistopatologia({ ...estrato(), id: 'cama_eu38a' }, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia({ ...estrato(), estrato: 'grupo_edad' } as IndicadorDatos, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(generalFixture as unknown as IndicadorDatos, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(estrato(), 'semestre', ['2025-S2'])).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(estrato(), 'mes')).toThrow(HistopatologiaIncompatible); + expect(periodosHistopatologia(estrato(), 'semestre', [PERIODO])).toEqual([PERIODO]); + }); + it.each([ + ['un estrato que el contrato no tiene', (d: any) => { fila(d, 'BIRADS_4', 'BENIGNO')['estrato'] = 'BIRADS_7'; }], + ['una categoría desconocida en una fila', (d: any) => { fila(d, 'BIRADS_4', 'BENIGNO')['categoria'] = 'OTRA'; }], + ['una categoría desconocida en el catálogo', (d: any) => { d.categorias['OTRA'] = { etiqueta: 'Otra', color: '#112233', grupo: 'NO_MALIGNO', gravedad: 5 }; }], + ['sin la categoría INVASOR en el catálogo', (d: any) => { delete d.categorias['INVASOR']; }], + ['un estrato desconocido en valores_estrato', (d: any) => { d.valores_estrato.push('BIRADS_7'); }], + ['filas duplicadas', (d: any) => { d.filas.push({ ...d.filas[0] }); }], + ['un grupo distinto de TOTAL', (d: any) => { d.filas[0]['grupo'] = 'OTRO'; }], + ['suprimido distinto de 0 o 1', (d: any) => { d.filas[0]['suprimido'] = 2; }], + ['un total que no es la suma de sus celdas', (d: any) => { d.totales_estrato[0]['n'] = 99; }], + ['un color que no es hexadecimal', (d: any) => { d.categorias['BENIGNO'].color = 'azul'; }], + ['una categoría sin grupo publicado', (d: any) => { d.categorias['BENIGNO'].grupo = 'NADA'; }], + ['sin catálogo de grupos', (d: any) => { delete d.grupos_de_categoria; }], + ])('rechaza %s', (_nombre, daño) => { + // Fails if a payload outside the contract is drawn, which could change a denominator unnoticed. + const d: any = estrato(); daño(d); + expect(() => base(d)).toThrow(HistopatologiaIncompatible); + }); + it('un color nulo en el catálogo usa el gris de respaldo', () => { + const d = estrato(); d.categorias['RIESGO_B3'].color = null; + expect(base(d).categorias[1].color).toBe('#8A9199'); + }); +}); + +describe('Histopatología por BI-RADS: tasas, selección y figuras', () => { + it('la vista base lee «maligno»: In situ más invasor entre las pacientes con resultado, con Wilson al 95 %', () => { + const m = base(), sel = seleccionBase(m); + expect(sel).toEqual({ grupo: 'MALIGNO' }); + expect(tasas(m, sel).map(t => [t.k, t.fila.den])).toEqual([[2, 4], [3, 5], [2, 4], [2, 4], [2, 4], [2, 4]]); + const [bajo, alto] = wilson(3, 5); + expect(tasas(m, sel)[1]).toMatchObject({ valor: 60, bajo, alto }); + expect(lectura(m, sel)).toBe('Pacientes con resultado maligno entre las que tienen resultado de biopsia'); + }); + it('grupo, categoría, segundo clic al grupo y centro a la base', () => { + const m = base(), sel = seleccionBase(m); + const noMaligno = clicHistopatologia(m, sel, 'grupos', 0); + expect(noMaligno).toEqual({ grupo: 'NO_MALIGNO' }); + expect(tasas(m, noMaligno).map(t => t.k)).toEqual([2, 2, 2, 2, 2, 2]); + expect(lectura(m, noMaligno)).toBe('Pacientes con resultado no maligno entre las que tienen resultado de biopsia'); + const b3 = clicHistopatologia(m, noMaligno, 'categorias', 1); + expect(b3).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + expect(tasas(m, b3).map(t => t.k)).toEqual([0, 1, 1, 1, 1, 1]); + expect(lectura(m, b3)).toBe('Proporción con resultado lesión de riesgo (b3)'); + expect(clicHistopatologia(m, b3, 'categorias', 1)).toEqual({ grupo: 'NO_MALIGNO' }); + expect(clicHistopatologia(m, b3, 'categorias', 3)).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); + expect(clicHistopatologia(m, b3, 'centro', 0)).toEqual(sel); + expect(clicHistopatologia(m, b3, 'otra', 0)).toEqual(b3); expect(clicHistopatologia(m, b3, 'grupos', 9)).toEqual(b3); + }); + it('un cero con denominador es una tasa de 0 %, no una ausencia', () => { + const m = base(), b3 = { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }; + const t = tasas(m, b3)[0]; + expect([t.k, t.valor, t.fila.den]).toEqual([0, 0, 4]); expect(t.bajo).toBe(0); expect(t.alto).toBeGreaterThan(0); + expect(estadoTasa(t)).toBe(''); + expect((figuraTasas(m, b3, 'claro').layout['annotations'] as { text: string }[])[0].text).toMatch(/0\/4$/); + }); + it('un estrato sin pacientes con resultado dice «Sin pacientes con resultado de biopsia», sin tasa', () => { + const d = estrato(); + for (const c of ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']) fila(d, 'BIRADS_6', c)['n'] = 0; + d.totales_estrato.find(t => t['estrato'] === 'BIRADS_6')!['n'] = 2; + const m = base(d), t = tasas(m, seleccionBase(m))[5]; + expect([m.filas[5].den, t.k, t.valor, estadoTasa(t)]).toEqual([0, null, null, 'Sin pacientes con resultado de biopsia']); + }); + it('figura de tasas: una traza, seis categorías con la 4 sin subtipo arriba, etiquetas «% y k/n» y eje en múltiplos de 5', () => { + const m = base(), sel = seleccionBase(m), f = figuraTasas(m, sel, 'claro'); + expect(f.data).toHaveLength(1); expect(f.data[0]['name']).toBe('tasas'); + expect(f.data[0]['y']).toEqual(m.filas.map(r => r.etiqueta)); + expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray[5]).toBe('BI-RADS 4 sin subtipo'); + expect(f.data[0]['x']).toEqual([50, 60, 50, 50, 50, 50]); + expect((f.layout['annotations'] as { text: string }[]).map(a => a.text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim())) + .toEqual(['50.0 % 2/4', '60.0 % 3/5', '50.0 % 2/4', '50.0 % 2/4', '50.0 % 2/4', '50.0 % 2/4']); + const range = (f.layout['xaxis'] as { range: number[] }).range; + expect(range).toEqual(rangoTasas(tasas(m, sel))); + expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); + expect(figuraTasas(m, sel, 'oscuro').layout['paper_bgcolor']).toBe('#081839'); + }); + it('dona de dos anillos: grupos dentro, categorías fuera; la selección atenúa sin cambiar valores y el centro dice «k de N con resultado»', () => { + const m = base(), d = donaHistopatologia(m, seleccionBase(m), 'claro'); + expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']); + expect(d.data[1]['values']).toEqual([12, 13]); expect(d.data[2]['values']).toEqual([7, 5, 6, 7]); + expect(d.data[0]['text']).toEqual(['13
de 25 con resultado']); + const otra = donaHistopatologia(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro'); + expect(otra.data[2]['values']).toEqual(d.data[2]['values']); + const colores = (otra.data[2]['marker'] as { colors: string[] }).colors; + expect(colores[1]).toMatch(/,1\)$/); expect(colores[0]).toMatch(/,0.3\)$/); + expect(otra.data[0]['text']).toEqual(['5
de 25 con resultado']); + }); + it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => { + // The general payload is what the history panel draws; it must not pass for the stratified one. + expect(Object.keys((generalFixture as any).categorias)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR', 'SIN_BIOPSIA', 'SIN_DATO']); + expect((generalFixture as any).filas.map((f: any) => f.n)).toEqual([7, 5, 6, 7, 6, 6]); + expect((generalFixture as any).estrato).toBeNull(); + }); +}); + +describe('Histopatología por BI-RADS: componente', () => { + const indicador = (catalogoFixture as unknown as Indicador[]).find(item => item.id === 'cama_histopatologia_birads')!; + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: [PERIODO] }, revision: 1 }; + let f: ReturnType>; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorHistopatologiaCama, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorHistopatologiaCama, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + f = TestBed.createComponent(IndicadorHistopatologiaCama); + f.componentRef.setInput('dominio', 'cama'); f.componentRef.setInput('indicador', indicador); + 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); f.detectChanges(); + } + const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys 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('.keys button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['No maligno', 'Maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('selección: 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 para datos sintéticos'); + }); + 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); + const volver = () => [...f.nativeElement.querySelectorAll('.legend > button')].find((b: Element) => b.textContent!.trim() === 'Volver') as HTMLButtonElement; + expect(volver().disabled).toBe(true); + 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(volver().disabled).toBe(false); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (b3)'); + b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); + boton('Carcinoma invasor').click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); + volver().click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + http.expectNone(() => true); + }); + 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); + 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('.rate-states').textContent).toContain('BI-RADS 4C: 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('.rate-states').textContent).toContain('BI-RADS 6: No disponible'); + }); + it('sin filas en el periodo lo dice y conserva la tabla vacía', () => { + const d = estrato(); d.filas = []; d.totales_estrato = []; + f.detectChanges(); flush(d); + expect(f.componentInstance.status()).toBe('empty'); + expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => { + f.detectChanges(); + solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); + f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' }); + expect(f.componentInstance.status()).toBe('incompatible'); + expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => { + f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + }); + it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => { + f.detectChanges(); flush(); + f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); + expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); + }); + it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido); + (f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges(); + expect(pedido).toHaveBeenCalledTimes(1); + expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador'); + f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [ + { figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); + f.detectChanges(); + const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement; + expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']); + for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente); + }); + + it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const card = TestBed.createComponent(IndicadorCatalogCard); + card.componentRef.setInput('dominio', 'cama'); card.componentRef.setInput('indicador', indicador); + card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorHistopatologiaCama))).toHaveLength(1); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0); + expect(card.nativeElement.querySelector('h2').textContent).toBe(indicador.titulo); + for (const [domain, id] of [['cacu', 'cama_histopatologia_birads'], ['cama', 'cama_biopsias']] as const) { + card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorHistopatologiaCama))).toHaveLength(0); + } + card.destroy(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts new file mode 100644 index 0000000..f52fb11 --- /dev/null +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -0,0 +1,251 @@ +import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Theme } from './indicadores-c2-palette'; +import { Celda, wilson } from './indicadores-confirmacion-citologia'; +import { percentNumber, shareText } from './indicadores-format'; +import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; + +// CaMa's histopathological result by BI-RADS (cama_histopatologia_birads): a C2 stratified by `birads`, one +// patient per period. This module turns the published matrix into what the view draws; it owns no HTTP and no +// drawing library, so another source of the same matrix (for example a MeasureReport adapter) only has to +// produce the same payload. The selection of units stays in the backend; here nothing is added, inferred or +// completed: a stratum or a cell that is not published is "No disponible", never zero, and a suppressed cell +// is "Suprimido". A total is only drawn over a complete matrix. +export const ID_HISTOPATOLOGIA = ID_HISTOPATOLOGIA_CAMA; +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> = { + 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 +// and MALIGNO the last two, as the catalog says. +export const CON_RESULTADO = ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR'] as const; +// Reported apart, outside the denominator and the donut: no biopsy reported at the cut-off, and a biopsy without grade. +export const APARTE = [ + { id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' }, + { id: 'SIN_DATO', etiqueta: 'Sin dato' }, +] as const; +const APARTE_IDS: readonly string[] = APARTE.map(a => a.id); +// The group the base view reads: the malignant results, the true positives of the suspicion. +const CATEGORIA_BASE = 'INVASOR'; +const COLOR_RESPALDO = '#8A9199'; + +export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } +export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; } +export interface FilaBirads { + id: string; etiqueta: string; + // The four categories with a result. + celdas: Record; + // SIN_BIOPSIA and SIN_DATO, when the catalog publishes them. + aparte: Record; + // 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. + den: number | null; estado: Celda['estado']; +} +export interface ModeloHistopatologia { + periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string; + filas: FilaBirads[]; totales: Record; conResultado: number | null; + aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; +} +export interface SeleccionHistopatologia { grupo: string; categoria?: string; } +export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } +export class HistopatologiaIncompatible extends Error {} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0; +const fail = (message: string): never => { throw new HistopatologiaIncompatible(message); }; +const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const miles = (v: number) => v.toLocaleString('es-MX'); +const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; +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. +function celda(fila?: Record): Celda { + if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' }; + return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0 + ? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' }; +} +const suma = (celdas: Celda[]): number | null => celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0); +const estadoDe = (celdas: Celda[]): Celda['estado'] => + celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; +function promedio(colores: string[]): string { + return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length) + .toString(16).padStart(2, '0')).join(''); +} +function rgba(hex: string, alfa: number): string { + const v = parseInt(hex.slice(1), 16); + return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; +} + +/** Validated periods of one stratified response, in request order or sorted. */ +export function periodosHistopatologia(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { + if (datos.id !== ID_HISTOPATOLOGIA || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_BIRADS + || !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length + || datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) + || (solicitados && datos.periodos.some(p => !solicitados.includes(p))) + || datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) { + return fail('Los datos no corresponden a la histopatología por BI-RADS o al periodo aplicado.'); + } + return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort(); +} + +/** One stratified /datos payload -> the matrix of a single period. */ +export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): ModeloHistopatologia { + periodosHistopatologia(datos, datos.tipo_periodo); + const cats = datos['categorias'], nombres = datos['grupos_de_categoria']; + if (!registro(cats) || !registro(nombres)) return fail('Catálogo de categorías incompleto.'); + // A category the view does not know would change the denominator without anyone noticing. + const conocidas: readonly string[] = [...CON_RESULTADO, ...APARTE_IDS]; + if (Object.keys(cats).some(id => !conocidas.includes(id)) || CON_RESULTADO.some(id => !Object.hasOwn(cats, id))) { + return fail('El catálogo no publica las categorías esperadas de la biopsia.'); + } + const categorias: Categoria[] = CON_RESULTADO.map(id => { + const c = cats[id]; + if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) + || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.'); + return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null | undefined) ?? COLOR_RESPALDO, grupo: c['grupo'] }; + }); + const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => { + const propias = categorias.filter(c => c.grupo === id); + return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) }; + }); + if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.'); + const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo; + const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => { + const c = cats[a.id]; + return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta }; + }); + + const indice = new Map>(); + for (const row of datos.filas.filter(f => f['periodo'] === periodo)) { + const c = row['categoria'], e = row['estrato']; + if (!esTotal(row['grupo']) || typeof e !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(e) || typeof c !== 'string' || !conocidas.includes(c) + || ![0, 1].includes(row['suprimido'] as number)) return fail('Fila de histopatología inválida.'); + const key = JSON.stringify([e, c]); + if (indice.has(key)) return fail('Filas de histopatología duplicadas.'); + indice.set(key, row); + } + const publicados = datos['valores_estrato']; + if (publicados !== undefined && (!Array.isArray(publicados) || !publicados.every(v => typeof v === 'string' && (ESTRATOS_BIRADS as readonly string[]).includes(v)))) { + return fail('Estratos de BI-RADS inválidos.'); + } + const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {}; + const totalesPublicados = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : []; + if (!totalesPublicados.every(registro)) return fail('Totales de BI-RADS inválidos.'); + const totalesDelPeriodo = (totalesPublicados as Record[]).filter(t => t['periodo'] === periodo); + if (totalesDelPeriodo.some(t => !esTotal(t['grupo']) || typeof t['estrato'] !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(t['estrato']) + || ![0, 1].includes(t['suprimido'] as number))) return fail('Totales de BI-RADS inválidos.'); + + const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => { + const rotulo = texto(etiquetas[id]) ? etiquetas[id] : ETIQUETA_ESTRATO[id]; + // A stratum the response does not publish has cells that are not available: it is never read as zero patients. + const celdas = Object.fromEntries(categorias.map(c => [c.id, celda(indice.get(JSON.stringify([id, c.id])))])); + const otras = Object.fromEntries(aparte.map(a => [a.id, celda(indice.get(JSON.stringify([id, a.id])))])); + const total = celda(totalesDelPeriodo.find(t => t['estrato'] === id)); + const valores = Object.values(celdas); + // The published total of a stratum has to be the sum of its cells, when both are known. + const todas = [...valores, ...Object.values(otras)]; + if (total.n !== null && todas.every(c => c.n !== null) && suma(todas) !== total.n) return fail('El total de ' + rotulo + ' no coincide con la suma de sus celdas.'); + // A suppressed published total suppresses the row, whatever its cells say. + return { id, etiqueta: rotulo, celdas, aparte: otras, total, + den: total.estado === 'Suprimido' ? null : suma(valores), estado: total.estado === 'Suprimido' ? 'Suprimido' : estadoDe(valores) }; + }); + // The donut and its total need the six strata complete: a partial sum would be a different, unpublished figure. + const porCategoria = Object.fromEntries(categorias.map(c => [c.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[c.id]))])); + return { periodo, categorias, grupos, base, filas, totales: porCategoria, + conResultado: suma(categorias.map(c => ({ n: porCategoria[c.id], estado: 'Publicado' as const }))), + aparte, vacio: indice.size === 0 && !totalesDelPeriodo.length, notas: [...new Set(datos.notas ?? [])] }; +} + +export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; } +export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] { + return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? []; +} +export function seleccionEtiqueta(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { + return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta; +} +/** A group selects the group; a category selects it and a second click returns to its group; the centre returns to the base. */ +export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, traza: string, indice: number): SeleccionHistopatologia { + 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]; + 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 (!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 ' + seleccionEtiqueta(m, sel).toLowerCase(); +} +/** Per BI-RADS stratum: the selected categories over the patients with a biopsy result. No biopsy and no data never enter. */ +export function tasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): Tasa[] { + const ids = seleccionadas(m, sel); + return m.filas.map(fila => { + if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null }; + const k = ids.reduce((s, c) => s + fila.celdas[c].n!, 0); + const [bajo, alto] = wilson(k, fila.den); + return { fila, k, valor: 100 * k / fila.den, bajo, alto }; + }); +} +export function estadoTasa(t: Tasa): string { + return t.fila.den === 0 ? 'Sin pacientes con resultado de biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado; +} +/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */ +export function rangoTasas(valores: Tasa[]): [number, number] { + const visibles = valores.filter(t => t.bajo !== null && t.alto !== null); + if (!visibles.length) return [0, 100]; + const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!)); + return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)]; +} + +/** Rates on the left: one point and horizontal Wilson interval per BI-RADS stratum, one trace always. */ +export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { + const p = c2Theme(tema); + 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 y = valores.map(t => t.fila.etiqueta); + return { data: [{ + type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), + marker: { size: 12, color }, cliponaxis: false, + error_x: { type: 'data', symmetric: false, color, 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}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', + }], layout: { + autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { l: 150, r: 96, t: 16, b: 64 }, + yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true }, + xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } }, + annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left', + font: { size: 12, color: p.text }, + text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), + }, config: { displayModeBar: false } }; +} + +/** Donut on the right: result groups inside, categories outside; selection dims, values stay. Empty over an incomplete matrix. */ +export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { + if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} }; + 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 comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; + const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes con resultado, %{customdata[1]}' }; + const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]); + return { data: [ + { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside', + text: [`${miles(k)}
de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text }, + marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, + { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, + labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), + marker: { colors: m.grupos.map(g => rgba(g.color, g.categorias.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, + labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), + marker: { colors: m.categorias.map(c => rgba(c.color, activos.has(c.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, + config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 357e9df..5822ac7 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -296,7 +296,9 @@ export class IndicadoresPage { // 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)); + 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. + 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() { diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index f40a8d4..a683da0 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -17,7 +17,7 @@ export interface Indicador { tipos_periodo: TipoPeriodo[]; filtros?: IndicadorFiltro[]; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado'; +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads'; export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 025e81a..260a74e 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -66,7 +66,7 @@ export class IndicadoresService { } let params = new HttpParams(); if (scope.estrato) { - if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); + if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); params = params.set('estrato', scope.estrato); } if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));