Compare commits

..

1 Commits

79 changed files with 249 additions and 17435 deletions
@@ -100,8 +100,8 @@
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
@@ -134,7 +134,7 @@
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
Recordar servidor, usuario y base de datos (nunca la contraseña)
</mat-checkbox>
}
@@ -1,6 +1,6 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
MENOR_40: 'Menores de 40 años', '<40': 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato',
};
const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/;
const HISTOLOGIA: Readonly<Record<string, string>> = {
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
@@ -1 +0,0 @@
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -1 +0,0 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,842 +0,0 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 8,
"link": [
{
"relation": "self",
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
}
],
"entry": [
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIOPSIAS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
"version": "0.2.0",
"name": "cama_biopsias",
"title": "Distribución de resultados de biopsia",
"status": "active",
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_biopsias"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grado"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
"version": "0.2.0",
"name": "cama_birads",
"title": "Distribución de BI-RADS",
"status": "active",
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS-CANCER-INVASOR",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"version": "0.1.0",
"name": "cama_birads_cancer_invasor",
"title": "BI-RADS de los cánceres invasores",
"status": "active",
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_cancer_invasor"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grupo_edad"
}
],
"text": "grupo_edad"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "estadio"
}
],
"text": "Estadio clínico"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "etapa"
}
],
"text": "Etapa"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "clasificacion"
}
],
"text": "Subtipo molecular"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "tamano"
}
],
"text": "Tamaño tumoral (T)"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-MASTOGRAFIA",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"version": "0.2.0",
"name": "cama_birads_456_mastografia",
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_mastografia"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-PACIENTE",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"version": "0.2.0",
"name": "cama_birads_456_paciente",
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_paciente"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"resource": {
"resourceType": "Measure",
"id": "CAMA-CONFIRMACION-BIRADS45",
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"version": "0.2.0",
"name": "cama_confirmacion_birads45",
"title": "Tasa de confirmación histopatológica",
"status": "active",
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C1"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "proportion"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "principal"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"description": "Denominador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"description": "Numerador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_numerador"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "episodio"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "increase"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"resource": {
"resourceType": "Measure",
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"version": "0.2.2",
"name": "cama_dias_toma_diagnostico",
"title": "Tiempo de tamizaje a diagnóstico",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
"resource": {
"resourceType": "Measure",
"id": "CAMA-EU38A",
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
"version": "0.2.1",
"name": "cama_eu38a",
"title": "Días de la toma de la mastografía a su resultado",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -1 +0,0 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
@@ -1 +0,0 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}], "paginacion": {"page": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -34,7 +34,7 @@
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
@@ -14,8 +14,6 @@ h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
.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; }
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
.donut-chart { --plot-min-width: 230px; }
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; }
@@ -38,7 +38,10 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
private subscription?: Subscription;
private key = '';
private loaded = false;
private anchoDona = 390;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
@@ -105,18 +108,12 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
ajustarAnchoDona(ancho: number) {
if (ancho === this.anchoDona) return;
this.anchoDona = ancho;
const m = this.model;
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
}
@@ -37,7 +37,7 @@
:host(.methodology-expanded) .figure-card { grid-row: auto; }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
@@ -30,8 +30,22 @@
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
<div class="figures">
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
@if (ratesFigure) {
@@ -47,21 +61,7 @@
} @else { <p role="status">{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}</p> }
</section>
</div>
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
</div>
</div>
}
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
@@ -1,109 +0,0 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
const miles = (v: number) => v.toLocaleString('es-MX');
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
const t = c2Theme(tema);
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
};
const config = { displayModeBar: false };
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
return {
data: [{
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
config,
};
}
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
const t = c2Theme(tema);
const grupos = c.grupos.filter(g => g.estado === 'disponible');
return {
data: [{
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
marker: { color: C2_PALETTE.series[1], size: 11 },
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
config,
};
}
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
const t = c2Theme(tema);
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
return {
data: [{
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
}],
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
plot_bgcolor: t.grid },
config,
};
}
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
const t = c2Theme(tema);
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
return {
actividad: {
data: [
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
],
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
config,
},
proporcion: {
data: [{
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
config,
},
};
}
@@ -1,298 +0,0 @@
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
// without data, suppressed or not published.
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
import {
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
import mapaData from './fixtures/cama_analisis_real_mapa.json';
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
const CORTE = '2026-11-16';
describe('Respuestas del análisis descriptivo', () => {
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
}
});
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
// Fails if the client draws figures from an answer that contradicts itself.
const d = copia(distBirads); d['items'][0].suprimido = true;
expect(() => distribucionDescriptiva(d)).toThrow();
const sin = copia(distBirads); delete sin['revision'];
expect(() => distribucionDescriptiva(sin)).toThrow();
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
expect(() => resumenDescriptivo(r)).toThrow();
});
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
const r = resumenDescriptivo(copia(resumenData));
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
expect(valorTarjeta(t['cohorte'])).toBe('61');
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
expect(valorTarjeta(oculta)).toBeNull();
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
});
});
describe('Figuras del análisis descriptivo', () => {
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
const d = distribucionDescriptiva(copia(distBirads));
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
expect(traza['y']).toEqual(['BI-RADS 4']);
expect(traza['x']).toEqual([54.1]);
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
});
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
// asymmetric. Fails if a group without data or a hidden one gets a point.
const c = comparacionDescriptiva(copia(compEdad));
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
expect(traza['x']).toHaveLength(3);
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
});
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
const m = mapaDescriptivo(copia(mapaData));
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
expect(traza['z'][iFila][iCol]).toBeNull();
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
expect(traza['z'][f][c]).toBe(publicada.n);
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
});
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
const mes = tendenciaDescriptiva(copia(tendMes));
const figuras = tendenciaFiguras(mes, 'claro', 'x');
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
});
});
describe('Análisis descriptivo de CaMa (componente)', () => {
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
async function abrir() {
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
}
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
// asked early or without the selection.
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
});
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
// count different patients or a banner of that kind appears.
await abrir();
const texto = root().textContent!;
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
expect(texto).toContain('No disponible con las fuentes actuales');
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
expect(texto).toContain('No hay estado vital');
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
});
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
// the list would open another selection.
await abrir();
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
expect(emitidas).toHaveLength(1);
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
// table. Fails if a choice in one section reloads the rest.
await abrir();
boton('Grupo de edad').click(); fixture.detectChanges();
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
http.expectNone(() => true);
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
});
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData);
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
});
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
await abrir();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
const c = fixture.componentInstance;
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
pide('/comparacion').flush(compEdad); await asentar();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
});
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
// Fails if a hidden share is written as a number or the partial period looks whole.
await abrir();
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
expect(tabla.textContent).toContain('(en curso)');
expect(tabla.textContent).toContain('No publicado');
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
});
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
// window it doesn't apply, or isn't refreshed when the cut-off changes.
await abrir();
const c = fixture.componentInstance;
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
d.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
http.expectNone(r => r.url.endsWith('/tendencia'));
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
t.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
});
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
await abrir();
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
expect(seccion).toContain('Actividad de reportes en el tiempo');
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
expect(seccion).toContain('Cuenta reportes, no pacientes');
expect(seccion).toContain((tendSem as any).alcance_biopsias);
expect(seccion).toContain('Reportes de biopsia');
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
});
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
await abrir();
const c = fixture.componentInstance;
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
await asentar();
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
await abrir();
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
const resumen = plegable.querySelector('summary')!;
expect(plegable.open).toBe(false);
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(false);
});
});
@@ -1,368 +0,0 @@
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { Observable, Subscription } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import {
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
import type { SeleccionPacientes } from './indicadores-analisis';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
const VACIA = { data: [], layout: {} } as PlotlyFigure;
const miles = (v: number) => v.toLocaleString('es-MX');
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
export function valorTarjeta(t: TarjetaAnalisis): string | null {
if (t.estado !== 'disponible' || t.valor === null) return null;
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
}
export function detalleTarjeta(t: TarjetaAnalisis): string {
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
const partes: string[] = [];
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
partes.push(t.descripcion);
return partes.join(' ');
}
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis-descriptivo',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="bloque" aria-labelledby="desc-resumen">
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
<form class="controles" (ngSubmit)="aplicar()">
<label>Ventana
<select name="meses" [(ngModel)]="meses">
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
</select></label>
<label>Categoría BI-RADS
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Grupo de edad
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Horizonte del seguimiento diagnóstico
<select name="horizonte" [(ngModel)]="horizonte">
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
</form>
@switch (resumen().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
}
@if (r(); as res) {
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
<div class="tarjetas">
@for (t of res.indicadores; track t.clave) {
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
}
</div>
}
</section>
<section class="bloque" aria-labelledby="desc-dist">
<h2 id="desc-dist">Distribución de pacientes</h2>
<div class="selector" role="group" aria-label="Distribuir por">
@for (d of dimensionesDist; track d.clave) {
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
}
</div>
@switch (distribucion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
}
@if (dist(); as d) {
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
@else {
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>@for (i of d.items; track i.codigo) {
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
}</tbody></table>
</div>
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
}
}
</section>
<section class="bloque" aria-labelledby="desc-comp">
<h2 id="desc-comp">Comparación entre grupos</h2>
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
<div class="controles">
<label>Comparar por
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
<label>Resultado
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
</div>
@switch (comparacion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
}
@if (comp(); as c) {
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
<table><caption>{{ c.denominador }}</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
<tbody>@for (g of c.grupos; track g.codigo) {
<tr><th scope="row">{{ g.etiqueta }}</th>
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
}
</section>
<section class="bloque" aria-labelledby="desc-mapa">
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
<div class="selector" role="group" aria-label="Medida del mapa">
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
</div>
@switch (mapa().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
}
@if (m(); as mm) {
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
<details><summary>Valores publicados</summary>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
</details>
}
</section>
<section class="bloque" aria-labelledby="desc-tend">
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
<div class="controles">
<label>Periodo
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
<label>Periodos a mostrar
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
</div>
@switch (tendencia().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
}
@if (t(); as tt) {
<div class="par">
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
</div>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
<tbody>@for (p of tt.periodos; track p.periodo) {
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
}
</section>
@if (r(); as res) {
<section class="bloque" aria-labelledby="desc-no">
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
<details class="plegable" data-plegable="no-disponibles">
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
<ul class="no-disponibles">
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
</ul>
</details>
</section>
}
`,
styles: `
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.bloque { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
p, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); }
caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); }
th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; }
td { font-variant-numeric: tabular-nums; }
.ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; }
.ver:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
.plegable > summary h2 { display: inline; }
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
`,
})
export class IndicadoresAnalisisDescriptivo {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly corte = input.required<string>();
readonly active = input(false);
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
readonly miles = miles; readonly decimal = decimal;
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
readonly por = signal('birads');
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
private readonly service = inject(AnalisisDescriptivoService);
private readonly destroy = inject(DestroyRef);
private readonly suscripciones = new Map<string, Subscription>();
private abierto = false; private corteCargado = ''; private tendCorte = '';
// The filters and window the sections were last asked with: one selection for all of them.
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
constructor() {
effect(() => {
const activa = this.active(), corte = this.corte();
if (!activa) return;
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
});
}
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
}
private pedido(): PedidoDescriptivo {
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
}
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
aplicar() {
this.pedidoVigente = this.pedido();
const p = this.pedidoVigente;
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
this.recargarDist(); this.recargarComp(); this.recargarMapa();
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
}
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
this.suscripciones.get(clave)?.unsubscribe();
destino.set({ estado: 'cargando' });
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
error: error => destino.set(this.fallo(error)),
}));
}
private fallo(error: unknown): Carga<never> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' };
if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' };
}
return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' };
}
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
if (!n) return;
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
this.verPacientes.emit({
origen: origen instanceof HTMLElement ? origen : null,
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
});
}
clicDist(evento: unknown) {
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
}
clicMapa(evento: unknown) {
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
}
}
@@ -55,119 +55,3 @@ export class AnalisisService {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
export interface AnalisisSeleccion {
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
ventana: { meses: number; desde: string; hasta: string };
filtros: Record<string, string | null>;
}
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
}
export interface TarjetaAnalisis {
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
}
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
export interface PeriodoTendencia {
periodo: string; inicio: string; fin: string; incompleto: boolean;
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
maligno: Proporcion;
}
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
export interface TendenciaAnalisis {
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
denominador: string; periodos: PeriodoTendencia[];
}
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
return v as unknown as AnalisisCatalogoDescriptivo;
}
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
return v as unknown as ResumenAnalisis;
}
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
&& record(i['seleccion']))) invalidoDescriptivo();
return v as unknown as DistribucionAnalisis;
}
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
return v as unknown as ComparacionAnalisis;
}
export function mapaDescriptivo(v: unknown): MapaAnalisis {
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
return v as unknown as MapaAnalisis;
}
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
return v as unknown as TendenciaAnalisis;
}
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
return params;
}
@Injectable({ providedIn: 'root' })
export class AnalisisDescriptivoService {
private readonly http = inject(HttpClient);
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
}
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
}
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
}
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
}
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
}
}
@@ -1,12 +1,12 @@
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
@@ -80,7 +80,7 @@ class ChartStub { readonly plotClick = output<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
@@ -1,7 +1,5 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { throwError } from 'rxjs';
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
@@ -47,12 +45,3 @@ export function listaCohorte(o: { corte?: string; filtros?: Record<string, strin
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
/**
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
* backend, so those specs keep counting only the requests they are about.
*/
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
@@ -7,7 +7,6 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
@@ -21,7 +20,7 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
@@ -55,7 +54,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
// a suppressed one says why it does not. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
@@ -113,7 +112,6 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
}
</article>
</section>
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
`,
styles: `
:host { display: block; min-width: 0; }
@@ -168,8 +166,6 @@ export class IndicadoresAnalisis {
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
// The cut-off of the last query: the descriptive sections follow it.
readonly corteConsultado = signal(this.hoy);
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
@@ -210,7 +206,6 @@ export class IndicadoresAnalisis {
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.corteConsultado.set(this.corte);
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
@@ -234,12 +229,6 @@ export class IndicadoresAnalisis {
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
this.verPacientes.emit(evento.seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
@@ -18,7 +18,7 @@ export function c1AlterationCapability(contract: string, representation: string)
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The any-alteration bar uses the second series colour; each alteration takes its own colour.
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
@@ -21,7 +21,7 @@ const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
};
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
// Green for the event, red for its complement; age groups get lighter shades.
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
// One colour per age group, the same in the donut (M21) and the bars (M22).
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
@@ -1,5 +1,5 @@
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { FigureSelection } from './indicadores.models';
import { donutFixture } from './indicadores-donut-drilldown.testing';
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
]);
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
@@ -158,18 +158,15 @@ describe('C2: datos publicados a Plotly', () => {
});
describe('paleta C2 institucional y semántica', () => {
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
expect(c2Color('#D98E4A', 0)).toBe('#D98E4A');
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
});
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
@@ -1,6 +1,6 @@
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
import { DonutHierarchy } from './indicadores-donut-drilldown';
import { c2Theme, groupBase, seriesColors } from './indicadores-c2-palette';
import { c2Color, c2Theme } from './indicadores-c2-palette';
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
// Normalized presentation nodes and a selection path are independent of Plotly.
@@ -81,7 +81,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
const colors = seriesColors(categories.map(c => c.color));
const colors = categories.map((c, i) => c2Color(c.color, i));
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
@@ -109,7 +109,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
marker: { colors: parents.map((_, i) => groupBase(i)), line: { color: theme.outline, width: 0.7 } },
marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } },
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
}
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
@@ -19,9 +19,7 @@ describe('selección local segura de barras generales C2', () => {
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!;
const marker = source.data[0]['marker'] as { color: string[] }, labels = source.data[0]['y'] as string[];
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'],
marker: { color: ['B', 'C'].map(label => marker.color[labels.indexOf(label)]) } });
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2, 2025-S2');
@@ -1,53 +0,0 @@
import { C2_PALETTE, groupBase, institutionalize, isHarmoniousColor, paintByGroup, recolorFigure } from './indicadores-c2-palette';
describe('paleta del logo ISSSTELEON', () => {
it('combina varios matices del logo y del verde azulado, sin repetir el mismo color', () => {
expect(new Set(C2_PALETTE.series).size).toBe(C2_PALETTE.series.length);
for (const color of C2_PALETTE.series) expect(isHarmoniousColor(color)).toBe(true);
expect(institutionalize(['#a8c243'])).toEqual(['#a8c243']);
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
});
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
]);
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
expect(edad).toBe('#2F6DB3');
expect(sinDato).toBe('#C9CDD2');
});
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
expect(new Set(colors.slice(0, 3)).size).toBe(3);
expect(colors[3]).toBe(groupBase(1));
expect(colors[0]).not.toBe(colors[3]);
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
});
it('pinta la tinta categórica, deja una escala continua y no toca texto ni fondo', () => {
const figure = recolorFigure({
data: [{
type: 'scatter', marker: { color: '#B55A1F' }, error_x: { color: 'rgba(0,68,204,0.4)' }, line: { color: '#C9CDD2' },
colorscale: [[0, '#0d0887'], [0.5, '#ed7953'], [1, '#f0f921']],
}],
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
});
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
expect(figure.data[0]['error_x']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
const scale = figure.data[0]['colorscale'] as [number, string][];
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
expect(scale[0][1]).not.toBe('#0d0887');
expect(scale[0][1]).not.toBe(scale[1][1]);
expect(figure.layout['font']).toEqual({ color: '#081839' });
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
expect(new Set([
(figure.data[0]['marker'] as { color: string }).color,
...(figure.layout['colorway'] as string[]),
]).size).toBe(3);
expect(recolorFigure(figure)).toBe(figure);
});
});
@@ -1,16 +1,11 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { Tema } from './indicadores.models';
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
// Matches src/styles.scss: interface tokens are the source of these candidates,
// not a certified brand guide. Published semantic colours always take priority.
export const C2_PALETTE = Object.freeze({
series: Object.freeze([
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
]),
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
@@ -18,206 +13,6 @@ export const C2_PALETTE = Object.freeze({
oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }),
});
export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; }
const ageKeys = new Set(C2_PALETTE.edades.map(color => parseColor(color)?.key).filter((key): key is string => !!key));
export function isAgeColor(color: string): boolean {
const key = parseColor(color)?.key;
return !!key && ageKeys.has(key);
}
export function c2Color(published: string | undefined, index: number): string {
// A published swatch stays. The series only fills a category that arrived without one.
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
return C2_PALETTE.series[index % C2_PALETTE.series.length];
}
/** One base hue per group, then lighter and darker steps so siblings stay related but distinct. */
export function paintByGroup(groups: readonly string[]): string[] {
const order = [...new Set(groups)];
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
const cursor = new Map<string, number>();
return groups.map(id => {
const index = cursor.get(id) ?? 0;
cursor.set(id, index + 1);
return stairs.get(id)![index];
});
}
export function groupBase(index: number): string {
return C2_PALETTE.series[index % C2_PALETTE.series.length];
}
/** Replace inharmonious hues. Same source colour keeps the same slot; grays and palette hues stay. */
export function institutionalize(colors: readonly string[]): string[] {
const parsed = colors.map(parseColor);
const foreign: string[] = [];
const seen = new Set<string>();
for (const item of parsed) {
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
seen.add(item.key);
foreign.push(item.key);
}
const assigned = new Map(foreign.map((key, i) => [key, C2_PALETTE.series[i % C2_PALETTE.series.length]]));
return colors.map((color, i) => {
const item = parsed[i];
const next = item && assigned.get(item.key);
return item && next ? formatAs(item, next) : color;
});
}
/** Keep a published colour; only a missing one takes the next series entry. */
export function seriesColors(published: readonly (string | undefined)[]): string[] {
return published.map((color, index) => c2Color(color, index));
}
const NAMED: Record<string, [number, number, number]> = {
black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
red: [255, 0, 0], blue: [0, 0, 255], green: [0, 128, 0], orange: [255, 165, 0], yellow: [255, 255, 0],
purple: [128, 0, 128], brown: [165, 42, 42], pink: [255, 192, 203], cyan: [0, 255, 255], magenta: [255, 0, 255],
gold: [255, 215, 0], navy: [0, 0, 128], teal: [0, 128, 128], maroon: [128, 0, 0], lime: [0, 255, 0], olive: [128, 128, 0],
};
interface Parsed { r: number; g: number; b: number; a: number; key: string; hue: number; sat: number; lum: number; kind: 'neutral' | 'harmonious' | 'foreign'; explicitAlpha: boolean; }
function parseColor(input: string): Parsed | undefined {
const text = input.trim();
let r = 0, g = 0, b = 0, a = 1, explicitAlpha = false;
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text);
const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
if (hex) {
const raw = hex[1].length === 3 ? hex[1].split('').map(c => c + c).join('') : hex[1];
r = parseInt(raw.slice(0, 2), 16); g = parseInt(raw.slice(2, 4), 16); b = parseInt(raw.slice(4, 6), 16);
} else if (rgb) {
r = Number(rgb[1]); g = Number(rgb[2]); b = Number(rgb[3]);
if (rgb[4] !== undefined) { a = Number(rgb[4]); explicitAlpha = true; }
if ([r, g, b].some(v => v > 255) || !Number.isFinite(a)) return undefined;
} else if (NAMED[text.toLowerCase()]) {
[r, g, b] = NAMED[text.toLowerCase()];
} else return undefined;
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
const sat = max === 0 ? 0 : d / max;
let hue = 0;
if (d !== 0) {
if (max === r) hue = ((g - b) / d) % 6;
else if (max === g) hue = (b - r) / d + 2;
else hue = (r - g) / d + 4;
hue *= 60; if (hue < 0) hue += 360;
}
const lum = luminance({ r, g, b });
const neutral = sat < 0.18;
const harmonious = !neutral && (
(hue >= 64 && hue <= 188 && sat >= 0.22)
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|| (hue >= 40 && hue < 64 && sat <= 0.42));
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
}
function steps(base: string, count: number): string[] {
if (count <= 1) return [base];
return Array.from({ length: count }, (_, i) => {
const t = i / (count - 1);
if (t < 0.5) return mixHex(base, [0, 0, 0], (0.5 - t) * 0.5);
return mixHex(base, [255, 255, 255], (t - 0.5) * 0.22);
});
}
function mixHex(base: string, toward: [number, number, number], amount: number): string {
const item = parseColor(base)!;
const channel = (from: number, to: number) => Math.round(from + (to - from) * amount);
return '#' + [channel(item.r, toward[0]), channel(item.g, toward[1]), channel(item.b, toward[2])]
.map(v => v.toString(16).padStart(2, '0')).join('');
}
function sampleScale(t: number): string {
const stops = C2_PALETTE.scale;
const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);
const index = Math.min(stops.length - 2, Math.floor(scaled));
const item = parseColor(stops[index])!, next = parseColor(stops[index + 1])!;
return mixHex(stops[index], [next.r, next.g, next.b], scaled - index);
}
function luminance(input: { r: number; g: number; b: number } | Parsed): number {
const c = [input.r, input.g, input.b].map(v => v / 255).map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
}
function formatAs(original: Parsed, hex: string): string {
if (!original.explicitAlpha) return hex;
const item = parseColor(hex)!;
const alpha = Number(original.a.toFixed(3));
return `rgba(${item.r},${item.g},${item.b},${alpha})`;
}
export function isNeutralColor(color: string): boolean { return parseColor(color)?.kind === 'neutral'; }
export function isHarmoniousColor(color: string): boolean { return parseColor(color)?.kind === 'harmonious'; }
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function collectStrings(value: unknown, into: string[]) {
if (typeof value === 'string') into.push(value);
else if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') into.push(value[1]);
else value.forEach(item => collectStrings(item, into));
}
}
function mapColors(value: unknown, lookup: Map<string, string>): unknown {
if (typeof value === 'string') return lookup.get(value) ?? value;
if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') return [value[0], lookup.get(value[1]) ?? value[1]];
return value.map(item => mapColors(item, lookup));
}
return value;
}
function paintTrace(trace: Record<string, unknown>, lookup: Map<string, string>) {
if (record(trace['marker'])) {
const marker = { ...trace['marker'] };
if ('color' in marker) marker['color'] = mapColors(marker['color'], lookup);
if ('colors' in marker) marker['colors'] = mapColors(marker['colors'], lookup);
if (record(marker['line']) && 'color' in marker['line']) marker['line'] = { ...marker['line'], color: mapColors(marker['line']['color'], lookup) };
trace['marker'] = marker;
}
if (record(trace['line']) && 'color' in trace['line']) trace['line'] = { ...trace['line'], color: mapColors(trace['line']['color'], lookup) };
if (typeof trace['fillcolor'] === 'string') trace['fillcolor'] = lookup.get(trace['fillcolor']) ?? trace['fillcolor'];
for (const key of ['error_x', 'error_y']) {
if (record(trace[key]) && 'color' in (trace[key] as Record<string, unknown>)) {
trace[key] = { ...(trace[key] as Record<string, unknown>), color: mapColors((trace[key] as Record<string, unknown>)['color'], lookup) };
}
}
if (Array.isArray(trace['colorscale'])) trace['colorscale'] = sequentialScale(trace['colorscale']);
}
function sequentialScale(stops: unknown[]): unknown[] {
return stops.map(stop => {
if (!Array.isArray(stop) || typeof stop[0] !== 'number' || typeof stop[1] !== 'string') return stop;
return [stop[0], sampleScale(stop[0])];
});
}
function scalePending(figure: PlotlyFigure): boolean {
return traceList(figure).some(trace => Array.isArray(trace['colorscale'])
&& JSON.stringify(sequentialScale(trace['colorscale'] as unknown[])) !== JSON.stringify(trace['colorscale']));
}
function traceList(host: { data?: unknown; frames?: unknown }): Record<string, unknown>[] {
const traces = Array.isArray(host.data) ? host.data.filter(record) : [];
if (Array.isArray(host.frames)) {
for (const frame of host.frames) {
if (record(frame) && Array.isArray(frame['data'])) traces.push(...frame['data'].filter(record));
}
}
return traces;
}
function gather(figure: PlotlyFigure): string[] {
const found: string[] = [];
for (const trace of traceList(figure)) {
const marker = record(trace['marker']) ? trace['marker'] : undefined;
collectStrings(marker?.['color'], found); collectStrings(marker?.['colors'], found);
collectStrings(record(marker?.['line']) ? marker['line']['color'] : undefined, found);
collectStrings(record(trace['line']) ? trace['line']['color'] : undefined, found);
collectStrings(trace['fillcolor'], found);
collectStrings(record(trace['error_x']) ? trace['error_x']['color'] : undefined, found);
collectStrings(record(trace['error_y']) ? trace['error_y']['color'] : undefined, found);
}
if (Array.isArray(figure.layout['colorway'])) collectStrings(figure.layout['colorway'], found);
return found;
}
/** Data ink of a published figure, without touching text, grid or background. */
export function recolorFigure<T extends PlotlyFigure>(figure: T): T {
const collected = gather(figure);
const painted = institutionalize(collected);
if (painted.every((color, i) => color === collected[i]) && !scalePending(figure)) return figure;
const lookup = new Map(collected.map((color, i) => [color, painted[i]]));
const copy = structuredClone(figure);
for (const trace of traceList(copy)) paintTrace(trace, lookup);
if (Array.isArray(copy.layout['colorway'])) copy.layout['colorway'] = mapColors(copy.layout['colorway'], lookup);
return copy;
return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length];
}
@@ -138,8 +138,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
expect(titulos.filter(([t]) => ['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
expect(titulos.filter(([t]) => ['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
.toEqual([['Resultado histopatológico por categoría BI-RADS', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]);
expect(graficas()).toHaveLength(3);
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]);
});
@@ -1,310 +0,0 @@
// What this module covers: CaMa's eight FHIR measures as the page reads them: their ids, catalog entries, category
// metadata, the rows of each contract (C1, C2, C3r) and what the summary's cards and figures make of them, for periods
// with data and for periods that legitimately have none.
// Fixtures (`fixtures/cama_fhir_*.json`): `reportes` are real `GET /cama/fhir/MeasureReport` answers of the local
// installation, cut to three semesters (2021-S1 without units, 2024-S2 and 2025-S2 with them) and two months;
// `measures` is the Measure bundle the WebApi serves from the current dbt definitions; `measures_instalada` is the one
// the installation served before the category metadata existed.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import { cajaDeDatos, categorias, datosDeReportes, FhirIndicadoresService, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { modelosConteos, parConteos, totalExamenes } from './indicadores-conteos-pareados';
import { CAMA_CONFIRMACION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import measuresData from './fixtures/cama_fhir_measures.json';
import installedData from './fixtures/cama_fhir_measures_instalada.json';
import reportsData from './fixtures/cama_fhir_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const installed = resources(installedData as unknown as Bundle, 'Measure') as Measure[];
const answers = reportsData.reports as unknown as Record<string, { semestre: Bundle; mes?: Bundle }>;
const measure = (fhirId: string, from = measures) => from.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start: string) =>
(resources(answers[fhirId][tipo]!, 'MeasureReport') as Report[]).filter(r => r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', from = measures): IndicadorDatos {
return datosValidos(datosDeReportes(measure(fhirId, from), reportsOf(fhirId, tipo, start), tipo), indicadorId(fhirId), tipo, [periodo]);
}
const SEMESTRE_VACIO = ['2021-01-01', '2021-S1'] as const;
const SEMESTRE_CON_DATOS = ['2025-07-01', '2025-S2'] as const;
describe('Identificadores de CaMa entre FHIR y la página', () => {
it('cada Measure publicada tiene un id de la página y ninguno se repite', () => {
// Pins down: the explicit table covers the eight measures the WebApi publishes and the page ids stay unique
// (`BIRADS456` is `birads_456`, which no rule derives). Fails if a measure is published without a
// correspondence, or two measures collapse into one page id.
const ids = measures.map(m => indicadorId(m.id!));
expect(ids.sort()).toEqual(['cama_biopsias', 'cama_birads', 'cama_birads_456_mastografia', 'cama_birads_456_paciente',
'cama_birads_cancer_invasor', 'cama_confirmacion_birads45', 'cama_dias_resultado_diagnostico', 'cama_dias_toma_diagnostico',
'cama_eu38a', 'cama_histopatologia_birads', 'cama_tasa_deteccion_histopatologica']);
expect(new Set(ids).size).toBe(measures.length);
expect(measures.every(m => Object.hasOwn(CAMA_MEASURE_IDS, m.id!))).toBe(true);
});
it('el id de una medida de otro dominio sigue la regla general', () => {
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
// ids of other domains or the generic rule changes.
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
});
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
// Pins down: the contract, the figures and the period types each CaMa measure publishes: a distribution offers
// the donut and the bars, a duration its box plot, a proportion none (its history is drawn from the data rows).
// Fails if the dbt definitions stop declaring them or the mapper drops them.
const catalog = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalog['cama_birads_456_paciente']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'], estratos: [] });
expect(catalog['cama_biopsias']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'] });
expect(catalog['cama_confirmacion_birads45']).toMatchObject({ contrato: 'C1', figuras: [], sentido: 'mayor_mejor' });
expect(catalog['cama_eu38a']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalog['cama_dias_toma_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'] });
expect(catalog['cama_birads_cancer_invasor']).toMatchObject({ contrato: 'C2', estratos: ['grupo_edad', 'estadio', 'etapa', 'clasificacion', 'tamano'] });
});
});
describe('Ficha técnica de CaMa', () => {
it('cada medida tiene su propio código y sus poblaciones con la métrica que las cuenta', () => {
// Pins down: the sheet's code is the measure's name without the domain (not `CAMA` for all eight) and each
// population names the dbt metric that counts it. Fails if the sheets of different measures read alike.
const codes = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codes).size).toBe(measures.length);
expect(metadatosDeMeasure(measure('CAMA-EU38A')).ficha!.codigo).toBe('EU38A');
expect(metadatosDeMeasure(measure('CAMA-BIRADS456-PACIENTE')).ficha!.codigo).toBe('BIRADS456-PACIENTE');
expect(metadatosDeMeasure(measure('CAMA-CONFIRMACION-BIRADS45')).poblaciones!.map(p => p.grupo)).toEqual(['poblacion', 'denominador', 'numerador']);
});
});
describe('Categorías de las composiciones de CaMa', () => {
it('BI-RADS 4 a 6 declara solo sus subcategorías y BI-RADS completo añade «Sin dato»', () => {
// Pins down: the labels and colours come from the Measure's extensions, in the order of the catalog, and the
// exams' and patients' measures declare the same categories. Fails if the dbt labels drift or one measure loses them.
expect(Object.keys(categorias(measure('CAMA-BIRADS456-PACIENTE')))).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6']);
expect(categorias(measure('CAMA-BIRADS456-MASTOGRAFIA'))).toEqual(categorias(measure('CAMA-BIRADS456-PACIENTE')));
expect(Object.keys(categorias(measure('CAMA-BIRADS')))).toEqual(['B0', 'B1', 'B2', 'B3', 'B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO']);
expect(categorias(measure('CAMA-BIRADS'))['B5']).toEqual({ etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null });
expect(Object.keys(categorias(measure('CAMA-BIOPSIAS')))).toEqual(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'SIN_DATO']);
});
it('un BI-RADS 4 sin subcategoría se muestra después de las categorías declaradas y no se pierde', () => {
// Pins down: the real 2025-S2 report counts patients in `B4`, which no Measure declares. The rows add it after the
// declared categories under the Core catalog's caption, and the total is still the report's units. Fails if
// undeclared categories are dropped (the card would show fewer patients than the report counts).
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6', 'B4']);
expect((periodo['categorias'] as Record<string, { etiqueta: string }>)['B4'].etiqueta).toBe('BI-RADS 4 (sin subcategoría)');
const total = periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total).toBe(36);
expect(periodo.filas.map(row => [row['categoria'], row['orden']])).toEqual([['B4A', 0], ['B4B', 1], ['B4C', 2], ['B5', 3], ['B6', 4], ['B4', 5]]);
});
it('una Measure sin metadatos de categoría deja ver las categorías con su código, sin perder unidades', () => {
// Pins down: against the Measure the installation served before the labels existed (no category extensions),
// every counted category is still listed (by its code) and the figure still draws the whole partition. Fails if a
// Measure without metadata makes the distribution empty or undercounts it.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS, 'semestre', installed);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4', 'B5', 'B6']);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(36);
});
});
describe('Composiciones (C2): BI-RADS y biopsias', () => {
it.each(['CAMA-BIRADS456-PACIENTE', 'CAMA-BIRADS456-MASTOGRAFIA', 'CAMA-BIRADS', 'CAMA-BIOPSIAS'])('%s se dibuja como dona y como barras con el total de sus unidades', fhirId => {
// Pins down: for a period with units, both published figures are supported and the total equals the report's
// `initial-population`. Fails if a category, a label or the unit total is lost between the report and the figure.
const periodo = datos(fhirId, ...SEMESTRE_CON_DATOS);
const units = reportsOf(fhirId, 'semestre', SEMESTRE_CON_DATOS[0])[0].group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const result = c2Figure(periodo, { dominio: 'cama', indicador: indicadorId(fhirId), figura, tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(`${fhirId} ${figura}: ${result.reason}`);
expect(result.model.total).toBe(units);
expect(result.model.total).toBeGreaterThan(0);
}
});
it('todas las composiciones de CaMa de los reportes reales suman las unidades de su periodo', () => {
// Pins down: for every C2 measure and every real period in the fixtures (semesters and months), the categories the
// mapper lists add up to the report's units, so none is dropped. Fails if a report counts a category the rows lose.
// The three measures of L3 have their own fixture (`indicadores-cama-l3.spec.ts`).
for (const m of measures.filter(item => indicadorDeMeasure(item).contrato === 'C2' && Object.hasOwn(answers, item.id!))) {
for (const tipo of ['semestre', 'mes'] as const) {
const bundle = answers[m.id!][tipo];
if (!bundle) continue;
const reports = resources(bundle, 'MeasureReport') as Report[];
const rows = datosDeReportes(m, reports, tipo).filas;
for (const report of reports) {
const units = report.group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
const label = report.period!.start;
const total = rows.filter(row => row['periodo'] === (tipo === 'mes' ? label.slice(0, 7) : label.slice(0, 4) + (label.slice(5, 7) < '07' ? '-S1' : '-S2'))).reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total, `${m.id} ${label}`).toBe(units);
}
}
}
});
it('un periodo sin unidades da una distribución vacía, no un error', () => {
// Pins down: a semester without mammograms (legitimate absence of data) is a supported figure with the
// «conteos en cero» message and every category at zero. Fails if an empty period turns into an unsupported figure.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_VACIO);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2021-S1'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(0);
expect(result.emptyMessage).toContain('cero');
expect(periodo.filas.every(row => row['n'] === 0)).toBe(true);
});
it('la tarjeta de pacientes BI-RADS 4, 5 y 6 suma las categorías del periodo', () => {
// Pins down: the opportunity card reads the patients' distribution: its value is the sum of the categories
// (including the undeclared B4) and the card says «Disponible». Fails if the card still sees the catalog without B4.
const result = kpiResult(datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS), KPI_BY_DOMAIN.cama[0], 'cama', apply('2025-S2'));
expect(result).toMatchObject({ state: 'Disponible', value: 36 });
expect(Object.values(result.categorias!).reduce((a, b) => a + b, 0)).toBe(36);
});
it('un mes con datos se lee igual que un semestre', () => {
// Pins down: the monthly search answers by `periodo` labels like `2025-12`, and the rows carry that label. Fails
// if the month's period is read as a semester or the categories are lost.
const periodo = datos('CAMA-BIRADS456-PACIENTE', '2025-12-01', '2025-12', 'mes');
expect(periodo.tipo_periodo).toBe('mes');
expect(periodo.periodos).toEqual(['2025-12']);
expect(periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0)).toBeGreaterThan(0);
});
it('las biopsias suman por grado histológico con los rótulos del catálogo', () => {
// Pins down: the grades arrive as `BENIGNO`, `CARCINOMA_IN_SITU` and `CARCINOMA_INVASOR` and are drawn with the
// catalog's captions. Fails if a grade loses its caption or is merged into another.
const periodo = datos('CAMA-BIOPSIAS', ...SEMESTRE_CON_DATOS);
const labels = Object.fromEntries(Object.entries(periodo['categorias'] as Record<string, { etiqueta: string }>).map(([k, v]) => [k, v.etiqueta]));
expect(labels).toEqual({ BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', SIN_DATO: 'Sin dato' });
expect(Object.fromEntries(periodo.filas.map(row => [row['categoria'], row['n']]))).toEqual({ BENIGNO: 11, CARCINOMA_IN_SITU: 1, CARCINOMA_INVASOR: 13, SIN_DATO: 0 });
});
});
describe('Proporción (C1): confirmación histopatológica', () => {
it('el grupo principal llega a la página como `total` con numerador, denominador y porcentaje', () => {
// Pins down: the WebApi's `principal` group is the page's `total`, and the score becomes a percentage next to
// its numerator and denominator. Fails if the group keeps its FHIR name (the card would find no rows).
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_CON_DATOS);
expect(periodo['grupos']).toEqual({ total: 'Total' });
expect(periodo.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador: 28, denominador: 37, valor: 75.7, suprimido: 0 })]);
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: '75.7',
info: '28 de 37 mastografías BI-RADS 4 y 5 con reporte de biopsia.' });
});
it('un periodo sin mastografías de sospecha no muestra un porcentaje', () => {
// Pins down: denominator zero and no score is «Sin valor disponible», never 0 %. Fails if an empty period is
// drawn as a measured zero.
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 0, valor: null });
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
});
describe('Duraciones (C3r): tiempos de CaMa', () => {
it('toma a resultado da mediana, cuartiles y número de mastografías', () => {
// Pins down: median 8 days with Q1 4 and Q3 12 over 101 mammograms for 2025-S2, and the card shows them. Fails if the
// quartiles or the observation count stop coming from the report's extensions and populations.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ grupo: 'TOTAL', n: 101, mediana: 8, q1: 4, q3: 12, n_sin_evento: 0, unidad: 'dias' });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 8,
info: '101 mastografías; Q1 a Q3: 4 a 12 días.' });
});
it('tamizaje a diagnóstico separa las mastografías medidas de las que no tienen diagnóstico', () => {
// Pins down: 55 measured and 43 without a diagnosis by the cut-off (FHIR's population exclusion), median 60 days.
// Fails if the unmeasured units are counted as observations or lost.
const periodo = datos('CAMA-DIAS-TOMA-DIAGNOSTICO', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ n: 55, n_sin_evento: 43, mediana: 60, q1: 41.5, q3: 131.5 });
expect(kpiResult(periodo, CAMA_TOMA_DIAGNOSTICO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 60 });
});
it('un periodo sin mastografías no tiene mediana', () => {
// Pins down: zero observations and no score is «Sin valor disponible», not a median of 0 days. Fails if an empty
// period is shown as an instant result.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ n: 0, mediana: null });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
it('la caja de cuartiles se dibuja con los semestres que tienen mediana', () => {
// Pins down: the box plot keeps the periods with a median and leaves out the empty one. Fails if an empty
// period becomes a box at zero.
const reports = ['2021-01-01', '2024-07-01', '2025-07-01'].flatMap(start => reportsOf('CAMA-EU38A', 'semestre', start));
const figure = cajaDeDatos(datosValidos(datosDeReportes(measure('CAMA-EU38A'), reports, 'semestre'), 'cama_eu38a', 'semestre'));
expect((figure.data[0] as Record<string, unknown>)['x']).toEqual(['2024-S2', '2025-S2']);
expect((figure.data[0] as Record<string, unknown>)['median']).toEqual([7.5, 8]);
});
});
describe('Servicio FHIR sobre CaMa', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide por el id de la página y consulta la medida por su canónico', async () => {
// Pins down: the page asks for `cama_birads_456_paciente` and the WebApi receives the canonical of
// `CAMA-BIRADS456-PACIENTE` with the periods asked for. Fails if the page id is sent as the measure or the table is bypassed.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('cama', 'cama_birads_456_paciente', 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
const request = http.expectOne(r => r.url === '/cama/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE');
expect(request.request.params.get('periodo')).toBe('2025-S2');
request.flush({ ...answers['CAMA-BIRADS456-PACIENTE'].semestre, entry: reportsOf('CAMA-BIRADS456-PACIENTE', 'semestre', '2025-07-01').map(resource => ({ resource })) });
expect((await answer).id).toBe('cama_birads_456_paciente');
});
it('el catálogo de CaMa publica los ocho ids de la página', async () => {
// Pins down: the catalog the page receives lists the correspondence ids, so its filters and cards find them.
// Fails if a measure reaches the page under its FHIR id.
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).catalogo('cama'));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
expect((await answer).map(item => item.id).sort()).toEqual(Object.values(CAMA_MEASURE_IDS).sort());
});
});
describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => {
const models = (examenes: IndicadorDatos, pacientes: IndicadorDatos) => modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, examenes, pacientes, 'semestre');
it('con datos reales del semestre da los conteos por categoría de ambas medidas', () => {
// Pins down: the page's pair reads the two real C2 answers (units `examen` and `paciente`, version 0.2.0 of the
// patients' measure) and gives the exams by category and the patients by BI-RADS family. Fails if an id, a unit or
// a category of either measure stops matching what the pair checks.
const [model] = models(datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS), datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS));
expect(model.pacientesVerificados).toBe(true);
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
});
it('un periodo sin BI-RADS 4 sin subcategoría cuenta cero en esa categoría y no rompe la tarjeta', () => {
// Pins down: `B4` is published only when some report counts it; a period set without it leaves the card
// working, with zero exams in that category. The reports are the real 2025-S2 ones with the `B4` stratum removed
// and the units reduced by its count. Fails if the card turns «categorías no coinciden» whenever no 4 arrives unqualified.
const without = (fhirId: string) => {
const [report] = reportsOf(fhirId, 'semestre', '2025-07-01');
const group = report.group![0];
const removed = group.stratifier![0].stratum!.find(s => s.value?.coding?.[0].code === 'B4')!.population![0].count!;
const units = group.population!.map(p => p.code?.coding?.[0].code === 'initial-population' ? { ...p, count: p.count! - removed } : p);
const stratifier = [{ ...group.stratifier![0], stratum: group.stratifier![0].stratum!.filter(s => s.value?.coding?.[0].code !== 'B4') }];
const copy = { ...report, group: [{ ...group, population: units, stratifier }] } as Report;
return datosValidos(datosDeReportes(measure(fhirId), [copy], 'semestre'), indicadorId(fhirId), 'semestre', ['2025-S2']);
};
const [model] = models(without('CAMA-BIRADS456-MASTOGRAFIA'), without('CAMA-BIRADS456-PACIENTE'));
expect(model.examenes.find(c => c.id === 'B4')!.n).toBe(0);
expect(model.filas.map(f => f.examenes)).toEqual([0, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
@@ -1,47 +0,0 @@
// How CaMa's FHIR measures map onto what the indicator page reads: the page's id of each measure, the name of a
// proportion's primary group and the categories a composition publishes beyond its declared ones.
//
// The WebApi names a measure `CAMA-BIRADS456-PACIENTE`; the page, its history and its cards use
// `cama_birads_456_paciente`. A rule can't derive one from the other (`BIRADS456` splits into `birads_456`), so the
// correspondence is explicit and a measure outside it keeps the generic rule.
export const CAMA_MEASURE_IDS: Readonly<Record<string, string>> = {
'CAMA-BIOPSIAS': 'cama_biopsias',
'CAMA-BIRADS': 'cama_birads',
'CAMA-BIRADS-CANCER-INVASOR': 'cama_birads_cancer_invasor',
'CAMA-BIRADS456-MASTOGRAFIA': 'cama_birads_456_mastografia',
'CAMA-BIRADS456-PACIENTE': 'cama_birads_456_paciente',
'CAMA-CONFIRMACION-BIRADS45': 'cama_confirmacion_birads45',
'CAMA-DIAS-RESULTADO-DIAGNOSTICO': 'cama_dias_resultado_diagnostico',
'CAMA-DIAS-TOMA-DIAGNOSTICO': 'cama_dias_toma_diagnostico',
'CAMA-EU38A': 'cama_eu38a',
'CAMA-HISTOPATOLOGIA-BIRADS': 'cama_histopatologia_birads',
'CAMA-TASA-DETECCION-HISTOPATOLOGICA': 'cama_tasa_deteccion_histopatologica',
};
export const esMedidaCama = (measureId: string | undefined): boolean =>
measureId !== undefined && Object.hasOwn(CAMA_MEASURE_IDS, measureId);
// A proportion's primary group is `principal` in the WebApi; CaMa's page names it `total`.
export const GRUPO_PRINCIPAL_PAGINA = 'total';
export const GRUPO_PRINCIPAL_FHIR = 'principal';
// A category a report counts that its Measure doesn't declare (a BI-RADS 4 without subcategory arrives as `B4`) is
// shown after the declared ones under the caption the Core catalog gives it.
export const ETIQUETA_CATEGORIA_NO_DECLARADA: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The histopathological result by BI-RADS (`CAMA-HISTOPATOLOGIA-BIRADS`) publishes the cross of two stratifiers, the
// BI-RADS of the mammogram and the grade of its biopsy, as FHIR codes (`B4A`, `CARCINOMA_IN_SITU`); the view that
// draws it reads the page's codes. The correspondence is explicit, one table per axis, so a code outside it is an error
// and never a silent zero. A grade is benign or malignant as the parameter `cama.biopsia_cancer` says; no biopsy and
// no grade belong to no group.
export const ESTRATO_BIRADS_PAGINA: Readonly<Record<string, string>> = {
B4: 'BIRADS_4', B4A: 'BIRADS_4A', B4B: 'BIRADS_4B', B4C: 'BIRADS_4C', B5: 'BIRADS_5', B6: 'BIRADS_6',
};
export const CATEGORIA_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, { id: string; grupo: string | null; gravedad: number | null }>> = {
BENIGNO: { id: 'BENIGNO', grupo: 'NO_MALIGNO', gravedad: 1 },
CARCINOMA_IN_SITU: { id: 'IN_SITU', grupo: 'MALIGNO', gravedad: 3 },
CARCINOMA_INVASOR: { id: 'INVASOR', grupo: 'MALIGNO', gravedad: 4 },
SIN_BIOPSIA: { id: 'SIN_BIOPSIA', grupo: null, gravedad: null },
SIN_DATO: { id: 'SIN_DATO', grupo: 'SIN_DATO', gravedad: null },
};
export const GRUPOS_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, string>> = { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' };
@@ -1,242 +0,0 @@
// What this module covers: the three CaMa measures of L3 as the page reads them from FHIR: the detection rate (C1), the
// time from the mammogram's result to the diagnosis (C3r) and the histopathological result by BI-RADS (C2 stratified by
// BI-RADS): their ids, catalog entries, numerators and denominators, medians, the BI-RADS by result matrix, the periods
// with no data and the reports that don't add up.
// Fixtures: `fixtures/cama_fhir_measures.json` (the Measure bundle the WebApi serves from the current dbt definitions) and
// `fixtures/cama_fhir_l3_reportes.json` (real `GET /cama/fhir/MeasureReport` answers over a read-only copy of the data of
// the 18092 installation, with L3's views applied on the copy), cut to six semesters and three months. The semesters:
// 2021-S1 (no data), 2024-S2, 2025-S1, 2025-S2, 2026-S1 and 2026-S2 (the one the cut-off cuts).
import { Bundle, resources } from './fhir';
import { datosDeReportes, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
import { ESTRATOS_BIRADS, modeloHistopatologia, periodosHistopatologia, seleccionBase, tasas } from './indicadores-histopatologia-cama';
import measuresData from './fixtures/cama_fhir_measures.json';
import l3Data from './fixtures/cama_fhir_l3_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const answers = l3Data.reports as unknown as Record<string, { semestre: Bundle; mes: Bundle }>;
const TASA = 'CAMA-TASA-DETECCION-HISTOPATOLOGICA', DIAS = 'CAMA-DIAS-RESULTADO-DIAGNOSTICO', HISTO = 'CAMA-HISTOPATOLOGIA-BIRADS';
const measure = (fhirId: string) => measures.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start?: string) =>
(resources(answers[fhirId][tipo], 'MeasureReport') as Report[]).filter(r => !start || r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', scope = {}): IndicadorDatos {
return datosDeReportes(measure(fhirId), reportsOf(fhirId, tipo, start), tipo, scope);
}
const SEMESTRES = [['2025-01-01', '2025-S1'], ['2025-07-01', '2025-S2'], ['2026-01-01', '2026-S1'], ['2026-07-01', '2026-S2']] as const;
const BIRADS_PACIENTES_2025_S2 = 36;
describe('Las tres medidas de L3 en el catálogo', () => {
it('cada una tiene su id de página, su contrato y su sentido', () => {
// Pins down: the explicit table names the three, none collides with another, and the catalog gives each its contract
// (a proportion, a duration with its box plot, a composition stratified by BI-RADS). Fails if a measure is published
// without a correspondence or its contract drifts.
expect(indicadorId(TASA)).toBe('cama_tasa_deteccion_histopatologica');
expect(indicadorId(DIAS)).toBe('cama_dias_resultado_diagnostico');
expect(indicadorId(HISTO)).toBe('cama_histopatologia_birads');
expect([TASA, DIAS, HISTO].every(id => Object.hasOwn(CAMA_MEASURE_IDS, id))).toBe(true);
const catalogo = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalogo['cama_tasa_deteccion_histopatologica']).toMatchObject({ contrato: 'C1', figuras: [], unidad: 'examen', tipos_periodo: ['semestre', 'mes'] });
expect(catalogo['cama_dias_resultado_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalogo['cama_histopatologia_birads']).toMatchObject({ contrato: 'C2', estratos: ['birads'], unidad: 'paciente' });
expect(new Set(measures.map(m => indicadorId(m.id!))).size).toBe(measures.length);
});
it('la ficha de cada una dice qué cuenta y qué no es', () => {
// Pins down: the description is the measure's definition: the detection rate is of biopsy reports and says it is not a
// rate over screened women nor the confirmation proportion; the time says its note isn't linked to the mammogram nor is
// the biopsy's date. Fails if the sheet is lost or reads like another indicator.
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/reporte de biopsia, no la\s+paciente/);
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/no es una tasa\s+sobre las mujeres tamizadas/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no está ligada a la mastografía/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no es la fecha de la biopsia/);
expect(metadatosDeMeasure(measure(HISTO)).descripcion).toMatch(/la misma regla de CAMA_BIRADS456_PACIENTE/);
const codigos = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codigos).size).toBe(measures.length);
expect(metadatosDeMeasure(measure(TASA)).ficha!.codigo).toBe('TASA-DETECCION-HISTOPATOLOGICA');
});
});
describe('Tasa de detección histopatológica (C1)', () => {
it.each([['2025-01-01', '2025-S1', 16, 24, 66.7], ['2025-07-01', '2025-S2', 14, 25, 56], ['2026-01-01', '2026-S1', 13, 18, 72.2], ['2026-07-01', '2026-S2', 10, 19, 52.6]] as const)(
'en %s el numerador y el denominador son los reportes de biopsia malignos y con resultado conocido', (inicio, periodo, numerador, denominador, valor) => {
// Pins down: each semester's rows carry the report counts (malignant over known result) and the percentage the card
// shows, in the page's group `total`, and the card reads «Disponible» with its sentence. Fails if a count is lost or
// the numerator leaves its denominator.
const d = datosValidos(datos(TASA, inicio, periodo), 'cama_tasa_deteccion_histopatologica', 'semestre', [periodo]);
expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
});
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
// Pins down: over the real periods, malignant ≤ known result, and the four semesters add up to 56 + ... = the reports
// (16+14+13+10 malignant of 24+25+18+19 with known result). Fails if a report is counted in two periods or one is dropped.
const filas = SEMESTRES.flatMap(([inicio, periodo]) => datos(TASA, inicio, periodo).filas);
expect(filas.every(f => (f['numerador'] as number) <= (f['denominador'] as number))).toBe(true);
expect(filas.reduce((s, f) => s + (f['numerador'] as number), 0)).toBe(53);
expect(filas.reduce((s, f) => s + (f['denominador'] as number), 0)).toBe(86);
});
it('un semestre sin reportes de biopsia no da una tasa: 0 de 0 es sin datos, no 0 %', () => {
// Pins down: 2021-S1 has no biopsy reports; the rows say 0 of 0 with no value and the card doesn't claim a rate.
// Fails if an empty period is shown as 0 % or as an error.
const d = datos(TASA, '2021-01-01', '2021-S1');
expect(d.filas).toEqual([expect.objectContaining({ numerador: 0, denominador: 0, valor: null })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Tiempo de resultado a diagnóstico (C3r)', () => {
it.each([['2025-01-01', '2025-S1', 56, 41, 65], ['2025-07-01', '2025-S2', 59, 41, 49], ['2026-01-01', '2026-S1', 61, 21, 58], ['2026-07-01', '2026-S2', 18, 0, 40]] as const)(
'en %s mide las mastografías con nota diagnóstica y deja fuera, contadas, las que no la tienen', (inicio, periodo, n, sinEvento, mediana) => {
// Pins down: the observations (mammograms with a diagnosing note in the horizon), those without one and the median in
// days, as the report publishes them, with the card reading the median. Fails if an unmeasured mammogram is dropped
// without being counted or a median is read as zero.
const d = datosValidos(datos(DIAS, inicio, periodo), 'cama_dias_resultado_diagnostico', 'semestre', [periodo]);
expect(d.filas).toEqual([expect.objectContaining({ n, mediana, n_sin_evento: sinEvento, unidad: 'dias' })]);
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(periodo))).toMatchObject({ state: 'Disponible', value: mediana });
});
it('las mastografías del periodo son las observadas más las que no tienen nota', () => {
// Pins down: initial population = observations + exclusions in every real semester, so no mammogram is lost between
// the population and the box plot. Fails if the report's counts don't close.
for (const [inicio] of SEMESTRES) {
const grupo = reportsOf(DIAS, 'semestre', inicio)[0].group![0];
const n = (c: string) => grupo.population!.find(p => p.code?.coding?.[0].code === c)!.count!;
expect(n('measure-observation') + n('measure-population-exclusion'), inicio).toBe(n('initial-population'));
}
});
it('un semestre sin mastografías no da una mediana', () => {
// Pins down: with no observations the card has no value (a median over zero observations is no value, not zero days).
// Fails if an empty period reads as 0 days.
const d = datos(DIAS, '2021-01-01', '2021-S1');
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Resultado histopatológico por categoría BI-RADS (C2 por BI-RADS)', () => {
const matriz = (inicio: string, periodo: string, tipo: TipoPeriodo = 'semestre') =>
modeloHistopatologia(datosValidos(datos(HISTO, inicio, periodo, tipo, { estrato: 'birads' }), 'cama_histopatologia_birads', tipo, [periodo], { estrato: 'birads' }), periodo);
const celdas = (m: ReturnType<typeof matriz>) => Object.fromEntries(m.filas.map(f => [f.id,
{ ...Object.fromEntries(Object.entries(f.celdas).map(([k, c]) => [k, c.n])), ...Object.fromEntries(Object.entries(f.aparte).map(([k, c]) => [k, c.n])), total: f.total.n }]));
it('2025-S1: la matriz BI-RADS por resultado es la del reporte, con ceros publicados en las categorías sin pacientes', () => {
// Pins down: the cells of the real report (BI-RADS 4: 8 benign, 6 invasive, 6 without biopsy; BI-RADS 5: 6 invasive, 1 in
// situ, 3 without biopsy), every other stratum a published zero (never «No disponible»), each stratum's total the sum of
// its cells and the matrix the 30 patients of the period. Fails if a cell moves, a zero turns unavailable or a total drifts.
const m = matriz('2025-01-01', '2025-S1');
expect(m.filas.map(f => f.id)).toEqual([...ESTRATOS_BIRADS]);
expect(celdas(m)).toEqual({
BIRADS_4: { BENIGNO: 8, IN_SITU: 0, INVASOR: 6, SIN_BIOPSIA: 6, SIN_DATO: 0, total: 20 },
BIRADS_4A: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4B: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4C: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_5: { BENIGNO: 0, IN_SITU: 1, INVASOR: 6, SIN_BIOPSIA: 3, SIN_DATO: 0, total: 10 },
BIRADS_6: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
});
expect(m.filas.every(f => Object.values(f.celdas).every(c => c.estado === 'Publicado'))).toBe(true);
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(30);
expect(m.conResultado).toBe(21);
});
it('la lesión de riesgo (B3) no se inventa: no hay esa categoría en las fuentes y la matriz no la dibuja', () => {
// Pins down: the source grades are benign, in situ and invasive; the page's optional «Lesión de riesgo (B3)» isn't
// published, so the model lists three categories and two groups (non malignant, malignant). Fails if a category the
// source lacks appears, or the model needs it.
const m = matriz('2025-01-01', '2025-S1');
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'IN_SITU', 'INVASOR']);
expect(m.categorias.map(c => c.etiqueta)).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor']);
expect(m.grupos.map(g => [g.id, g.categorias])).toEqual([['NO_MALIGNO', ['BENIGNO']], ['MALIGNO', ['IN_SITU', 'INVASOR']]]);
expect(m.aparte.map(a => a.id)).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
});
it('las tasas por categoría usan solo a las pacientes con resultado de biopsia y llevan su intervalo', () => {
// Pins down: for the malignant group the rate of BI-RADS 4 is 6 of 14 and BI-RADS 5 is 7 of 7 (no biopsy and no data
// never enter the denominator), and a stratum with no patients has no rate. Fails if «sin biopsia» enters a denominator.
const m = matriz('2025-01-01', '2025-S1');
const t = Object.fromEntries(tasas(m, seleccionBase(m)).map(x => [x.fila.id, x]));
expect([t['BIRADS_4'].k, t['BIRADS_4'].fila.den]).toEqual([6, 14]);
expect([t['BIRADS_5'].k, t['BIRADS_5'].fila.den]).toEqual([7, 7]);
expect(t['BIRADS_5'].valor).toBe(100);
expect(t['BIRADS_4'].bajo).toBeLessThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_4'].alto).toBeGreaterThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_6'].valor).toBeNull();
});
it('el total de la matriz de cada semestre es el de pacientes BI-RADS 4, 5 y 6 del periodo', () => {
// Pins down: the matrix counts the same patients as CAMA_BIRADS456_PACIENTE (36 in 2025-S2, the report of the earlier
// fixture), and in every real semester the units of the report are the matrix's cells. Fails if the two measures count
// different patients.
const total = (inicio: string, periodo: string) => matriz(inicio, periodo).filas.reduce((s, f) => s + f.total.n!, 0);
expect(total('2025-07-01', '2025-S2')).toBe(BIRADS_PACIENTES_2025_S2);
for (const [inicio, periodo] of SEMESTRES) {
expect(total(inicio, periodo), periodo).toBe(reportsOf(HISTO, 'semestre', inicio)[0].group![0].population![0].count);
}
});
it('un semestre sin pacientes es una matriz de ceros publicados, no un error', () => {
// Pins down: 2021-S1 has no mammograms: the matrix is complete with zeros and the denominators are zero (no rate).
// Fails if an empty period breaks the view or turns into «No disponible».
const m = matriz('2021-01-01', '2021-S1');
expect(m.filas.every(f => f.total.n === 0 && f.den === 0)).toBe(true);
expect(m.conResultado).toBe(0);
});
it('un mes con pacientes se lee igual que un semestre', () => {
// Pins down: the monthly answer carries the month label and the same matrix shape. Fails if the month is read as a semester.
const m = matriz('2025-12-01', '2025-12', 'mes');
expect(m.periodo).toBe('2025-12');
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(8);
});
it('el catálogo de categorías sale de la Measure y los códigos desconocidos son un error, no ceros', () => {
// Pins down: an unknown BI-RADS or grade code in a report, or cells that don't add up to the units, throw instead of
// being read as zero. Fails if the adapter hides an inconsistent report.
const clon = (): Report[] => structuredClone(reportsOf(HISTO, 'semestre', '2025-01-01'));
const conCodigo = clon();
conCodigo[0].group![0].stratifier![1]['stratum']![0].component![0].value!.coding![0].code = 'B9';
expect(() => datosDeReportes(measure(HISTO), conCodigo, 'semestre', { estrato: 'birads' })).toThrow(/no reconocido/);
const desajustado = clon();
desajustado[0].group![0].stratifier![1]['stratum']![0].population![0].count! += 1;
expect(() => datosDeReportes(measure(HISTO), desajustado, 'semestre', { estrato: 'birads' })).toThrow(/no suman/);
const sinCruce = clon();
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
expect(() => datosDeReportes(measure(HISTO), sinCruce, 'semestre', { estrato: 'birads' })).toThrow(/no admitida/);
});
it('sin pedir el estrato, la medida se lee como una distribución por resultado y suma las mismas pacientes', () => {
// Pins down: asked without the stratum the measure is a plain C2 (categories of the biopsy result); its categories add
// to the report's units. Fails if the stratified reading changes the plain one.
const d = datos(HISTO, '2025-01-01', '2025-S1');
expect(d.filas.reduce((s, f) => s + (f['n'] as number), 0)).toBe(30);
expect(periodosHistopatologia(datos(HISTO, '2025-01-01', '2025-S1', 'semestre', { estrato: 'birads' }), 'semestre')).toEqual(['2025-S1']);
});
});
describe('Resumen e Histórico leen lo mismo', () => {
type Traza = { name?: string; x: (string | null)[]; y: (number | null)[] };
const serie = (d: IndicadorDatos, nombre: string): Traza =>
((historicoFigura(d, 'claro').figure as unknown as { data: Traza[] }).data).find(t => t.name === nombre)!;
it.each([[TASA, 'Porcentaje', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(p)).value)],
[DIAS, 'Mediana', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(p)).value)]] as const)(
'%s: el valor de la tarjeta de cada semestre es el punto del Histórico en ese semestre', (fhirId, nombre, tarjeta) => {
// Pins down: the card of one semester and the history of all of them are built from the same reports, so the number on the
// card is the point of the series for that period. Fails if the two screens compute the figure differently.
const historico = datosDeReportes(measure(fhirId), SEMESTRES.map(([inicio]) => reportsOf(fhirId, 'semestre', inicio)[0]), 'semestre');
const traza = serie(historico, nombre);
for (const [inicio, periodo] of SEMESTRES) {
const i = traza.x.indexOf(etiquetaPeriodo(periodo));
expect(i, periodo).toBeGreaterThanOrEqual(0);
expect(traza.y[i], periodo).toBe(tarjeta(datos(fhirId, inicio, periodo), periodo));
}
});
});
@@ -1,151 +0,0 @@
// What this module covers: CaMa's follow-up as the WebApi's cohort endpoint answers it (`GET /cama/seguimiento`):
// the answer's validation and labels, the table the page draws from it, its states, the record of one patient and the
// rows of a file. Nothing here is a status, a priority or a figure the data doesn't hold.
// Fixtures (`fixtures/cama_seguimiento_cohorte_real*.json`): answers of the endpoint over the local installation's
// synthetic CaMa data: `_inicial` (default: today, three months), `_consulta` (six months, BI-RADS 5), the whole cohort
// at 2026-11-16 and the 403 body of a group of fewer than five patients.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ComponentFixture } from '@angular/core/testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { consultaAplicada, contextoDe, seguimientoTablaResponse, SeguimientoTablaQuery } from './seguimiento-tabla.service';
import { identidadesDe } from './paciente-identidad';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { flatTable } from './export/tracking-export-table';
import inicialData from './fixtures/cama_seguimiento_cohorte_real_inicial.json';
import consultaData from './fixtures/cama_seguimiento_cohorte_real_consulta.json';
import cohorteData from './fixtures/cama_seguimiento_cohorte_real.json';
import pequenoData from './fixtures/cama_seguimiento_cohorte_real_403.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
describe('Seguimiento de CaMa sobre la cohorte del servidor', () => {
it('la respuesta cumple el contrato, nombra la cohorte y rotula los códigos sin cambiar los valores enviados', () => {
// Pins down: the answer is accepted as is (every row names its patient by `pac_id`, a decimal text), the cohort
// context is read from it, and codes read as the clinic writes them while the code stays in `<clave>_codigo`.
// Fails if the endpoint's shape stops passing the client's validation, or a label replaces a code the requests send.
const respuesta = seguimientoTablaResponse(copia(cohorteData));
expect(respuesta.items).toHaveLength(61);
expect(identidadesDe(respuesta.items)!.every(i => i.campo === 'pac_id' && /^[1-9][0-9]*$/.test(i.id))).toBe(true);
expect(contextoDe(respuesta)).toEqual({ cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: expect.stringMatching(/^[0-9a-f]{64}$/) });
const fila = respuesta.items.find(i => i['birads_codigo'] === 'BIRADS_4')!;
expect(fila['birads']).toBe('BI-RADS 4');
expect(respuesta.filtros_disponibles.find(f => f.clave === 'birads')!.opciones.map(o => [o.codigo, o.etiqueta]))
.toContainEqual(['BIRADS_4A', 'BI-RADS 4A']);
expect(respuesta.filtros_disponibles.find(f => f.clave === 'grupo_edad')!.opciones.map(o => o.etiqueta))
.toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']);
expect(respuesta.columnas.map(c => c.clave)).toEqual(['pac_id', 'grupo_edad', 'birads', 'biopsia']);
});
it('una página o un archivo solo se acepta si es de la consulta, la cohorte y la revisión que se pidieron', () => {
// Pins down: the answer must repeat the window, filters and context asked for. Fails if rows of another revision
// or another selection could be shown under the title of this one.
const respuesta = seguimientoTablaResponse(copia(consultaData));
const contexto = contextoDe(respuesta)!;
const pedido: SeguimientoTablaQuery = { corte: respuesta.corte, meses: 6, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto };
expect(consultaAplicada(pedido, respuesta)).toBe(true);
expect(consultaAplicada({ ...pedido, contexto: { ...contexto, revision: 'otra' } }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, filtros: {} }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, meses: 3 }, respuesta)).toBe(false);
});
it('la ficha de una paciente muestra lo que trae la fila y deja sin dato estatus, prioridad y días', () => {
// Pins down: the record reads BI-RADS, its date, the age group and the biopsy from the row, and what the list
// doesn't carry stays `null` (shown as «No disponible»), never a value made up. Fails if the summary fills
// status, priority or the days to diagnosis from anywhere.
const r = seguimientoTablaResponse(copia(cohorteData));
const conBiopsia = r.items.find(i => i['biopsia'] !== null)!, sinBiopsia = r.items.find(i => i['biopsia'] === null)!;
const resumen = toCamaPatientSummary(conBiopsia, r.corte, r.columnas)!;
expect(resumen).toMatchObject({ patientId: String(conBiopsia['pac_id']), idField: 'pac_id', cutoff: r.corte, status: null, priority: null,
daysMammographyToDiagnosis: null, birads: conBiopsia['birads'], biopsyDate: conBiopsia['biopsia_fecha'] });
expect(resumen.biopsyDateLabel).toBe('Fecha de reporte');
expect(toCamaPatientSummary(sinBiopsia, r.corte, r.columnas)).toMatchObject({ histopathology: null, biopsyDate: null });
});
it('el archivo lleva las columnas del servidor, sin estatus, prioridad ni días de diagnóstico', () => {
// Pins down: the file's columns are the announced ones (with their date details) and no other, and a missing biopsy
// is `null`. Fails if the files add a column the cohort doesn't have.
const r = seguimientoTablaResponse(copia(cohorteData));
const tabla = flatTable({ corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items });
expect(tabla.columns.map(c => c.label)).toEqual(['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Última mastografía: Fecha',
'Resultado histopatológico', 'Resultado histopatológico: Fecha de reporte']);
expect(tabla.rows).toHaveLength(61);
expect(tabla.rows.some(fila => fila[4] === null && fila[5] === null)).toBe(true);
});
});
describe('Seguimiento de CaMa (tabla) con las respuestas del servidor', () => {
let fixture: ComponentFixture<IndicadoresSeguimientoTabla>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes]
.filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' ')));
const elegir = (etiqueta: string, valor: string) => {
const s = campo(etiqueta).querySelector('select')!;
s.value = [...s.options].find(o => o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change'));
};
it('la primera consulta pide la ventana de 3 meses y dibuja las cuatro columnas de la cohorte con los datos que hay', async () => {
// Pins down: the table has the cohort's four columns and no status, priority or days; the first request is three
// months, page one of 50, with no cut-off (the server's today); a patient without biopsy reads «No disponible».
// Fails if the table asks for or draws a column the endpoint doesn't announce.
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(inicialData); await asentar();
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(
['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Resultado histopatológico']);
expect(filas()).toHaveLength(16);
const sin = filas().find(f => f[3] === 'No disponible');
expect(sin).toBeDefined();
expect(sin![2]).toMatch(/^BI-RADS (4|4A|4B|4C|5|6) Fecha: 20\d\d-\d\d-\d\d$/);
expect(root().textContent).toContain(`Ventana consultada: ${(inicialData as any).ventana.desde} al ${(inicialData as any).ventana.hasta}.`);
});
it('el formulario ofrece los filtros que anuncia el servidor y Consultar envía el filtro elegido, el corte y la revisión que devolvió', async () => {
// Pins down: the filters are BI-RADS, age group and biopsy result as announced, and a second query sends the cut-off
// the first answer gave, with its cohort, scenario and revision, plus the chosen window and filter. Fails if the revision isn't quoted back or a filter the server doesn't announce appears
// (BRCA, stage, size, priority...).
solicitud().flush(inicialData); await asentar();
expect([...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim()))
.toEqual(['Fecha de corte', 'Ventana de meses', 'Categoría BI-RADS', 'Grupo de edad', 'Resultado de la biopsia', 'Registros por página']);
expect([...campo('Resultado de la biopsia').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
['Todos', 'Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Biopsia reportada sin resultado', 'Sin biopsia reportada']);
elegir('Ventana de meses', '6'); elegir('Categoría BI-RADS', 'BIRADS_5'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({
meses: '6', page: '1', page_size: '50', corte: (inicialData as any).corte, birads: 'BIRADS_5',
cohorte: (inicialData as any).cohorte, escenario: (inicialData as any).escenario, revision: (inicialData as any).revision });
r.flush(consultaData); await asentar();
expect(root().textContent).toContain(`Ventana consultada: ${(consultaData as any).ventana.desde} al ${(consultaData as any).ventana.hasta}.`);
expect(filas().every(f => f[2].startsWith('BI-RADS 5'))).toBe(true);
});
it('un grupo de menos de cinco pacientes se dice con su motivo y no se dibuja ninguna fila', async () => {
// Pins down: the server's 403 for a small selection is shown as a message and clears the table. Fails if rows of a
// previous selection stay on screen or the page says nothing.
solicitud().flush(inicialData); await asentar();
elegir('Categoría BI-RADS', 'BIRADS_6'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
solicitud().flush(pequenoData, { status: 403, statusText: 'Forbidden' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(filas()).toHaveLength(0);
});
it('si el servidor responde 404 en CaMa dice que la cohorte no está disponible, sin pantalla vacía', async () => {
// Pins down: an endpoint that isn't there leaves an informative state. Fails if the tab shows an empty table or an
// unhandled error.
solicitud().flush({}, { status: 404, statusText: 'Not Found' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('cohorte no está disponible');
});
});
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
@@ -69,6 +69,10 @@ function suma(celdas: Celda[]): number | null {
function estado(celdas: Celda[]): Celda['estado'] {
return 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})`;
@@ -97,21 +101,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
const c = cats[a.id];
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
});
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
});
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
const colores = paintByGroup(conColor.map(g => g.grupo));
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
const ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
const propios = grados.filter(g => g.grupo === id);
const indice = ordenGrupos.indexOf(id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
// Off-catalogue grades share the group but not its colour.
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
grados: propios.map(g => g.id) };
});
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
@@ -87,24 +87,50 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
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.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
expect(dona.layout.annotations[0].text).toBe('<b>35</b><br>mastografías');
});
});
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
const dona = () => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro') as unknown as Figura;
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
it('mantiene las etiquetas con porcentaje fuera del sector', () => {
const f = dona(), t = f.data[0];
expect(t['textinfo']).toBe('none');
expect(t['hovertemplate']).toBe('%{value}<extra></extra>');
expect(f.layout.annotations.slice(2).map(a => a['text']).sort()).toEqual([
'BI-RADS 4<br>(sin<br>subcategoría)<br>45.5 %', 'BI-RADS 5<br>54.5 %',
]);
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
// percentage or its guide line, or if the short labels or the centre total change.
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
expect(t['text'][0]).toBe('');
expect(t['text'][1]).toBe('');
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
expect(f.layout.annotations).toHaveLength(2);
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
expect(llamada['showarrow']).toBe(true);
expect(llamada['arrowhead']).toBe(0);
expect(llamada['textangle']).toBeUndefined();
});
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
const f = dona(), llamada = f.layout.annotations[1];
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
expect(llamada['xanchor']).toBe('left');
expect(llamada['ax']).toBeGreaterThan(0);
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
expect(f.layout.margin['l']).toBeLessThan(20);
expect(f.layout.showlegend).toBe(false);
expect(f.layout.annotations.slice(0, 2).map(a => a['text'])).toEqual(['<b>33</b>', 'mastografías']);
});
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
const f = dona(true);
expect(f.layout.annotations).toHaveLength(1);
expect(f.layout.showlegend).toBe(true);
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
expect(f.layout.margin['r']).toBeLessThan(20);
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
});
});
@@ -42,10 +42,10 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
// The kit publishes a 4 without subcategory as «B4», with no colour.
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The categories a response lists only when some unit falls in them: a period set without any has none, not an unknown.
const OPCIONALES: ReadonlySet<string> = new Set(Object.keys(ETIQUETA_RESPALDO));
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
const COLOR_NEUTRO = '#8A9199';
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
const LARGO_ETIQUETA_INTERIOR = 12;
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; }
@@ -82,24 +82,21 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
};
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 => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
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<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
const de = (filas: Record<string, unknown>[], cat: Record<string, unknown>, periodo: string, id: string) =>
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
return periodos.map(periodo => ({
periodo,
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: de(filasE, catExamenes, periodo, id) })),
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 => de(filasP, catPacientes, periodo, id))) : null,
examenes: sumar(g.categorias.map(id => de(filasE, catExamenes, periodo, id))),
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 ?? [])])],
@@ -107,62 +104,49 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
const ALTO_DONA = 400, MARGEN_DONA = 8;
const DIAMETRO_MAXIMO_DONA = 270;
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
/**
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
* callouts give way to a legend under the donut.
*/
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
const total = totalExamenes(m);
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
const radio = diametro / 2;
const fraccionVertical = radio / (ALTO_DONA - 2 * MARGEN_DONA);
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
const etiquetas = m.examenes.map(c => escapar(c.etiqueta));
const porcentajes = n.map(v => percentNumber(100 * v / total));
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
// so even several adjacent slivers get separate labels and their guide lines keep the same order.
let acumulado = 0;
const puntos = n.flatMap((valor, i) => {
const angulo = 2 * Math.PI * (acumulado + valor / 2) / total;
acumulado += valor;
if (!valor) return [];
const x = radio * Math.sin(angulo), y = radio * Math.cos(angulo);
return [{ i, x, y }];
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
// Each long label is a callout whose guide line ends inside its slice.
let antes = 0;
const llamadas = n.flatMap((v, i) => {
const angulo = 2 * Math.PI * (antes + v / 2) / total;
antes += v;
if (compacta || !larga(i)) return [];
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
});
const llamadas = [-1, 1].flatMap(lado => {
const columna = puntos.filter(punto => (punto.x < 0 ? -1 : 1) === lado).sort((a, b) => b.y - a.y);
return columna.map(({ i, x, y }, fila) => {
const altura = (columna.length - 1 - 2 * fila) * 24;
const texto = etiquetas[i].replace(' (sin subcategoría)', '<br>(sin<br>subcategoría)');
return {
annotation: { ...centro, xshift: lado * (radio + 10), yshift: altura,
xanchor: lado < 0 ? 'right' : 'left', align: lado < 0 ? 'right' : 'left',
font: { size: fuenteEtiqueta, color: p.text }, text: texto + '<br>' + porcentajes[i] + ' %' },
shape: { type: 'path', xref: 'paper', yref: 'paper', xsizemode: 'pixel', ysizemode: 'pixel',
xanchor: .5, yanchor: .5, line: { color: p.text, width: 1 },
path: 'M ' + Math.round(x) + ',' + Math.round(y) + ' L ' + lado * (radio + 3) + ',' + y + ' L ' + lado * (radio + 8) + ',' + altura },
};
});
});
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
hovertemplate: '%{value}<extra></extra>' }],
layout: { autosize: true, height: ALTO_DONA, showlegend: false, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_DONA, b: MARGEN_DONA, l: MARGEN_DONA, r: MARGEN_DONA },
shapes: llamadas.map(({ shape }) => shape),
annotations: [
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: par.unidades.examenes },
...llamadas.map(({ annotation }) => annotation),
] }, config: { displayModeBar: false } };
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
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((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
domain: { x: [0, 1], y: [.05, .95] },
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
}
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } from './indicadores-c2-palette';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
@@ -39,6 +39,10 @@ function estado(celdas: Celda[]): Escenario['estado'] {
return 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})`;
@@ -124,10 +128,9 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
// Missing rows remain unavailable. Catalog order is used only for the accessible
// list of missing categories; a partial distribution is never drawn as a donut.
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
const grupos = [...new Set(categorias.map(c => c.grupo))].map((id, i) => ({ id, etiqueta: nombres[id], color: groupBase(i) }));
const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
const totals = porEscenario['totales_estrato'];
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
@@ -9,13 +9,14 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import {
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, periodoIniciado,
cajaDeDatos, datosDeReportes, FhirIndicadoresPeriodos, FhirIndicadoresService, indicadorDeMeasure, Measure, metadatosDeMeasure,
periodoIniciado,
periodosDesde, Report,
} from './indicadores-fhir';
import * as fx from './indicadores-fhir.fixtures';
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
import { c2Figure } from './indicadores-c2-adapter';
import { datosValidos } from './indicadores.service';
import { datosValidos, metadatosValidos } from './indicadores.service';
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
import { IndicadorDatos } from './indicadores.models';
@@ -33,6 +34,30 @@ describe('Indicadores sobre FHIR', () => {
expect(catalog.find(i => i.id === 'M25_dias_mchat_diagnostico')).toMatchObject({ contrato: 'C3r', sentido: 'menor_mejor' });
});
it('la ficha técnica sale de las extensiones y citas de la Measure, y sin ellas de su código y descripción', () => {
// Pins down: `ficha`, `figura-detalle`, `relatedArtifact` and the populations' descriptions become the sheet,
// references, figure texts and populations the page reads; a Measure without them keeps its code, unit and
// description as the sheet. Fails if `metadatosDeMeasure` stops reading one of them or drops the fallback.
const url = 'https://isssteleon.org/fhir/StructureDefinition/';
const written: Measure = {
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', description: 'Descripción',
extension: [
{ url: url + 'ficha', extension: [{ url: 'para', valueString: 'Médico' }, { url: 'pregunta', valueString: '¿Cómo?' }, { url: 'codigo', valueString: 'EU7' }] },
{ url: url + 'figura-detalle', extension: [{ url: 'figura', valueString: 'fig_c2_donas' }, { url: 'descripcion', valueString: 'Dona' }, { url: 'como-leer', valueString: 'Uno' }, { url: 'como-leer', valueString: 'Dos' }] },
],
relatedArtifact: [{ type: 'citation', display: 'Guía europea', citation: 'indicador 7' }],
group: [{ population: [{ code: { coding: [{ code: 'initial-population' }] }, description: 'Pacientes del periodo', criteria: { expression: 'cacu_eu7' } }] }],
};
const sheet = metadatosValidos(metadatosDeMeasure(written));
expect(sheet.ficha).toEqual({ codigo: 'EU7', unidad: null, definicion: 'Descripción', para: 'Médico', pregunta: '¿Cómo?' });
expect(sheet.referencias).toEqual([{ tipo: 'citation', etiqueta: 'Guía europea', ref: 'indicador 7' }]);
expect(sheet.figuras_detalle).toEqual([{ figura: 'fig_c2_donas', descripcion: 'Dona', como_leer: ['Uno', 'Dos'] }]);
expect(sheet.poblaciones).toEqual([{ grupo: 'poblacion', codigo: 'cacu_eu7', descripcion: 'Pacientes del periodo' }]);
const bare = metadatosValidos(metadatosDeMeasure(measure('M21-diagnosticados-con-eeg')));
expect(bare.ficha?.codigo).toBe('M21');
expect(bare.referencias).toEqual([]);
expect(bare.figuras_detalle).toEqual([]);
});
it('los grupos de M30 llegan como filas por alteración y dibujan sus barras', () => {
// Pins down: a report's extra groups become one row each under the group's code, labelled by the Measure, and
// that is what `fig_c1_barras_alteracion` draws. The report is written here in the WebApi's shape (the fixtures
@@ -9,10 +9,6 @@ import {
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
import {
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
} from './indicadores-cama-fhir';
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
@@ -27,11 +23,12 @@ interface Group { code?: Concept; population?: Population[]; measureScore?: Scor
export interface Measure extends Resource {
url?: string; version?: string; name?: string; title?: string; description?: string;
scoring?: Concept; subjectCodeableConcept?: Concept; improvementNotation?: Concept; group?: Group[];
relatedArtifact?: { type?: string; display?: string; citation?: string }[];
}
export interface Report extends Resource {
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
}
interface Categoria { etiqueta: string; color: string | null; grupo: string | null; gravedad?: number | null }
interface Categoria { etiqueta: string; color: string | null; grupo: null }
const MAX_COUNT = 200;
const POPULATION_GROUP: Record<string, string> = {
@@ -39,9 +36,8 @@ const POPULATION_GROUP: Record<string, string> = {
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
};
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
@@ -89,24 +85,36 @@ export function indicadorDeMeasure(measure: Measure): Indicador & Record<string,
};
}
// TEA's measures are named by their first segment (`M21`); CaMa's share the domain's, so theirs is the rest (`BIRADS456-PACIENTE`).
const codigoDeFicha = (measureId: string) => esMedidaCama(measureId) ? measureId.slice(measureId.indexOf('-') + 1) : measureId.split('-')[0];
const FICHA_FIELDS = ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota'] as const;
// The technical sheet: the measure's `ficha` extension when it has one, and without it its code, unit and description.
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
const unidad = code(measure.subjectCodeableConcept) ?? null;
const sheet = extensions(measure, 'ficha')[0];
const written = Object.fromEntries(FICHA_FIELDS.flatMap(f => {
const value = extension(sheet, f)?.valueString;
return value ? [[f, value]] : [];
}));
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
descripcion: measure.description ?? null,
ficha: { codigo: codigoDeFicha(measure.id ?? ''), unidad, definicion: measure.description ?? null },
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null, ...written },
unidad,
referencias: [],
referencias: (measure.relatedArtifact ?? []).filter(a => !!a.display)
.map(a => ({ tipo: a.type ?? 'citation', etiqueta: a.display!, ref: a.citation ?? null })),
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
grupo: POPULATION_GROUP[code(p.code) ?? ''] ?? code(p.code) ?? '',
codigo: p.criteria?.expression ?? code(p.code) ?? '',
descripcion: p.description ?? '',
})),
figuras_detalle: [],
figuras_detalle: extensions(measure, 'figura-detalle').flatMap(e => {
const figura = extension(e, 'figura')?.valueString;
return figura ? [{
figura, descripcion: extension(e, 'descripcion')?.valueString ?? null,
como_leer: extensions(e, 'como-leer').map(l => l.valueString).filter((l): l is string => !!l),
}] : [];
}),
categorias: categorias(measure),
};
}
@@ -156,67 +164,12 @@ function stratumValue(stratum: Stratum): string | undefined {
return value === undefined ? undefined : estratoValor(value);
}
// The categories a composition's reports count that its Measure doesn't declare, in order of appearance, with their
// captions. Only CaMa's: its BI-RADS 4 without subcategory is published this way.
function categoriasNoDeclaradas(reports: Report[], declaradas: Record<string, Categoria>): Map<string, string> {
const found = new Map<string, string>();
for (const report of reports) {
for (const stratum of report.group?.flatMap(g => g.stratifier?.[0]?.stratum ?? []) ?? []) {
const categoria = code(stratum.value);
if (!categoria || Object.hasOwn(declaradas, categoria) || found.has(categoria) || !(stratum.population?.[0]?.count)) continue;
found.set(categoria, ETIQUETA_CATEGORIA_NO_DECLARADA[categoria] ?? display(stratum.value) ?? categoria);
}
}
return found;
}
// The cross of the two stratifiers of CaMa's histopathological result (BI-RADS by biopsy grade) in one report, in the
// page's codes. FHIR publishes only the cells that have patients; the report is complete, so a cell it doesn't list is
// zero. A code the correspondence tables don't know, or cells that don't add up to the report's units, is an error.
function cruceDeHistopatologia(group: Group, estrato: string): Map<string, number> {
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
const unidades = count(group.population, 'initial-population');
// A report with no units has no cell to cross: it is a published matrix of zeros, not a missing stratifier.
if (!stratifier && unidades === 0) return new Map();
if (!stratifier) throw new Error('Dimensión no admitida');
const celdas = new Map<string, number>();
for (const stratum of stratifier.stratum ?? []) {
const bi = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
const e = ESTRATO_BIRADS_PAGINA[code(bi?.value) ?? ''], c = CATEGORIA_HISTOPATOLOGIA_PAGINA[code(cat?.value) ?? ''];
if (!e || !c) throw new Error('Código de histopatología no reconocido');
const clave = `${e}|${c.id}`;
celdas.set(clave, (celdas.get(clave) ?? 0) + (stratum.population?.[0]?.count ?? 0));
}
if (unidades !== null && [...celdas.values()].reduce((sum, n) => sum + n, 0) !== unidades) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
return celdas;
}
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
const declaradas = categorias(measure);
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
const cats: Record<string, Categoria> = cruzado
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
if (!m) throw new Error('Categoría de histopatología no reconocida');
return [m.id, { ...c, grupo: m.grupo, gravedad: m.gravedad }];
}))
: { ...declaradas,
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
const totales: Record<string, unknown>[] = [];
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = nombre(code(g.code));
return [id, id === 'TOTAL' || id === GRUPO_PRINCIPAL_PAGINA ? 'Total' : display(g.code) ?? id];
const id = code(g.code) ?? 'TOTAL';
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
}));
const valores = new Map<string, string>();
const filas: Record<string, unknown>[] = [];
@@ -226,29 +179,9 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
const periodo = periodLabel(report.period);
periodos.push(periodo);
for (const group of report.group ?? []) {
const grupo = nombre(code(group.code));
if (cruzado) {
const celdas = cruceDeHistopatologia(group, estrato!);
Object.values(ESTRATO_BIRADS_PAGINA).forEach(e => {
let total = 0;
Object.keys(cats).forEach((categoria, orden) => {
const n = celdas.get(`${e}|${categoria}`) ?? 0;
total += n;
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
});
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
valores.set(e, e);
});
continue;
}
const grupo = code(group.code) ?? 'TOTAL';
if (kind === 'C2') {
const strata = group.stratifier?.[0]?.stratum ?? [];
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
// A report whose categories don't add up to its units can't be drawn as a partition; say so, don't undercount.
const units = count(group.population, 'initial-population');
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
@@ -279,11 +212,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
tipo_periodo: tipo,
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado ? { totales_estrato: totales } : {}),
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
grupos,
categorias: cats,
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
grupos_de_categoria: {},
notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas,
@@ -242,11 +242,7 @@ describe('Histopatología por BI-RADS: componente', () => {
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']);
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
const seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement;
expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true);
expect(grafica.nextElementSibling?.nextElementSibling).toBe(seleccion);
expect(seleccion.textContent).toContain('selección: Maligno');
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']);
@@ -21,7 +21,6 @@ const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
// 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;
const OBLIGATORIAS: readonly string[] = ['BENIGNO', 'IN_SITU', 'INVASOR'];
// 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' },
@@ -101,11 +100,10 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
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];
// The risk lesion (B3) is only published by a source that has it: the others have to be there.
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.some(id => !Object.hasOwn(cats, id))) {
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.filter(id => Object.hasOwn(cats, id)).map(id => {
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.');
@@ -113,7 +111,7 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
});
const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => {
const propias = categorias.filter(c => c.grupo === id);
return { id, etiqueta: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.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;
@@ -46,7 +46,7 @@ describe('Histórico de CaMa', () => {
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
// Answers in waves, because the shared request queue runs four at a time.
function responder(fallo?: (r: TestRequest) => boolean, sinDatos?: (periodo: string) => boolean) {
function responder(fallo?: (r: TestRequest) => boolean) {
const vistos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
@@ -56,9 +56,7 @@ describe('Histórico de CaMa', () => {
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
else {
const periodos = r.request.params.get('periodos')!.split(',');
const d = datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos);
if (sinDatos) d.filas = d.filas.filter(fila => !sinDatos(fila.periodo));
r.flush(d);
r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos));
}
}
fixture.detectChanges();
@@ -83,32 +81,10 @@ describe('Histórico de CaMa', () => {
montar(CATALOGO, true); responder();
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']);
expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
});
it('los periodos sin dato van en una sección plegable cerrada, con una etiqueta breve, y al abrirla salen completos', () => {
// Pins down: a chart with months without data keeps its figure and its caption and puts the list of those months in a
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
// list is open from the start, is cut short, or the figure changes.
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
const panel = paneles()[1];
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
expect(plegable).not.toBeNull();
expect(plegable.open).toBe(false);
expect(plegable.querySelector('summary')!.textContent!.trim()).toBe('Periodos sin dato (5)');
expect(plegable.querySelector('p')!.textContent).toMatch(/Sin dato: .*mar 2025.*abr 2025.*may 2025.*jun 2025.*jul 2025./);
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
expect(panel.querySelector('.nota')!.textContent!.length).toBeGreaterThan(0);
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
fixture.detectChanges();
expect(plegable.open).toBe(true);
});
it('un panel sin periodos sin dato no muestra la sección', () => {
// Fails if an empty disclosure appears where every period has data.
montar(CATALOGO, true); responder();
expect(root().querySelector('details[data-plegable="sin-dato"]')).toBeNull();
});
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
montar(CATALOGO, true); responder();
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
@@ -28,15 +28,10 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
fixture.componentInstance.changeSection('analisis');
fixture.detectChanges();
expect(fixture.componentInstance.activeSection()).toBe('resumen');
expect(root().querySelector('#panel-analisis')).toBeNull();
http.expectNone(request => request.url.startsWith('/cama/analisis'));
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
@@ -26,7 +26,7 @@ const PERSONALIZADO = -1;
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico por categoría BI-RADS' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
@@ -109,12 +109,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
</details>
}
@if (panel.figura.sinDato.length) {
<details class="nota-pie" data-plegable="sin-dato">
<summary>Periodos sin dato ({{ panel.figura.sinDato.length }})</summary>
<p>Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p>
</details>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
}
}
</article>
@@ -63,9 +63,9 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
],
};
// CaMa's four opportunity cards, in display order. Two of them have no measure in the FHIR catalog yet
// (`cama_tasa_deteccion_histopatologica` and `cama_dias_resultado_diagnostico`), so they stay outside
// KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
// CaMa's four opportunity cards, in display order. Two of them have no indicator in the catalog yet
// (indicadores_kit defines neither `cama_tasa_deteccion_histopatologica` nor `cama_dias_resultado_diagnostico`),
// so they stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [
KPI_BY_DOMAIN.cama[0],
CAMA_TASA_DETECCION_KPI,
@@ -83,11 +83,8 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[]
// The summary draws the paired card and the histopathology card; the rest of CaMa's indicators are in Histórico
// and in Datos y definiciones, which still list the whole catalog.
// The two published opportunity indicators draw their KPI card only; their evolution is in Histórico.
// `cama_birads` is replaced by the exams' and patients' counts, and `cama_birads_cancer_invasor` is the
// epidemiological analysis' measure: neither has a card of its own.
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_birads', 'cama_birads_cancer_invasor',
'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_tasa_deteccion_histopatologica',
'cama_dias_resultado_diagnostico'];
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a',
'cama_tasa_deteccion_histopatologica', 'cama_dias_resultado_diagnostico'];
export const ID_HISTOPATOLOGIA_CAMA = 'cama_histopatologia_birads';
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
const C1_GROUP: Record<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };
@@ -135,7 +135,7 @@
@if (conAnalisis) {
<section id="panel-analisis" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-analisis" tabindex="0" [hidden]="activeSection() !== 'analisis'">
<p>En desarrollo</p>
<app-indicadores-analisis [dominio]="dominio" [tema]="tema" [active]="activeSection() === 'analisis'" (verPacientes)="verPacientes($event)" />
</section>
}
@@ -42,23 +42,19 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
// between its history and its follow-up list.
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
export const CAMA_ANALYSIS_ENABLED = false;
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
{ id: 'seguimiento', label: 'Análisis de Riesgos' }, SECTIONS_WITH_HISTORY[3]];
const SECTIONS_WITH_ANALYSIS: readonly { id: DashboardSection; label: string }[] = [
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1], { id: 'analisis', label: 'Análisis epidemiológico' }, SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
@Component({
selector: 'app-indicadores-page',
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, IndicadoresAnalisis, TeaResumenPeriodo],
templateUrl: './indicadores-page.html',
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get sections(): readonly { id: DashboardSection; label: string }[] { return this.conAnalisis ? SECTIONS_WITH_ANALYSIS : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
get conAnalisis() { return this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
private readonly analisis = viewChild(IndicadoresAnalisis);
@@ -2,21 +2,19 @@
// «Volver al análisis», with the analysis as it was and the focus on the control that opened the list; the selection going
// with the domain; CaCu and TEA keeping their three sections; and the wording of every screen of the journey.
// Fixtures: indicadores-analisis.testing.ts (the aggregate) and fixtures/cama_seguimiento.json (the list).
// The journey through the Análisis tab only runs while the page offers that tab (CAMA_ANALYSIS_ENABLED); with it
// withdrawn those tests are reported as skipped, and the selection and sections tests keep running without it.
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from '../../app.routes';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CAMA_ANALYSIS_ENABLED, IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso, seleccionDeGrupo } from './indicadores-analisis';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis';
import { IndicadorFigureCard } from './indicador-figure-card';
import { agregadoJson, CONTEXTO, listaCohorte, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing';
import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing';
import { Indicador } from './indicadores.models';
@@ -24,7 +22,6 @@ import { Indicador } from './indicadores.models';
class ChartStub { readonly plotClick = output<unknown>(); }
const catalogoCama: Indicador[] = [{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras'], tipos_periodo: ['mes'] }];
const conAnalisis = CAMA_ANALYSIS_ENABLED ? it : it.skip;
const base = () => structuredClone(fixtureData) as unknown as Record<string, any>;
// What the cohort's list answers to the group BI-RADS 5: the whole cohort, the cut-off asked for, the filter applied and the cohort quoted back.
const cohorte = (corte: string) => ({ ...base(), ...CONTEXTO, corte, ventana: { meses: 0, desde: '2025-01-01', hasta: corte },
@@ -42,7 +39,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
const corte = hoyIso();
beforeEach(() => {
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
@@ -66,7 +63,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
const lista = () => http.expectOne(q => q.url === '/cama/seguimiento');
const parametros = (r: ReturnType<typeof lista>) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]));
conAnalisis('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
it('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => {
// Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded.
const e = await entrar();
await abrirAnalisis(e);
@@ -108,7 +105,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectNone(q => q.url === '/cama/seguimiento');
expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5');
});
conAnalisis('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => {
// Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it.
const ELEGIDO = '2026-09-01';
const descargas: string[] = [];
@@ -138,7 +135,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
expect(descargas).toHaveLength(1);
expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/);
});
conAnalisis('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => {
// Fails if a stale revision shows rows, or the way back to the analysis is lost with the error.
const e = await entrar();
await abrirAnalisis(e);
@@ -153,7 +150,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
it('al cambiar de dominio la selección se limpia; CaCu y TEA no tienen Análisis y conservan sus secciones', async () => {
// Fails if a selection survives into another domain, or the analysis tab leaks into CaCu or TEA.
const e = await entrar();
e.page.verPacientes(seleccionDeGrupo(agregadoJson({ corte }), 'BIRADS_5')!); e.harness.detectChanges();
await abrirAnalisis(e);
e.root.querySelector<HTMLButtonElement>('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges();
lista().flush(cohorte(corte)); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeDefined();
for (const dominio of ['cacu', 'tea'] as const) {
@@ -169,7 +167,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(e.root.querySelector('.seleccion')).toBeNull();
});
conAnalisis('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
it('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => {
// Fails if the missing endpoint is hidden or shown as a broken page, or the wording leaks the environment.
const e = await entrar();
e.tab('analisis').click(); e.harness.detectChanges();
@@ -1,20 +0,0 @@
// What this module covers: that the FHIR mapping shared by all domains gives CaCu and TEA what it gave them before CaMa's
// measures got their own correspondences, categories and groups.
// Fixtures: `fixtures/regresion_cacu_tea_fhir.json` (real Measure bundles and two semesters of reports of every CaCu and
// TEA measure, from the local installation) and `fixtures/regresion_cacu_tea_mapeo.json` (what the mapper returned for
// them before the CaMa changes: ids, catalog entries, sheets and data rows, without and with each stratum).
import { datosDeReportes, indicadorDeMeasure, indicadorId, metadatosDeMeasure } from './indicadores-fhir';
import { mapeoDeCacuYTea } from './indicadores-regresion-fhir.testing';
import esperado from './fixtures/regresion_cacu_tea_mapeo.json';
describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// regenerate the recorded mapping and say why in the change.
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
for (const clave of Object.keys(esperado)) expect(actual[clave], clave).toEqual((esperado as Record<string, unknown>)[clave]);
});
});
@@ -1,32 +0,0 @@
// The FHIR mapping of every CaCu and TEA measure over real answers, as one comparable object: what the page reads of
// each Measure (id, catalog entry, technical sheet) and its data rows without and with each stratum the catalog offers.
// A mapper that changes for another domain shows up as a difference here.
import { Bundle, resources } from './fhir';
import type { Measure, Report } from './indicadores-fhir';
import { DimensionEstrato, IndicadorDatos, TipoPeriodo } from './indicadores.models';
import data from './fixtures/regresion_cacu_tea_fhir.json';
export interface Mapeador {
indicadorId: (measureId: string) => string;
indicadorDeMeasure: (measure: Measure) => unknown;
metadatosDeMeasure: (measure: Measure) => unknown;
datosDeReportes: (measure: Measure, reports: Report[], tipo: TipoPeriodo, scope?: { estrato?: DimensionEstrato }) => IndicadorDatos;
}
export function mapeoDeCacuYTea(mapeador: Mapeador): Record<string, unknown> {
const salida: Record<string, unknown> = {};
for (const dominio of ['cacu', 'tea'] as const) {
const measures = resources(data.measures[dominio] as unknown as Bundle, 'Measure') as Measure[];
for (const measure of measures) {
const reports = resources((data.reports[dominio] as Record<string, unknown>)[measure.id!] as Bundle, 'MeasureReport') as Report[];
const indicador = mapeador.indicadorDeMeasure(measure) as { estratos: DimensionEstrato[] };
const datos: Record<string, unknown> = {};
for (const estrato of [undefined, ...indicador.estratos]) {
try { datos[estrato ?? 'total'] = mapeador.datosDeReportes(measure, reports, 'semestre', estrato ? { estrato } : {}); }
catch (error) { datos[estrato ?? 'total'] = { error: (error as Error).message }; }
}
salida[`${dominio}/${measure.id}`] = { id: mapeador.indicadorId(measure.id!), indicador, metadatos: mapeador.metadatosDeMeasure(measure), datos };
}
}
return JSON.parse(JSON.stringify(salida));
}
@@ -37,8 +37,8 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
// TEA and CaMa also have Histórico; CaMa adds Análisis epidemiológico before Seguimiento; CaCu keeps its three.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
@@ -66,16 +66,6 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => {
expect(fixture.componentInstance.etiquetaDatos()).toBe('Categoría BI-RADS: BI-RADS 5');
expect(exportar()).not.toBeNull();
});
it.each([1, 3, 6, 12])('una selección calculada con la ventana de %i meses pide esa misma ventana, con el corte, el filtro y la cohorte, y no avisa de diferencia si los pacientes coinciden', async (m) => {
// Fails if a bar computed over a window opens the whole cohort (or another window), so the list shows other patients than counted.
abrirCon(seleccion(m, { meses: m, filtros: { birads: 'BIRADS_5', grupo_edad: '50-59' } }));
const r = solicitud();
expect(parametros(r)).toEqual({ ...PARAMS, meses: String(m), grupo_edad: '50-59' });
r.flush(cohorte({ birads: 'BIRADS_5', grupo_edad: '50-59' }, 1, 50, { ventana: { meses: m, desde: '2026-01-01', hasta: CORTE } })); await asentar();
expect(root().querySelector('.diferencia')).toBeNull();
expect(fixture.componentInstance.draft.meses).toBe(m);
expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true);
});
it('sin una selección la ventana no ofrece «Toda la cohorte» y la consulta no cita ninguna cohorte', async () => {
// Fails if the whole cohort becomes a plain window of the list, or a plain query quotes a revision.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
@@ -18,10 +18,9 @@ type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: str
/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */
type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string };
// What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the
// list must quote back, the window of months it was computed over (0: the whole cohort), how to name it, how many patients the
// analysis counts there and an id that changes with each click.
// list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click.
export interface SeleccionSeguimiento {
filtros: Record<string, string>; etiqueta: string; corte?: string; meses?: number; esperados?: number | null; contexto?: ContextoLista; id: number;
filtros: Record<string, string>; etiqueta: string; corte?: string; esperados?: number | null; contexto?: ContextoLista; id: number;
}
const ETIQUETA_COHORTE = 'Cohorte del análisis epidemiológico';
/** The answer does not apply the cut-off, window or filters that were asked for: it is neither shown nor exported. */
@@ -261,7 +260,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
// Whatever was on screen belongs to another query: it goes before the selection is asked for.
this.data.set(undefined); this.etiquetaDatos.set(undefined);
if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); }
this.draft = { ...this.draft, meses: (sel.meses ?? 0) as MesesVentana, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.draft = { ...this.draft, meses: 0, corte: sel.corte ?? this.draft.corte, filtros: { ...sel.filtros } };
this.aplicar(sel.etiqueta);
return;
}
@@ -304,7 +303,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
aplicar(seleccion?: string) {
const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record<string, string>;
const activa = this.activa, contexto = this.contextoActivo;
const exacta = !!seleccion || (!!activa && this.draft.meses === (activa.meses ?? 0) && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte));
// In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months.
// The banner names the analysis' selection, or the cohort of the analysis once the user has refined it.
const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined);
@@ -1,6 +1,6 @@
import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { DonutSelection } from './indicadores-donut-drilldown';
import { c2Theme, seriesColors } from './indicadores-c2-palette';
import { c2Color, c2Theme } from './indicadores-c2-palette';
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -43,7 +43,6 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
const cells: StratifiedCell[] = [];
const theme = c2Theme(tema);
const palette = seriesColors(categories.map(([, c]) => c.color));
const figure: PlotlyFigure = { data: strata.map((s, series) => {
const selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s]));
@@ -53,7 +52,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
return value;
});
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x: selected, y: categories.map(([, c]) => escape(c.label)),
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
marker: { color: categories.map(([, c], i) => c2Color(c.color, i)), pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
hovertemplate: '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
}), layout: { title: { text: 'Distribución estratificada, ' + period }, barmode: 'group', autosize: true,
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
-7
View File
@@ -32,13 +32,6 @@ export class GovernanceApi {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/promote`, {});
}
/** Exports the scenario's latest dbt cohort build, trains a PROD version and tries to promote it, the same
* one-shot pipeline the `entrenar` compose profile runs. 409 when it trained but needs its reports attached
* before it can be promoted; 503 with no dbt manifest configured or an operational failure. */
trainModelVersion(domain: string, scenario: string): Observable<{ output: string }> {
return this.http.post<{ output: string }>(`/governance/model-versions/${domain}/${scenario}/train`, {});
}
retireModelVersion(domain: string, scenario: string, version: string): Observable<ModelVersion> {
return this.http.post<ModelVersion>(`/governance/model-versions/${domain}/${scenario}/${version}/retire`, {});
}
@@ -1,29 +0,0 @@
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { PendingRiskBatch } from './risk-batches.types';
/** `/<domain>/riesgos/lotes`: risk batches a model produced and nobody has reviewed yet (ADR-MD-008). Only `cacu`
* is served today. */
@Injectable({ providedIn: 'root' })
export class RiskBatchesApi {
private readonly http = inject(HttpClient);
listPending(domain: string): Observable<PendingRiskBatch[]> {
return this.http.get<PendingRiskBatch[]>(`/${domain}/riesgos/lotes`);
}
/** Moves every current evaluation of the batch to `final`: it becomes the one patient records read. */
confirm(domain: string, loteId: number, reason: string): Observable<{ lote_id: number; evaluaciones_cambiadas: number }> {
return this.http.post<{ lote_id: number; evaluaciones_cambiadas: number }>(
`/${domain}/riesgos/lotes/${loteId}/confirmar`, { reason },
);
}
/** Moves every current evaluation of the batch to `entered-in-error` instead. */
void(domain: string, loteId: number, reason: string): Observable<{ lote_id: number; evaluaciones_cambiadas: number }> {
return this.http.post<{ lote_id: number; evaluaciones_cambiadas: number }>(
`/${domain}/riesgos/lotes/${loteId}/anular`, { reason },
);
}
}
@@ -1,9 +0,0 @@
/** A risk batch waiting for someone to confirm or void it (ADR-MD-008); invisible to patient records until
* confirmed. */
export interface PendingRiskBatch {
lote_id: number;
modelo_nombre: string;
modelo_version: string;
evaluado_en: string;
n_evaluaciones: number;
}
@@ -22,10 +22,5 @@
<app-ocr-review-panel></app-ocr-review-panel>
</div>
</mat-tab>
<mat-tab label="Lotes de riesgo">
<div class="governance__panel">
<app-risk-batches-panel></app-risk-batches-panel>
</div>
</mat-tab>
</mat-tab-group>
</div>
@@ -4,16 +4,15 @@ import { MatToolbarModule } from '@angular/material/toolbar';
import { ExperimentsPanel } from '../experiments-panel/experiments-panel';
import { ModelVersionsPanel } from '../model-versions-panel/model-versions-panel';
import { OcrReviewPanel } from '../ocr-review-panel/ocr-review-panel';
import { RiskBatchesPanel } from '../risk-batches-panel/risk-batches-panel';
/**
* The "Gobernanza de modelos" page (route `/gobernanza`): model versions,
* notebooks run on cohort builds, the OCR review queue and pending risk batches, one tab each. Every tab is a
* notebooks run on cohort builds and the OCR review queue, one tab each. Every tab is a
* self-contained panel that loads its own data.
*/
@Component({
selector: 'app-governance-page',
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel, RiskBatchesPanel],
imports: [ExperimentsPanel, MatTabsModule, MatToolbarModule, ModelVersionsPanel, OcrReviewPanel],
templateUrl: './governance-page.html',
styleUrl: './governance-page.scss',
})
@@ -6,16 +6,12 @@
}
</mat-button-toggle-group>
<span class="models__spacer"></span>
<button mat-stroked-button type="button" [disabled]="training()" (click)="train()"
matTooltip="Entrena el modelo cacu/cin2_logistic con la cohorte de vigilancia vigente y lo pone en producción">
<mat-icon aria-hidden="true">model_training</mat-icon>Entrenar cacu/cin2_logistic
</button>
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
</div>
@if (loading() || training()) {
@if (loading()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
@@ -17,14 +17,10 @@ import { ModelVersion } from '../../api/governance.types';
import { ModelStatusChip } from '../model-status-chip/model-status-chip';
import { ModelVersionDialog } from '../model-version-dialog/model-version-dialog';
/** The only scenario with a trainer today (ML-cin2_logistic, CaCu): `entrenar`'s own domain and scenario. */
const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
/**
* Every registered model version with its status (desarrollo, candidata,
* en producción, retirada). The detail dialog holds the promotion
* checklist, lineage, artifacts and reports. The toolbar also offers
* training the one scenario with a trainer, over HTTP instead of a shell.
* checklist, lineage, artifacts and reports.
*/
@Component({
selector: 'app-model-versions-panel',
@@ -54,7 +50,6 @@ export class ModelVersionsPanel implements OnInit {
readonly versions = signal<ModelVersion[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly training = signal(false);
readonly displayedColumns = ['version', 'scenario', 'environment', 'armado', 'status', 'created_at', 'acciones'];
@@ -99,23 +94,4 @@ export class ModelVersionsPanel implements OnInit {
metrics(version: ModelVersion): { key: string; value: unknown }[] {
return Object.entries(version.metrics ?? {}).map(([key, value]) => ({ key, value }));
}
train(): void {
this.training.set(true);
this.api
.trainModelVersion(TRAINABLE.domain, TRAINABLE.scenario)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: () => {
this.training.set(false);
this.snackBar.open(`El modelo ${TRAINABLE.domain}/${TRAINABLE.scenario} se entrenó correctamente.`, 'OK', { duration: 3000 });
this.reload();
},
error: (error) => {
this.training.set(false);
this.snackBar.open(apiErrorMessage(error, 'No se pudo entrenar el modelo.'), 'OK', { duration: 5000 });
if (error?.status === 409) this.reload();
},
});
}
}
@@ -1,62 +0,0 @@
<div class="batches">
<div class="batches__toolbar">
<span class="batches__spacer"></span>
<button mat-icon-button type="button" (click)="reload()" aria-label="Recargar" matTooltip="Recargar">
<mat-icon aria-hidden="true">refresh</mat-icon>
</button>
</div>
@if (loading()) {
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
}
@if (loadError(); as error) {
<p class="batches__alert" role="alert"><mat-icon aria-hidden="true">error</mat-icon>{{ error }}</p>
}
<table mat-table [dataSource]="batches()" class="batches__table">
<ng-container matColumnDef="modelo">
<th mat-header-cell *matHeaderCellDef>Modelo</th>
<td mat-cell *matCellDef="let b">{{ b.modelo_nombre }}:{{ b.modelo_version }}</td>
</ng-container>
<ng-container matColumnDef="evaluado_en">
<th mat-header-cell *matHeaderCellDef>Calculado</th>
<td mat-cell *matCellDef="let b">{{ b.evaluado_en | date: 'short' }}</td>
</ng-container>
<ng-container matColumnDef="n_evaluaciones">
<th mat-header-cell *matHeaderCellDef>Pacientes</th>
<td mat-cell *matCellDef="let b">{{ b.n_evaluaciones }}</td>
</ng-container>
<ng-container matColumnDef="motivo">
<th mat-header-cell *matHeaderCellDef>Motivo</th>
<td mat-cell *matCellDef="let b">
<mat-form-field appearance="outline" subscriptSizing="dynamic" class="batches__reason">
<input matInput [formControl]="reasonFor(b)" placeholder="Motivo de la confirmación o anulación" />
</mat-form-field>
</td>
</ng-container>
<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef></th>
<td mat-cell *matCellDef="let b">
<button mat-button type="button" color="primary" [disabled]="!reasonFor(b).value.trim() || deciding() === b.lote_id"
(click)="confirm(b)">
<mat-icon aria-hidden="true">check_circle</mat-icon>Confirmar
</button>
<button mat-button type="button" color="warn" [disabled]="!reasonFor(b).value.trim() || deciding() === b.lote_id"
(click)="void(b)">
<mat-icon aria-hidden="true">block</mat-icon>Anular
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
@if (!loading() && batches().length === 0) {
<p class="batches__empty"><mat-icon aria-hidden="true">task_alt</mat-icon>No hay lotes de riesgo pendientes de revisión.</p>
}
</div>
@@ -1,43 +0,0 @@
.batches {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.batches__toolbar {
align-items: center;
display: flex;
gap: var(--space-2);
}
.batches__spacer {
flex: 1;
}
.batches__alert {
align-items: center;
background: var(--mat-sys-error-container);
color: var(--mat-sys-on-error-container);
display: flex;
gap: var(--space-2);
margin: 0;
padding: var(--space-2) var(--space-3);
}
.batches__table {
width: 100%;
}
.batches__reason {
min-width: 220px;
width: 100%;
}
.batches__empty {
align-items: center;
color: var(--mat-sys-on-surface-variant);
display: flex;
font: var(--mat-sys-body-small);
gap: var(--space-2);
margin: 0;
}
@@ -1,113 +0,0 @@
import { DatePipe } from '@angular/common';
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatTooltipModule } from '@angular/material/tooltip';
import { apiErrorMessage } from '../../../connect/api/api.types';
import { RiskBatchesApi } from '../../api/risk-batches.api';
import { PendingRiskBatch } from '../../api/risk-batches.types';
const DOMAIN = 'cacu';
/**
* Risk batches a model produced that nobody has confirmed or voided yet (ADR-MD-008): invisible to patient
* records until someone decides, with a reason. Only CaCu has a model estimating risks today.
*/
@Component({
selector: 'app-risk-batches-panel',
imports: [
DatePipe,
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSnackBarModule,
MatTableModule,
MatTooltipModule,
ReactiveFormsModule,
],
templateUrl: './risk-batches-panel.html',
styleUrl: './risk-batches-panel.scss',
})
export class RiskBatchesPanel implements OnInit {
private readonly api = inject(RiskBatchesApi);
private readonly snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
readonly batches = signal<PendingRiskBatch[]>([]);
readonly loading = signal(false);
readonly loadError = signal<string | null>(null);
readonly deciding = signal<number | null>(null);
readonly displayedColumns = ['modelo', 'evaluado_en', 'n_evaluaciones', 'motivo', 'acciones'];
private readonly reasons = new Map<number, FormControl<string>>();
ngOnInit(): void {
this.reload();
}
reload(): void {
this.loading.set(true);
this.loadError.set(null);
this.api
.listPending(DOMAIN)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe({
next: (batches) => {
this.loading.set(false);
this.batches.set(batches);
},
error: (error) => {
this.loading.set(false);
this.loadError.set(apiErrorMessage(error, 'No se pudieron cargar los lotes de riesgo.'));
},
});
}
reasonFor(batch: PendingRiskBatch): FormControl<string> {
let control = this.reasons.get(batch.lote_id);
if (!control) {
control = new FormControl('', { nonNullable: true });
this.reasons.set(batch.lote_id, control);
}
return control;
}
confirm(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.confirm(DOMAIN, batch.lote_id, reason), 'confirmado');
}
void(batch: PendingRiskBatch): void {
this.decide(batch, (reason) => this.api.void(DOMAIN, batch.lote_id, reason), 'anulado');
}
private decide(
batch: PendingRiskBatch,
request: (reason: string) => ReturnType<RiskBatchesApi['confirm']>,
verb: string,
): void {
const reason = this.reasonFor(batch).value.trim();
if (!reason) return;
this.deciding.set(batch.lote_id);
request(reason).subscribe({
next: () => {
this.deciding.set(null);
this.reasons.delete(batch.lote_id);
this.snackBar.open(`El lote ${batch.lote_id} quedó ${verb}.`, 'OK', { duration: 3000 });
this.reload();
},
error: (error) => {
this.deciding.set(null);
this.snackBar.open(apiErrorMessage(error, 'La operación no se pudo completar.'), 'OK', { duration: 5000 });
},
});
}
}