feat(indicadores): panel de tasa de confirmación histopatológica, tiempos pareados y ficha técnica
Agrega el panel de tasa de confirmación histopatológica (cacu_confirmacion_citologia): tasas por resultado citológico de alto grado con su intervalo de Wilson a la izquierda, dona del grado de biopsia a la derecha y tabla de contingencia; la vista base es «LIEAG o más» y las pacientes sin biopsia aún no entran al denominador. Une en una sola figura los tiempos de toma a resultado (pedido por id, oculto en el catálogo) y de toma a diagnóstico. La pestaña Datos y definiciones muestra la ficha técnica y las reglas del kit en tablas; las notas de cada figura pasan a su Cómo leer, las tarjetas dejan solo valor, n y periodo, y el Cómo leer de EU7 muestra solo lo que publica el kit. Las transiciones animadas quedan fuera, como entrega aparte para el diseñador. CSO5.5
This commit is contained in:
@@ -17,11 +17,15 @@ import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia],
|
||||
template: `
|
||||
<mat-card>
|
||||
<header>
|
||||
@@ -40,6 +44,14 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (isConfirmacion) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
<app-indicador-confirmacion-citologia [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (tiempos; as par) {
|
||||
<div #visibilityRegion class="tiempos-region">
|
||||
<app-indicador-tiempos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (selectedFigure) {
|
||||
@if (!pair.length || otherFigures.length) {
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
@@ -121,6 +133,9 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; }
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@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> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (periods.length > 1) {
|
||||
<nav class="periods" aria-label="Periodos de la confirmación histopatológica">
|
||||
<button type="button" aria-label="Periodo anterior de la confirmación" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
<span role="status">{{ periods[periodIndex] }} · {{ periodIndex + 1 }} / {{ periods.length }}</span>
|
||||
<button type="button" aria-label="Periodo siguiente de la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
@if (model; as m) {
|
||||
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }} · Selección: {{ selectionLabel }} · {{ reading }}</p>
|
||||
@if (status() === 'empty') { <p role="status">No hay citologías de alto grado publicadas para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
|
||||
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista base de la confirmación">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@for (g of m.grupos; track g.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Grados del anillo exterior">
|
||||
@for (c of m.grados; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure rates"><h3>Por resultado de la citología · {{ m.periodo }}</h3>
|
||||
@if (ratesFigure) {
|
||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Confirmación · Tasas por citología · ' + 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 class="figure donut"><h3>Resultado de la biopsia · {{ m.periodo }}</h3>
|
||||
@if (m.conBiopsia !== null && m.conBiopsia > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Confirmación · Dona de grados de biopsia · ' + m.periodo + ' · ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.conBiopsia === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin mujeres con biopsia en el periodo.' }}</p> }
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia · {{ m.periodo }} · mujeres</caption>
|
||||
<thead><tr><th scope="col">Citología</th>@for (g of m.grados; track g.id) { <th scope="col">{{ g.etiqueta }}</th> }<th scope="col">Con biopsia</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }</tr></thead>
|
||||
<tbody>@for (fila of m.filas; track fila.id) {
|
||||
<tr><th scope="row">{{ fila.etiqueta }}</th>@for (g of m.grados; track g.id) { <td>{{ cellText(fila.celdas[g.id]) }}</td> }<td>{{ denText(fila.den, fila.estado) }}</td>@for (a of m.aparte; track a.id) { <td>{{ cellText(fila.aparte[a.id]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,37 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.confirmacion { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.selection-status { font-weight: 600; }
|
||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
||||
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.legend > button { justify-self: start; }
|
||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
||||
border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
.keys button { display: inline-flex; align-items: center; gap: .4rem; text-align: start; overflow-wrap: anywhere; }
|
||||
button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inset 0 0 0 1px var(--issste-accent); font-weight: 700; }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
button:focus-visible, summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.swatch { display: inline-block; width: .85rem; height: .85rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 50%; }
|
||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1rem; }
|
||||
.figure { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
.periods span { text-align: center; }
|
||||
.periods button { min-width: 44px; font-size: 1.5rem; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
||||
.rate-states:empty { display: none; }
|
||||
/* 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); } }
|
||||
@@ -0,0 +1,140 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
||||
|
||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
||||
const FIGURAS = [['fig_c2_donas', 'Dona de grados de biopsia'], ['fig_c2_barras', 'Tasas por resultado de la citología']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-confirmacion-citologia',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-confirmacion-citologia.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
message = '';
|
||||
selection?: SeleccionConfirmacion;
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloConfirmacion;
|
||||
donutFigure?: PlotlyFigure;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloConfirmacion[] = [];
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
||||
readonly estadoTasa = estadoTasa;
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_CITOLOGIA })
|
||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.clear();
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private clear() {
|
||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== ID_CONFIRMACION || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
||||
{ estrato: ESTRATO_CITOLOGIA }).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosConfirmacion(datos, this.applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloConfirmacion(datos, p));
|
||||
// The most recent period first, as the prototype; navigation goes back.
|
||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.clear();
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof ConfirmacionIncompatible ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof ConfirmacionIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activatePeriod() {
|
||||
this.model = this.pages[this.periodIndex];
|
||||
this.selection = this.model ? seleccionBase(this.model) : undefined;
|
||||
this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty');
|
||||
}
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
this.selection = clicConfirmacion(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model || !this.selection) return;
|
||||
this.donutFigure = donaConfirmacion(this.model, this.selection, this.tema);
|
||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -3,29 +3,14 @@
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
<p>El anillo interior muestra grupos y el exterior categorías Bethesda. «Sin dato» se informa fuera de la dona.</p>
|
||||
<p>Las barras usan el total con resultado válido de cada escenario, excluyendo «Sin dato». Al seleccionar un grupo o categoría se conserva ese denominador.</p>
|
||||
<p>El escenario clínico corresponde al estatus de seguimiento al inicio del periodo, calculado con la historia previa.</p>
|
||||
<p>Selecciona un grupo para expandirlo y una categoría para resaltarla. Repite el clic para liberar la selección. El centro o el botón Volver regresa de categoría a grupo y después a TOTAL. También puedes usar Tab y Enter o Espacio en la leyenda.</p>
|
||||
<p>Los nulos y celdas suprimidas no son ceros. Si el denominador es desconocido, el escenario no muestra una barra porcentual.</p>
|
||||
@if (metadata; as info) {
|
||||
@if (info.descripcion) { <p>{{ info.descripcion }}</p> }
|
||||
@if (info.ficha; as ficha) {
|
||||
@if (ficha.pregunta) { <p>{{ ficha.pregunta }}</p> }
|
||||
@if (ficha.definicion) { <p>{{ ficha.definicion }}</p> }
|
||||
@if (ficha.unidad) { <p>Unidad: {{ ficha.unidad }}</p> }
|
||||
@if (ficha.nota) { <p>{{ ficha.nota }}</p> }
|
||||
}
|
||||
<details><summary>Metadatos publicados de las figuras originales</summary>
|
||||
<p>Estas descripciones corresponden a las figuras publicadas originales. En esta vista coordinada, «Sin dato» queda fuera de la dona y las barras son porcentajes por escenario.</p>
|
||||
@for (detail of info.figuras_detalle; track detail.figura) {
|
||||
@if (detail.figura === 'fig_c2_donas' || detail.figura === 'fig_c2_barras') {
|
||||
<p>{{ detail.descripcion }}</p>
|
||||
@for (line of detail.como_leer; track $index) { <p>{{ line }}</p> }
|
||||
}
|
||||
}
|
||||
@for (reference of info.referencias; track $index) { <p>{{ reference.etiqueta }} {{ reference.ref }}</p> }
|
||||
</details>
|
||||
@if (metadata) {
|
||||
@for (guide of readingGuide; track guide.figura) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@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> }
|
||||
</section>
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para estas figuras.</p> }
|
||||
} @else { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -27,3 +27,7 @@ table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); } }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
|
||||
@@ -136,6 +136,36 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
||||
expect(f.componentInstance.selection.grupo).toBe('ANORMAL'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de dona y barras, sin la ficha', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
const toggle = f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
toggle.click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
|
||||
f.componentRef.setInput('metadata', {
|
||||
descripcion: 'Descripción del indicador',
|
||||
ficha: { pregunta: '¿Pregunta?', definicion: 'Definición', unidad: 'pacientes', nota: 'Nota de ficha' },
|
||||
referencias: [{ tipo: 'cita', etiqueta: 'Referencia', ref: null }],
|
||||
figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Barras por escenario.', como_leer: ['Lee las barras así.', ' '] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona así.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra figura', como_leer: ['No va.'] },
|
||||
],
|
||||
}); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
const guides = [...help.querySelectorAll('.reading-guide')] as HTMLElement[];
|
||||
expect(guides.map(g => g.querySelector('h3')!.textContent)).toEqual(['Dona de dos anillos', 'Barras por escenario clínico']);
|
||||
expect([...guides[0].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona así.']);
|
||||
expect(guides[1].querySelector('p')!.textContent).toBe('Barras por escenario.');
|
||||
expect([...guides[1].querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las barras así.']);
|
||||
for (const absent of ['Descripción del indicador', '¿Pregunta?', 'Nota de ficha', 'Unidad', 'Referencia', 'No va.', 'Otra figura', 'figuras publicadas originales', 'El anillo interior'])
|
||||
expect(help.textContent).not.toContain(absent);
|
||||
expect(help.querySelector('details')).toBeNull();
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [] }); f.detectChanges();
|
||||
expect(help.textContent).toContain('no publica instrucciones de lectura');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('solo CaCu EU7 monta la excepción y mantiene los otros paneles C2', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
|
||||
@@ -13,6 +13,8 @@ import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
@@ -64,6 +66,16 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })),
|
||||
{ escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]);
|
||||
}
|
||||
// "Cómo leer" shows only what the kit publishes for the two figures of this view.
|
||||
get readingGuide() {
|
||||
const details = this.metadata?.figuras_detalle ?? [];
|
||||
return EU7_FIGURES.flatMap(([figura, nombre]) => {
|
||||
const detail = details.find(item => item.figura === figura);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||
percentText(value: number | null) { return percentText(value); }
|
||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
||||
|
||||
@@ -13,6 +13,12 @@
|
||||
@for (line of interpretation; track $index) { <li>{{ line }}</li> }
|
||||
</ul>
|
||||
<p class="period-note">{{ periodInterpretation }}</p>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
<h3 class="footnotes-title">Notas de la figura</h3>
|
||||
<section class="methodological-footnotes" aria-label="Notas de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
@@ -92,11 +98,7 @@
|
||||
</div>
|
||||
}
|
||||
<div class="figure-footer" [hidden]="state.status !== 'ready'">
|
||||
@if (state.footnotes?.length) {
|
||||
<section class="methodological-footnotes" aria-label="Notas al pie de la figura">
|
||||
@for (note of state.footnotes; track $index) { <p>{{ note }}</p> }
|
||||
</section>
|
||||
}
|
||||
@if (cutoffDate; as cutoff) { <p class="figure-cutoff">Fecha de corte: {{ cutoff }}</p> }
|
||||
</div>
|
||||
<div class="figure-labels" [hidden]="state.status !== 'ready'">
|
||||
@if (state.categoryLabels?.length) {
|
||||
|
||||
@@ -44,8 +44,11 @@
|
||||
.notes { padding: 1rem; overflow-wrap: anywhere; }
|
||||
.notes h2 { font-size: 1rem; }
|
||||
.notes p { line-height: 1.5; }
|
||||
.footnotes-title { margin: var(--issste-space-4) 0 var(--issste-space-2); font-size: .9375rem; font-family: var(--issste-font-heading); }
|
||||
.figure-cutoff { margin: 0; padding: .5rem 1rem .75rem; font-size: .8125rem; color: var(--issste-text-secondary); }
|
||||
.dark .figure-cutoff { color: var(--mat-sys-outline); }
|
||||
.methodological-footnotes {
|
||||
padding: .75rem 1rem 1rem;
|
||||
padding: 0;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -145,25 +145,33 @@ describe('IndicadorFigureCard', () => {
|
||||
fixture.detectChanges(); expect(fixture.componentInstance.activeParent).toBeUndefined();
|
||||
expect(fixture.componentInstance.chartFigure?.data).toHaveLength(1);
|
||||
});
|
||||
it.each(['tea', 'cacu', 'cama'])('UX-07D.2 presenta notas %s como texto seguro inmediatamente después del gráfico', dominio => {
|
||||
it.each(['tea', 'cacu', 'cama'])('presenta notas %s como texto seguro dentro de «Cómo leer» y deja visible la fecha de corte', dominio => {
|
||||
fixture.componentRef.setInput('dominio', dominio);
|
||||
const original: PlotlyFigure = { data: [{ y: [0] }], layout: {} };
|
||||
const notes = ['Fuente: A & B\nSegunda línea', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
const notes = ['Nota de la ficha\nFuente: A & B · Fecha de corte: 2025-08-01\nLeyenda', '<img src=x onerror=alert(1)>', 'ID_'.repeat(150)];
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: notes,
|
||||
minimumPlotWidth: 1200, categoryLabels: [{ axis: 'x', original: 'Categoría', abbreviated: 'Cat.' }] });
|
||||
const section = fixture.nativeElement.querySelector('.methodological-footnotes') as HTMLElement;
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas al pie de la figura');
|
||||
expect(section.getAttribute('aria-label')).toBe('Notas de la figura');
|
||||
expect([...section.querySelectorAll('p')].map(p => p.textContent)).toEqual(notes);
|
||||
expect(section.querySelector('img, script, a')).toBeNull();
|
||||
expect(section.parentElement?.previousElementSibling?.querySelector('app-plotly-chart')).toBeTruthy();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details')).toBeNull();
|
||||
expect(section.parentElement?.parentElement?.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
const detail = section.closest('.methodology-detail') as HTMLElement;
|
||||
expect(detail).not.toBeNull(); expect(detail.hidden).toBe(true);
|
||||
expect(section.previousElementSibling?.textContent).toBe('Notas de la figura');
|
||||
// Interpretation lines come first; the notes are paragraphs, never list items.
|
||||
expect(detail.querySelector('ul')!.compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(section.querySelector('li')).toBeNull();
|
||||
expect(section.closest('.plot-viewport, app-plotly-chart, details, .figure-footer')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-footer').textContent.trim()).toBe('Fecha de corte: 2025-08-01');
|
||||
expect(fixture.nativeElement.querySelector('.figure-labels .category-labels')).toBeTruthy();
|
||||
for (const status of ['loading', 'deferred', 'error', 'incompatible', 'idle'] as const) {
|
||||
state({ status });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes')).toBeNull();
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
}
|
||||
state({ status: 'ready', figure: original, presentationFigure: original, footnotes: ['Nota nueva'] });
|
||||
expect(fixture.nativeElement.querySelector('.methodological-footnotes').textContent).toBe('Nota nueva');
|
||||
expect(fixture.nativeElement.querySelector('.figure-cutoff')).toBeNull();
|
||||
});
|
||||
it('UX-07D conserva el ancho desplazable durante carga y lo revierte sin recrear el host', async () => {
|
||||
const original: PlotlyFigure = { data: [{ type: 'bar', x: ['A', 'B', 'C'], y: [0, null, 20] }], layout: {} };
|
||||
|
||||
@@ -10,7 +10,7 @@ import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { CategoryLabel } from './indicadores-axis-labels';
|
||||
import { figureIdentity, identityElementId } from './indicadores-identities';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { contractInterpretation, figureMetadataInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
|
||||
// The panel owns requests; the card receives the original and its presentation copy.
|
||||
@@ -143,23 +143,23 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
: this.figuraId.startsWith('fig_c2') ? 'C2'
|
||||
: this.figuraId.startsWith('fig_c3r') ? 'C3r' : this.selected?.contrato;
|
||||
}
|
||||
private get complementaryLineCount(): number {
|
||||
return this.contract === 'C1' ? 1
|
||||
: this.contract === 'C2' ? (this.dominio === 'tea' ? 2 : 1) : 0;
|
||||
}
|
||||
get methodologyDetail(): readonly string[] {
|
||||
return this.interpretation.slice(0, this.complementaryLineCount);
|
||||
}
|
||||
get visibleInterpretation(): readonly string[] {
|
||||
return this.interpretation.slice(this.complementaryLineCount);
|
||||
}
|
||||
readonly hasNoVisibleValues = hasNoVisibleValues;
|
||||
readonly figureTitle = figureTitle;
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get interpretation(): readonly string[] {
|
||||
return figureMetadataInterpretation(this.metadata, this.figuraId)
|
||||
?? contractInterpretation(this.contract, this.dominio, this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
return figureInterpretation(this.metadata, this.figuraId, this.contract, this.dominio,
|
||||
this.state.figure?.data.some(trace => trace['type'] === 'pie'));
|
||||
}
|
||||
// The figure's notes live in "Cómo leer"; the cut-off date stays under the plot
|
||||
// because it is the only temporal reference of the data on the card.
|
||||
get cutoffDate(): string | undefined {
|
||||
if (this.state.status !== 'ready') return undefined;
|
||||
for (const note of this.state.footnotes ?? []) {
|
||||
const match = /Fecha de corte: (\d{4}-\d{2}-\d{2})/.exec(note);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
// KPI scope only: graphic cards stay outside the viewport, so coordinated views
|
||||
// (such as the CaCu paired times) do not add their own /datos requests.
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
function load(domain: Dominio, missing = false, periods = ['2025-S1'], initial = domain === 'tea') {
|
||||
// Ordinary consumer tests begin after initialization; dedicated P0 suites
|
||||
// exercise the real shared search for all three domains.
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
section + section { margin-top: var(--issste-space-4); }
|
||||
h4 { margin: 0 0 var(--issste-space-2); font-size: 1rem; }
|
||||
.metadata-copy { max-width: 75ch; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ficha-fields { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 3fr); gap: var(--issste-space-2) var(--issste-space-4); max-width: 75ch; margin: 0; }
|
||||
.ficha-fields > div { display: contents; }
|
||||
dt { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
dd { margin: 0; }
|
||||
ul { padding-inline-start: 1.5rem; }
|
||||
li + li { margin-top: var(--issste-space-2); }
|
||||
.table-scroll { max-width: 100%; overflow-x: auto; }
|
||||
table { border-collapse: collapse; width: 100%; max-width: 75rem; }
|
||||
th, td { text-align: left; vertical-align: top; padding: var(--issste-space-2); border-bottom: 1px solid var(--issste-border); }
|
||||
thead th, tbody th { color: var(--issste-text-secondary); font-weight: 600; }
|
||||
.ficha-table th { width: 10rem; }
|
||||
.rules-table code { overflow-wrap: anywhere; }
|
||||
.rules-table td:nth-child(2) { min-width: 8rem; }
|
||||
@media (max-width: 36rem) {
|
||||
.ficha-fields { grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-1); }
|
||||
dd { margin-bottom: var(--issste-space-2); }
|
||||
.ficha-table th { width: 6rem; }
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
expect(text).toContain('Guía <img src=x onerror=alert(1)>');
|
||||
expect(fixture.nativeElement.querySelector('img')).toBeNull();
|
||||
expect(text).toContain('Segunda línea');
|
||||
expect(text).not.toContain('Ficha metodológica');
|
||||
expect(text).not.toContain('Ficha técnica');
|
||||
expect(text).not.toContain('Título del catálogo');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
@@ -32,7 +32,35 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
descripcion: 'Información general.',
|
||||
ficha: { codigo: 'IND-01', para: 'Personas atendidas', unidad: 'Porcentaje', pregunta: '¿Qué proporción?', definicion: 'Casos que cumplen el criterio.', nota: 'Dato sujeto a revisión.' },
|
||||
});
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha metodológica', 'Código', 'IND-01', 'Para', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
for (const content of ['Descripción', 'Información general.', 'Ficha técnica', 'Código', 'IND-01', 'Para quién', 'Personas atendidas', 'Unidad', 'Porcentaje', 'Pregunta', '¿Qué proporción?', 'Definición', 'Casos que cumplen el criterio.', 'Nota', 'Dato sujeto a revisión.']) expect(text).toContain(content);
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('presenta la ficha en una tabla y las reglas con valor legible, estado y fuente', () => {
|
||||
const { fixture, http, text } = render({
|
||||
ficha: { codigo: 'EU-T', definicion: 'Días de la toma al diagnóstico.' },
|
||||
parametros: [
|
||||
{ clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario para poder calcular.' },
|
||||
{ clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'confirmado', fuente: null },
|
||||
],
|
||||
});
|
||||
const ficha = fixture.nativeElement.querySelector('table.ficha-table') as HTMLTableElement;
|
||||
expect([...ficha.querySelectorAll('th[scope=row]')].map(th => th.textContent)).toEqual(['Código', 'Definición']);
|
||||
const rules = fixture.nativeElement.querySelector('table.rules-table') as HTMLTableElement;
|
||||
expect([...rules.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Clave', 'Valor', 'Estado', 'Fuente']);
|
||||
const rows = [...rules.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell => cell.textContent));
|
||||
expect(rows).toEqual([
|
||||
['cacu.horizontes.toma_diagnostico_dias', '180', 'Provisional', 'Arbitrario para poder calcular.'],
|
||||
['cacu.diagnostico.cie', 'Z014, R87', 'Confirmado', '—'],
|
||||
]);
|
||||
expect(text).toContain('Reglas'); expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
it('muestra sólo reglas cuando no hay ficha', () => {
|
||||
const { fixture, http, text } = render({ parametros: [{ clave: 'comun.umbral_supresion', valor: 5, estado: 'provisional' }] });
|
||||
expect(text).toContain('comun.umbral_supresion'); expect(text).not.toContain('Ficha técnica');
|
||||
expect(text).not.toContain('no está disponible');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
@@ -56,7 +84,7 @@ describe('Metadatos metodológicos opcionales', () => {
|
||||
it('muestra estado vacío con descripción y ficha ausentes o nulas', () => {
|
||||
const { fixture, http, text } = render({ descripcion: null, ficha: null, referencias: null, poblaciones: null });
|
||||
expect(text).toContain('La información metodológica ampliada no está disponible para este indicador.');
|
||||
expect(text).not.toContain('Ficha metodológica'); expect(text).not.toContain('Descripción');
|
||||
expect(text).not.toContain('Ficha técnica'); expect(text).not.toContain('Descripción');
|
||||
http.verify(); fixture.destroy();
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,21 @@ import { catchError, of, Subject, switchMap } from 'rxjs';
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
|
||||
const RULE_STATES: Record<string, string> = { provisional: 'Provisional', confirmado: 'Confirmado' };
|
||||
|
||||
// Readable rule value: lists separated by commas, objects by their label when they carry one.
|
||||
export function ruleValue(value: unknown): string {
|
||||
if (value === null || value === undefined) return 'Sin definir';
|
||||
if (Array.isArray(value)) return value.length ? value.map(ruleValue).join(', ') : 'Lista vacía';
|
||||
if (typeof value === 'boolean') return value ? 'Sí' : 'No';
|
||||
if (typeof value === 'number') return value.toLocaleString('es-MX');
|
||||
if (typeof value === 'object') {
|
||||
const label = (value as Record<string, unknown>)['etiqueta'];
|
||||
return typeof label === 'string' && label.trim() ? label : JSON.stringify(value);
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-metadata',
|
||||
styleUrl: './indicador-metadata.scss',
|
||||
@@ -17,10 +32,27 @@ import { IndicadoresService } from './indicadores.service';
|
||||
}
|
||||
@if (fichaFields.length) {
|
||||
<section aria-labelledby="metadata-ficha-title">
|
||||
<h4 id="metadata-ficha-title">Ficha metodológica</h4>
|
||||
<dl class="ficha-fields">@for (field of fichaFields; track field.key) {
|
||||
<div><dt>{{ field.label }}</dt><dd class="metadata-copy">{{ field.value }}</dd></div>
|
||||
}</dl>
|
||||
<h4 id="metadata-ficha-title">Ficha técnica</h4>
|
||||
<div class="table-scroll">
|
||||
<table class="ficha-table">
|
||||
<tbody>@for (field of fichaFields; track field.key) {
|
||||
<tr><th scope="row">{{ field.label }}</th><td class="metadata-copy">{{ field.value }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
@if (rules.length) {
|
||||
<section aria-labelledby="metadata-rules-title">
|
||||
<h4 id="metadata-rules-title">Reglas</h4>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de reglas del indicador" tabindex="0">
|
||||
<table class="rules-table">
|
||||
<thead><tr><th scope="col">Clave</th><th scope="col">Valor</th><th scope="col">Estado</th><th scope="col">Fuente</th></tr></thead>
|
||||
<tbody>@for (rule of rules; track rule.clave) {
|
||||
<tr><th scope="row"><code>{{ rule.clave }}</code></th><td>{{ rule.valor }}</td><td>{{ rule.estado }}</td><td class="metadata-copy">{{ rule.fuente }}</td></tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
@if (references.length) {
|
||||
@@ -47,7 +79,7 @@ export class IndicadorMetadata implements OnChanges {
|
||||
loading = false;
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private readonly fichaLabels = [
|
||||
['codigo', 'Código'], ['para', 'Para'], ['unidad', 'Unidad'],
|
||||
['codigo', 'Código'], ['para', 'Para quién'], ['unidad', 'Unidad'],
|
||||
['pregunta', 'Pregunta'], ['definicion', 'Definición'], ['nota', 'Nota'],
|
||||
] as const;
|
||||
hasText(value: unknown): value is string { return typeof value === 'string' && value.trim().length > 0; }
|
||||
@@ -56,9 +88,17 @@ export class IndicadorMetadata implements OnChanges {
|
||||
const ficha = this.metadata?.ficha;
|
||||
return ficha ? this.fichaLabels.flatMap(([key, label]) => this.hasText(ficha[key]) ? [{ key, label, value: ficha[key]!.trim() }] : []) : [];
|
||||
}
|
||||
get rules() {
|
||||
return (this.metadata?.parametros ?? []).map(rule => ({
|
||||
clave: rule.clave,
|
||||
valor: ruleValue(rule.valor),
|
||||
estado: RULE_STATES[rule.estado] ?? rule.estado,
|
||||
fuente: this.hasText(rule.fuente) ? rule.fuente.trim() : '—',
|
||||
}));
|
||||
}
|
||||
get references() { return (this.metadata?.referencias ?? []).filter(ref => this.hasText(ref.etiqueta)); }
|
||||
get populations() { return (this.metadata?.poblaciones ?? []).filter(population => this.hasText(population.descripcion)); }
|
||||
get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.references.length || this.populations.length); }
|
||||
get hasUsableMetadata() { return !!(this.description || this.fichaFields.length || this.rules.length || this.references.length || this.populations.length); }
|
||||
constructor() {
|
||||
this.requests.pipe(switchMap(() => this.service.metadatos(this.dominio, this.indicador).pipe(catchError(() => of(undefined)))), takeUntilDestroyed(inject(DestroyRef))).subscribe(value => { this.metadata = value; this.loading = false; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<section class="tiempos" aria-label="Días desde la toma: resultado y diagnóstico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
||||
@if (helpOpen) {
|
||||
<div class="methodology">
|
||||
@for (guide of readingGuide; track guide.clave) {
|
||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
||||
<h3>{{ guide.nombre }}</h3>
|
||||
@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> }
|
||||
</section>
|
||||
}
|
||||
<p class="caveat">{{ caveat }}</p>
|
||||
@if (metadataPending) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
|
||||
</div>
|
||||
}
|
||||
@switch (status()) {
|
||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando tiempos de resultado y diagnóstico" /><p role="status">Cargando los mismos periodos para los dos tiempos…</p> }
|
||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
@case ('incompatible') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (model; as m) {
|
||||
<h3 class="figure-title">Días desde la toma: resultado y diagnóstico</h3>
|
||||
@if (status() === 'empty') { <p role="status">No hay cajas publicadas para estos periodos.</p> }
|
||||
@else if (figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Tiempos por periodo · ' + par.etiquetas.reporte + ' y ' + par.etiquetas.diagnostico" />
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados y cajas no disponibles</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos por periodo" tabindex="0">
|
||||
<table><caption>Q1, mediana y Q3 en días por periodo</caption>
|
||||
<thead><tr><th scope="col">Periodo</th>@for (clave of claves; track clave) { <th scope="col">{{ par.etiquetas[clave] }}</th> }</tr></thead>
|
||||
<tbody>@for (periodo of m.periodos; track periodo) {
|
||||
<tr><th scope="row">{{ periodo }}</th>@for (clave of claves; track clave) { <td>{{ cajaTexto(m.cajas[clave][periodo]) }}</td> }</tr>
|
||||
}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
</section>
|
||||
@@ -0,0 +1,17 @@
|
||||
:host { display: block; min-width: 0; }
|
||||
.tiempos { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
||||
.reading-guide + .reading-guide, .caveat { margin-top: 1rem; }
|
||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
||||
.reading-guide li + li { margin-top: .25rem; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
app-plotly-chart { --plot-height: 440px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.table-scroll { overflow: auto; max-height: 28rem; }
|
||||
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||
caption { text-align: start; font-weight: 600; }
|
||||
@@ -0,0 +1,131 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { catchError, combineLatest, of, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { cajaTexto, CLAVES, Clave, FIGURA_C3R, figuraTiempos, hayCajas, ModeloTiempos, modeloTiempos, ParTiempos,
|
||||
TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-tiempos-pareados',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-tiempos-pareados.html',
|
||||
styleUrl: './indicador-tiempos-pareados.scss',
|
||||
})
|
||||
export class IndicadorTiemposPareados implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
@Input({ required: true }) par!: ParTiempos;
|
||||
// The card's indicator (diagnosis). Its partner (lab result) is hidden from the
|
||||
// catalog and requested directly by id, for data and metadata.
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly claves = CLAVES;
|
||||
readonly cajaTexto = cajaTexto;
|
||||
message = '';
|
||||
model?: ModeloTiempos;
|
||||
figure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
partnerMetadata?: IndicadorMetadatos;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private metadataSubscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
|
||||
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
// TODO: mover al kit (como_leer de la vista coordinada de tiempos).
|
||||
get caveat() {
|
||||
return `Las dos cajas no cuentan exactamente a las mismas ${this.par.estudios}: cada indicador tiene su propio horizonte `
|
||||
+ 'y la segunda solo incluye las que llegaron a diagnóstico. La diferencia entre las medianas no es el tiempo del tramo intermedio.';
|
||||
}
|
||||
/** "Cómo leer": only what the kit publishes for each C3r figure, plus the caveat above. */
|
||||
get readingGuide() {
|
||||
const fuentes: Record<Clave, IndicadorMetadatos | undefined> = { reporte: this.partnerMetadata, diagnostico: this.metadata };
|
||||
return CLAVES.flatMap(clave => {
|
||||
const detail = fuentes[clave]?.figuras_detalle?.find(item => item.figura === FIGURA_C3R);
|
||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
||||
return descripcion || como_leer.length ? [{ clave, nombre: this.par.etiquetas[clave], descripcion, como_leer }] : [];
|
||||
});
|
||||
}
|
||||
get metadataPending() { return !this.metadata || !this.partnerMetadata; }
|
||||
toggleHelp() {
|
||||
this.helpOpen = !this.helpOpen;
|
||||
if (!this.helpOpen) return;
|
||||
if (!this.metadata) this.metadataRequested.emit();
|
||||
if (!this.partnerMetadata) {
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.service.metadatos(this.dominio, this.par.reporte).pipe(catchError(() => of(undefined)))
|
||||
.subscribe(value => { this.partnerMetadata = value; this.changeDetector.markForCheck(); });
|
||||
}
|
||||
}
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([
|
||||
this.par.reporte, this.par.diagnostico, this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
if (changes['dominio'] || changes['par']) { this.partnerMetadata = undefined; this.metadataSubscription?.unsubscribe(); }
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.model = undefined; this.figure = undefined;
|
||||
if (!this.visible) { this.status.set('deferred'); return; }
|
||||
this.load();
|
||||
} else if (this.visible && !this.loaded) this.load();
|
||||
else if (this.model && changes['tema']) this.draw();
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.figure = undefined;
|
||||
if (this.indicador.id !== this.par.diagnostico || this.indicador.contrato !== 'C3r') {
|
||||
this.message = 'El catálogo no publica el indicador de tiempo necesario para esta vista.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
// The partner shares the diagnosis periodicity; its response is validated by id, contract and period.
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (!compatibility.compatible) { this.message = compatibility.reason; this.status.set('incompatible'); return; }
|
||||
const key = this.key;
|
||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = combineLatest([
|
||||
this.snapshots.datos(this.dominio, this.par.reporte, this.applied.tipo, periods),
|
||||
this.snapshots.datos(this.dominio, this.par.diagnostico, this.applied.tipo, periods, this.indicador.version),
|
||||
]).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: ([reporte, diagnostico]) => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.model = modeloTiempos(this.par, { reporte, diagnostico }, this.applied.tipo, periods);
|
||||
this.draw();
|
||||
this.status.set(hayCajas(this.model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
},
|
||||
error: error => { if (key === this.key) this.failure(error); },
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.figure = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof TiemposIncompatibles ? error.message : httpMessage(error);
|
||||
this.status.set(error instanceof TiemposIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
||||
? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.figure = figuraTiempos(this.model, this.par, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.metadataSubscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -117,7 +117,7 @@ describe('selección local segura de barras generales C2', () => {
|
||||
expect(source).toEqual(before);
|
||||
});
|
||||
it.each([
|
||||
{ id: 'cacu_biopsias', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
{ id: 'c2_grados_biopsia_sintetico', unit: 'examen', groups: { NO_ANORMAL: 'Sin lesión de alto grado', ANORMAL: 'Lesión de alto grado o mayor', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['LIEBG', 'LIEBG (CIN 1)', 'NO_ANORMAL'], ['LIEAG', 'LIEAG (CIN 2 y 3)', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['CARCINOMA', 'Carcinoma invasor', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
{ id: 'cacu_eu7', unit: 'paciente', groups: { NO_ANORMAL: 'Sin anomalía', ANORMAL: 'Anormal', SIN_DATO: 'Sin dato' },
|
||||
categories: [['NORMAL', 'Normal', 'NO_ANORMAL'], ['ASC-US', 'ASC-US', 'NO_ANORMAL'], ['LIEBG', 'LIEBG', 'ANORMAL'], ['ASC-H', 'ASC-H', 'ANORMAL'], ['LIEAG', 'LIEAG', 'ANORMAL'], ['CIS', 'Carcinoma in situ', 'ANORMAL'], ['SIN_DATO', 'Sin dato', 'SIN_DATO']] },
|
||||
|
||||
@@ -23,7 +23,7 @@ const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'):
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de confirmación histopatológica'),
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r'),
|
||||
item('ind1', 'Pacientes con citología anómala'),
|
||||
item('ordinary', 'Otra gráfica'),
|
||||
@@ -91,7 +91,7 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
expect(kpis[2].querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 3');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(2);
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('confirmación histopatológica');
|
||||
expect(root.querySelector('.kpi-section')?.textContent).not.toContain('detección histopatológica');
|
||||
expect(card('cacu_eu13')).toBeDefined();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { Component, input, output } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
const GRADOS = ['NORMAL', 'LIEBG', 'LIEAG', 'CIS', 'CARCINOMA'];
|
||||
// Real kit shape: both apart keys, an off-catalogue grade (CIN2, colour null) and
|
||||
// valores_estrato as texts. Counts per cytology: NORMAL, LIEBG, LIEAG, CIS, CARCINOMA,
|
||||
// SIN_BIOPSIA (no biopsy yet), SIN_DATO (biopsy without grade), CIN2.
|
||||
const CATEGORIAS = [...GRADOS, 'SIN_BIOPSIA', 'SIN_DATO', 'CIN2'];
|
||||
const CONTEOS: Record<string, number[]> = {
|
||||
'ASC-H': [16, 11, 9, 1, 1, 20, 2, 0], LIEAG: [6, 10, 31, 8, 2, 22, 2, 1], CIS: [0, 1, 4, 4, 3, 11, 2, 0],
|
||||
};
|
||||
function respuesta(periodos = ['2026-S2'], conteos = CONTEOS): IndicadorDatos {
|
||||
const filas = periodos.flatMap(periodo => Object.entries(conteos).flatMap(([estrato, ns]) =>
|
||||
CATEGORIAS.map((categoria, orden) => ({ periodo, grupo: 'TOTAL', estrato, categoria, n: ns[orden], orden, suprimido: 0 }))));
|
||||
const color = ['#9DBFE3', '#E8C28E', '#D98E4A', '#B55A1F', '#7A2E0E'];
|
||||
const estratos = Object.keys(conteos);
|
||||
return {
|
||||
id: 'cacu_confirmacion_citologia', contrato: 'C2', tipo_periodo: 'semestre', periodos, filas, version: '1',
|
||||
estrato: 'citologia_alto_grado', valores_estrato: estratos,
|
||||
etiquetas_estrato: Object.fromEntries(estratos.map(e => [e, e === 'CIS' ? 'Carcinoma in situ' : e])),
|
||||
totales_estrato: periodos.flatMap(periodo => estratos.map(estrato => ({ periodo, grupo: 'TOTAL', estrato,
|
||||
n: conteos[estrato].reduce((a, b) => a + b, 0), suprimido: 0 }))),
|
||||
categorias: {
|
||||
...Object.fromEntries(GRADOS.map((id, i) => [id, { etiqueta: id === 'CIS' ? 'Carcinoma in situ' : id, color: color[i],
|
||||
grupo: i < 2 ? 'NO_ANORMAL' : 'ANORMAL', gravedad: i + 1 }])),
|
||||
SIN_BIOPSIA: { etiqueta: 'Sin biopsia aún', color: '#C9CDD2', grupo: null, gravedad: null },
|
||||
SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: 'SIN_DATO', gravedad: null },
|
||||
CIN2: { etiqueta: 'CIN2', color: null, grupo: 'NO_ANORMAL', gravedad: null },
|
||||
},
|
||||
grupos_de_categoria: { NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Sin dato' },
|
||||
};
|
||||
}
|
||||
|
||||
describe('Confirmación histopatológica: modelo', () => {
|
||||
it('denominador: mujeres con biopsia y grado; SIN_BIOPSIA y SIN_DATO van aparte; CIN2 cuenta en su grupo', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
expect(m.filas.map(f => f.id)).toEqual(['CIS', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.etiqueta)).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect(m.filas.map(f => f.den)).toEqual([12, 58, 38]);
|
||||
expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]);
|
||||
expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n])).toEqual([[11, 2], [22, 2], [20, 2]]);
|
||||
expect(m.grados.map(g => g.id)).toEqual([...GRADOS, 'CIN2']);
|
||||
expect(m.grados.find(g => g.id === 'CIN2')).toMatchObject({ grupo: 'NO_ANORMAL', color: '#8A9199' });
|
||||
expect(m.grupos.find(g => g.id === 'NO_ANORMAL')!.grados).toEqual(['NORMAL', 'LIEBG', 'CIN2']);
|
||||
expect(m.conBiopsia).toBe(108); expect(m.base).toBe('ANORMAL');
|
||||
});
|
||||
it('estratos ausentes de valores_estrato dicen «Sin mujeres con biopsia»; total suprimido suprime la fila', () => {
|
||||
const d = respuesta(['2026-S2'], { LIEAG: CONTEOS['LIEAG'] });
|
||||
const m = modeloConfirmacion(d, '2026-S2');
|
||||
expect(m.filas.map(f => f.den)).toEqual([0, 58, 0]);
|
||||
expect(tasas(m, seleccionBase(m)).map(estadoTasa)).toEqual(['Sin mujeres con biopsia', '', 'Sin mujeres con biopsia']);
|
||||
expect(m.filas[0].etiqueta).toBe('Carcinoma in situ');
|
||||
(d['totales_estrato'] as Record<string, unknown>[])[0]['suprimido'] = 1;
|
||||
const s = modeloConfirmacion(d, '2026-S2');
|
||||
expect([s.filas[1].den, s.filas[1].estado]).toEqual([null, 'Suprimido']);
|
||||
expect(s.conBiopsia).toBeNull();
|
||||
expect((figuraTasas(s, seleccionBase(s), 'claro').layout['annotations'] as { text: string }[])[1].text).toBe('Suprimido');
|
||||
});
|
||||
it('Wilson al 95 % con la fórmula del kit y extremos 0 y n', () => {
|
||||
const [bajo, alto] = wilson(11, 12);
|
||||
expect(bajo).toBeCloseTo(64.61, 1); expect(alto).toBeCloseTo(98.51, 1);
|
||||
expect(wilson(0, 10)[0]).toBe(0); expect(wilson(10, 10)[1]).toBe(100);
|
||||
});
|
||||
it('vista base LIEAG o más; grupo, grado, segundo clic al grupo y centro a la base', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
const base = seleccionBase(m);
|
||||
expect(tasas(m, base).map(t => [t.k, t.fila.den])).toEqual([[11, 12], [41, 58], [11, 38]]);
|
||||
expect(lectura(m, base)).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const menor = clicConfirmacion(m, base, 'grupos', m.grupos.findIndex(g => g.id === 'NO_ANORMAL'));
|
||||
expect(menor).toEqual({ grupo: 'NO_ANORMAL' }); expect(lectura(m, menor)).toBe('Sin confirmación de alto grado');
|
||||
const normal = clicConfirmacion(m, menor, 'categorias', 0);
|
||||
expect(normal).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(lectura(m, normal)).toBe('Falsos positivos: la biopsia no confirmó lesión');
|
||||
expect(tasas(m, normal).map(t => t.k)).toEqual([0, 6, 16]);
|
||||
expect(clicConfirmacion(m, normal, 'categorias', 0)).toEqual({ grupo: 'NO_ANORMAL' });
|
||||
const cis = clicConfirmacion(m, normal, 'categorias', 3);
|
||||
expect(lectura(m, cis)).toBe('Proporción con biopsia Carcinoma in situ');
|
||||
expect(clicConfirmacion(m, cis, 'centro', 0)).toEqual(base);
|
||||
});
|
||||
it('figura de tasas: una traza siempre, etiquetas «xx.x %» y «k/n», eje acotado a múltiplos de 5', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data).toHaveLength(1); expect(f.data[0]['type']).toBe('scatter');
|
||||
expect(f.data[0]['y']).toEqual(['Carcinoma in situ', 'LIEAG', 'ASC-H']);
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray).toEqual(['ASC-H', 'LIEAG', 'Carcinoma in situ']);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(['<b>91.7 %</b><br>11/12', '<b>70.7 %</b><br>41/58', '<b>28.9 %</b><br>11/38']);
|
||||
const range = (f.layout['xaxis'] as { range: number[] }).range;
|
||||
expect(range).toEqual(rangoTasas(tasas(m, base)));
|
||||
expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(range[0]).toBeGreaterThanOrEqual(0); expect(range[1]).toBeLessThanOrEqual(100);
|
||||
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Verdaderos positivos (valor predictivo positivo)');
|
||||
const otra = figuraTasas(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'oscuro');
|
||||
expect(otra.data).toHaveLength(1); expect(otra.layout['paper_bgcolor']).toBe('#081839');
|
||||
});
|
||||
it('fila suprimida o nula dice Suprimido o No disponible, nunca 0, y la dona no suma un total parcial', () => {
|
||||
const d = respuesta();
|
||||
Object.assign(d.filas.find(f => f['estrato'] === 'CIS' && f['categoria'] === 'LIEAG')!, { n: null, suprimido: 1 });
|
||||
d.filas = d.filas.filter(f => !(f['estrato'] === 'ASC-H' && f['categoria'] === 'NORMAL'));
|
||||
const m = modeloConfirmacion(d, '2026-S2'), base = seleccionBase(m);
|
||||
expect(m.filas.map(f => [f.den, f.estado])).toEqual([[null, 'Suprimido'], [58, 'Publicado'], [null, 'No disponible']]);
|
||||
const f = figuraTasas(m, base, 'claro');
|
||||
expect(f.data[0]['x']).toEqual([null, 100 * 41 / 58, null]);
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(['Suprimido', '<b>70.7 %</b><br>41/58', 'No disponible']);
|
||||
expect(JSON.stringify(f.layout['annotations'])).not.toContain('0/');
|
||||
expect(m.conBiopsia).toBeNull(); expect(donaConfirmacion(m, base, 'claro').data).toHaveLength(0);
|
||||
});
|
||||
it('dona de dos anillos; la selección atenúa sin cambiar valores y el centro dice «k de N con biopsia»', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2'), base = seleccionBase(m);
|
||||
const d = donaConfirmacion(m, base, 'claro');
|
||||
expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']);
|
||||
expect(d.data[1]['values']).toEqual([45, 63]);
|
||||
expect(d.data[2]['values']).toEqual([22, 22, 44, 13, 6, 1]);
|
||||
expect(d.data[0]['text']).toEqual(['<b>63</b><br>de 108 con biopsia']);
|
||||
const otra = donaConfirmacion(m, { grupo: 'NO_ANORMAL', categoria: 'NORMAL' }, 'claro');
|
||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[0]).toMatch(/,1\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0.3\)$/);
|
||||
});
|
||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), estrato: 'estatus_seguimiento' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
expect(() => periodosConfirmacion(respuesta(), 'semestre', ['2026-S1'])).toThrow(ConfirmacionIncompatible);
|
||||
const dup = respuesta(); dup.filas.push({ ...dup.filas[0] });
|
||||
expect(() => modeloConfirmacion(dup, '2026-S2')).toThrow(ConfirmacionIncompatible);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Confirmación histopatológica: componente', () => {
|
||||
const indicador: Indicador = { id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica', contrato: 'C2', version: '1',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'] };
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2026-S1', '2026-S2'] }, revision: 1 };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorConfirmacionCitologia>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorConfirmacionCitologia, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorConfirmacionCitologia, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
function flush(body: unknown = respuesta(['2026-S1', '2026-S2'])) {
|
||||
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_confirmacion_citologia/datos');
|
||||
expect(r.request.params.get('estrato')).toBe('citologia_alto_grado');
|
||||
expect(r.request.params.get('periodos')).toBe('2026-S1,2026-S2');
|
||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
||||
}
|
||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible, periodos y tabla', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S2');
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
||||
const normal = [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === 'NORMAL') as HTMLButtonElement;
|
||||
normal.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(normal.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Falsos positivos');
|
||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
const table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(['Citología', ...GRADOS.map(g => g === 'CIS' ? 'Carcinoma in situ' : g), 'CIN2', 'Con biopsia', 'Sin biopsia aún', 'Sin dato']);
|
||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].slice(-3).map(td => td.textContent))).toEqual([['12', '11', '2'], ['58', '22', '2'], ['38', '20', '2']]);
|
||||
f.componentInstance.changePeriod(-1); f.detectChanges();
|
||||
expect(f.componentInstance.model!.periodo).toBe('2026-S1'); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('error se anuncia y el reintento recupera; respuesta incompatible no dibuja', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url.endsWith('/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); flush({ ...respuesta(['2026-S1', '2026-S2']), estrato: 'otro' });
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('filtro general incompatible no pide datos', () => {
|
||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo descripción y como_leer de fig_c2_donas y fig_c2_barras', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('pendientes');
|
||||
f.componentRef.setInput('metadata', { descripcion: 'No va', ficha: { nota: 'Tampoco' }, figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] },
|
||||
{ figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.', 'Lee las tasas.']);
|
||||
for (const absent of ['No va', 'Tampoco', 'Otra', 'No.']) expect(help.textContent).not.toContain(absent);
|
||||
});
|
||||
it('la tarjeta conecta el panel solo por id de CaCu; cacu_eu13 sigue igual', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', indicador);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(1);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, id] of [['cacu', 'cacu_eu13'], ['cama', 'cacu_confirmacion_citologia']] as const) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorConfirmacionCitologia))).toHaveLength(0);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
|
||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
||||
// a C2 stratified by the last valid cytology of the period; the category is the grade
|
||||
// of the biopsy it originated. Unknown or suppressed cells never become zero.
|
||||
export const ID_CONFIRMACION = 'cacu_confirmacion_citologia';
|
||||
export const ESTRATO_CITOLOGIA = 'citologia_alto_grado';
|
||||
// Outside the denominator and the donut, reported apart in the table:
|
||||
// SIN_BIOPSIA = no biopsy reported at the cut-off; SIN_DATO = biopsy reported without a grade.
|
||||
export const APARTE = [
|
||||
{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia aún' },
|
||||
{ id: 'SIN_DATO', etiqueta: 'Biopsia sin grado' },
|
||||
] as const;
|
||||
const APARTE_IDS: readonly string[] = APARTE.map(a => a.id);
|
||||
// Grades outside the published catalog (CIN2, DESCONOCIDO…) arrive without a colour.
|
||||
const COLOR_RESPALDO = '#8A9199';
|
||||
// Fixed vertical axis, most severe cytology on top.
|
||||
export const FILAS_CITOLOGIA = [
|
||||
{ id: 'CIS', etiqueta: 'Carcinoma in situ' },
|
||||
{ id: 'LIEAG', etiqueta: 'LIEAG' },
|
||||
{ id: 'ASC-H', etiqueta: 'ASC-H' },
|
||||
] as const;
|
||||
export const Z95 = 1.959963984540054;
|
||||
|
||||
export interface Celda { n: number | null; estado: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export interface Grado { id: string; etiqueta: string; color: string; grupo: string; }
|
||||
export interface GrupoGrados { id: string; etiqueta: string; color: string; grados: string[]; }
|
||||
export interface FilaCitologia {
|
||||
id: string; etiqueta: string; celdas: Record<string, Celda>;
|
||||
// SIN_BIOPSIA and SIN_DATO cells, when the response publishes those categories.
|
||||
aparte: Record<string, Celda>;
|
||||
// Women of the row with a biopsy: the denominator. Null when any of its cells is unknown.
|
||||
den: number | null; estado: Celda['estado'];
|
||||
}
|
||||
export interface ModeloConfirmacion {
|
||||
periodo: string; grados: Grado[]; grupos: GrupoGrados[]; base: string;
|
||||
filas: FilaCitologia[]; totales: Record<string, number | null>; conBiopsia: number | null;
|
||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||
}
|
||||
export interface SeleccionConfirmacion { grupo: string; categoria?: string; }
|
||||
export interface Tasa { fila: FilaCitologia; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||
export class ConfirmacionIncompatible extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;
|
||||
const fail = (message: string): never => { throw new ConfirmacionIncompatible(message); };
|
||||
const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||
|
||||
/** Wilson score interval at 95 %, in percent; same formula as the kit (oro/calculo.py:wilson). */
|
||||
export function wilson(k: number, n: number): [number, number] {
|
||||
const p = k / n, z2 = Z95 * Z95, base = 1 + z2 / n;
|
||||
const centro = (p + z2 / (2 * n)) / base;
|
||||
const mitad = Z95 * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / base;
|
||||
return [100 * Math.max(0, Math.min(p, centro - mitad)), 100 * Math.min(1, Math.max(p, centro + mitad))];
|
||||
}
|
||||
|
||||
function celda(fila?: Record<string, unknown>): Celda {
|
||||
if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' };
|
||||
return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0
|
||||
? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' };
|
||||
}
|
||||
function suma(celdas: Celda[]): number | null {
|
||||
return celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0);
|
||||
}
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function promedio(colores: string[]): string {
|
||||
return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length)
|
||||
.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
// grupos_de_categoria publishes a label, or an object with `etiqueta`.
|
||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||
|
||||
/** Validated periods of one stratified response, in request order or sorted. */
|
||||
export function periodosConfirmacion(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
if (datos.id !== ID_CONFIRMACION || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_CITOLOGIA
|
||||
|| !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length
|
||||
|| datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|
||||
|| (solicitados && datos.periodos.some(p => !solicitados.includes(p)))
|
||||
|| datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) {
|
||||
return fail('Los datos no corresponden a la confirmación histopatológica o al periodo aplicado.');
|
||||
}
|
||||
return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort();
|
||||
}
|
||||
|
||||
/** One /datos payload -> the contingency table of a single period. */
|
||||
export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): ModeloConfirmacion {
|
||||
periodosConfirmacion(datos, datos.tipo_periodo);
|
||||
const cats = datos['categorias'], nombres = datos['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(nombres)) return fail('Catálogo de grados incompleto.');
|
||||
const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => {
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
});
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades share the group but not its colour.
|
||||
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
const base = grados.find(g => g.id === 'LIEAG')?.grupo ?? fail('El catálogo no publica el grado LIEAG.');
|
||||
if (grupos.length !== 2) fail('Se esperaban dos grupos de grados.');
|
||||
const index = new Map<string, Record<string, unknown>>();
|
||||
for (const row of datos.filas.filter(f => f['periodo'] === periodo)) {
|
||||
const c = row['categoria'], e = row['estrato'];
|
||||
if (!esTotal(row['grupo']) || typeof e !== 'string' || typeof c !== 'string'
|
||||
|| (!grados.some(g => g.id === c) && !aparte.some(a => a.id === c)) || ![0, 1].includes(row['suprimido'] as number)) {
|
||||
return fail('Fila de confirmación inválida.');
|
||||
}
|
||||
const key = JSON.stringify([e, c]);
|
||||
if (index.has(key)) return fail('Filas de confirmación duplicadas.');
|
||||
index.set(key, row);
|
||||
}
|
||||
// valores_estrato may list only the strata with data; a fixed row absent from it has no women.
|
||||
const publicados = Array.isArray(datos['valores_estrato']) ? (datos['valores_estrato'] as unknown[]) : undefined;
|
||||
if (publicados && !publicados.every(v => typeof v === 'string')) fail('Estratos de citología inválidos.');
|
||||
const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {};
|
||||
const totales = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : [];
|
||||
if (!totales.every(registro)) fail('Totales de citología inválidos.');
|
||||
const filas = FILAS_CITOLOGIA.map(({ id, etiqueta }) => {
|
||||
const rotulo = texto(etiquetas[id]) ? etiquetas[id] : registro(cats[id]) && texto(cats[id]['etiqueta']) ? cats[id]['etiqueta'] : etiqueta;
|
||||
const tieneFilas = [...index.keys()].some(k => JSON.parse(k)[0] === id);
|
||||
const ausente = !tieneFilas && (!publicados || !publicados.includes(id));
|
||||
const cero = (): Celda => ({ n: 0, estado: 'Publicado' });
|
||||
const celdas = Object.fromEntries(grados.map(g => [g.id, ausente ? cero() : celda(index.get(JSON.stringify([id, g.id])))]));
|
||||
const otras = Object.fromEntries(aparte.map(a => [a.id, ausente ? cero() : celda(index.get(JSON.stringify([id, a.id])))]));
|
||||
// A suppressed published total suppresses the row, whatever its cells say.
|
||||
const suprimida = (totales as Record<string, unknown>[]).some(t => t['periodo'] === periodo && t['estrato'] === id && t['suprimido'] === 1);
|
||||
const valores = Object.values(celdas);
|
||||
return { id, etiqueta: rotulo, celdas, aparte: otras,
|
||||
den: suprimida ? null : suma(valores), estado: suprimida ? 'Suprimido' as const : estado(valores) };
|
||||
});
|
||||
const porGrado = Object.fromEntries(grados.map(g => [g.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[g.id]))]));
|
||||
return { periodo, grados, grupos, base, filas, totales: porGrado,
|
||||
conBiopsia: suma(grados.map(g => ({ n: porGrado[g.id], estado: 'Publicado' as const }))),
|
||||
aparte, vacio: index.size === 0, notas: [...new Set(datos.notas ?? [])] };
|
||||
}
|
||||
|
||||
export function seleccionBase(m: ModeloConfirmacion): SeleccionConfirmacion { return { grupo: m.base }; }
|
||||
export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string[] {
|
||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.grados ?? [];
|
||||
}
|
||||
export function seleccionEtiqueta(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
return sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta;
|
||||
}
|
||||
/** Group selects the group; a grade selects it and a second click returns to its group; the centre returns to the base. */
|
||||
export function clicConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, traza: string, indice: number): SeleccionConfirmacion {
|
||||
if (traza === 'centro') return seleccionBase(m);
|
||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.grados[indice];
|
||||
if (!c) return sel;
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
/** The axis title says what the rate reads. */
|
||||
export function lectura(m: ModeloConfirmacion, sel: SeleccionConfirmacion): string {
|
||||
if (!sel.categoria && sel.grupo === m.base) return 'Verdaderos positivos (valor predictivo positivo)';
|
||||
if (sel.categoria === 'NORMAL') return 'Falsos positivos: la biopsia no confirmó lesión';
|
||||
if (!sel.categoria) return 'Sin confirmación de alto grado';
|
||||
return 'Proporción con biopsia ' + seleccionEtiqueta(m, sel);
|
||||
}
|
||||
/** Per cytology: selected grades over women with a biopsy. "No biopsy yet" never enters. */
|
||||
export function tasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion): Tasa[] {
|
||||
const cats = seleccionados(m, sel);
|
||||
return m.filas.map(fila => {
|
||||
if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null };
|
||||
const k = cats.reduce((s, c) => s + fila.celdas[c].n!, 0);
|
||||
const [bajo, alto] = wilson(k, fila.den);
|
||||
return { fila, k, valor: 100 * k / fila.den, bajo, alto };
|
||||
});
|
||||
}
|
||||
export function estadoTasa(t: Tasa): string {
|
||||
return t.fila.den === 0 ? 'Sin mujeres con biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado;
|
||||
}
|
||||
/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */
|
||||
export function rangoTasas(valores: Tasa[]): [number, number] {
|
||||
const visibles = valores.filter(t => t.bajo !== null && t.alto !== null);
|
||||
if (!visibles.length) return [0, 100];
|
||||
const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!));
|
||||
return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)];
|
||||
}
|
||||
|
||||
/** Rates on the left: one point and horizontal Wilson interval per cytology, one trace always. */
|
||||
export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const valores = tasas(m, sel);
|
||||
const color = sel.categoria ? m.grados.find(g => g.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color;
|
||||
const y = valores.map(t => t.fila.etiqueta);
|
||||
return { data: [{
|
||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||
marker: { size: 12, color }, cliponaxis: false,
|
||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
||||
customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]),
|
||||
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||
}], layout: {
|
||||
autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { l: 130, r: 96, t: 16, b: 64 },
|
||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true },
|
||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } },
|
||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||
font: { size: 12, color: p.text },
|
||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
/** Donut on the right: groups inside, grades outside; selection dims, values stay. */
|
||||
export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmacion, tema: Tema): PlotlyFigure {
|
||||
if (m.conBiopsia === null || m.conBiopsia === 0) return { data: [], layout: {} };
|
||||
const p = c2Theme(tema), activos = new Set(seleccionados(m, sel)), total = m.conBiopsia;
|
||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
|
||||
const exterior = m.grados.map(g => m.totales[g.id]!);
|
||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
||||
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia · %{customdata[1]}<extra></extra>' };
|
||||
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
|
||||
return { data: [
|
||||
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
|
||||
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], textfont: { size: 16, color: p.text },
|
||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
config: { displayModeBar: false } };
|
||||
}
|
||||
@@ -29,10 +29,6 @@
|
||||
@if (item.tipos_periodo.length) {
|
||||
<ul>@for (tipo of item.tipos_periodo; track tipo) { <li>{{ periodNames[tipo] }}</li> }</ul>
|
||||
} @else { <p>Pendiente de información.</p> }
|
||||
<h4>Cómo interpretar este indicador</h4>
|
||||
@if (interpretation(item).length) {
|
||||
<ul>@for (line of interpretation(item); track $index) { <li>{{ line }}</li> }</ul>
|
||||
}
|
||||
@if (opened.has(dominio + ':' + item.id)) {
|
||||
<app-indicador-metadata [dominio]="dominio" [indicador]="item.id" />
|
||||
} @else {
|
||||
@@ -52,5 +48,5 @@
|
||||
<li>Los periodos se presentan sin consolidar datos de distintos periodos, grupos o estratos.</li>
|
||||
<li>Los intervalos de confianza, cuando están disponibles, describen incertidumbre y no garantizan certeza poblacional; su amplitud puede verse afectada por un tamaño de muestra pequeño.</li>
|
||||
</ul>
|
||||
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. Las notas de cada gráfica incluyen detalles adicionales para interpretar los datos mostrados.</p>
|
||||
<p>Uso para investigación; la información no constituye aprobación clínica ni establece metas institucionales. El botón «Cómo leer» de cada gráfica explica cómo interpretarla e incluye sus notas.</p>
|
||||
</section>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Component, Input, output } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { Dominio, Indicador, TipoPeriodo } from './indicadores.models';
|
||||
import { figureDisplayName } from './indicadores-figure-labels';
|
||||
import { contractInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { IndicadorMetadata } from './indicador-metadata';
|
||||
|
||||
@Component({
|
||||
@@ -24,15 +24,4 @@ export class IndicadoresDefinitions {
|
||||
readonly figureDisplayName = figureDisplayName;
|
||||
readonly periodInterpretation = PERIOD_INTERPRETATION;
|
||||
get periodTypes() { return [...new Set(this.catalog.flatMap(item => item.tipos_periodo))]; }
|
||||
interpretation(item: Indicador) {
|
||||
if (!item.contrato) return [];
|
||||
const lines = contractInterpretation(item.contrato, this.dominio);
|
||||
// Catalog metadata does not describe the traces. Keep the shared C2 guidance
|
||||
// independent of bars/sectors; the actual figure retains its full explanation.
|
||||
return lines.filter(line =>
|
||||
!line.includes('Los valores nulos o suprimidos') &&
|
||||
!line.includes('Los puntos suprimidos') &&
|
||||
!line.includes('No hay una explicación específica disponible'),
|
||||
).slice(item.contrato === 'C2' ? 1 : 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
const definitions = KPI_BY_DOMAIN[domain];
|
||||
const otherDomain = domain === 'cacu' ? 'cama' : 'cacu';
|
||||
const items = [...definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, tipos_periodo: ['semestre'], figuras: ['f', 'g'] })),
|
||||
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f'] }];
|
||||
// Two figures, so every domain keeps an ordinary card whose representation can change.
|
||||
{ id: 'other', titulo: 'Otra figura', contrato: 'C1', tipos_periodo: ['semestre'], figuras: ['f', 'g'] }];
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
@@ -108,9 +109,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
it('todas las figuras reciben el periodo compartido y mantienen carga diferida', () => {
|
||||
choose(); http.expectNone(r => r.url.includes('/figuras/'));
|
||||
cards().forEach(card => { expect(card.applied).toBe(page.filters!.applied); card.setVisible(true); });
|
||||
// EU7 now owns a coordinated C2 view. This temporal fixture publishes only
|
||||
// placeholder f/g figures, so that card must stop as incompatible, without GET.
|
||||
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7).length); http.expectNone(() => true);
|
||||
// EU7 and the CaCu paired times own coordinated views. This temporal fixture publishes
|
||||
// only placeholder f/g figures, so EU7 stops as incompatible without GET; the paired times
|
||||
// ask /datos for the same shared period, including the partner hidden from the catalog.
|
||||
fixture.detectChanges(); flushFigures(periods[1], cards().filter(card => !card.isEu7 && !card.tiempos).length);
|
||||
const tiempos = http.match(r => r.url.endsWith('/datos'));
|
||||
expect(tiempos.some(r => r.request.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos')).toBe(domain === 'cacu');
|
||||
for (const r of tiempos) { expect(r.request.params.get('periodos')).toBe(periods[1]); r.flush('', { status: 404, statusText: 'Missing' }); }
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('KPI secundarios sin datos no retroceden a otro periodo', () => {
|
||||
request(periods[0]).flush(data(0, periods[0])); fixture.detectChanges();
|
||||
@@ -128,7 +134,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
it('tema, ancho y representación no reinician el periodo ni la búsqueda', () => {
|
||||
choose(); const applied = page.filters!.applied;
|
||||
page.changeTema('oscuro'); window.dispatchEvent(new Event('resize')); fixture.detectChanges(); http.expectNone(() => true);
|
||||
const card = cards().find(card => !card.isEu7)!;
|
||||
const card = cards().find(card => !card.isEu7 && !card.tiempos)!;
|
||||
card.setVisible(true); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
card.selectFigure('g'); fixture.detectChanges(); flushFigures(periods[1], 1);
|
||||
expect(card.selectedFigure).toBe('g'); http.expectNone(() => true);
|
||||
|
||||
@@ -140,6 +140,6 @@ describe('KPI de CaMa con respuestas reales de WebApi', () => {
|
||||
});
|
||||
it('tiempo de tamizaje a diagnóstico: la mediana del C3r', () => {
|
||||
expect(result(2).state).toBe('Disponible');
|
||||
expect(result(2).info).toContain('El horizonte de 180 días es provisional.');
|
||||
expect(result(2).info).toMatch(/^[\d.,]+ mastografías; Q1 a Q3: [\d.]+ a [\d.]+ días\.$/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,10 +21,10 @@ describe.each(['tea', 'cacu', 'cama'] as const)('KPI %s', domain => {
|
||||
expect(result.value).toBe('33.4'); expect(result.info).toContain('2 de 6');
|
||||
expect(run(1, [{ ...total, grupo: c1Group, valor: 0, numerador: 0, denominador: 6 }]).value).toBe('0.0');
|
||||
});
|
||||
it('C3r conserva mediana cero y Q1/Q3, referencia provisional solo en CaCu y CaMa', () => {
|
||||
it('C3r conserva mediana cero y Q1/Q3, sin reglas provisionales en la tarjeta', () => {
|
||||
const result = run(2, [{ ...total, mediana: 0, n: 5, q1: 0, q3: 7, unidad: 'dias' }]);
|
||||
expect(result.value).toBe(0); expect(result.info).toContain('0 a 7 días');
|
||||
if (domain === 'tea') expect(result.info).not.toContain('provisional'); else expect(result.info).toContain('provisional');
|
||||
expect(result.info).not.toContain('provisional');
|
||||
});
|
||||
it.each([0, 1, 2])('suprimido en %s oculta cualquier cifra', index => {
|
||||
expect(run(index, [{ ...total, grupo: index === 1 ? c1Group : 'TOTAL', categoria: 'A', n: 5, valor: 100, mediana: 7, suprimido: 2 }])).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
|
||||
@@ -32,8 +32,8 @@ const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => strin
|
||||
};
|
||||
const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> = {
|
||||
tea: (n, q1, q3) => `${n} pacientes; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días. El horizonte de 180 días es provisional.`,
|
||||
cacu: (n, q1, q3) => `${n} citologías; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
};
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; }
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Dominio, IndicadorMetadatos } from './indicadores.models';
|
||||
|
||||
// Existing WebApp explanations, shared by figures and the definitions section.
|
||||
// These are editorial guidance, not additional metadata supplied by WebApi.
|
||||
// Editorial fallback for a figure whose metadata publishes no `como_leer`
|
||||
// (metadata not loaded yet, failed, or an older kit). Not WebApi metadata.
|
||||
const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
C1: [
|
||||
'El punto representa la proporción observada.',
|
||||
@@ -17,14 +17,15 @@ const CONTRACT_INTERPRETATIONS: Readonly<Record<string, readonly string[]>> = {
|
||||
};
|
||||
export const PERIOD_INTERPRETATION = 'Un periodo puede tener reportes calculados sin valores estadísticos representables. La leyenda de la figura no permite determinar la disponibilidad real de cada periodo.';
|
||||
|
||||
export function figureMetadataInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string): readonly string[] | undefined {
|
||||
const detail = metadata?.figuras_detalle?.find(item => item.figura === figureId);
|
||||
if (!detail) return undefined;
|
||||
const instructions = detail.como_leer ?? [];
|
||||
return instructions.some(line => line.trim().length > 0) ? instructions : undefined;
|
||||
// "Cómo leer" of a figure: the kit's `como_leer` when it publishes one, otherwise
|
||||
// the generic guidance of the figure's contract.
|
||||
export function figureInterpretation(metadata: IndicadorMetadatos | undefined, figureId: string,
|
||||
contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
|
||||
const instructions = metadata?.figuras_detalle?.find(item => item.figura === figureId)?.como_leer ?? [];
|
||||
return instructions.some(line => line.trim().length > 0) ? instructions : contractInterpretation(contract, domain, pie);
|
||||
}
|
||||
|
||||
export function contractInterpretation(contract: string | undefined, domain: Dominio, pie = false): readonly string[] {
|
||||
function contractInterpretation(contract: string | undefined, domain: Dominio, pie: boolean): readonly string[] {
|
||||
if (contract === 'C2') return [
|
||||
pie
|
||||
? 'Los sectores muestran la composición porcentual de las categorías publicadas para cada periodo.'
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { Component, input } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { figuraTiempos, modeloTiempos, PARES_TIEMPOS, parTiempos, TiemposIncompatibles } from './indicadores-tiempos-pareados';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); }
|
||||
|
||||
const par = PARES_TIEMPOS.find(p => p.dominio === 'cacu')!;
|
||||
const item = (id: string, titulo: string): Indicador => ({ id, titulo, contrato: 'C3r', version: '1', figuras: ['fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] });
|
||||
const diagnostico = item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico');
|
||||
const reporte = item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado');
|
||||
const row = (periodo: string, n: number | null, q1: number | null, mediana: number | null, q3: number | null, suprimido = 0) =>
|
||||
({ periodo, grupo: 'TOTAL', estrato: null, n, q1, mediana, q3, n_sin_evento: 0, n_excluido: 0, suprimido, unidad: 'dias' });
|
||||
function datos(id: string, filas: Record<string, unknown>[], periodos = ['2025-S1', '2025-S2']): IndicadorDatos {
|
||||
return { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos, filas, version: '1' };
|
||||
}
|
||||
const lab = () => datos(reporte.id, [row('2025-S1', 120, 7, 12, 20), row('2025-S2', 98, 6, 10, 18)]);
|
||||
const dx = () => datos(diagnostico.id, [row('2025-S1', 3, null, null, null, 1), row('2025-S2', 40, 30, 52, 90)]);
|
||||
|
||||
describe('Tiempos pareados: modelo y figura', () => {
|
||||
it('una caja por indicador y periodo; suprimidos y nulos nunca se dibujan como cero', () => {
|
||||
const m = modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre');
|
||||
expect(m.periodos).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(m.cajas.diagnostico['2025-S1']).toEqual({ estado: 'Suprimido' });
|
||||
expect(m.cajas.reporte['2025-S2']).toEqual({ estado: 'Publicado', n: 98, q1: 6, mediana: 10, q3: 18 });
|
||||
const f = figuraTiempos(m, par, 'claro');
|
||||
expect(f.layout['boxmode']).toBe('group');
|
||||
expect(f.data.map(t => t['name'])).toEqual(['Toma → resultado (laboratorio)', 'Toma → diagnóstico']);
|
||||
expect(f.data.map(t => t['type'])).toEqual(['box', 'box']);
|
||||
expect(f.data[0]['marker']).not.toEqual(f.data[1]['marker']);
|
||||
expect(f.data[0]['x']).toEqual(['2025-S1', '2025-S2']);
|
||||
expect(f.data[1]['x']).toEqual(['2025-S2']);
|
||||
expect(f.data[1]).toMatchObject({ q1: [30], median: [52], q3: [90], lowerfence: [30], upperfence: [90] });
|
||||
expect(f.data[1]['customdata']).toEqual([['40', '30', '52', '90']]);
|
||||
expect(f.data[1]['hovertemplate']).toContain('n = %{customdata[0]} citologías');
|
||||
expect(f.data[1]['hovertemplate']).toContain('Mediana: %{customdata[2]} días');
|
||||
expect(JSON.stringify(f.data)).not.toContain('null');
|
||||
expect(figuraTiempos(m, par, 'oscuro').layout['paper_bgcolor']).toBe('#081839');
|
||||
});
|
||||
it('cuartiles incompletos o desordenados quedan no disponibles', () => {
|
||||
const d = datos(diagnostico.id, [row('2025-S1', 4, 5, 3, 9), row('2025-S2', 0, 0, 0, 0)]);
|
||||
const m = modeloTiempos(par, { reporte: lab(), diagnostico: d }, 'semestre');
|
||||
expect(m.cajas.diagnostico['2025-S1'].estado).toBe('No disponible');
|
||||
expect(m.cajas.diagnostico['2025-S2'].estado).toBe('No disponible');
|
||||
});
|
||||
it('rechaza datos de otro indicador, contrato, periodo o con dos totales por periodo', () => {
|
||||
expect(() => modeloTiempos(par, { reporte: dx(), diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
expect(() => modeloTiempos(par, { reporte: { ...lab(), contrato: 'C1' }, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
expect(() => modeloTiempos(par, { reporte: lab(), diagnostico: dx() }, 'semestre', ['2025-S2'])).toThrow(TiemposIncompatibles);
|
||||
const twice = datos(reporte.id, [row('2025-S1', 1, 1, 1, 1), row('2025-S1', 2, 2, 2, 2)]);
|
||||
expect(() => modeloTiempos(par, { reporte: twice, diagnostico: dx() }, 'semestre')).toThrow(TiemposIncompatibles);
|
||||
});
|
||||
it('el par de CaMa existe pero solo CaCu está conectado', () => {
|
||||
expect(parTiempos('cacu', 'cacu_dias_toma_diagnostico')).toBe(par);
|
||||
expect(parTiempos('cacu', 'cacu_eu_tiempo_reporte')).toBeUndefined();
|
||||
expect(PARES_TIEMPOS.some(p => p.dominio === 'cama' && p.diagnostico === 'cama_dias_toma_diagnostico')).toBe(true);
|
||||
expect(parTiempos('cama', 'cama_dias_toma_diagnostico')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tiempos pareados: componente', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }, revision: 1 };
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorTiemposPareados>>;
|
||||
let http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorTiemposPareados, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorTiemposPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorTiemposPareados);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('par', par);
|
||||
f.componentRef.setInput('indicador', diagnostico);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
function flush(a = lab(), b = dx()) {
|
||||
const r = http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos');
|
||||
const d = http.expectOne(req => req.url === '/cacu/indicadores/cacu_dias_toma_diagnostico/datos');
|
||||
expect(r.request.params.get('periodos')).toBe('2025-S1,2025-S2');
|
||||
expect(d.request.params.get('periodos')).toBe(r.request.params.get('periodos'));
|
||||
r.flush(a); d.flush(b); f.detectChanges();
|
||||
}
|
||||
it('carga diferida; dos GET de los mismos periodos; una gráfica y tabla con supresión', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading'); flush();
|
||||
expect(f.componentInstance.status()).toBe('ready');
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub));
|
||||
expect(charts).toHaveLength(1);
|
||||
expect((charts[0].componentInstance as ChartStub).figure()).toBe(f.componentInstance.figure);
|
||||
const text = f.nativeElement.querySelector('table').textContent as string;
|
||||
expect(text).toContain('Suprimido'); expect(text).toContain('mediana 52');
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
||||
});
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
f.detectChanges();
|
||||
flush(datos(reporte.id, [row('2025-S1', 2, null, null, null, 1)]), datos(diagnostico.id, []));
|
||||
expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay cajas publicadas');
|
||||
});
|
||||
it('con filtro incompatible u otro indicador no hay GET', () => {
|
||||
f.componentRef.setInput('indicador', { ...diagnostico, tipos_periodo: ['mes'] }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('indicador', { ...diagnostico, contrato: 'C1' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
||||
});
|
||||
it('la pareja oculta del catálogo se pide por id; un 404 se anuncia como error, sin cajas', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url === '/cacu/indicadores/cacu_eu_tiempo_reporte/datos' && req.params.get('periodos') === '2025-S1,2025-S2').flush({}, { status: 404, statusText: 'Not Found' });
|
||||
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
||||
f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
});
|
||||
it('error HTTP se anuncia y el reintento vuelve a pedir', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(req => req.url.includes('cacu_eu_tiempo_reporte')).flush({}, { status: 500, statusText: 'Error' });
|
||||
http.match(req => req.url.includes('cacu_dias_toma_diagnostico'));
|
||||
f.detectChanges(); expect(f.componentInstance.status()).toBe('error');
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('«Cómo leer» muestra el como_leer de las dos figuras y la advertencia de poblaciones distintas', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const requested = vi.fn(); f.componentInstance.metadataRequested.subscribe(requested);
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
expect(requested).toHaveBeenCalledTimes(1);
|
||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('Metadatos publicados pendientes');
|
||||
http.expectOne('/cacu/indicadores/cacu_eu_tiempo_reporte/metadatos').flush({ ficha: { nota: 'No va' },
|
||||
figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: null, como_leer: ['Caja del laboratorio.'] }] });
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [{ figura: 'fig_c3r_caja', descripcion: 'Caja de diagnóstico.', como_leer: ['Lee el diagnóstico.'] }] });
|
||||
f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('.reading-guide h3')].map(h => h.textContent)).toEqual(['Toma → resultado (laboratorio)', 'Toma → diagnóstico']);
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Caja del laboratorio.', 'Lee el diagnóstico.']);
|
||||
expect(help.querySelector('.caveat')!.textContent).toContain('no es el tiempo del tramo intermedio');
|
||||
expect(help.textContent).not.toContain('No va'); expect(help.textContent).not.toContain('pendientes');
|
||||
});
|
||||
it('la tarjeta de CaCu sustituye el diagnóstico por la vista pareada; las demás quedan igual', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
const card = TestBed.createComponent(IndicadorCatalogCard);
|
||||
card.componentRef.setInput('dominio', 'cacu'); card.componentRef.setInput('indicador', diagnostico);
|
||||
card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges();
|
||||
const view = card.debugElement.query(By.directive(IndicadorTiemposPareados));
|
||||
expect(view).not.toBeNull();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0);
|
||||
for (const [domain, indicator] of [['cacu', reporte], ['cama', { ...diagnostico, id: 'cama_dias_toma_diagnostico' }]] as const) {
|
||||
card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', indicator); card.detectChanges();
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorTiemposPareados))).toHaveLength(0);
|
||||
expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(1);
|
||||
}
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Dominio, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
|
||||
|
||||
// Two C3r indicators that share the sample date (toma) and differ in their end
|
||||
// event: the lab result and the diagnosis note. They are drawn side by side per
|
||||
// period so the slower stretch is visible. C3r publishes only Q1, median and Q3:
|
||||
// no individual observations, so boxes have no whiskers and no violin is possible.
|
||||
export interface ParTiempos {
|
||||
dominio: Dominio;
|
||||
reporte: string;
|
||||
diagnostico: string;
|
||||
estudios: string;
|
||||
etiquetas: { reporte: string; diagnostico: string };
|
||||
// Only connected pairs replace the diagnosis card in the catalog.
|
||||
conectado: boolean;
|
||||
}
|
||||
export const PARES_TIEMPOS: readonly ParTiempos[] = [
|
||||
{ dominio: 'cacu', reporte: 'cacu_eu_tiempo_reporte', diagnostico: 'cacu_dias_toma_diagnostico', estudios: 'citologías',
|
||||
etiquetas: { reporte: 'Toma → resultado (laboratorio)', diagnostico: 'Toma → diagnóstico' }, conectado: true },
|
||||
{ dominio: 'cama', reporte: 'cama_eu38a', diagnostico: 'cama_dias_toma_diagnostico', estudios: 'mastografías',
|
||||
etiquetas: { reporte: 'Toma → resultado', diagnostico: 'Toma → diagnóstico' }, conectado: false },
|
||||
];
|
||||
export function parTiempos(dominio: Dominio, id: string): ParTiempos | undefined {
|
||||
return PARES_TIEMPOS.find(par => par.conectado && par.dominio === dominio && par.diagnostico === id);
|
||||
}
|
||||
export const FIGURA_C3R = 'fig_c3r_caja';
|
||||
|
||||
export type Clave = 'reporte' | 'diagnostico';
|
||||
export const CLAVES: readonly Clave[] = ['reporte', 'diagnostico'];
|
||||
export interface Caja {
|
||||
estado: 'Publicado' | 'Suprimido' | 'No disponible';
|
||||
n?: number; q1?: number; mediana?: number; q3?: number;
|
||||
}
|
||||
export interface ModeloTiempos { periodos: string[]; cajas: Record<Clave, Record<string, Caja>>; notas: string[]; }
|
||||
export class TiemposIncompatibles extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const finito = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const conteo = (v: unknown): v is number => finito(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const fail = (message: string): never => { throw new TiemposIncompatibles(message); };
|
||||
|
||||
function caja(fila: Record<string, unknown> | undefined): Caja {
|
||||
if (!fila) return { estado: 'No disponible' };
|
||||
if (fila['suprimido'] === 1) return { estado: 'Suprimido' };
|
||||
const { n, q1, mediana, q3 } = fila;
|
||||
// Null quantiles are not zeros: without a complete published box nothing is drawn.
|
||||
if (fila['suprimido'] !== 0 || !conteo(n) || n === 0 || !finito(q1) || !finito(mediana) || !finito(q3)
|
||||
|| q1 < 0 || q1 > mediana || mediana > q3) return { estado: 'No disponible' };
|
||||
return { estado: 'Publicado', n, q1, mediana, q3 };
|
||||
}
|
||||
|
||||
/** Two immutable C3r /datos payloads -> boxes per period, without mixing groups or strata. */
|
||||
export function modeloTiempos(par: ParTiempos, datos: Record<Clave, IndicadorDatos>, tipo: TipoPeriodo,
|
||||
solicitados?: readonly string[]): ModeloTiempos {
|
||||
const cajas = { reporte: {}, diagnostico: {} } as Record<Clave, Record<string, Caja>>;
|
||||
for (const clave of CLAVES) {
|
||||
const d = datos[clave];
|
||||
if (d.id !== par[clave] || d.contrato !== 'C3r' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|
||||
|| new Set(d.periodos).size !== d.periodos.length
|
||||
|| (solicitados && d.periodos.some(p => !solicitados.includes(p)))) {
|
||||
fail('Los datos de tiempos no corresponden al indicador o al periodo aplicado.');
|
||||
}
|
||||
for (const fila of d.filas) {
|
||||
if (!registro(fila) || typeof fila['periodo'] !== 'string' || !d.periodos.includes(fila['periodo'])) fail('Fila C3r fuera de los periodos publicados.');
|
||||
if (fila['grupo'] !== 'TOTAL' || fila['estrato'] != null) continue;
|
||||
if (fila['unidad'] !== undefined && fila['unidad'] !== 'dias') fail('Unidad de tiempo distinta de días.');
|
||||
const periodo = fila['periodo'] as string;
|
||||
if (cajas[clave][periodo]) fail('Más de una fila total por periodo.');
|
||||
cajas[clave][periodo] = caja(fila);
|
||||
}
|
||||
for (const periodo of d.periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
||||
}
|
||||
const periodos = solicitados ? [...solicitados]
|
||||
: [...new Set([...datos.reporte.periodos, ...datos.diagnostico.periodos])].sort();
|
||||
for (const clave of CLAVES) for (const periodo of periodos) cajas[clave][periodo] ??= { estado: 'No disponible' };
|
||||
return { periodos, cajas, notas: [...new Set([...(datos.reporte.notas ?? []), ...(datos.diagnostico.notas ?? [])])] };
|
||||
}
|
||||
|
||||
export function hayCajas(m: ModeloTiempos): boolean {
|
||||
return CLAVES.some(clave => m.periodos.some(p => m.cajas[clave][p].estado === 'Publicado'));
|
||||
}
|
||||
|
||||
const COLORES: Record<Clave, string> = { reporte: C2_PALETTE.series[0], diagnostico: C2_PALETTE.series[2] };
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
const dias = (v: number) => v.toLocaleString('es-MX', { maximumFractionDigits: 1 });
|
||||
|
||||
/** Grouped boxes from published quartiles; whiskers equal the box (fences are unknown). */
|
||||
export function figuraTiempos(m: ModeloTiempos, par: ParTiempos, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const data = CLAVES.map(clave => {
|
||||
const periodos = m.periodos.filter(periodo => m.cajas[clave][periodo].estado === 'Publicado');
|
||||
const cajas = periodos.map(periodo => m.cajas[clave][periodo]);
|
||||
return {
|
||||
type: 'box', name: par.etiquetas[clave], legendgroup: clave, x: periodos,
|
||||
q1: cajas.map(c => c.q1), median: cajas.map(c => c.mediana), q3: cajas.map(c => c.q3),
|
||||
lowerfence: cajas.map(c => c.q1), upperfence: cajas.map(c => c.q3),
|
||||
marker: { color: COLORES[clave] }, line: { color: COLORES[clave], width: 2 }, fillcolor: rgba(COLORES[clave], .35),
|
||||
customdata: cajas.map(c => [c.n!.toLocaleString('es-MX'), dias(c.q1!), dias(c.mediana!), dias(c.q3!)]),
|
||||
hoveron: 'boxes',
|
||||
hovertemplate: `${par.etiquetas[clave]}<br>%{x}<br>n = %{customdata[0]} ${par.estudios}`
|
||||
+ '<br>Q1: %{customdata[1]} días<br>Mediana: %{customdata[2]} días<br>Q3: %{customdata[3]} días<extra></extra>',
|
||||
};
|
||||
});
|
||||
return { data, layout: {
|
||||
boxmode: 'group', autosize: true, height: 440, showlegend: true,
|
||||
legend: { orientation: 'h', x: 0, y: 1.02, xanchor: 'left', yanchor: 'bottom' },
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 48, l: 64, r: 16, b: 56 },
|
||||
xaxis: { type: 'category', categoryorder: 'array', categoryarray: m.periodos, title: { text: 'Periodo' } },
|
||||
yaxis: { title: { text: 'días' }, rangemode: 'tozero', gridcolor: p.grid, zeroline: false },
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
export function cajaTexto(c: Caja): string {
|
||||
return c.estado !== 'Publicado' ? c.estado
|
||||
: `n = ${c.n!.toLocaleString('es-MX')} · Q1 ${dias(c.q1!)} · mediana ${dias(c.mediana!)} · Q3 ${dias(c.q3!)} días`;
|
||||
}
|
||||
@@ -17,7 +17,7 @@ export interface Indicador {
|
||||
tipos_periodo: TipoPeriodo[];
|
||||
filtros?: IndicadorFiltro[];
|
||||
}
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento';
|
||||
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
|
||||
export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; }
|
||||
export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; }
|
||||
export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; }
|
||||
@@ -40,9 +40,17 @@ export interface IndicadorFiguraDetalle {
|
||||
descripcion: string | null;
|
||||
como_leer: string[] | null;
|
||||
}
|
||||
// A rule the kit used to compute the indicator (horizon, code lists, thresholds).
|
||||
export interface IndicadorParametro {
|
||||
clave: string;
|
||||
valor: unknown;
|
||||
estado: string;
|
||||
fuente?: string | null;
|
||||
}
|
||||
export interface IndicadorMetadatos {
|
||||
descripcion?: string | null;
|
||||
ficha?: IndicadorFicha | null;
|
||||
parametros?: IndicadorParametro[] | null;
|
||||
referencias?: { tipo: string; etiqueta: string; ref: string | null }[] | null;
|
||||
poblaciones?: { grupo: string; codigo: string; descripcion: string }[] | null;
|
||||
figuras_detalle?: IndicadorFiguraDetalle[] | null;
|
||||
|
||||
@@ -48,6 +48,32 @@ describe('IndicadoresService HTTP', () => {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it('acepta parámetros publicados con valores de cualquier tipo y fuente opcional', () => {
|
||||
const parametros = [
|
||||
{ clave: 'cacu.horizontes.toma_diagnostico_dias', valor: 180, estado: 'provisional', fuente: 'Arbitrario para poder calcular.' },
|
||||
{ clave: 'cacu.diagnostico.cie', valor: ['Z014', 'R87'], estado: 'provisional', fuente: null },
|
||||
{ clave: 'comun.umbral_supresion', valor: 5, estado: 'confirmado' },
|
||||
];
|
||||
let value: unknown, nulo: unknown;
|
||||
service.metadatos('cacu', 'p').subscribe(v => value = v);
|
||||
http.expectOne('/cacu/indicadores/p/metadatos').flush({ parametros });
|
||||
service.metadatos('cacu', 'n').subscribe(v => nulo = v);
|
||||
http.expectOne('/cacu/indicadores/n/metadatos').flush({ parametros: null });
|
||||
expect(value).toMatchObject({ parametros }); expect(nulo).toMatchObject({ parametros: null });
|
||||
});
|
||||
it.each([
|
||||
{ parametros: 'incorrecto' },
|
||||
{ parametros: [{ clave: '', valor: 1, estado: 'provisional' }] },
|
||||
{ parametros: [{ clave: 'a', estado: 'provisional' }] },
|
||||
{ parametros: [{ clave: 'a', valor: 1, estado: 1 }] },
|
||||
{ parametros: [{ clave: 'a', valor: 1, estado: 'confirmado', fuente: 2 }] },
|
||||
])('rechaza parámetros mal formados $parametros', payload => {
|
||||
let error: unknown;
|
||||
service.metadatos('cacu', 'i').subscribe({ error: value => error = value });
|
||||
http.expectOne('/cacu/indicadores/i/metadatos').flush(payload);
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it.each(['tea', 'cacu', 'cama'] as const)('lee catálogo sintético dinámico de %s y sus tipos publicados', dominio => {
|
||||
service.catalogo(dominio).subscribe(items => {
|
||||
expect(items).toEqual(syntheticCatalogs[dominio]);
|
||||
|
||||
@@ -40,6 +40,13 @@ export class IndicadoresService {
|
||||
if (content !== undefined && content !== null && typeof content !== 'string') throw new Error('Metadatos inválidos');
|
||||
}
|
||||
}
|
||||
const parameters = value['parametros'];
|
||||
if (parameters !== undefined && parameters !== null && (!Array.isArray(parameters) || !parameters.every(v => record(v)
|
||||
&& typeof v['clave'] === 'string' && v['clave'].trim().length > 0 && Object.hasOwn(v, 'valor')
|
||||
&& typeof v['estado'] === 'string'
|
||||
&& (v['fuente'] === undefined || v['fuente'] === null || typeof v['fuente'] === 'string')))) {
|
||||
throw new Error('Metadatos inválidos');
|
||||
}
|
||||
for (const field of ['referencias', 'poblaciones']) {
|
||||
const list = value[field];
|
||||
if (list !== undefined && list !== null && (!Array.isArray(list) || !list.every(v => record(v) && (field === 'referencias'
|
||||
@@ -66,7 +73,7 @@ export class IndicadoresService {
|
||||
}
|
||||
let params = new HttpParams();
|
||||
if (scope.estrato) {
|
||||
if (!['grupo_edad', 'estatus_seguimiento'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
|
||||
params = params.set('estrato', scope.estrato);
|
||||
}
|
||||
if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(','));
|
||||
|
||||
Reference in New Issue
Block a user