feat(cama): TEA tabs, follow-up list from announced columns and histopathology donut by BI-RADS category

This commit is contained in:
rockdrigo
2026-11-09 17:55:34 -06:00
parent 53edec8692
commit 39974b8533
20 changed files with 301 additions and 102 deletions
@@ -1,4 +1,6 @@
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number; }
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string; page: number; page_size: number;
// Filters a list announces in `filtros_disponibles`, by key.
filtros?: Record<string, string>; }
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
export interface SeguimientoPaciente {
id_seudonimo: string;
@@ -91,13 +91,6 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[2],ultima_citologia:{...fixtureData.items[2].ultima_citologia,calidad:42}}]})).toThrow();
open().flush({...fixtureData,simulado:false}); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull();
});
it.each(['cama'])('%s conserva su estado pendiente sin consultas de pacientes', dominio => {
fixture.componentRef.setInput('dominio',dominio); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
expect(fixture.nativeElement.textContent).toContain('El seguimiento aún no está disponible');
expect(fixture.nativeElement.textContent).not.toContain('Columnas propuestas para revisión.');
expect(fixture.nativeElement.querySelector('table')).not.toBeNull();
expect(fixture.nativeElement.querySelector('caption')).toBeNull();
});
it('valida parámetros antes del transporte sin confundir fechas del filtro general', () => {
const service=TestBed.inject(CacuSeguimientoService);
for(const q of [{corte:'2026-02-30'},{page:0},{page_size:201},{meses:2}]) expect(()=>service.consultar({meses:3,page:1,page_size:50,...q} as never)).toThrow();
@@ -15,6 +15,7 @@ import { filterCompatibility } from './indicadores-memory';
import { DonutSelection } from './indicadores-donut-drilldown';
import { IndicadoresService } from './indicadores.service';
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
@@ -120,7 +121,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
});
}
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isEu7() { return !!vistaEscenario(this.dominio, this.indicador); }
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); }
@@ -1,4 +1,4 @@
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
<section class="eu7" [attr.aria-label]="indicador.titulo + ' por ' + etiquetaEstrato">
<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) {
@@ -16,24 +16,24 @@
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' || status() === 'empty') {
@if (periods.length > 1) {
<nav class="periods" aria-label="Periodos de dona y barras EU7">
<button type="button" aria-label="Periodo anterior de EU7" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<nav class="periods" [attr.aria-label]="'Periodos de dona y barras, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
<span role="status">{{ periods[periodIndex] }}, {{ periodIndex + 1 }} de {{ periods.length }}</span>
<button type="button" aria-label="Periodo siguiente de EU7" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
<button type="button" aria-label="Periodo siguiente" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
<div class="legend" role="group" [attr.aria-label]="'Explorar grupos y categorías, ' + indicador.titulo">
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selecció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.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
@@ -48,27 +48,27 @@
<div class="figures">
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
@if (m.total !== null && m.total > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="indicador.titulo + ', dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado disponible para la dona.' }}</p> }
<p>{{ sinDatoNote }}</p>
</section>
<section class="figure"><h3>{{ selectionLabel }} por escenario clínico, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada escenario; excluye «Sin dato».</p>
<section class="figure"><h3>{{ selectionLabel }} por {{ etiquetaEstrato }}, {{ m.periodo }}</h3>
<p>Porcentaje del total válido de cada {{ etiquetaEstrato }}; excluye «{{ m.sinDatoEtiqueta }}».</p>
@if (m.escenarios.length && barsFigure) {
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="'EU7, barras por escenario clínico, ' + m.periodo + ', ' + selectionLabel" />
<app-plotly-chart [figure]="barsFigure" [animated]="true" [showNotes]="false" [style.--plot-min-width]="'440px'" [label]="indicador.titulo + ', barras por ' + etiquetaEstrato + ', ' + m.periodo + ', ' + selectionLabel" />
}
</section>
</div>
}
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" aria-label="Tabla de valores EU7" tabindex="0">
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>Datos generales, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Conteo</th></tr></thead>
<tbody>@for (row of generalCells; track $index) { <tr><th scope="row">{{ row.etiqueta }}</th><td>{{ cellText(row.celda) }}</td></tr> }</tbody>
</table>
<table><caption>Escenarios clínicos, {{ m.periodo }}, porcentajes sin «Sin dato»</caption>
<thead><tr><th scope="col">Escenario</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<table><caption>Por {{ etiquetaEstrato }}, {{ m.periodo }}, porcentajes sin «{{ m.sinDatoEtiqueta }}»</caption>
<thead><tr><th scope="col">{{ etiquetaEstrato.charAt(0).toUpperCase() + etiquetaEstrato.slice(1) }}</th><th scope="col">Categoría</th><th scope="col">Conteo</th><th scope="col">Denominador válido</th><th scope="col">Porcentaje</th></tr></thead>
<tbody>@for (row of scenarioCells; track $index) { <tr><th scope="row">{{ row.escenario }}</th><td>{{ row.categoria }}</td><td>{{ cellText(row.celda) }}</td><td>{{ row.den === null ? 'No disponible / no aplica' : row.den }}</td><td>{{ percentText(row.pct) }}</td></tr> }</tbody>
</table>
</div>
@@ -126,7 +126,7 @@ describe('EU7 integración Angular y caché compartida', () => {
f.detectChanges(); flush(); expect(f.nativeElement.textContent).toContain('Suprimido');
expect(f.nativeElement.textContent).not.toContain('987654');
expect(f.nativeElement.querySelector('table caption')).not.toBeNull();
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').tabIndex).toBe(0);
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores, Distribución de resultados citológicos"]').tabIndex).toBe(0);
});
it('catálogo sin capacidad temporal o clínica no inicia GET', () => {
f.componentRef.setInput('indicador', { ...indicador, filtros: [] }); f.detectChanges();
@@ -4,16 +4,14 @@ import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
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;
import { barras, Celda, clic, dona, esEu7, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta, vistaEscenario } from './indicadores-eu7-escenario';
@Component({
selector: 'app-indicador-eu7-escenario',
@@ -44,6 +42,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private key = '';
private loaded = false;
private pages: Modelo[] = [];
get vista(): VistaEscenario | undefined { return vistaEscenario(this.dominio, this.indicador); }
get etiquetaEstrato() { return this.vista?.etiqueta ?? 'escenario clínico'; }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; }
get sinDatoNote() {
@@ -51,6 +51,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
if (!m) return '';
if (m.vacio) return 'No hay registros publicados en este periodo.';
const n = m.sinDato.n;
if (this.vista && !esEu7(this.vista)) return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: `Fuera de la dona: ${n} pacientes con «${m.sinDatoEtiqueta}»${m.total === null ? '' : ` de ${m.total + n}`}.`;
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.`
: m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.`
: `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
@@ -69,7 +71,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
// "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 figuras = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por ' + this.etiquetaEstrato]] as const;
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);
@@ -99,10 +102,11 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
const vista = this.vista;
if (!vista || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|| !stratifiedCapabilities(this.indicador).includes(vista.estrato) || !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;
@@ -110,13 +114,13 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
this.status.set('loading');
this.subscription = combineLatest([
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }),
this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: vista.estrato }),
]).pipe(timeout({ first: 40000 })).subscribe({
next: ([general, escenarios]) => {
if (key !== this.key) return;
try {
this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods);
this.pages = this.periods.map(p => modelo(general, escenarios, p));
this.pages = this.periods.map(p => modelo(general, escenarios, p, vista.estrato));
this.periodIndex = 0; this.activatePeriod();
} catch (error) { this.failure(error); }
},
@@ -151,7 +155,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
private draw() {
if (!this.model) return;
this.donutFigure = dona(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema);
this.barsFigure = barras(this.model, this.selection, this.tema, `% de pacientes de cada ${this.etiquetaEstrato}`);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
@@ -1,11 +1,18 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, VistaEscenario } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
// A C2 distribution with category groups, next to the same categories by one stratum. Unknown cells never become zero.
export const ESTRATO = 'estatus_seguimiento';
const SIN_DATO = 'SIN_DATO';
// CaCu's EU7 predates the catalog's `escenario` field.
const EU7: VistaEscenario = { estrato: ESTRATO, etiqueta: 'escenario clínico' };
export function vistaEscenario(dominio: Dominio, indicador: Indicador): VistaEscenario | undefined {
if (indicador.escenario) return indicador.escenario;
return dominio === 'cacu' && indicador.id === 'cacu_eu7' ? EU7 : undefined;
}
export const esEu7 = (vista: VistaEscenario) => vista === EU7;
export interface Seleccion { grupo?: string; categoria?: string; }
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
export interface Grupo { id: string; etiqueta: string; color: string; }
@@ -64,7 +71,7 @@ function catalogo(data: IndicadorDatos): Categoria[] {
/** Validate the common temporal scope before exposing any period's figures. */
export function periodosCompatibles(general: IndicadorDatos, escenarios: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
for (const d of [general, escenarios]) {
if (d.id !== 'cacu_eu7' || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
if (d.id !== general.id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos)
|| new Set(d.periodos).size !== d.periodos.length || d.periodos.some(p => typeof p !== 'string'
|| !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p))
|| !Array.isArray(d.filas) || d.filas.some(f => !registro(f) || !d.periodos.includes(f['periodo'] as string))) {
@@ -80,10 +87,10 @@ export function periodosCompatibles(general: IndicadorDatos, escenarios: Indicad
}
/** Two immutable /datos payloads -> one safe presentation model for a single period. */
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string): Modelo {
export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, periodo: string, estrato: DimensionEstrato = ESTRATO): Modelo {
periodosCompatibles(general, porEscenario, general.tipo_periodo);
const valores = porEscenario['valores_estrato'], etiquetas = porEscenario['etiquetas_estrato'];
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== ESTRATO || !general.periodos.includes(periodo)
if ((general['estrato'] ?? null) !== null || porEscenario['estrato'] !== estrato || !general.periodos.includes(periodo)
|| !Array.isArray(valores) || !valores.every(v => typeof v === 'string') || new Set(valores).size !== valores.length
|| !registro(etiquetas) || valores.some(v => typeof etiquetas[v] !== 'string')
|| [general, porEscenario].some(d => registro(d['filtros']) ? Object.keys(d['filtros']).length > 0 : d['filtros'] != null)) {
@@ -212,7 +219,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
config: { displayModeBar: false } };
}
/** Selection never changes the original denominator or renormalizes a subset. */
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
export function barras(m: Modelo, sel: Seleccion, tema: Tema, eje = '% de pacientes del escenario con resultado'): PlotlyFigure {
const p = c2Theme(tema);
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
const y = m.escenarios.map(s => escapar(s.etiqueta));
@@ -235,7 +242,7 @@ export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
xaxis: { title: { text: eje }, ticksuffix: ' %', gridcolor: p.grid,
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 112],
tickvals: sel.grupo || sel.categoria ? undefined : [0, 20, 40, 60, 80, 100] },
annotations: m.escenarios.map((s, i) => ({ y: y[i], x: sumas[i] ?? 0, xanchor: 'left', xshift: 6, showarrow: false,
@@ -126,12 +126,12 @@ describe('Pestaña Histórico', () => {
it('cada intervalo se consulta una vez y cambiar de tema no vuelve a consultar', () => {
abrir();
http.expectOne(r => r.url === datosUrl).flush(datos('mes', ['2024-01', '2024-02'])); render();
fixture.componentInstance.tipo.set('semestre'); render();
fixture.componentInstance.elegido.set('semestre'); render();
const semestre = http.expectOne(r => r.url === datosUrl);
expect(semestre.request.params.get('periodos')).toBe('2024-S1');
semestre.flush(datos('semestre', ['2024-S1'])); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('2024 S1 (1 semestre)');
fixture.componentInstance.tipo.set('mes'); render();
fixture.componentInstance.elegido.set('mes'); render();
fixture.componentRef.setInput('tema', 'oscuro'); render();
http.expectNone(() => true);
});
@@ -147,11 +147,11 @@ describe('Pestaña Histórico', () => {
c.elegirVentana(5); render();
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('ago 2024 a dic 2024 (5 meses)');
http.expectNone(() => true);
c.tipo.set('semestre'); render();
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos('semestre', semestres)); render();
expect(c.opciones().map(o => o.etiqueta)).toEqual(['Últimos 5 semestres', 'Todos (6 semestres)', 'Personalizado…']);
c.tipo.set('mes'); render();
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(5);
http.expectNone(() => true);
});
@@ -191,10 +191,10 @@ describe('Pestaña Histórico', () => {
expect(c.opciones().at(-1)!.etiqueta).toBe('Personalizado (1 mes)');
expect(fixture.nativeElement.querySelector('.rango').textContent).toBe('feb 2024 (1 mes, elegidos)');
// The other granularity keeps its own choice.
c.tipo.set('semestre'); render();
c.elegido.set('semestre'); render();
expect(c.ventana()).toBe(0);
http.expectOne(r => r.url === datosUrl).flush(datos_('semestre', ['2024-S1'])); render();
c.tipo.set('mes'); render();
c.elegido.set('mes'); render();
expect(c.ventana()).toBe(-1);
http.expectNone(() => true);
});
@@ -51,9 +51,9 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="tipo.set($event.value)">
<mat-button-toggle value="mes">Mensual</mat-button-toggle>
<mat-button-toggle value="semestre">Semestral</mat-button-toggle>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
@@ -123,7 +123,13 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
readonly tipo = signal<TipoPeriodo>('mes');
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.catalog().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
readonly tipo = computed<TipoPeriodo>(() => {
const elegido = this.elegido(), tipos = this.tipos();
return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes';
});
// How many of the latest periods to show, per granularity; 0 shows them all.
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
@@ -89,7 +89,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
const ongoing = request(periods[0]);
for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.initialPeriodState()).toBe('loading');
expect(ongoing.cancelled).toBe(false);
http.expectNone(() => true);
@@ -109,7 +109,7 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
editor().select([periods[2]]); fixture.detectChanges();
for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) {
page.changeSection(section); fixture.detectChanges();
for (const req of http.match(r => r.url === '/cacu/seguimiento' || r.url === '/tea/seguimiento')) req.flush({}, { status: 404, statusText: 'Pending' });
for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' });
expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied);
expect(editor().selectedPeriods).toEqual([periods[2]]);
expect(cards()).toContain(card); expect(card.selectedFigure).toBe('g');
@@ -127,7 +127,7 @@
</section>
</div>
@if (dominio === 'tea') {
@if (conHistorico) {
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
</section>
@@ -12,6 +12,7 @@ import { MatSelect, MatSelectModule } from '@angular/material/select';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { catchError, first, map, of, startWith, Subject, switchMap, takeUntil } from 'rxjs';
import { Dominio, DOMINIOS, isDominio, Indicador, Tema } from './indicadores.models';
import { vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadoresService } from './indicadores.service';
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
import { IndicadorPeriodFilters } from './indicador-period-filters';
@@ -35,8 +36,9 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
{ id: 'seguimiento', label: 'Seguimiento' },
{ id: 'datos', label: 'Datos y definiciones' },
];
// Only TEA has enough periods for its history to say anything.
const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
// Domains with enough periods for their history to say anything.
const CON_HISTORICO: readonly Dominio[] = ['tea', 'cama'];
const HISTORICO_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
@Component({
selector: 'app-indicadores-page',
@@ -45,7 +47,8 @@ const TEA_SECTIONS: readonly { id: DashboardSection; label: string }[] = [SECTIO
styleUrl: './indicadores-page.scss',
})
export class IndicadoresPage {
get sections() { return this.dominio === 'tea' ? TEA_SECTIONS : SECTIONS; }
get sections() { return this.conHistorico ? HISTORICO_SECTIONS : SECTIONS; }
get conHistorico() { return CON_HISTORICO.includes(this.dominio); }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
setFichaPacienteAbierta(open: boolean) {
@@ -310,9 +313,10 @@ export class IndicadoresPage {
// Stable presentation priority; pins still take precedence in the grid.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
return this.dominio === 'cacu'
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')]
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
// The interactive views go first.
const resumen = catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
const primero = (item: Indicador) => !!vistaEscenario(this.dominio, item);
return [...resumen.filter(primero), ...resumen.filter(item => !primero(item))];
});
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
readonly selectionSummary = computed(() => {
@@ -37,7 +37,7 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea'
expect(tabs.map(t => t.textContent?.trim())).toEqual(domain === 'tea' || domain === 'cama'
? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(tabs.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
@@ -53,25 +53,14 @@ describe('Secciones compartidas por dominio', () => {
}
const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance);
tab('seguimiento').click(); harness.detectChanges();
if (domain === 'cacu' || domain === 'tea') {
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
}
http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' });
harness.detectChanges();
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
expect(tracking.hidden).toBe(false);
expect(tracking.textContent).toContain('El seguimiento aún no está disponible');
if (domain === 'cacu') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else if (domain === 'tea') {
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
} else {
expect(tracking.querySelectorAll('thead th')).toHaveLength(6);
expect(tracking.querySelectorAll('tbody tr')).toHaveLength(1);
expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6');
expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0);
}
// Every domain queries its list; until it is published there is no table, only the form.
expect(tracking.querySelector('tbody')).toBeNull();
expect(tracking.querySelector('input[type=date]')).not.toBeNull();
tab('datos').click(); harness.detectChanges();
expect(root.querySelector<HTMLElement>('#panel-datos')!.hidden).toBe(false);
tab('resumen').click(); harness.detectChanges();
@@ -6,7 +6,7 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
return item.contrato === 'C2' && Array.isArray(item.filtros)
? (['grupo_edad', 'estatus_seguimiento'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
? (['grupo_edad', 'estatus_seguimiento', 'birads'] as const).filter(d => item.filtros!.some(f => f?.estrato === d
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
}
@@ -5,24 +5,23 @@
}
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
<h2>Seguimiento de {{ domainLabel }}</h2>
@if (dominio !== 'cacu' && dominio !== 'tea') {
<p>El seguimiento aún no está disponible.</p>
<div class="tracking-table" role="region" aria-label="Estructura prevista de seguimiento" tabindex="0">
<table>
<thead><tr><th scope="col">Paciente / identificación</th><th scope="col">Proceso o etapa</th><th scope="col">Estado</th><th scope="col">Fecha de referencia</th><th scope="col">Responsable</th><th scope="col">Acciones</th></tr></thead>
<tbody><tr><td colspan="6">No hay registros de seguimiento disponibles.</td></tr></tbody>
</table>
</div>
} @else {
<form (ngSubmit)="apply()">
<label>Fecha de corte <input name="corte" type="date" [(ngModel)]="draft.corte" /></label>
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
</select></label>
@if (propio) {
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
</select></label>
}
@for (f of filtrosTabla; track f.clave) {
<label>{{ f.etiqueta }} <select [name]="'filtro-' + f.clave" [attr.name]="'filtro-' + f.clave" [(ngModel)]="filtrosDraft[f.clave]">
<option [ngValue]="undefined">Todos</option>
@for (o of f.opciones; track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
</select></label>
}
@if (dominio === 'tea') {
<label>Grupo de edad <select name="grupo_edad" [(ngModel)]="draft.grupo_edad">
<option [ngValue]="undefined">Todos</option>
@@ -92,6 +91,22 @@
</tbody>
</table>
</div>
} @else if (tablaData; as response) {
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
<caption>Resultados disponibles por paciente</caption>
<thead><tr>@for (c of response.columnas; track c.clave) { <th scope="col">{{ c.etiqueta }}</th> }</tr></thead>
<tbody>
@for (item of response.items; track item['id_seudonimo']) {
<tr [attr.data-paciente]="item['id_seudonimo']">
@for (c of response.columnas; track c.clave) {
<td>{{ valorTabla(item[c.clave]) }}@for (d of detallesTabla(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { <small>{{ d.etiqueta }}: {{ valorTabla(item[d.clave]) }}</small> } }</td>
}
</tr>
} @empty { <tr><td [attr.colspan]="response.columnas.length">No hay registros para los filtros aplicados.</td></tr> }
</tbody>
</table>
</div>
} @else if (data; as response) {
<div class="tracking-table" role="region" aria-label="Lista de seguimiento de demostración" tabindex="0">
<table>
@@ -117,5 +132,4 @@
<button type="button" [disabled]="response.paginacion.page >= response.paginacion.total_pages" (click)="navigate(response.paginacion.page + 1)">Siguiente</button>
</nav>
}
}
</div>
@@ -12,6 +12,7 @@ import { Dominio } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
import { SeguimientoColumna, SeguimientoFiltro, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor } from './seguimiento-tabla.service';
@Component({
selector: 'app-indicadores-tracking',
@@ -27,6 +28,7 @@ export class IndicadoresTracking implements OnChanges {
private readonly service = inject(CacuSeguimientoService);
private readonly indicators = inject(IndicadoresService);
private readonly teaService = inject(TeaSeguimientoService);
private readonly tablaService = inject(SeguimientoTablaService);
private readonly destroy = inject(DestroyRef);
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly injector = inject(Injector);
@@ -35,18 +37,22 @@ export class IndicadoresTracking implements OnChanges {
private controlPaciente?: HTMLElement;
private readonly requests = new Subject<SeguimientoQuery | null>();
private readonly teaRequests = new Subject<SeguimientoQuery | null>();
private readonly tablaRequests = new Subject<{ dominio: Dominio; q: SeguimientoQuery } | null>();
private initialized = false;
private previousDomain?: Dominio;
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
message = '';
data?: SeguimientoResponse;
teaData?: TeaSeguimientoResponse;
// Domains whose list announces its own filters and columns.
tablaData?: SeguimientoTablaResponse;
filtrosTabla: SeguimientoFiltro[] = [];
// One open summary at a time, like an accordion.
teaAbierto?: string;
statuses: SeguimientoStatus[] = [];
private metadataLoaded = false;
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50, filtros: {} };
private applied: SeguimientoQuery = { ...this.draft };
readonly latestStudy = latestStudy;
readonly gruposEdad = GRUPOS_EDAD_TEA;
@@ -57,7 +63,8 @@ export class IndicadoresTracking implements OnChanges {
// Kept from the last answer, so the filter doesn't empty while a query is running.
tiposAlteracion: { codigo: string; etiqueta: string }[] = [];
get provisional() { return this.data?.reglas.some(r => r.estado === 'provisional'); }
get response() { return this.dominio === 'tea' ? this.teaData : this.data; }
get response() { return this.dominio === 'tea' ? this.teaData : this.dominio === 'cacu' ? this.data : this.tablaData; }
get propio() { return this.dominio === 'cacu' || this.dominio === 'tea'; }
constructor() {
const failure = (error: unknown, q: SeguimientoQuery) => of({ data: undefined, status: error instanceof HttpErrorResponse && error.status === 404 && q.page === 1 ? 'pending' as const : 'error' as const,
message: error instanceof HttpErrorResponse && error.status === 400 ? 'Revisa la fecha, la ventana y los filtros seleccionados.'
@@ -93,24 +100,43 @@ export class IndicadoresTracking implements OnChanges {
this.draft = { ...this.applied };
}
});
this.tablaRequests.pipe(switchMap(r => r ? defer(() => this.tablaService.consultar(r.dominio, r.q)).pipe(
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, r.q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
if (!result) return;
this.changeDetector.markForCheck();
this.status = result.status; this.tablaData = result.data; this.message = result.message;
if (result.data) {
const data = result.data;
this.filtrosTabla = data.filtros_disponibles;
const filtros = Object.fromEntries(Object.entries(data.filtros).filter((e): e is [string, string] => e[1] !== null));
this.applied = { corte: data.corte, meses: data.ventana.meses, filtros, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied, filtros: { ...filtros } };
}
});
}
ngOnChanges() {
if (this.previousDomain !== this.dominio) {
if (this.pacienteDetalle.estado().tipo !== 'cerrado') this.fichaPacienteAbierta.emit(false);
this.pacienteDetalle.cerrar(); this.controlPaciente = undefined;
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.data = undefined; this.teaData = undefined;
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
this.previousDomain = this.dominio; this.requests.next(null); this.teaRequests.next(null); this.tablaRequests.next(null);
this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.filtrosTabla = [];
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50, filtros: {} }; this.applied = { ...this.draft };
}
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
if (this.dominio === 'tea' && this.active && !this.initialized) { this.initialized = true; this.statuses = ALTERACIONES_EEG; this.load(this.applied); }
if (!this.propio && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
}
private load(q: SeguimientoQuery) {
if (this.dominio !== 'cacu' && this.dominio !== 'tea') return;
if (!validSeguimientoQuery(q)) { this.message = 'Revisa la fecha, la ventana y el tamaño de página (1 a 200).'; return; }
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.tablaData = undefined; this.applied = { ...q };
if (this.dominio === 'tea') this.teaRequests.next(q);
else if (this.dominio === 'cacu') this.requests.next(q);
else this.tablaRequests.next({ dominio: this.dominio, q });
}
apply() { this.load({ ...this.draft, page: 1 }); }
apply() { this.load({ ...this.draft, filtros: Object.fromEntries(Object.entries(this.draft.filtros ?? {}).filter(([, v]) => v)), page: 1 }); }
valorTabla(v: SeguimientoValor | undefined) { return v === null || v === undefined || v === '' ? 'No disponible' : typeof v === 'number' ? v.toLocaleString('es-MX') : v; }
detallesTabla(c: SeguimientoColumna) { return c.detalles ?? []; }
get filtrosDraft() { return this.draft.filtros ??= {}; }
retry() { this.load(this.applied); }
navigate(page: number) {
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
@@ -18,8 +18,13 @@ export interface Indicador {
filtros?: IndicadorFiltro[];
// Tabs that show it; without this field, all of them.
vistas?: string[];
// Interactive donut and bars by one stratum, like CaCu's EU7.
escenario?: VistaEscenario;
}
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado';
export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads';
export const DIMENSIONES_ESTRATO: readonly DimensionEstrato[] = ['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'];
// `etiqueta` names one value of the stratum in lower case, as in «por escenario clínico».
export interface VistaEscenario { estrato: DimensionEstrato; etiqueta: string; }
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; }
@@ -1,7 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
import { DatosScope, DIMENSIONES_ESTRATO, DimensionEstrato, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -20,7 +20,9 @@ export class IndicadoresService {
&& new Set(item['figuras']).size === item['figuras'].length
&& Array.isArray(item['tipos_periodo']) && item['tipos_periodo'].length > 0
&& item['tipos_periodo'].every((tipo: unknown) => tipo === 'semestre' || tipo === 'mes')
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length)) {
&& new Set(item['tipos_periodo']).size === item['tipos_periodo'].length
&& (item['escenario'] === undefined || record(item['escenario']) && typeof item['escenario']['etiqueta'] === 'string'
&& DIMENSIONES_ESTRATO.includes(item['escenario']['estrato'] as DimensionEstrato)))) {
throw new Error('Respuesta de catálogo inválida');
}
if (new Set(value.map(item => item['id'])).size !== value.length) throw new Error('IDs de catálogo duplicados');
@@ -66,7 +68,7 @@ export class IndicadoresService {
}
let params = new HttpParams();
if (scope.estrato) {
if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida');
if (!DIMENSIONES_ESTRATO.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(','));
@@ -0,0 +1,56 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { isoDate, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
import { validSeguimientoQuery } from './cacu-seguimiento.service';
import { Dominio, requireDominio } from './indicadores.models';
// Follow-up list whose filters and columns come with the answer, so a domain needs no code of its own.
export type SeguimientoValor = string | number | null;
// `detalles` are shown under the value, each with its label (for example the date of a result).
export interface SeguimientoColumna { clave: string; etiqueta: string; detalles?: { clave: string; etiqueta: string }[] }
export interface SeguimientoFiltro { clave: string; etiqueta: string; opciones: SeguimientoStatus[] }
export interface SeguimientoTablaResponse extends Pick<SeguimientoResponse, 'simulado' | 'corte' | 'ventana' | 'paginacion'> {
filtros: Record<string, string | null>;
filtros_disponibles: SeguimientoFiltro[];
columnas: SeguimientoColumna[];
// Every item has `id_seudonimo`; the rest are the columns' keys and their details.
items: Record<string, SeguimientoValor>[];
}
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0;
const valor = (v: unknown) => v === null || typeof v === 'string' || typeof v === 'number' && Number.isFinite(v);
// Keys travel as query parameters, so they are restricted to what can't collide with the shared ones.
const clave = (v: unknown) => text(v) && /^[a-z][a-z0-9_]*$/.test(v) && !['meses', 'page', 'page_size', 'corte'].includes(v);
const opcion = (v: unknown) => record(v) && text(v['codigo']) && text(v['etiqueta']);
export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
// Same rule as CaCu and TEA: demonstration records only.
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'], available = v['filtros_disponibles'], columns = v['columnas'];
if (!isoDate(v['corte']) || !record(window) || ![1, 3, 6, 12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|| !Array.isArray(available) || !available.every(f => record(f) && clave(f['clave']) && text(f['etiqueta']) && Array.isArray(f['opciones']) && f['opciones'].every(opcion))
|| new Set(available.map(f => f['clave'])).size !== available.length
|| !record(filters) || !Object.entries(filters).every(([k, f]) => f === null || typeof f === 'string' && available.some(a => a['clave'] === k))
|| !Array.isArray(columns) || !columns.length || !columns.every(c => record(c) && text(c['clave']) && text(c['etiqueta'])
&& (c['detalles'] === undefined || Array.isArray(c['detalles']) && c['detalles'].every(d => record(d) && text(d['clave']) && text(d['etiqueta']))))
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number)
|| !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor)))
throw new Error('Respuesta de seguimiento inválida');
return v as unknown as SeguimientoTablaResponse;
}
@Injectable({ providedIn: 'root' })
export class SeguimientoTablaService {
private readonly http = inject(HttpClient);
consultar(dominio: Dominio, query: SeguimientoQuery) {
if (!validSeguimientoQuery(query) || !Object.keys(query.filtros ?? {}).every(clave)) throw new Error('Parámetros de seguimiento inválidos');
let params = new HttpParams().set('meses', query.meses).set('page', query.page).set('page_size', query.page_size);
if (query.corte) params = params.set('corte', query.corte);
for (const [k, v] of Object.entries(query.filtros ?? {})) if (v) params = params.set(k, v);
return this.http.get<unknown>(`/${requireDominio(dominio)}/seguimiento`, { params }).pipe(map(seguimientoTablaResponse));
}
}
@@ -0,0 +1,90 @@
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import eu7 from './fixtures/eu7-c2-ejemplos.json';
import { Indicador, IndicadorDatos } from './indicadores.models';
import { modelo, vistaEscenario } from './indicadores-eu7-escenario';
import { IndicadoresTracking } from './indicadores-tracking';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
// Covers what lets a domain reuse CaCu's views without code of its own: the interactive donut and bars
// chosen by the catalog's `escenario`, and the follow-up list whose filters and columns come in the answer.
// Fixtures: `eu7-c2-ejemplos.json` (CaCu's EU7 answers, relabelled here as another stratum) and `lista`,
// a two-patient CaMa list built below.
// Two CaMa patients, one without a biopsy, with the filters and columns the list announces.
const lista = () => ({
simulado: true, corte: '2026-10-20', ventana: { meses: 3, desde: '2026-07-21', hasta: '2026-10-20' },
filtros: { birads: null }, filtros_disponibles: [{ clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: [{ codigo: 'BIRADS_5', etiqueta: 'BI-RADS 5' }] }],
columnas: [{ clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' },
{ clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] },
{ clave: 'biopsia', etiqueta: 'Resultado histopatológico' }],
paginacion: { page: 1, page_size: 50, total_items: 2, total_pages: 1 },
items: [{ id_seudonimo: 'M-0001', birads: 'BI-RADS 5', mastografia_fecha: '2026-09-01', biopsia: 'Carcinoma invasor' },
{ id_seudonimo: 'M-0002', birads: 'BI-RADS 4A', mastografia_fecha: '2026-08-15', biopsia: null }],
});
describe('Vista de dona y barras por estrato', () => {
const item = (extra: Partial<Indicador> = {}): Indicador => ({ id: 'x', titulo: 'X', contrato: 'C2', figuras: [], tipos_periodo: ['semestre'], ...extra });
it('la elige el campo escenario del catálogo, y CaCu EU7 la conserva sin él', () => {
// Fails if the view goes back to being recognised by CaCu's indicator id only.
expect(vistaEscenario('cama', item({ escenario: { estrato: 'birads', etiqueta: 'categoría BI-RADS' } }))?.estrato).toBe('birads');
expect(vistaEscenario('cacu', item({ id: 'cacu_eu7' }))?.estrato).toBe('estatus_seguimiento');
expect(vistaEscenario('cama', item())).toBeUndefined();
});
it('arma el modelo con otro indicador y otro estrato', () => {
// Fails if `modelo` checks CaCu's id or its stratum instead of the ones it is given.
const relabel = (d: unknown, estrato: string | null) => ({ ...structuredClone(d) as IndicadorDatos, id: 'cama_histopatologia_birads', ...(estrato ? { estrato } : {}) });
const general = relabel(eu7.general, null), porBirads = relabel(eu7.estatus_seguimiento, 'birads');
expect(modelo(general, porBirads, '2025-S2', 'birads').total).toBe(946);
expect(() => modelo(general, porBirads, '2025-S2')).toThrow();
});
});
describe('Seguimiento con filtros y columnas anunciados', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresTracking>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresTracking); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'CaMa');
fixture.componentRef.setInput('active', true); fixture.detectChanges();
});
afterEach(() => { fixture.destroy(); http.verify(); });
const text = () => fixture.nativeElement.textContent as string;
it('pinta las columnas, los detalles y los valores ausentes de la respuesta', () => {
// Fails if CaMa stops querying its own list or the table stops following `columnas`.
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
const headers = Array.from(fixture.nativeElement.querySelectorAll('thead th')).map(e => (e as HTMLElement).textContent?.trim());
expect(headers).toEqual(['Identificador seudónimo', 'Última mastografía', 'Resultado histopatológico']);
expect(text()).toContain('Fecha: 2026-09-01');
expect(fixture.nativeElement.querySelectorAll('tbody tr')[1].textContent).toContain('No disponible');
});
it('envía cada filtro anunciado con su clave y sin los vacíos', () => {
// Fails if the announced filters stop reaching the query, or an empty choice is sent as a value.
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista()); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('select[name="filtro-birads"]')).not.toBeNull();
expect(fixture.nativeElement.querySelector('select[name="estatus"]')).toBeNull();
fixture.componentInstance.filtrosDraft['birads'] = 'BIRADS_5'; fixture.componentInstance.apply();
let req = http.expectOne(r => r.url === '/cama/seguimiento');
expect(req.request.params.get('birads')).toBe('BIRADS_5');
req.flush({ ...lista(), filtros: { birads: 'BIRADS_5' } });
fixture.componentInstance.filtrosDraft['birads'] = ''; fixture.componentInstance.apply();
req = http.expectOne(r => r.url === '/cama/seguimiento');
expect(req.request.params.has('birads')).toBe(false);
req.flush(lista());
});
it('sin lista publicada queda pendiente', () => {
// Fails if a 404 on the first page is shown as an error instead of a list not yet published.
http.expectOne(r => r.url === '/cama/seguimiento').flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges();
expect(text()).toContain('Funcionalidad pendiente de publicación');
});
it('solo admite datos de demostración y respuestas coherentes', () => {
// Fails if the validation stops guarding the table from real records or from filters it didn't announce.
expect(() => seguimientoTablaResponse({ ...lista(), simulado: false })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), filtros: { edad: '40-49' } })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), filtros_disponibles: [{ clave: 'page', etiqueta: 'X', opciones: [] }] })).toThrow();
expect(() => seguimientoTablaResponse({ ...lista(), items: [{ birads: 'BI-RADS 5' }] })).toThrow();
http.expectOne(r => r.url === '/cama/seguimiento').flush(lista());
});
});