feat(isssteleon): add EU7 clinical scenario charts

This commit is contained in:
Angel Capetillo Zavala
2026-10-23 13:18:57 -06:00
parent ec642df834
commit 1940f4fa47
10 changed files with 1711 additions and 10 deletions
@@ -0,0 +1,936 @@
{
"_nota": "Datos SIMULADOS con la forma exacta de GET /cacu/indicadores/cacu_eu7/datos (contrato C2, kit 054837b). Sin 'reportes' (procedencia). Las tres respuestas son del mismo semestre y suman lo mismo.",
"general": {
"id": "cacu_eu7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S2"
],
"estrato": null,
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"NORMAL": {
"etiqueta": "Normal",
"color": "#9DBFE3",
"grupo": "NO_ANORMAL",
"gravedad": 1
},
"ASC-US": {
"etiqueta": "ASC-US",
"color": "#2F6DB3",
"grupo": "NO_ANORMAL",
"gravedad": 2
},
"LIEBG": {
"etiqueta": "LIEBG",
"color": "#E8C28E",
"grupo": "ANORMAL",
"gravedad": 3
},
"ASC-H": {
"etiqueta": "ASC-H",
"color": "#D98E4A",
"grupo": "ANORMAL",
"gravedad": 4
},
"LIEAG": {
"etiqueta": "LIEAG",
"color": "#B55A1F",
"grupo": "ANORMAL",
"gravedad": 5
},
"CIS": {
"etiqueta": "Carcinoma in situ",
"color": "#7A2E0E",
"grupo": "ANORMAL",
"gravedad": 6
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_ANORMAL": "Sin anomalía",
"ANORMAL": "Anormal",
"SIN_DATO": "Sin dato"
},
"notas": [
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
],
"filas": [
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "NORMAL",
"n": 798,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "ASC-US",
"n": 62,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "LIEBG",
"n": 46,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "ASC-H",
"n": 17,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "LIEAG",
"n": 19,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "CIS",
"n": 4,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": null,
"categoria": "SIN_DATO",
"n": 87,
"orden": 6,
"suprimido": 0
}
],
"totales_estrato": []
},
"estatus_seguimiento": {
"id": "cacu_eu7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S2"
],
"estrato": "estatus_seguimiento",
"valores_estrato": [
"VIGILANCIA",
"POST_COLPOSCOPIA",
"POST_TRATAMIENTO",
"INFO_INSUFICIENTE"
],
"etiquetas_estrato": {
"VIGILANCIA": "Vigilancia",
"POST_COLPOSCOPIA": "Post colposcopia",
"POST_TRATAMIENTO": "Post tratamiento",
"INFO_INSUFICIENTE": "Información insuficiente"
},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"NORMAL": {
"etiqueta": "Normal",
"color": "#9DBFE3",
"grupo": "NO_ANORMAL",
"gravedad": 1
},
"ASC-US": {
"etiqueta": "ASC-US",
"color": "#2F6DB3",
"grupo": "NO_ANORMAL",
"gravedad": 2
},
"LIEBG": {
"etiqueta": "LIEBG",
"color": "#E8C28E",
"grupo": "ANORMAL",
"gravedad": 3
},
"ASC-H": {
"etiqueta": "ASC-H",
"color": "#D98E4A",
"grupo": "ANORMAL",
"gravedad": 4
},
"LIEAG": {
"etiqueta": "LIEAG",
"color": "#B55A1F",
"grupo": "ANORMAL",
"gravedad": 5
},
"CIS": {
"etiqueta": "Carcinoma in situ",
"color": "#7A2E0E",
"grupo": "ANORMAL",
"gravedad": 6
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_ANORMAL": "Sin anomalía",
"ANORMAL": "Anormal",
"SIN_DATO": "Sin dato"
},
"notas": [
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
],
"filas": [
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "NORMAL",
"n": 610,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "ASC-US",
"n": 38,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "LIEBG",
"n": 22,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "ASC-H",
"n": 6,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "LIEAG",
"n": 5,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "CIS",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"categoria": "SIN_DATO",
"n": 48,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "NORMAL",
"n": 92,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "ASC-US",
"n": 14,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "LIEBG",
"n": 16,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "ASC-H",
"n": 7,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "LIEAG",
"n": 9,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "CIS",
"n": 2,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"categoria": "SIN_DATO",
"n": 11,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "NORMAL",
"n": 41,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "ASC-US",
"n": 6,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "LIEBG",
"n": 5,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "ASC-H",
"n": 3,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "LIEAG",
"n": 4,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "CIS",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"categoria": "SIN_DATO",
"n": 7,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "NORMAL",
"n": 55,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "ASC-US",
"n": 4,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "LIEBG",
"n": 3,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "ASC-H",
"n": 1,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "LIEAG",
"n": 1,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "CIS",
"n": 0,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"categoria": "SIN_DATO",
"n": 21,
"orden": 6,
"suprimido": 0
}
],
"totales_estrato": [
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "VIGILANCIA",
"n": 730,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_COLPOSCOPIA",
"n": 151,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "POST_TRATAMIENTO",
"n": 67,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "INFO_INSUFICIENTE",
"n": 85,
"suprimido": 0
}
]
},
"grupo_edad": {
"id": "cacu_eu7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.0",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2025-S2"
],
"estrato": "grupo_edad",
"valores_estrato": [
"<25",
"25-34",
"35-44",
"45-54",
"55-64"
],
"etiquetas_estrato": {
"<25": "<25",
"25-34": "25-34",
"35-44": "35-44",
"45-54": "45-54",
"55-64": "55-64"
},
"grupos": {
"TOTAL": "Total"
},
"categorias": {
"NORMAL": {
"etiqueta": "Normal",
"color": "#9DBFE3",
"grupo": "NO_ANORMAL",
"gravedad": 1
},
"ASC-US": {
"etiqueta": "ASC-US",
"color": "#2F6DB3",
"grupo": "NO_ANORMAL",
"gravedad": 2
},
"LIEBG": {
"etiqueta": "LIEBG",
"color": "#E8C28E",
"grupo": "ANORMAL",
"gravedad": 3
},
"ASC-H": {
"etiqueta": "ASC-H",
"color": "#D98E4A",
"grupo": "ANORMAL",
"gravedad": 4
},
"LIEAG": {
"etiqueta": "LIEAG",
"color": "#B55A1F",
"grupo": "ANORMAL",
"gravedad": 5
},
"CIS": {
"etiqueta": "Carcinoma in situ",
"color": "#7A2E0E",
"grupo": "ANORMAL",
"gravedad": 6
},
"SIN_DATO": {
"etiqueta": "Sin dato",
"color": "#C9CDD2",
"grupo": "SIN_DATO",
"gravedad": null
}
},
"grupos_de_categoria": {
"NO_ANORMAL": "Sin anomalía",
"ANORMAL": "Anormal",
"SIN_DATO": "Sin dato"
},
"notas": [
"Pacientes con citología tomada en el semestre, por el resultado de su última citología con resultado que no es insatisfactoria. «Sin dato»: ninguna tiene un resultado así."
],
"filas": [
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "NORMAL",
"n": 40,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "ASC-US",
"n": 5,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "LIEBG",
"n": 4,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "ASC-H",
"n": 0,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "LIEAG",
"n": 0,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "CIS",
"n": 0,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"categoria": "SIN_DATO",
"n": 6,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "NORMAL",
"n": 190,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "ASC-US",
"n": 18,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "LIEBG",
"n": 17,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "ASC-H",
"n": 4,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "LIEAG",
"n": 4,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "CIS",
"n": 0,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"categoria": "SIN_DATO",
"n": 22,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "NORMAL",
"n": 230,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "ASC-US",
"n": 20,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "LIEBG",
"n": 14,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "ASC-H",
"n": 6,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "LIEAG",
"n": 7,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "CIS",
"n": 2,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"categoria": "SIN_DATO",
"n": 25,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "NORMAL",
"n": 205,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "ASC-US",
"n": 12,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "LIEBG",
"n": 7,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "ASC-H",
"n": 4,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "LIEAG",
"n": 5,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "CIS",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"categoria": "SIN_DATO",
"n": 20,
"orden": 6,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "NORMAL",
"n": 133,
"orden": 0,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "ASC-US",
"n": 7,
"orden": 1,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "LIEBG",
"n": 4,
"orden": 2,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "ASC-H",
"n": 3,
"orden": 3,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "LIEAG",
"n": 3,
"orden": 4,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "CIS",
"n": 1,
"orden": 5,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"categoria": "SIN_DATO",
"n": 14,
"orden": 6,
"suprimido": 0
}
],
"totales_estrato": [
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "<25",
"n": 55,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "25-34",
"n": 255,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "35-44",
"n": 304,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "45-54",
"n": 254,
"suprimido": 0
},
{
"periodo": "2025-S2",
"grupo": "TOTAL",
"estrato": "55-64",
"n": 165,
"suprimido": 0
}
]
}
}
@@ -79,14 +79,14 @@ describe('UX-06E.D.2.1 selector de representación', () => {
expect(select().options.map(o => o.value)).toEqual(['f']); request('f').flush({ data: [], layout: {} }); http.expectNone(() => true);
});
it('comparte una sola solicitud de metadatos entre las dos figuras y asocia por ID exacto', () => {
fixture.componentRef.setInput('indicador', { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2',
fixture.componentRef.setInput('indicador', { id: 'cacu_eu13', titulo: 'EU13', contrato: 'C2',
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre'] });
fixture.detectChanges();
const helps = fixture.nativeElement.querySelectorAll('.methodology-toggle') as NodeListOf<HTMLButtonElement>;
expect(helps).toHaveLength(2);
helps[0].click(); helps[1].click(); fixture.detectChanges();
const metadata = http.expectOne('/cacu/indicadores/cacu_eu7/metadatos');
http.expectNone('/cacu/indicadores/cacu_eu7/metadatos');
const metadata = http.expectOne('/cacu/indicadores/cacu_eu13/metadatos');
http.expectNone('/cacu/indicadores/cacu_eu13/metadatos');
metadata.flush({ figuras_detalle: [
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Instrucción para donas.'] },
{ figura: 'fig_c2_barras', descripcion: null, como_leer: ['Instrucción para barras.'] },
@@ -16,11 +16,12 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { filterCompatibility } from './indicadores-memory';
import { DonutSelection } from './indicadores-donut-drilldown';
import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
@Component({
selector: 'app-indicador-catalog-card',
host: { '[class.dual-card]': 'isDual' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel],
host: { '[class.dual-card]': 'isDual || isEu7' },
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario],
template: `
<mat-card>
<header>
@@ -35,7 +36,11 @@ import { IndicadoresService } from './indicadores.service';
</button>
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
<p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p>
@if (selectedFigure) {
@if (isEu7) {
<div #visibilityRegion class="eu7-region">
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
</div>
} @else if (selectedFigure) {
@if (!pair.length || otherFigures.length) {
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Representación gráfica</mat-label>
@@ -115,6 +120,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
});
}
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
@@ -0,0 +1,94 @@
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p>
<p>Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.</p>
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p>
<p>Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.</p>
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p>
@if (metadata; as info) {
@if (info.descripcion) { <p>{{ info.descripcion }}</p> }
@if (info.ficha; as ficha) {
@if (ficha.pregunta) { <p>{{ ficha.pregunta }}</p> }
@if (ficha.definicion) { <p>{{ ficha.definicion }}</p> }
@if (ficha.unidad) { <p>Unidad: {{ ficha.unidad }}</p> }
@if (ficha.nota) { <p>{{ ficha.nota }}</p> }
}
<details><summary>Metadatos publicados de las figuras originales</summary>
<p>Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.</p>
@for (detail of info.figuras_detalle; track detail.figura) {
@if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') {
<p>{{ detail.descripcion }}</p>
@for (line of detail.como_leer; track $index) { <p>{{ line }}</p> }
}
}
@for (reference of info.referencias; track $index) { <p>{{ reference.etiqueta }} {{ reference.ref }}</p> }
</details>
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de dona y barras EU7">
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }} · {{ periodIndex + 1 }} / {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }} · Selección: {{ selectionLabel }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">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.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" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (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"><h3>Distribución de resultados · {{ m.periodo }}</h3>
@if (m.total !== null && m.total > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'EU7 · Dona de dos anillos · ' + m.periodo + ' · ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado válido para la dona.' }}</p> }
<p>{{ sinDatoNote }}</p>
</section>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico · {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
@if (m.escenarios.length && barsFigure) {
<app-plotly-chart [figure]="barsFigure" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7 · Barras por escenario clínico · ' + m.periodo + ' · ' + selectionLabel" />
}
@for (s of m.escenarios; track s.id) { <p>{{ s.etiqueta }}: {{ scenarioText(s) }}.</p> }
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados y celdas suprimidas</summary>
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
<table><caption>Datos generales · {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
</table>
<table><caption>Escenarios clínicos · {{ m.periodo }} · Porcentajes sin «Sin dato»</caption>
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
</table>
</div>
</details>
}
}
</section>
@@ -0,0 +1,29 @@
:host { display: block; min-width: 0; }
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
p, h3, summary { overflow-wrap: anywhere; }
.applied-summary, .note { color: var(--issste-text-secondary); }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.selection-status { font-weight: 600; }
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
button:disabled { opacity: .5; cursor: default; }
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
h3 { font-size: 1rem; line-height: 1.5; }
app-plotly-chart { --plot-height: 440px; }
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
.periods span { text-align: center; }
.periods button { min-width: 44px; font-size: 1.5rem; }
summary { cursor: pointer; padding-block: .75rem; }
.table-scroll { overflow: auto; max-height: 28rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; }
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
@@ -0,0 +1,150 @@
import { Component, input, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { By } from '@angular/platform-browser';
import fixtureData from './fixtures/eu7-c2-ejemplos.json';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadoresSnapshots } from './indicadores-snapshots';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { GlobalApplied } from './indicadores-memory';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub {
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>();
plotClick = output<unknown>();
}
describe('EU7 integración Angular y caché compartida', () => {
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
let f: ReturnType<typeof TestBed.createComponent<IndicadorEu7Escenario>>;
let http: HttpTestingController;
let data: typeof fixtureData;
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
f = TestBed.createComponent(IndicadorEu7Escenario);
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
});
afterEach(() => { f.destroy(); http.verify(); vi.useRealTimers(); });
function requests() {
const general = http.expectOne(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
const escenarios = http.expectOne(r => r.url.endsWith('/datos') && r.params.get('estrato') === 'estatus_seguimiento');
expect(general.request.params.get('periodos')).toBe(escenarios.request.params.get('periodos'));
return { general, escenarios };
}
function flush() { const r = requests(); r.general.flush(data.general); r.escenarios.flush(data.estatus_seguimiento); f.detectChanges(); }
it('carga diferida; dos GET compartidos con el KPI y ningún GET por clic, tema o navegación de selección', () => {
f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
flush(); expect(f.componentInstance.model!.total).toBe(946);
const general = data.general; const original = structuredClone(applied);
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub;
chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges();
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
expect(f.componentInstance.selection).toEqual({});
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
});
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
const periods: [string, string] = ['2025-S1', '2025-S2'];
for (const d of [data.general, data.estatus_seguimiento]) {
d.periodos = periods; d.filas = [...d.filas.map(r => ({ ...r, periodo: '2025-S1', n: r.n * 2 })), ...d.filas] as typeof d.filas;
d.totales_estrato = [...d.totales_estrato.map(t => ({ ...t, periodo: '2025-S1', n: t.n * 2 })), ...d.totales_estrato];
}
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
});
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
f.detectChanges(); const r = requests(); r.general.flush(data.general);
r.escenarios.flush({}, { status: 500, statusText: 'Internal Server Error' }); f.detectChanges();
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
f.componentInstance.retry(); http.expectNone(r => r.url.endsWith('/datos') && !r.params.has('estrato'));
http.expectOne(r => r.params.get('estrato') === 'estatus_seguimiento').flush(data.estatus_seguimiento); f.detectChanges();
expect(f.componentInstance.status()).toBe('ready');
});
it('timeout cancela transportes y permite recuperación', async () => {
vi.useFakeTimers(); f.detectChanges(); const r = requests();
await vi.advanceTimersByTimeAsync(40001); f.detectChanges();
expect(r.general.cancelled && r.escenarios.cancelled).toBe(true);
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.textContent).toContain('tardó demasiado');
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
});
it('error de red permite reintento sin figuras engañosas', () => {
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
expect(f.componentInstance.donutFigure).toBeUndefined();
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
});
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
f.detectChanges(); const old = requests();
f.componentRef.setInput('visible', false); f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
f.detectChanges(); expect(old.general.cancelled && old.escenarios.cancelled).toBe(true);
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
for (const d of [data.general, data.estatus_seguimiento]) { d.periodos = ['2025-S1']; d.filas.forEach(r => r.periodo = '2025-S1'); d.totales_estrato.forEach(t => t.periodo = '2025-S1'); }
f.componentRef.setInput('visible', true); f.detectChanges(); flush(); expect(f.componentInstance.model!.periodo).toBe('2025-S1');
});
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
});
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
});
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
Object.assign(data.general.filas[0], { n: 987654, suprimido: 1 });
Object.assign(data.estatus_seguimiento.filas[0], { n: 987654, suprimido: 1 });
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
expect(f.nativeElement.textContent).not.toContain('987654');
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
});
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
});
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
f.componentRef.setInput('visible', true); f.detectChanges();
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
});
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
f.componentRef.setInput('visible', false); f.detectChanges();
const card = TestBed.createComponent(IndicadorCatalogCard);
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(1);
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['tea', 'M23_pacientes_evaluados'], ['cama', 'cama_birads_456_paciente'], ['tea', 'cacu_eu7']]) {
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
expect(card.debugElement.queryAll(By.directive(IndicadorEu7Escenario))).toHaveLength(0);
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(2);
}
card.destroy(); http.expectNone(() => true);
});
});
@@ -0,0 +1,146 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
@Component({
selector: 'app-indicador-eu7-escenario',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
templateUrl: './indicador-eu7-escenario.html',
styleUrl: './indicador-eu7-escenario.scss',
})
export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: Indicador;
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
selection: Seleccion = {};
periods: string[] = [];
periodIndex = 0;
model?: Modelo;
donutFigure?: PlotlyFigure;
barsFigure?: PlotlyFigure;
helpOpen = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
private pages: Modelo[] = [];
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
get sinDatoNote() {
const m = this.model;
if (!m) return '';
if (m.vacio) return 'No hay registros publicados en este periodo.';
const n = m.sinDato.n;
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: m.total === null ? `Fuera de la dona: ${n} pacientes sin resultado válido. Total con resultado no disponible.`
: `Fuera de la dona: ${n} de ${m.total + n} pacientes sin resultado válido en el periodo.`;
}
get generalCells() {
const m = this.model;
return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })),
{ etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }];
}
get scenarioCells() {
const m = this.model;
return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta,
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
}
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
percentText(value: number | null) { return value === null ? 'No disponible' : value.toFixed(1) + ' %'; }
scenarioText(s: Escenario) { return s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado' : `${s.den} pacientes con resultado`; }
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]);
if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
this.pages = []; this.periods = []; this.model = undefined;
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
if (!this.visible) { this.status.set('deferred'); return; }
this.load();
} else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw();
// Visibility and metadata changes must not restart Plotly rendering.
}
retry() { if (this.visible) this.load(); }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
this.status.set('incompatible'); return;
}
const key = this.key;
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([general, escenarios]) => {
if (key !== this.key) return;
try {
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
this.pages = this.periods.map(p => modelo(general, escenarios, p));
this.periodIndex = 0; this.activatePeriod();
} catch (error) { this.failure(error); }
},
error: error => { if (key === this.key) this.failure(error); },
});
}
private failure(error: unknown) {
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
: error instanceof Eu7Incompatible ? error.message
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
&& this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : '');
this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
? 'incompatible' : 'error');
}
private activatePeriod() {
this.model = this.pages[this.periodIndex]; this.selection = {};
this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty');
}
changePeriod(step: number) {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.activatePeriod();
}
select(trace: string, index = 0) {
if (!this.model || this.status() !== 'ready') return;
this.selection = clic(this.model, this.selection, trace, index); this.draw();
}
plotClicked(event: unknown) {
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
}
private draw() {
if (!this.model) return;
this.donutFigure = dona(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -0,0 +1,101 @@
import fixture from './fixtures/eu7-c2-ejemplos.json';
import { IndicadorDatos } from './indicadores.models';
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
function eu7Datos() {
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
}
describe('EU7 modelo de presentación del entregable', () => {
let data: ReturnType<typeof eu7Datos>;
beforeEach(() => data = eu7Datos());
const periodo = '2025-S2';
const model = () => modelo(data.general, data.escenarios, periodo);
it('946 con resultado y 87 sin dato; anillos pie conservan categorías, colores y no mutan el original', () => {
const original = structuredClone(data), m = model(), f = dona(m, {}, 'claro');
expect(m.total).toBe(946); expect(m.sinDato.n).toBe(87);
expect(f.data.map(t => t['type'])).toEqual(['pie', 'pie', 'pie']);
expect(f.data[2]['labels']).not.toContain('Sin dato');
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
expect(data).toEqual(original);
});
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
const m = model(); let s: Seleccion = {};
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
s = clic(m, s, 'grupos', g); expect(s).toEqual({ grupo: 'ANORMAL' });
s = clic(m, s, 'categorias', c); expect(s).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
expect(clic(m, s, 'categorias', c)).toEqual({ grupo: 'ANORMAL' });
s = clic(m, s, 'centro', 0); expect(s).toEqual({ grupo: 'ANORMAL' });
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' });
expect(clic(m, {}, 'otra', c)).toEqual({});
expect(clic(m, {}, 'grupos', -1)).toEqual({});
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
});
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
const m = model(), f = barras(m, {}, 'claro');
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
.toEqual(['5.0', '24.3', '21.7', '7.8']);
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
expect(category.data).toHaveLength(1);
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
});
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
if (kind === 'estrato') data.escenarios['estrato'] = 'grupo_edad';
if (kind === 'categorias') (data.escenarios['categorias'] as any)['LIEAG'].etiqueta = 'Otra';
if (kind === 'periodos') data.escenarios.periodos = ['2025-S1'];
if (kind === 'orden') data.escenarios.filas[0]['orden'] = 5;
if (kind === 'duplicado') data.escenarios.filas.push(data.escenarios.filas[0]);
if (kind === 'version') data.escenarios['version'] = 'otra';
if (kind === 'filtros') data.escenarios['filtros'] = { grupo_edad: '25-34' };
if (kind === 'total') (data.escenarios['totales_estrato'] as any[])[0].n++;
if (kind === 'diferencia') data.general.filas[0]['n'] = 800;
expect(model).toThrow();
});
it('no acepta periodos omitidos por el servidor ni respuestas fuera de la selección', () => {
expect(() => periodosCompatibles(data.general, data.escenarios, 'semestre', ['2025-S1', periodo])).toThrow();
expect(() => periodosCompatibles(data.general, data.escenarios, 'mes', [periodo])).toThrow();
});
it('rechaza procedencias diferentes entre respuestas incluso con conteos iguales', () => {
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
expect(model).toThrow(/reportes distintos/);
});
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => {
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
expect(m.escenarios[0].den).toBeNull(); expect(f.data[0]['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
expect(JSON.stringify(f)).not.toContain('123456');
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
});
it.each(['suprimido', 'nulo', 'sin fila'])('general con %s nunca produce una dona parcial ni convierte null en cero', kind => {
if (kind === 'sin fila') data.general.filas.splice(0, 1);
else Object.assign(data.general.filas[0], { n: null, suprimido: kind === 'suprimido' ? 1 : 0 });
const m = model(); expect(m.total).toBeNull(); expect(dona(m, {}, 'claro').data).toEqual([]);
});
it('escenario ausente no se inventa; solo se dibujan escenarios con filas publicadas', () => {
const removed = data.escenarios.filas.filter(f => f['estrato'] === 'INFO_INSUFICIENTE');
data.escenarios.filas = data.escenarios.filas.filter(f => f['estrato'] !== 'INFO_INSUFICIENTE');
data.general.filas.forEach(f => f['n'] = (f['n'] as number) - (removed.find(r => r['categoria'] === f['categoria'])!['n'] as number));
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
});
it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => {
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
});
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
expect(m.celdas['NORMAL'].n).toBeNull();
});
});
@@ -0,0 +1,236 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
export const ESTRATO = 'estatus_seguimiento';
const SIN_DATO = 'SIN_DATO';
export interface Seleccion { grupo?: string; categoria?: string; }
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
export interface Grupo { id: string; etiqueta: string; color: string; }
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
export interface Escenario {
id: string; etiqueta: string; celdas: Record<string, Celda>;
den: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible';
}
export interface Modelo {
periodo: string; categorias: Categoria[]; grupos: Grupo[];
celdas: Record<string, Celda>; total: number | null; sinDato: Celda;
escenarios: Escenario[]; vacio: boolean; notas: string[];
sinDatoEtiqueta: string;
}
export class Eu7Incompatible extends Error {}
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const escapar = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const miles = (v: number) => v.toLocaleString('es-MX');
const fail = (message: string): never => { throw new Eu7Incompatible(message); };
function celda(fila?: Record<string, unknown>): Celda {
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
return typeof fila?.['n'] === 'number' && fila['suprimido'] === 0
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
}
function suma(celdas: Celda[]): number | null {
if (celdas.some(c => c.n === null)) return null;
const value = celdas.reduce((s, c) => s + c.n!, 0);
return Number.isSafeInteger(value) ? value : fail('Conteos fuera de rango.');
}
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})`;
}
function catalogo(data: IndicadorDatos): Categoria[] {
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
const result = Object.entries(cats).map(([id, c]) => {
if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim()
|| typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])
|| typeof c['grupo'] !== 'string' || typeof grupos[c['grupo']] !== 'string'
|| (id === SIN_DATO) !== (c['grupo'] === SIN_DATO)) return fail('Categorías EU7 incompatibles.');
return { id, etiqueta: c['etiqueta'], color: c['color'], grupo: c['grupo'] };
});
if (result.length < 2 || new Set(result.map(c => c.etiqueta)).size !== result.length) return fail('Categorías EU7 ambiguas.');
return result;
}
/** Validate the common temporal scope before exposing any period's figures. */
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
for (const d of [general, escenarios]) {
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
return fail('Los datos EU7 no corresponden al indicador o al periodo aplicado.');
}
}
if (general.periodos.length !== escenarios.periodos.length || general.periodos.some(p => !escenarios.periodos.includes(p))
|| (solicitados && (solicitados.length !== general.periodos.length || solicitados.some(p => !general.periodos.includes(p))))
|| general['version'] !== escenarios['version'] || general['unidad'] !== escenarios['unidad']) {
return fail('Las respuestas general y estratificada no comparten periodos, versión o unidad.');
}
return solicitados ? [...solicitados] : [...general.periodos].sort();
}
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
periodosCompatibles(general, porEscenario, general.tipo_periodo);
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
return fail('Respuestas EU7 inválidas para el escenario clínico sin filtros locales.');
}
const cats = catalogo(general), other = catalogo(porEscenario);
const nombres = general['grupos_de_categoria'] as Record<string, string>;
const otrosNombres = porEscenario['grupos_de_categoria'] as Record<string, string>;
if (cats.length !== other.length || cats.some(c => {
const o = other.find(v => v.id === c.id);
return !o || o.etiqueta !== c.etiqueta || o.color !== c.color || o.grupo !== c.grupo
|| nombres[c.grupo] !== otrosNombres[c.grupo];
})) return fail('Los catálogos general y estratificado son diferentes.');
const orden = new Map<string, number>();
const indexar = (d: IndicadorDatos, estratificado: boolean) => {
const index = new Map<string, Record<string, unknown>>();
for (const row of d.filas.filter(f => f['periodo'] === periodo)) {
const c = row['categoria'], e = row['estrato'], n = row['n'], o = row['orden'];
if (row['grupo'] !== 'TOTAL' || typeof c !== 'string' || !cats.some(cat => cat.id === c)
|| (estratificado ? typeof e !== 'string' || !valores.includes(e) : e != null)
|| typeof o !== 'number' || !Number.isSafeInteger(o) || o < 0
|| ![0, 1].includes(row['suprimido'] as number)
|| (n !== null && (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0))) return fail('Fila EU7 inválida.');
const key = JSON.stringify([estratificado ? e : null, c]);
if (index.has(key) || (orden.has(c) && orden.get(c) !== o)) return fail('Filas u orden EU7 ambiguos.');
orden.set(c, o); index.set(key, row);
}
return index;
};
const g = indexar(general, false), e = indexar(porEscenario, true);
const reporte = (d: IndicadorDatos) => {
const reports = d['reportes'];
if (reports === undefined) return undefined;
if (!Array.isArray(reports) || !reports.every(registro)) return fail('Procedencia EU7 inválida.');
const active = reports.filter(r => r['periodo'] === periodo);
if (active.length !== 1) return fail('Procedencia del periodo EU7 ambigua.');
return active[0];
};
const rg = reporte(general), re = reporte(porEscenario);
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
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 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.');
const escenarios: Escenario[] = (valores as string[]).filter(v => [...e.values()].some(row => row['estrato'] === v)).map(id => {
const cells = Object.fromEntries(cats.map(c => [c.id, celda(e.get(JSON.stringify([id, c.id])))]));
const matches = (totals as Record<string, unknown>[] | undefined)?.filter(t => t['periodo'] === periodo && t['estrato'] === id) ?? [];
if (matches.length > 1 || matches.some(t => t['grupo'] !== 'TOTAL' || ![0, 1].includes(t['suprimido'] as number)
|| (t['n'] !== null && (typeof t['n'] !== 'number' || !Number.isSafeInteger(t['n']) || t['n'] < 0)))) return fail('Total de escenario ambiguo.');
const total = matches[0] && celda(matches[0]);
const estadoEscenario = estado([...Object.values(cells), ...(total ? [total] : [])]);
const completo = suma(Object.values(cells));
if (completo !== null && total?.n != null && completo !== total.n) return fail('El total del escenario difiere de sus categorías.');
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
});
// Compare only fully published sums. Never derive a hidden value by subtraction.
if (escenarios.length) {
for (const c of cats) {
const total = suma(escenarios.map(s => s.celdas[c.id]));
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
}
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
}
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id]));
export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string {
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL';
}
/** Same state machine as the deliverable, with guards for unrelated/stale events. */
export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number): Seleccion {
if (traza === 'centro') return sel.categoria && sel.grupo ? { grupo: sel.grupo } : {};
if (traza === 'grupos') {
const g = m.grupos[indice]?.id;
return !g ? sel : sel.grupo === g ? {} : { grupo: g };
}
if (traza !== 'categorias') return sel;
const c = m.categorias[indice];
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id };
}
export function porcentaje(s: Escenario, categoria: string): number | null {
const n = s.celdas[categoria]?.n;
return s.den !== null && s.den > 0 && n != null ? 100 * n / s.den : null;
}
/** Three pies share one square plot area; SIN_DATO never enters their values. */
export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
if (m.total === null || m.total === 0) return { data: [], layout: {} };
const p = c2Theme(tema);
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
const rotulos = (values: number[], labels: string[], pct: boolean) => {
const total = values.reduce((s, n) => s + n, 0);
return values.map((v, i) => !total || v / total < .05 ? '' : escapar(labels[i]) + (pct ? `<br>${(100 * v / total).toFixed(0)} %` : ''));
};
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes · %{customdata[1]} % del total con resultado<extra></extra>' };
const custom = (values: number[]) => values.map(n => [miles(n), (100 * n / m.total!).toFixed(1)]);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
textfont: { size: 11 }, customdata: custom(exterior),
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
}
/** Selection never changes the original denominator or renormalizes a subset. */
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
const p = c2Theme(tema);
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta));
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
return { data: m.categorias.filter(c => visibles.includes(c.id)).map(c => {
const x = m.escenarios.map(s => porcentaje(s, c.id));
return { type: 'bar', orientation: 'h', name: escapar(c.etiqueta), y, x,
marker: { color: c.color, line: { color: p.background, width: 1 } },
text: x.map(v => v !== null && v >= 6 ? `${v.toFixed(0)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
customdata: m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]),
hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` };
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 36, b: 90 }, showlegend: false,
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 100] },
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
: sel.grupo || sel.categoria ? `<b>${sumas[i]!.toFixed(1)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${s.den})` : '' })),
}, config: { displayModeBar: false } };
}
@@ -108,7 +108,9 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
choose(); http.expectNone(r => r.url.includes('/figuras/'));
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
fixture.detectChanges(); flushFigures(periods[1], items.length); http.expectNone(() => true);
// EU7 now owns a coordinated C2 view. This temporal fixture publishes only
// placeholder f/g figures, so that card must stop as incompatible, without GET.
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true);
});
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
@@ -126,9 +128,10 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
choose(); const applied = page.filters!.applied;
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
cards()[0].setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
cards()[0].selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
expect(cards()[0].selectedFigure).toBe('g'); http.expectNone(() => true);
const card = cards().find(card => !card.isEu7)!;
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
expect(page.filters!.applied).toBe(applied); expect(page.initialPeriodState()).toBe('ready');
});
it('regreso de otro dominio restaura el periodo manual sin imponer el inicial', () => {