Compare commits

...

2 Commits

Author SHA1 Message Date
Manuel Aurrecoechea Castillo 03cc9c9800 20261119 CaMa: donas de BI-RADS y etiquetas del resumen
La oportunidad dice confirmación histopatológica, la tarjeta de mastografías muestra dos donas y Cómo leer puede reintentar los metadatos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:50:01 -06:00
Manuel Aurrecoechea Castillo de3d247d0d 20261119 Favicon colores textos 2026-11-19 15:10:59 -06:00
32 changed files with 377 additions and 178 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 34 KiB

@@ -32,12 +32,12 @@ import { parConteos } from './indicadores-conteos-pareados';
<mat-card> <mat-card>
<header> <header>
<div class="card-identity"> <div class="card-identity">
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2> <h2 [id]="titleId" tabindex="-1">{{ tituloVisible }}</h2>
</div> </div>
</header> </header>
@if (!sobrio) { @if (!sobrio) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned" <button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo" [attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + tituloVisible"
(click)="pinChanged.emit()"> (click)="pinChanged.emit()">
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }} <mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button> </button>
@@ -62,7 +62,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</div> </div>
} @else if (conteos; as par) { } @else if (conteos; as par) {
<div #visibilityRegion class="conteos-region"> <div #visibilityRegion class="conteos-region">
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" /> <app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [metadataAttempt]="metadataAttempt" (metadataRequested)="loadMetadata()" />
</div> </div>
} @else if (selectedFigure) { } @else if (selectedFigure) {
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual"> <div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@@ -126,6 +126,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
private metadataSubscription?: Subscription; private metadataSubscription?: Subscription;
private metadataKey = ''; private metadataKey = '';
metadata?: IndicadorMetadatos; metadata?: IndicadorMetadatos;
metadataAttempt = 0;
private activatedKey = ''; private activatedKey = '';
constructor() { constructor() {
effect(() => { effect(() => {
@@ -135,6 +136,10 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
} }
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup. // CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; } get sobrio() { return this.dominio === 'cama'; }
// The published title keeps «individual»; the card does not.
get tituloVisible() {
return this.indicador.id === 'cama_birads_456_mastografia' ? this.indicador.titulo.replace(' individual', '') : this.indicador.titulo;
}
get pair() { return dualFigures(this.indicador); } get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
@@ -220,6 +225,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.metadataKey !== key) return; if (this.metadataKey !== key) return;
if (!value) this.metadataKey = ''; if (!value) this.metadataKey = '';
this.metadata = value; this.metadata = value;
this.metadataAttempt++;
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
}); });
} }
@@ -35,6 +35,22 @@ summary { cursor: pointer; padding-block: .75rem; }
table { border-collapse: collapse; width: 100%; margin-block: 1rem; } table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
caption { text-align: start; font-weight: 600; } caption { text-align: start; font-weight: 600; }
.histo-meta { display: flex; justify-content: flex-end; align-items: flex-start; gap: .75rem; }
.view-context { display: flex; flex-direction: column; align-items: flex-end; gap: .1rem; margin: .15rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; }
.histo .figure { border-top: 0; }
.histo .figure + .figure { border-top: 1px solid var(--issste-border); padding-top: .25rem; }
.histo .help { position: relative; display: flex; justify-content: flex-end; padding-bottom: .35rem; }
.histo .help .methodology-toggle { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border-radius: 50%; font-weight: 800; font-size: 1rem; line-height: 1; background: color-mix(in srgb, var(--issste-accent) 14%, var(--issste-surface)); }
.histo .help .methodology { position: absolute; z-index: 8; top: 100%; right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
.histo .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
.histo .tab-bar { display: flex; align-items: flex-end; gap: .5rem; border-bottom: 1px solid var(--issste-border); }
.histo .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
.histo .tabs .tab { border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
.histo .tabs .tab[aria-selected=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
.histo .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; padding: .65rem .1rem .1rem; }
.histo .tab-panel .child { border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
.histo .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); }
.histo .tab .swatch, .histo .tab-panel .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); }
.reading-guide h3 { margin: 0 0 .25rem; } .reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide + .reading-guide { margin-top: 1rem; } .reading-guide + .reading-guide { margin-top: 1rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } .reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
@@ -43,4 +59,7 @@ app-plotly-chart { --plot-height: 360px; }
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); } .rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
.rate-states:empty { display: none; } .rate-states:empty { display: none; }
/* Rates on the left, donut on the right (the reverse of EU7). */ /* Rates on the left, donut on the right (the reverse of EU7). */
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } } @media (min-width: 1100px) {
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
}
@@ -1,21 +1,7 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)"> <section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button> <div class="conteos-head">
@if (helpOpen) { <button type="button" class="help-icon" aria-label="Cómo leer" [matTooltip]="helpText" matTooltipClass="issste-help-tooltip" matTooltipPosition="below" (mouseenter)="showHelp()" (focus)="showHelp()"><span aria-hidden="true">!</span></button>
<div class="methodology"> </div>
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
<h3>Dona por categoría</h3>
@if (donutGuide; as guide) {
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
</section>
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
<p>Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.</p>
</section>
</div>
}
@switch (status()) { @switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> } @case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> } @case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@@ -38,12 +24,13 @@
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> } } @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> } @if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section> </section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3> <section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} por categoría, {{ m.periodo }}</h3>
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" /> @if (totalPacientes) {
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="indicador.titulo + ', dona de pacientes por categoría BI-RADS, ' + m.periodo" />
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> } @if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
</section> </section>
</div> </div>
<p class="note">Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> } @for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary> <details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0"> <div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
@@ -11,8 +11,15 @@ h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; } border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
.periods button:disabled { opacity: .5; cursor: default; } .periods button:disabled { opacity: .5; cursor: default; }
// The two figures share the card in equal halves; one above the other on a narrow card. // The two figures share the card in equal halves; one above the other on a narrow card.
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .conteos-head { display: flex; justify-content: flex-end; }
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
.figure + .figure { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-4); padding-top: var(--issste-space-4); }
@media (min-width: 1100px) {
.figures { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.figure + .figure { border-top: 0; margin-top: 0; padding-top: 0; border-inline-start: 1px solid var(--issste-border); padding-inline-start: var(--issste-space-6); }
}
app-plotly-chart { --plot-height: 400px; } app-plotly-chart { --plot-height: 400px; }
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards. // Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
.donut-chart { --plot-min-width: 230px; } .donut-chart { --plot-min-width: 230px; }
@@ -4,16 +4,17 @@ import { TitleCasePipe } from '@angular/common';
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { filterCompatibility, GlobalApplied } from './indicadores-memory'; import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados'; import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
@Component({ @Component({
selector: 'app-indicador-conteos-pareados', selector: 'app-indicador-conteos-pareados',
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe], imports: [MatButtonModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, TitleCasePipe],
templateUrl: './indicador-conteos-pareados.html', templateUrl: './indicador-conteos-pareados.html',
styleUrl: './indicador-conteos-pareados.scss', styleUrl: './indicador-conteos-pareados.scss',
}) })
@@ -26,46 +27,68 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@Input({ required: true }) applied!: GlobalApplied; @Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true; @Input() visible = true;
@Input() metadata?: IndicadorMetadatos; @Input() metadata?: IndicadorMetadatos;
// Bumps when a metadata request finishes, including a failure that leaves metadata empty.
@Input() metadataAttempt = 0;
readonly metadataRequested = output<void>(); readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = ''; message = '';
periodIndex = 0; periodIndex = 0;
pages: ModeloConteos[] = []; pages: ModeloConteos[] = [];
donutFigure?: PlotlyFigure; donutFigure?: PlotlyFigure;
barsFigure?: PlotlyFigure; patientsFigure?: PlotlyFigure;
private readonly snapshots = inject(IndicadoresSnapshots); private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef); private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription; private subscription?: Subscription;
private key = ''; private key = '';
private loaded = false; private loaded = false;
private anchoDona = 390; private anchoDona = 390;
private anchoPacientes = 390;
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; } get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; } get total() { return this.model ? totalExamenes(this.model) : null; }
get totalPacientes() { return this.model ? totalPacientes(this.model) : null; }
texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); } texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); }
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); } textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
helpOpen = false; // True only while a metadata request is outstanding. A failure leaves metadata empty, so the next
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's // hover may ask again; the catalog card ignores a second ask until that request finishes.
// description of its own bars does not apply to them and is not used. private helpAsked = false;
// "Cómo leer": what the kit publishes for the exams' donut. Both donuts use the same categories.
get donutGuide() { get donutGuide() {
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas'); const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
const descripcion = detail?.descripcion?.trim() ?? ''; const descripcion = detail?.descripcion?.trim() ?? '';
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined; return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
} }
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } get helpText() {
const guide = this.donutGuide;
const dona = guide
? ['Dona por categoría', guide.descripcion, ...guide.como_leer].filter(line => line.length)
: [this.metadata ? 'El servicio no publica instrucciones de lectura para esta figura.' : 'Metadatos publicados pendientes.'];
const pacientes = this.par.unidades.pacientes;
const examenes = this.par.unidades.examenes;
return [...dona, `${pacientes[0].toUpperCase()}${pacientes.slice(1)} y ${examenes}`,
`Cada ${pacientes.slice(0, -1)} cuenta una vez en el periodo, en la categoría más grave de sus ${examenes}. Cada ${examenes.slice(0, -1)} cuenta en su propia categoría. Cada dona muestra uno de esos conteos; no se calcula cuántas ${examenes} tiene cada ${pacientes.slice(0, -1)}, porque no son las mismas poblaciones.`,
].join('\n');
}
showHelp() {
if (this.metadata || this.helpAsked) return;
this.helpAsked = true;
this.metadataRequested.emit();
}
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
if (changes['metadata'] && this.metadata) this.helpAsked = false;
else if (changes['metadataAttempt'] && !this.metadata) this.helpAsked = false;
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]); const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
if (key !== this.key) { if (key !== this.key) {
this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.helpAsked = false; this.clear();
if (!this.visible) { this.status.set('deferred'); return; } if (!this.visible) { this.status.set('deferred'); return; }
this.load(); this.load();
} else if (this.visible && !this.loaded) this.load(); } else if (this.visible && !this.loaded) this.load();
else if (this.model && changes['tema']) this.draw(); else if (this.model && changes['tema']) this.draw();
} }
retry() { if (this.visible) this.load(); } retry() { if (this.visible) this.load(); }
private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; } private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
private load() { private load() {
this.subscription?.unsubscribe(); this.subscription?.unsubscribe();
this.loaded = true; this.clear(); this.loaded = true; this.clear();
@@ -111,11 +134,17 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
const m = this.model; const m = this.model;
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho); if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
} }
ajustarAnchoPacientes(ancho: number) {
if (ancho === this.anchoPacientes) return;
this.anchoPacientes = ancho;
const m = this.model;
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
}
private draw() { private draw() {
const m = this.model; const m = this.model;
if (!m) return; if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona); this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
this.barsFigure = barrasConteos(m, this.par, this.tema); this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
this.changeDetector.markForCheck(); this.changeDetector.markForCheck();
} }
ngOnDestroy() { this.subscription?.unsubscribe(); } ngOnDestroy() { this.subscription?.unsubscribe(); }
@@ -1,20 +1,27 @@
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS"> <section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> <div class="histo-meta">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button> <div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
@if (helpOpen) { <button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
<div class="methodology"> @if (helpOpen) {
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p> <div class="methodology" id="histo-como-leer" role="tooltip">
@if (metadata) { <p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@for (guide of readingGuide; track guide.figura) { @if (metadata) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre"> @for (guide of readingGuide; track guide.figura) {
<h3>{{ guide.nombre }}</h3> <section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> } <h3>{{ guide.nombre }}</h3>
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> } @if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
</section> @if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
} }
} </div>
</div> }
} </div>
<p class="view-context">
<span>{{ intervalLabel }}</span>
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
</p>
</div>
@switch (status()) { @switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> } @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 la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> } @case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@@ -32,14 +39,31 @@
@if (model; as m) { @if (model; as m) {
@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> } @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 { @else {
<div class="legend">
<div class="tab-bar">
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
@for (g of m.grupos; track g.id; let gi = $index) {
<button type="button" role="tab" class="tab" [id]="'histo-tab-' + g.id" [style.--swatch]="g.color" [attr.aria-selected]="selection?.grupo === g.id" [attr.aria-controls]="'histo-panel-' + g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
</div>
@for (g of m.grupos; track g.id) {
@if (selection?.grupo === g.id) {
<div class="tab-panel" role="tabpanel" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id" [attr.aria-label]="'Resultados de ' + g.etiqueta">
@for (c of m.categorias; track c.id; let ci = $index) {
@if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
}
</div>
}
}
</div>
<div class="figures"> <div class="figures">
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3> <section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
@if (ratesFigure) { @if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" /> <app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
} }
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
</ul>
</section> </section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3> <section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) { @if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
@@ -47,25 +71,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> } } @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> </section>
</div> </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="families">
@for (g of m.grupos; track g.id; let gi = $index) {
<section class="family">
<button type="button" class="parent" [style.--swatch]="g.color" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
<div class="children" role="group" [attr.aria-label]="'Resultados de ' + g.etiqueta">
@for (c of m.categorias; track c.id; let ci = $index) {
@if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
}
</div>
</section>
}
</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> } @for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary> <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"> <div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
@@ -5,7 +5,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar'; import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http'; import { httpMessage } from './indicadores-http';
import { Celda } from './indicadores-confirmacion-citologia'; import { Celda } from './indicadores-confirmacion-citologia';
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
donutFigure?: PlotlyFigure; donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure; ratesFigure?: PlotlyFigure;
helpOpen = false; helpOpen = false;
private helpPinned = false;
private readonly snapshots = inject(IndicadoresSnapshots); private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef); private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription; private subscription?: Subscription;
@@ -54,7 +55,11 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
private readonly alCambiarAncho = () => this.draw(); private readonly alCambiarAncho = () => this.draw();
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); } constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; }
get contextPeriod() {
return this.model?.periodo ?? this.periods[this.periodIndex]
?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : '');
}
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
}); });
} }
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } toggleHelp() {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
this.helpPinned = true;
this.showHelp();
}
showHelp() {
if (this.helpOpen) return;
this.helpOpen = true;
this.metadataRequested.emit();
}
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
onHelpFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
this.helpPinned = false;
this.helpOpen = false;
}
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS }) const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba'); expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba'); expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba'); expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
expect(fixture.nativeElement.querySelector('.period-label')).toBeNull();
fixture.componentRef.setInput('temporalReference', '2025-S2'); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.period-label').textContent).toBe('Periodo:');
expect(fixture.nativeElement.querySelector('.kpi-foot').textContent).toContain('2025-S2');
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba'); expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba'); expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional'); expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
@if (value !== null && value !== undefined) { @if (value !== null && value !== undefined) {
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p> <p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
} }
@if (temporalReference) { <p>{{ temporalReference }}</p> } <div class="kpi-foot">
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p> @if (temporalReference) {
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> } <p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
}
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</div>
</mat-card> </mat-card>
`, `,
styles: ` styles: `
:host { display: block; min-width: 0; } :host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6); mat-card { box-sizing: border-box; display: flex; flex-direction: column; flex: 1 1 auto; height: auto; min-height: 100%; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; } border-radius: var(--issste-radius); box-shadow: none; }
.kpi-foot { margin-top: auto; }
.period { display: flex; flex-wrap: wrap; align-items: baseline; gap: .35rem; }
.period-label { font-weight: 600; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; } h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
h3, p { overflow-wrap: anywhere; } h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; } p { margin: var(--issste-space-3) 0 0; }
@@ -46,6 +53,10 @@ export class IndicadorKpiCard {
// A card that shows its value needs no "Disponible" line. // A card that shows its value needs no "Disponible" line.
@Input() quietWhenAvailable = false; @Input() quietWhenAvailable = false;
@Input() additionalInfo?: string; @Input() additionalInfo?: string;
get labeledPeriod(): boolean {
const text = this.temporalReference?.trim();
return !!text && text.split(',').every(part => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(part.trim()));
}
get informationLine(): string | undefined { get informationLine(): string | undefined {
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value); const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
return [...new Set(lines)].join(' '); return [...new Set(lines)].join(' ');
@@ -2,11 +2,13 @@
<section aria-label="Editor de filtros generales del proyecto"> <section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> } @if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields compact"> <div class="fields compact">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label> <div class="interval">
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)"> <span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> } <mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
</mat-select> @if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
</mat-form-field> @if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label> <mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])"> <mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger> <mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -51,11 +53,13 @@
<section aria-label="Editor de filtros generales del proyecto"> <section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> } @if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields"> <div class="fields">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label> <div class="interval">
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)"> <span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> } <mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
</mat-select> @if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
</mat-form-field> @if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label> <mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])"> <mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger> <mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -8,7 +8,9 @@
:host(.compacto) .apply-button { min-height: 40px; } :host(.compacto) .apply-button { min-height: 40px; }
:host(.compacto) .period-builder button { min-height: 40px; } :host(.compacto) .period-builder button { min-height: 40px; }
section { min-width: 0; } section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); } .fields { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; } mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
.period-builder mat-form-field { flex: 0 1 10rem; } .period-builder mat-form-field { flex: 0 1 10rem; }
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; } .period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
@@ -138,16 +138,11 @@ describe('UX-04 control asistido', () => {
fixture.nativeElement.querySelector('button[mat-flat-button]').click(); fixture.nativeElement.querySelector('button[mat-flat-button]').click();
expect(apply).toHaveBeenCalledTimes(1); expect(apply).toHaveBeenCalledTimes(1);
}); });
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => { it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent); const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
expect(labels).toContain('Intervalo de análisis'); expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
expect(labels).not.toContain('Modalidad'); expect(labels).not.toContain('Modalidad');
const select = fixture.debugElement.queryAll(By.css('mat-form-field')) expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
expect(options).toEqual(['Semestral', 'Mensual']);
select.componentInstance.close();
}); });
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => { it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {}, fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
@@ -1,6 +1,7 @@
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core'; import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select'; import { MatSelectModule } from '@angular/material/select';
@@ -10,7 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
@Component({ @Component({
selector: 'app-indicador-period-filters', selector: 'app-indicador-period-filters',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule], imports: [FormsModule, MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatInputModule, MatSelectModule],
host: { '[class.compacto]': 'compact' }, host: { '[class.compacto]': 'compact' },
templateUrl: './indicador-period-filters.html', templateUrl: './indicador-period-filters.html',
styleUrl: './indicador-period-filters.scss', styleUrl: './indicador-period-filters.scss',
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'], ['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]); ]);
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([ expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']); 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]); expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
}); });
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => { it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
@@ -215,7 +215,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false); expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false);
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad'); expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
expect(cards().map(card => text(card, 'h3'))).toEqual([ expect(cards().map(card => text(card, 'h3'))).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']); 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]); expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]);
expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']); expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
expect(cards()[1].textContent).toContain('aún no está publicado'); expect(cards()[1].textContent).toContain('aún no está publicado');
@@ -266,7 +266,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull(); expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
expect(text).not.toContain('Cáncer de mama, investigación'); expect(text).not.toContain('Cáncer de mama, investigación');
expect(text).toContain('Explora los indicadores de cáncer de mama.'); expect(text).toContain('Explora los indicadores de cáncer de mama.');
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros generales'); expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros');
expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull(); expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull();
expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.'); expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
expect(text).not.toContain('Filtro general aplicado'); expect(text).not.toContain('Filtro general aplicado');
@@ -312,7 +312,8 @@ describe('Filtros generales de CaMa: periodo único', () => {
it('muestra Intervalo de análisis, Periodo seleccionado y Aplicar en una fila, sin modalidad ni resúmenes de edición', () => { it('muestra Intervalo de análisis, Periodo seleccionado y Aplicar en una fila, sin modalidad ni resúmenes de edición', () => {
// Fails if the multi-period controls or the editing summaries come back to CaMa. // Fails if the multi-period controls or the editing summaries come back to CaMa.
mount(true); mount(true);
expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']); expect(fixture.nativeElement.querySelector('.field-label').textContent!.trim()).toBe('Intervalo de análisis');
expect(labels()).toEqual(['Periodo seleccionado']);
expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull(); expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull();
const text = fixture.nativeElement.textContent as string; const text = fixture.nativeElement.textContent as string;
expect(text).not.toContain('Modalidad'); expect(text).not.toContain('Modalidad');
@@ -46,16 +46,16 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
const section = () => root().querySelector('.graphic-section') as HTMLElement; const section = () => root().querySelector('.graphic-section') as HTMLElement;
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
it('CaMa: «Indicadores clínicos» y un contador que cuenta lo que la sección muestra', () => { it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
// Fails if the heading or the counter go back to the whole catalog (6) while a card is not drawn. // Fails if the heading goes back to the whole catalog while a card is not drawn.
open('cama', CAMA); open('cama', CAMA);
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
expect(titles()).not.toContain('Distribución de resultados de biopsia'); expect(titles()).not.toContain('Distribución de resultados de biopsia');
// The patients' counts go on the exams' card, so the partner indicator has no card of its own. // The patients' counts go on the exams' card, so the partner indicator has no card of its own.
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6'); expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
// Only the paired card is a published indicator the summary draws; the other three are in Histórico. // Only the paired card is a published indicator the summary draws; the other three are in Histórico.
expect(titles()).toEqual(['Porcentaje individual de mastografías']); expect(titles()).toEqual(['Porcentaje de mastografías']);
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado'); expect(root().textContent).not.toContain('indicador publicado');
}); });
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => { it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones. // Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
@@ -111,7 +111,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
expect(root().querySelector('.catalog-search')).not.toBeNull(); expect(root().querySelector('.catalog-search')).not.toBeNull();
expect(root().querySelectorAll('.pin-toggle').length).toBe(6); expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
expect(section().textContent).toContain('2 figuras publicadas'); expect(section().textContent).toContain('2 figuras publicadas');
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados'); expect(root().textContent).not.toContain('indicadores publicados');
}); });
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => { it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
open('cacu', OTRO('cacu')); open('cacu', OTRO('cacu'));
@@ -14,7 +14,7 @@ import { IndicadorConteosPareados } from './indicador-conteos-pareados';
import { IndicadoresMemory } from './indicadores-memory'; import { IndicadoresMemory } from './indicadores-memory';
import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorDatos } from './indicadores.models'; import { IndicadorDatos } from './indicadores.models';
import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes } from './indicadores-conteos-pareados'; import { barrasConteos, ConteosIncompatibles, donaConteos, donaPacientes, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
const PAR = parConteos('cama', 'cama_birads_456_mastografia')!; const PAR = parConteos('cama', 'cama_birads_456_mastografia')!;
const CATEGORIAS = { const CATEGORIAS = {
@@ -89,6 +89,16 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]); expect(dona.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.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
}); });
it('la dona de pacientes usa la categoría más grave de cada paciente, con ceros y sin razón', () => {
const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P));
expect(totalPacientes(m)).toBe(31);
const dona = donaPacientes(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } };
expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']);
expect(dona.data[0].values).toEqual([13, 0, 0, 0, 18, 0]);
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>31</b>', 'pacientes']);
expect(JSON.stringify(dona)).not.toMatch(/≈|por paciente|razón/i);
expect(donaPacientes(modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })), PAR, 'claro').data).toEqual([]);
});
}); });
describe('Conteos pareados de CaMa: etiquetas de la dona', () => { describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
@@ -192,20 +202,21 @@ describe('Tarjeta pareada de CaMa en la página', () => {
// Fails if the patients' indicator keeps a card of its own beside the pair. // Fails if the patients' indicator keeps a card of its own beside the pair.
const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary. // Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
expect(titulos).toEqual(['Porcentaje individual de mastografías']); expect(titulos).toEqual(['Porcentaje de mastografías']);
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado'); expect(root().textContent).not.toContain('indicador publicado');
}); });
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => { it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
abrir(); abrir();
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim(); const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim()); const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes y mastografías, 2025-S2']); expect(h3).toEqual(['Mastografías por categoría, 2025-S2', 'Pacientes por categoría, 2025-S2']);
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
expect(graficas).toHaveLength(2); expect(graficas).toHaveLength(2);
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 2]); expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]);
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]); expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
expect(texto('app-indicador-conteos-pareados')).toContain('no se calcula la razón de mastografías por paciente'); expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente');
expect(root().querySelector('.help-icon')?.getAttribute('aria-label')).toBe('Cómo leer');
expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato'); expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato');
}); });
it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => { it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => {
@@ -213,7 +224,8 @@ describe('Tarjeta pareada de CaMa en la página', () => {
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim())); const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]); expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
expect(root().textContent).toContain('Pacientes pendientes'); expect(root().textContent).toContain('Pacientes pendientes');
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2); expect(root().textContent).toContain('Dona de pacientes no disponible');
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
}); });
it('una respuesta incompatible no dibuja cifras y lo dice', () => { it('una respuesta incompatible no dibuja cifras y lo dice', () => {
// Fails if a pair of responses that are not the two indicators is drawn as if it were. // Fails if a pair of responses that are not the two indicators is drawn as if it were.
@@ -236,3 +248,45 @@ describe('Tarjeta pareada de CaMa en la página', () => {
expect(pedidos().length).toBeGreaterThan(0); expect(pedidos().length).toBeGreaterThan(0);
}); });
}); });
describe('Cómo leer de conteos pareados: reintento tras un fallo', () => {
it('vuelve a pedir los metadatos después de un fallo, sin duplicar la consulta abierta ni la ya recibida', () => {
TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.configureTestingModule({ imports: [IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
const fixture = TestBed.createComponent(IndicadorCatalogCard);
const http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama');
fixture.componentRef.setInput('indicador', {
id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías', contrato: 'C2',
figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'],
});
fixture.componentRef.setInput('tema', 'claro');
fixture.componentRef.setInput('applied', { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 });
fixture.detectChanges();
fixture.componentInstance.setVisible(true);
fixture.detectChanges();
const conteos = fixture.debugElement.query(By.directive(IndicadorConteosPareados)).componentInstance as IndicadorConteosPareados;
const meta = () => http.match(r => r.url.endsWith('/metadatos'));
conteos.showHelp();
fixture.detectChanges();
const primero = meta();
expect(primero).toHaveLength(1);
conteos.showHelp();
fixture.detectChanges();
expect(meta()).toHaveLength(0);
primero[0].flush('no', { status: 500, statusText: 'Error' });
fixture.detectChanges();
conteos.showHelp();
fixture.detectChanges();
const segundo = meta();
expect(segundo).toHaveLength(1);
segundo[0].flush({ descripcion: 'Lectura de la dona' });
fixture.detectChanges();
conteos.showHelp();
fixture.detectChanges();
expect(meta()).toHaveLength(0);
fixture.destroy();
http.match(() => true);
http.verify();
});
});
@@ -50,7 +50,7 @@ const COLOR_NEUTRO = '#8A9199';
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; } export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; } export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
export interface ModeloConteos { export interface ModeloConteos {
periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; periodo: string; examenes: CategoriaConteo[]; pacientes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
// False when the patients' version is not one whose definition was checked: their cells stay unknown. // False when the patients' version is not one whose definition was checked: their cells stay unknown.
pacientesVerificados: boolean; notas: string[]; pacientesVerificados: boolean; notas: string[];
} }
@@ -97,6 +97,8 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
return periodos.map(periodo => ({ return periodos.map(periodo => ({
periodo, periodo,
examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })), examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })),
// The same published cells the family rows add up, kept by category for the patients' donut.
pacientes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catPacientes, id), color: color(id, index), n: verificados ? de(filasP, catPacientes, periodo, id) : null })),
// Only the exams the response reports apart; an indicator that lists no such category has none. // 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, sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
filas: par.grupos.map(g => ({ filas: par.grupos.map(g => ({
@@ -109,14 +111,15 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
})); }));
} }
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n)); export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
export const totalPacientes = (m: ModeloConteos) => m.pacientesVerificados ? sumar(m.pacientes.map(c => c.n)) : null;
const ALTO_DONA = 400, MARGEN_DONA = 8; const ALTO_DONA = 400, MARGEN_DONA = 8;
const DIAMETRO_MAXIMO_DONA = 270; const DIAMETRO_MAXIMO_DONA = 270;
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure { function donaDe(categorias: CategoriaConteo[], unidad: string, tema: Tema, ancho: number): PlotlyFigure {
const total = totalExamenes(m); const total = sumar(categorias.map(c => c.n));
if (!total) return { data: [], layout: {} }; if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!); const p = c2Theme(tema), n = categorias.map(c => c.n!);
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines. // 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 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 diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
@@ -125,7 +128,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10); const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7))); const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8; const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
const etiquetas = m.examenes.map(c => escapar(c.etiqueta)); const etiquetas = categorias.map(c => escapar(c.etiqueta));
const porcentajes = n.map(v => percentNumber(100 * v / total)); const porcentajes = n.map(v => percentNumber(100 * v / total));
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false }; 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, // The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
@@ -154,7 +157,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
}); });
}); });
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas, return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none', marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] }, domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
customdata: n.map((v, i) => [miles(v), porcentajes[i]]), customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
hovertemplate: '%{value}<extra></extra>' }], hovertemplate: '%{value}<extra></extra>' }],
@@ -163,11 +166,20 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
shapes: llamadas.map(({ shape }) => shape), shapes: llamadas.map(({ shape }) => shape),
annotations: [ annotations: [
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` }, { ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: par.unidades.examenes }, { ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: unidad },
...llamadas.map(({ annotation }) => annotation), ...llamadas.map(({ annotation }) => annotation),
] }, config: { displayModeBar: false } }; ] }, config: { displayModeBar: false } };
} }
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
return donaDe(m.examenes, par.unidades.examenes, tema, ancho);
}
/** Patients in the most severe BI-RADS category of the period. Same slices as the exams' donut; no ratio. */
export function donaPacientes(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
return donaDe(m.pacientes, par.unidades.pacientes, tema, ancho);
}
/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */ /** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure { export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta)); const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
@@ -58,8 +58,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
load(undefined, domain); load(undefined, domain);
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1); expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>; const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(sections[0].textContent).toContain(domain === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + page.domainLabels[domain]); expect(sections[0].querySelector('#global-filters-title')!.textContent!.trim()).toBe('Filtros');
if (domain === 'cama') expect(sections[0].textContent).not.toContain('Filtros generales de ');
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0); expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title'); expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
expect(page.filters!.applied.selection.mode).toBe('todos'); expect(page.filters!.applied.selection.mode).toBe('todos');
@@ -241,7 +241,7 @@ describe('Histopatología por BI-RADS: componente', () => {
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO); expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
r.flush(body as Record<string, unknown>); f.detectChanges(); r.flush(body as Record<string, unknown>); f.detectChanges();
} }
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.families button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement; const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.legend button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => { it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
f.componentRef.setInput('visible', false); f.detectChanges(); f.componentRef.setInput('visible', false); f.detectChanges();
@@ -250,16 +250,22 @@ describe('Histopatología por BI-RADS: componente', () => {
flush(); expect(f.componentInstance.status()).toBe('ready'); flush(); expect(f.componentInstance.status()).toBe('ready');
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[]; const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']); expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
expect([...f.nativeElement.querySelectorAll('.families button')].map((b: Element) => b.textContent!.trim())) expect([...f.nativeElement.querySelectorAll('.tabs button')].map((b: Element) => b.textContent!.trim()))
.toEqual(['No maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Maligno', 'Carcinoma in situ', 'Carcinoma invasor']); .toEqual(['No maligno', 'Maligno']);
expect(f.nativeElement.querySelectorAll('.family')).toHaveLength(2); expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno');
expect([...f.nativeElement.querySelectorAll('.family')[1].querySelectorAll('button')].map((b: Element) => b.textContent!.trim())) expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim()))
.toEqual(['Maligno', 'Carcinoma in situ', 'Carcinoma invasor']); .toEqual(['Carcinoma in situ', 'Carcinoma invasor']);
const grafica = f.nativeElement.querySelector('.figures') as HTMLElement; const grafica = f.nativeElement.querySelector('.figures') as HTMLElement;
const seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement; const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement;
expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true); const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement;
expect(grafica.nextElementSibling?.nextElementSibling).toBe(seleccion); expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
expect(seleccion.textContent).toContain('selección: Maligno'); expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado');
expect(f.nativeElement.querySelector('.selection-status')).toBeNull();
expect(f.nativeElement.querySelector('.rate-states')).toBeNull();
expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia');
expect(contexto.textContent).toContain('Intervalo semestral');
expect(contexto.textContent).toContain('Periodo 2025-S1');
expect(f.componentInstance.selectionLabel).toBe('Maligno');
const table = f.nativeElement.querySelector('table') as HTMLTableElement; const table = f.nativeElement.querySelector('table') as HTMLTableElement;
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual( 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']); ['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']);
@@ -272,16 +278,17 @@ describe('Histopatología por BI-RADS: componente', () => {
it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => { it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => {
f.detectChanges(); flush(); f.detectChanges(); flush();
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub); const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
const volver = () => [...f.nativeElement.querySelectorAll('.legend > button')].find((b: Element) => b.textContent!.trim() === 'Volver') as HTMLButtonElement; expect(f.nativeElement.textContent).not.toContain('Volver');
expect(volver().disabled).toBe(true); boton('No maligno').click(); f.detectChanges();
const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges(); const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
expect(b3.getAttribute('aria-pressed')).toBe('true'); expect(volver().disabled).toBe(false); expect(b3.getAttribute('aria-pressed')).toBe('true');
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (B3)'); expect(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)');
b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' });
boton('Maligno').click(); f.detectChanges();
boton('Carcinoma invasor').click(); f.detectChanges(); boton('Carcinoma invasor').click(); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' });
volver().click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); boton('Maligno').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges(); charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges();
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges(); charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
@@ -295,7 +302,7 @@ describe('Histopatología por BI-RADS: componente', () => {
f.detectChanges(); flush(d); f.detectChanges(); flush(d);
expect(f.componentInstance.status()).toBe('ready'); expect(f.componentInstance.status()).toBe('ready');
expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos'); expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 4C: Suprimido'); expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('Suprimido');
const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent)); const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent));
expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4'); expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4');
}); });
@@ -305,7 +312,7 @@ describe('Histopatología por BI-RADS: componente', () => {
f.detectChanges(); flush(d); f.detectChanges(); flush(d);
const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement; const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement;
expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]); expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]);
expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 6: No disponible'); expect(f.nativeElement.querySelector('.rates').textContent).not.toContain('No disponible');
}); });
it('sin filas en el periodo lo dice y conserva la tabla vacía', () => { it('sin filas en el periodo lo dice y conserva la tabla vacía', () => {
const d = estrato(); d.filas = []; d.totales_estrato = []; const d = estrato(); d.filas = []; d.totales_estrato = [];
@@ -99,7 +99,8 @@ describe('Histórico de CaMa', () => {
expect(plegable.querySelector('summary')!.textContent!.trim()).toBe('Periodos sin dato (5)'); 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(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('app-plotly-chart')).not.toBeNull();
expect(panel.querySelector('.nota')!.textContent!.length).toBeGreaterThan(0); expect(panel.querySelector('.nota')).toBeNull();
expect(panel.textContent).not.toContain('Cada barra es el total de pacientes');
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true })); plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
fixture.detectChanges(); fixture.detectChanges();
expect(plegable.open).toBe(true); expect(plegable.open).toBe(true);
@@ -87,6 +87,12 @@ describe('Histórico: C2 (conteos por categoría)', () => {
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } }); expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías'); expect(r.comoLeer).toContain('mastografías');
}); });
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => {
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
expect(pacientes.comoLeer).toBe('');
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
expect(figura(d(completo)).comoLeer).toContain('Cada barra es el total de pacientes');
});
it('un periodo con una celda suprimida se sombrea completo y sus barras no se dibujan como cero', () => { it('un periodo con una celda suprimida se sombrea completo y sus barras no se dibujan como cero', () => {
// Fails if the known cells of a partly suppressed period pass for its total. // Fails if the known cells of a partly suppressed period pass for its total.
const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f); const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f);
@@ -14,6 +14,12 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette. // The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] }; const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose.
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = {
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' },
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
};
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
// sortedPeriods lists the newest first, for selectors; time here runs left to right. // sortedPeriods lists the newest first, for selectors; time here runs left to right.
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
@@ -56,7 +62,7 @@ function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], te
}; };
} }
// One polygon per run of consecutive values: a band must not bridge a gap in the line. // One polygon per run of consecutive values: a band must not bridge a gap in the line.
function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) { function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string, fillcolor = color + '40') {
const x: (string | null)[] = [], y: (number | null)[] = []; const x: (string | null)[] = [], y: (number | null)[] = [];
let run: number[] = []; let run: number[] = [];
const cerrar = () => { const cerrar = () => {
@@ -69,7 +75,7 @@ function banda(periodos: string[], bajo: (number | null)[], alto: (number | null
}; };
periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); }); periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); });
cerrar(); cerrar();
return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' }; return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor, line: { width: 0 }, hoverinfo: 'skip' };
} }
// Separate rows from what is missing or suppressed; a period is judged by its only row. // Separate rows from what is missing or suppressed; a period is judged by its only row.
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) { function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
@@ -107,10 +113,13 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo { function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
const periodos = validar(data), unidad = unidadDe(data); const periodos = validar(data), unidad = unidadDe(data);
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
const propio = DIAS[data.id];
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
return { return {
figure: { data: [ figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line), banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 }, { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, marker: { color: linea },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''), text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' }, hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => { ], layout: (() => {
@@ -152,7 +161,8 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores, return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' }; marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, }), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, comoLeer: data.id === 'cama_birads_456_paciente' ? ''
: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
suprimidos, sinDato, suprimidos, sinDato,
}; };
} }
@@ -63,6 +63,16 @@ describe('Figuras de histórico', () => {
expect(traza(data, 0).y).toEqual([30, 10]); expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]); expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
}); });
it('las líneas de días de CaMa usan el azul, el morado y el rosa de la histopatología', () => {
const color = (id: string, tema: 'claro' | 'oscuro') => {
const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure;
return { linea: (figure.data[1]['line'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
};
expect(color('cama_dias_toma_diagnostico', 'claro')).toEqual({ linea: '#2F6DB3', banda: '#9DBFE380' });
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' });
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' });
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3');
});
it('las líneas usan el verde legible en cada tema', () => { it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }; const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color; const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color;
@@ -63,18 +63,23 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: ` template: `
<div class="controles"> <div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span> <h2>Filtros</h2>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)"> <div class="controles-fila">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> } <div class="interval">
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> } <span id="historico-intervalo" class="field-label">Intervalo de análisis</span>
</mat-button-toggle-group> <mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
<mat-form-field appearance="outline" subscriptSizing="dynamic"> @if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
<mat-label>Periodos a mostrar</mat-label> @if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)"> </mat-button-toggle-group>
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> } </div>
</mat-select> <mat-form-field appearance="outline" subscriptSizing="dynamic">
</mat-form-field> <mat-label>Periodos a mostrar</mat-label>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> } <mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
</div>
</div> </div>
<div class="paneles"> <div class="paneles">
@for (panel of paneles(); track panel.item.id) { @for (panel of paneles(); track panel.item.id) {
@@ -102,7 +107,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure" <app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" /> [label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
} }
<p class="nota">{{ panel.figura.comoLeer }}</p> @if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
@if (panel.figura.suprimidos.length) { @if (panel.figura.suprimidos.length) {
<details class="nota-pie"> <details class="nota-pie">
<summary>Datos suprimidos</summary> <summary>Datos suprimidos</summary>
@@ -123,8 +128,12 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
`, `,
styles: ` styles: `
:host { display: block; min-width: 0; } :host { display: block; min-width: 0; }
.controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); .controles { display: flex; flex-direction: column; align-items: stretch; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
.controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
@@ -141,7 +150,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); } .pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } } @container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); } h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { min-width: 18rem; } mat-form-field { flex: 0 1 14rem; width: 14rem; min-width: 14rem; max-width: 24rem; }
`, `,
}) })
export class IndicadoresHistorico { export class IndicadoresHistorico {
@@ -24,7 +24,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)',
}; };
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = { export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%', id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`, c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
}; };
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
@@ -22,7 +22,7 @@
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'"> <div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
@if (!catalogLoading() && filters; as state) { @if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio"> <section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">{{ dominio === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + domainLabels[dominio] }}</h2> <h2 id="global-filters-title" class="section-title">Filtros</h2>
@if (dominio !== 'cama') { @if (dominio !== 'cama') {
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p> <p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
} }
@@ -74,9 +74,6 @@
<section class="graphic-section" aria-labelledby="graphic-section-title"> <section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading"> <div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2> <h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ shownIndicators }} {{ shownIndicators === 1 ? 'indicador publicado' : 'indicadores publicados' }}</p>
}
</div> </div>
@if (catalogLoading()) { @if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" /> <mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
@@ -3,7 +3,7 @@
// own `:host`) -- not present upstream, whose shell lays this out differently. // own `:host`) -- not present upstream, whose shell lays this out differently.
// The workspace shell clips overflow, so the page scrolls itself. // The workspace shell clips overflow, so the page scrolls itself.
:host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); } :host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); }
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; } .dashboard { max-width: 1680px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; } h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); } .domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
@@ -13,8 +13,11 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); } .global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; } .section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; } .section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { min-width: 0; } .kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: calc(var(--space-4) * -1);
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); } padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); background: color-mix(in srgb, var(--issste-border) 42%, var(--issste-background)); }
.kpi-section > .section-title { margin-bottom: var(--issste-space-4); }
.graphic-section { margin-top: var(--issste-space-6); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } .kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; } .kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
.catalog-grid { align-items: stretch; } .catalog-grid { align-items: stretch; }
@@ -22,7 +25,6 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } .reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; } .catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); } .catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); } .catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; } .catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
.catalog-search button { min-height: 48px; } .catalog-search button { min-height: 48px; }
@@ -93,8 +93,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']); expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
// Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página. // Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull(); expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados'); expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
toggle(0); toggle(1); flushAll(); toggle(0); toggle(1); flushAll();
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]); expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]);
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']); expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']);
@@ -114,7 +113,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
it('Resumen omite los indicadores publicados solo para otra pestaña', () => { it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
load([item, { ...second, vistas: ['historico'] }]); load([item, { ...second, vistas: ['historico'] }]);
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]); expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicador publicado'); expect(fixture.nativeElement.textContent).not.toContain('indicador publicado');
expect(page.catalog()).toHaveLength(2); expect(page.catalog()).toHaveLength(2);
http.expectNone(r => r.url.endsWith('/figuras/f1')); http.expectNone(r => r.url.endsWith('/figuras/f1'));
}); });
@@ -323,7 +323,6 @@ export class IndicadoresPage {
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA); && !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
} }
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get shownIndicators() { return this.catalogOrder().length; }
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period. // TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined { get teaResumenPeriodo(): string | undefined {
@@ -67,7 +67,7 @@ describe('Selección de indicadores gráficos', () => {
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]); expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores'); expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.'); expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados'); expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo'); choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original); expect(page.catalog()).toBe(original);
http.expectNone(() => true); http.expectNone(() => true);
+1
View File
@@ -141,6 +141,7 @@ body {
.indicator-select-panel .option-go { flex: none; padding: .25rem .6rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); .indicator-select-panel .option-go { flex: none; padding: .25rem .6rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius);
color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; } color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; }
.indicator-select-panel .option-go:hover { background: var(--issste-accent); } .indicator-select-panel .option-go:hover { background: var(--issste-accent); }
.issste-help-tooltip { max-width: min(28rem, calc(100vw - 2rem)); white-space: pre-line; line-height: 1.45; }
.indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } .indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
// The TEA report: while it's being prepared, charts draw at a width that fits a page. // The TEA report: while it's being prepared, charts draw at a width that fits a page.