Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bfcba8ad1f | |||
| f04c40b1e1 | |||
| bd3f63b20a | |||
| 860c66ba5c | |||
| 5c8e2866ef | |||
| 29d021b347 | |||
| 98e9b60e83 | |||
| 5061350dd8 | |||
| eb887be447 | |||
| 0b22b3c309 | |||
| 6ade415f63 | |||
| 5791928976 | |||
| f4d1829cd3 | |||
| 069cc459a4 | |||
| 881c613744 | |||
| be46429627 | |||
| 25f584c864 | |||
| 561a5dde36 | |||
| bf89099ce8 | |||
| ff1f6758ba | |||
| f38a2c6bb4 | |||
| 40c19a6a1f | |||
| 329c0891ae | |||
| 34c6f2af3a | |||
| 7ab2567dc9 | |||
| 14d6875d9b | |||
| f82ce8cc38 | |||
| 61867ff973 | |||
| 8bca0fbcdf | |||
| ec8542de9f | |||
| 29c9e6853b | |||
| b1ff6cadb2 | |||
| 26285a87fa | |||
| f058f1f476 | |||
| 7f1e43bdc5 | |||
| 5bf6af8ecf | |||
| 253290ed6a | |||
| ec5b8fde6b | |||
| 2a36397fac | |||
| eada50d2ff | |||
| 396902541d | |||
| 68b5e927e7 | |||
| 990cab0e37 | |||
| 39e1e3e094 | |||
| 4e08bb8c4b | |||
| 686580af81 | |||
| 60c71bfc3d | |||
| ad4edbe2a1 | |||
| 1af0c21291 | |||
| dd356efb6b | |||
| 01271621b7 | |||
| 4c181af291 |
@@ -14,3 +14,25 @@ npx ng build # compilación de producción en dist/WebApp
|
||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||
|
||||
## CaCu en Windows con la instalación del puerto 5210
|
||||
|
||||
En `feature/cacu-update`, desde la carpeta de WebApp:
|
||||
|
||||
```powershell
|
||||
npm ci
|
||||
npm run start:cacu
|
||||
```
|
||||
|
||||
Abre [Indicadores CaCu](http://127.0.0.1:4300/indicadores/cacu) e inicia sesión
|
||||
con la cuenta de CaCu de la aplicación. La sesión se valida en el navegador.
|
||||
Detén Angular con `Ctrl+C` en la misma terminal.
|
||||
|
||||
El lockfile de Angular admite Node.js `^22.22.3`, `^24.15.0` o `>=26.0.0`.
|
||||
`package.json` declara npm `11.17.0`. El arranque se probó con Node.js
|
||||
`26.13.0` y npm `11.20.0`.
|
||||
|
||||
`start:cacu` escucha en `127.0.0.1:4300`. El proxy de Angular reenvía
|
||||
solicitudes GET de CaCu a `http://10.0.10.41:5210`, incluida la lista
|
||||
`/cacu/seguimiento` y los recursos FHIR `Measure`, `MeasureReport` y
|
||||
`RiskAssessment`. La ruta `/indicadores/cacu` la sirve Angular.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start:cacu": "ng serve --host 127.0.0.1 --port 4300 --proxy-config proxy.cacu-readonly.cjs",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Keep the installed API read-only for local CaCu development.
|
||||
module.exports = {
|
||||
'^/(?:health|cacu/(?:seguimiento|fhir/(?:Measure|MeasureReport|RiskAssessment|metadata)))(?:\\?|$)': {
|
||||
target: 'http://10.0.10.41:5210',
|
||||
changeOrigin: true,
|
||||
bypass(request, response) {
|
||||
if (request.method === 'GET') return;
|
||||
if (!response) return false;
|
||||
response.writeHead(405, { Allow: 'GET' });
|
||||
response.end();
|
||||
return request.url;
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { BarrasHorizontales } from './barras-horizontales';
|
||||
import { ConjuntoBarras, FilaBarra, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras';
|
||||
|
||||
const fila = (id: string, etiqueta: string, n: number | null, estado: FilaBarra['estado'] = 'Publicado'): FilaBarra => ({ id, etiqueta, n, estado, color: '#438B53' });
|
||||
const suma = (fs: FilaBarra[]) => fs.some(f => f.n === null) ? null : fs.reduce((s, f) => s + f.n!, 0);
|
||||
// Cytology with more than 95 % normal results: the others are small counts, one of them a single record.
|
||||
const normales = [fila('NORMAL', 'Normal', 912)];
|
||||
const anormales = [fila('ASC-US', 'ASC-US', 14), fila('LIEBG', 'LIEBG', 9), fila('ASC-H', 'ASC-H', 3), fila('LIEAG', 'LIEAG', 5), fila('CIS', 'Carcinoma in situ', 1)];
|
||||
const citologia = (activas: string[] | null = null): ConjuntoBarras => ({ den: 944, unidad: 'pacientes con resultado', activas: activas ? new Set(activas) : null, grupos: [
|
||||
{ id: 'SIN', etiqueta: 'Sin anomalía', color: '#247A71', subtotal: 912, filas: normales }, { id: 'ANORMAL', etiqueta: 'Anormal', color: '#656677', subtotal: suma(anormales), filas: anormales }] });
|
||||
const plano = (filas: FilaBarra[], den: number | null): ConjuntoBarras => ({ den, unidad: 'reportes de VPH elegibles', activas: null, grupos: [{ id: null, etiqueta: null, color: '#8A9199', subtotal: den, filas }] });
|
||||
|
||||
describe('Barras horizontales: escala', () => {
|
||||
it('el límite es un número redondo y par que contiene la barra o el subtotal más largo', () => {
|
||||
expect([0, 1, 5, 44, 63, 912, 946, 1892].map(limiteEscala)).toEqual([2, 2, 6, 50, 80, 1000, 1000, 2000]);
|
||||
expect(maximoDelConjunto(citologia())).toBe(912);
|
||||
// A group's subtotal can exceed its categories: the scale holds it.
|
||||
expect(maximoDelConjunto({ den: 108, unidad: 'x', activas: null, grupos: [{ id: 'g', etiqueta: 'g', color: '#000', subtotal: 63, filas: [fila('a', 'a', 44), fila('b', 'b', 13), fila('c', 'c', 6)] }] })).toBe(63);
|
||||
});
|
||||
it('la suma de lo seleccionado es nula sin selección o con una celda desconocida', () => {
|
||||
expect(sumaActivas(citologia())).toBeNull(); expect(sumaActivas(citologia(['ASC-US', 'CIS']))).toBe(15);
|
||||
expect(sumaActivas({ ...plano([fila('a', 'a', null, 'Suprimido'), fila('b', 'b', 2)], 2), activas: new Set(['a', 'b']) })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Barras horizontales: componente', () => {
|
||||
beforeEach(() => TestBed.configureTestingModule({}));
|
||||
function montar(conjunto: ConjuntoBarras) {
|
||||
const f = TestBed.createComponent(BarrasHorizontales);
|
||||
f.componentRef.setInput('conjunto', conjunto); f.componentRef.setInput('titulo', 'Resultados'); f.detectChanges();
|
||||
return f.nativeElement as HTMLElement;
|
||||
}
|
||||
const texto = (e: Element | null) => (e?.textContent ?? '').replace(/\s+/g, ' ').trim();
|
||||
const filas = (r: HTMLElement) => [...r.querySelectorAll('.filas .fila')];
|
||||
|
||||
it('denominador y unidad, escala absoluta rotulada y sin barra de longitud artificial', () => {
|
||||
const r = montar(citologia());
|
||||
expect(texto(r.querySelector('.den'))).toContain('Total: 944 pacientes con resultado'); expect(texto(r.querySelector('.titulo-eje'))).toBe('Escala: cantidad de pacientes con resultado (de 0 a 1,000)');
|
||||
expect([...r.querySelectorAll('.marcas span')].map(x => x.textContent)).toEqual(['0', '500', '1,000']);
|
||||
const ancho = (etiqueta: string) => (filas(r).find(x => texto(x).startsWith(etiqueta))!.querySelector('.pista i') as HTMLElement).style.width;
|
||||
expect(ancho('Normal')).toBe('91.2%'); expect(ancho('ASC-US')).toBe('1.4%'); expect(ancho('Carcinoma in situ')).toBe('0.1%');
|
||||
// The count and the percentage are always written, whatever the bar length.
|
||||
expect(filas(r).map(x => texto(x))).toEqual(['Normal 912 96.6 %', 'ASC-US 14 1.5 %', 'LIEBG 9 1.0 %', 'ASC-H 3 0.3 %', 'LIEAG 5 0.5 %', 'Carcinoma in situ 1 0.1 %']);
|
||||
});
|
||||
it('un valor demasiado corto para verse lleva un marcador hueco en su posición, sin alargar la barra', () => {
|
||||
const r = montar(citologia());
|
||||
const ci = filas(r).find(x => texto(x).startsWith('Carcinoma'))!;
|
||||
expect((ci.querySelector('.minima') as HTMLElement).style.left).toBe('0.1%');
|
||||
expect(filas(r).find(x => texto(x).startsWith('Normal'))!.querySelector('.minima')).toBeNull();
|
||||
expect(filas(r).find(x => texto(x).startsWith('ASC-US'))!.querySelector('.minima')).not.toBeNull();
|
||||
});
|
||||
it('los grupos son encabezados con su subtotal y no cuentan como categorías de la distribución', () => {
|
||||
const r = montar(citologia());
|
||||
const grupos = [...r.querySelectorAll('.grupo')];
|
||||
expect(grupos.map(g => g.getAttribute('aria-label'))).toEqual(['Sin anomalía', 'Anormal']);
|
||||
expect(grupos.map(g => texto(g.querySelector('.cabecera')))).toEqual(['Grupo Sin anomalía 912 96.6 %', 'Grupo Anormal 32 3.4 %']);
|
||||
expect(filas(r)).toHaveLength(6); expect(r.querySelectorAll('.cabecera')).toHaveLength(2);
|
||||
// The subtotals add up to the total once, never together with their categories.
|
||||
expect(912 + 32).toBe(944);
|
||||
});
|
||||
it('un cero publicado tiene marca punteada y ninguna barra; lo no disponible se rotula y no es cero', () => {
|
||||
const r = montar(plano([fila('a', 'Negativo', 5), fila('b', 'Positivo 16 y 18', 0), fila('c', 'Indeterminado', null, 'No disponible'), fila('d', 'Otro', null, 'Suprimido')], 5));
|
||||
const [a, b, c, d] = filas(r);
|
||||
expect(b.querySelector('.pista i')).toBeNull(); expect(b.querySelector('.cero-marca')).not.toBeNull(); expect(texto(b)).toBe('Positivo 16 y 18 0 0.0 %');
|
||||
expect(c.classList.contains('nd')).toBe(true); expect(c.querySelector('.pista i')).toBeNull(); expect(texto(c)).toBe('Indeterminado No disponible'); expect(texto(d)).toBe('Otro Suprimido');
|
||||
expect(a.querySelector('.cero-marca')).toBeNull(); expect(c.querySelector('.cero-marca')).toBeNull();
|
||||
});
|
||||
it('sin denominador se muestran las cantidades y se dice que el porcentaje no está disponible', () => {
|
||||
const r = montar(plano([fila('a', 'Negativo', 5)], null));
|
||||
expect(texto(r.querySelector('.den'))).toContain('no disponible'); expect(texto(filas(r)[0])).toBe('Negativo 5 % no disponible');
|
||||
});
|
||||
it('la selección atenúa lo no seleccionado y dice cuánto suma; sin selección nada se atenúa', () => {
|
||||
const r = montar(citologia(['ASC-US', 'CIS']));
|
||||
expect(filas(r).filter(x => x.classList.contains('atenuada')).map(x => texto(x).split(' ')[0])).toEqual(['Normal', 'LIEBG', 'ASC-H', 'LIEAG']);
|
||||
expect(r.querySelectorAll('.cabecera.atenuada')).toHaveLength(1); expect(texto(r.querySelector('.seleccion'))).toBe('Selección: 15 de 944 (1.6 %)');
|
||||
const s = montar(citologia()); expect(s.querySelectorAll('.atenuada')).toHaveLength(0); expect(s.querySelector('.seleccion')).toBeNull();
|
||||
});
|
||||
it('accesibilidad: el nombre del conjunto, barras decorativas y cada dato leído una sola vez', () => {
|
||||
const r = montar(citologia());
|
||||
expect(r.querySelector('[role=group]')!.getAttribute('aria-label')).toBe('Resultados');
|
||||
expect([...r.querySelectorAll('.pista, .eje')].every(e => e.getAttribute('aria-hidden') === 'true')).toBe(true);
|
||||
expect(r.querySelectorAll('[role=img]')).toHaveLength(0); expect(r.querySelectorAll('[aria-label]:not(.barras):not(.grupo)')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { NgTemplateOutlet } from '@angular/common';
|
||||
import { shareText } from './indicadores-format';
|
||||
import { ConjuntoBarras, FilaBarra, GrupoBarras, limiteEscala, maximoDelConjunto, sumaActivas } from './indicadores-barras';
|
||||
|
||||
/**
|
||||
* Horizontal bars of one indicator: a bar per category with its name at the left and «count · % of the total» at the
|
||||
* right, clinical groups as headers with their subtotal. The scale is the absolute count, from 0 to a rounded upper
|
||||
* limit that is written under the bars; the bar of a value is exactly its share of that limit (no minimum length).
|
||||
* A value too short to see keeps its figure and gets a hollow marker at its position; a published zero has a dotted
|
||||
* tick and no bar; an unavailable value has a hatched track and says so.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-barras-horizontales',
|
||||
imports: [NgTemplateOutlet],
|
||||
template: `
|
||||
@let c = conjunto();
|
||||
<div class="barras" role="group" [attr.aria-label]="titulo()">
|
||||
<p class="den">@if (c.den !== null) { Total: <strong>{{ c.den.toLocaleString('es-MX') }}</strong> {{ c.unidad }}. Barras en cantidades; porcentaje del total. } @else { Total de {{ c.unidad }} no disponible: se muestran las cantidades publicadas, sin porcentaje. }</p>
|
||||
@if (seleccionado(); as s) { <p class="seleccion" role="status">Selección: <strong>{{ s.toLocaleString('es-MX') }}</strong>@if (c.den !== null) { de {{ c.den.toLocaleString('es-MX') }} ({{ pct(s) }}) } </p> }
|
||||
@for (g of c.grupos; track g.id ?? $index) {
|
||||
@if (g.etiqueta) {
|
||||
<div class="grupo" role="group" [attr.aria-label]="g.etiqueta" [style.--c]="g.color">
|
||||
<div class="fila cabecera" [class.atenuada]="atenuado(g)">
|
||||
<span class="et"><span class="marca-grupo">Grupo</span> {{ g.etiqueta }}</span>{{ ' ' }}
|
||||
{{ ' ' }}<span class="pista" aria-hidden="true">@if (g.subtotal !== null && g.subtotal > 0) { <i [style.width.%]="ancho(g.subtotal)"></i> }</span>
|
||||
<span class="v">@if (g.subtotal !== null) { <strong>{{ g.subtotal.toLocaleString('es-MX') }}</strong>{{ ' ' }}@if (c.den !== null) { <small>{{ pct(g.subtotal) }}</small> } } @else { <strong>No disponible</strong> }</span>
|
||||
</div>
|
||||
<ul class="filas hijas">@for (f of g.filas; track f.id) { <ng-container [ngTemplateOutlet]="fila" [ngTemplateOutletContext]="{ f: f }" /> }</ul>
|
||||
</div>
|
||||
} @else {
|
||||
<ul class="filas">@for (f of g.filas; track f.id) { <ng-container [ngTemplateOutlet]="fila" [ngTemplateOutletContext]="{ f: f }" /> }</ul>
|
||||
}
|
||||
}
|
||||
<div class="eje" aria-hidden="true"><span></span><div class="marcas"><span>0</span><span>{{ (limite() / 2).toLocaleString('es-MX') }}</span><span>{{ limite().toLocaleString('es-MX') }}</span></div><span></span></div>
|
||||
<p class="titulo-eje">Escala: cantidad de {{ c.unidad }} (de 0 a {{ limite().toLocaleString('es-MX') }})</p>
|
||||
</div>
|
||||
<ng-template #fila let-f="f">
|
||||
<li class="fila" [class.atenuada]="atenuado(f)" [class.nd]="f.n === null" [class.cero]="f.n === 0" [style.--c]="f.color">
|
||||
<span class="et">{{ f.etiqueta }}</span>{{ ' ' }}
|
||||
<span class="pista" aria-hidden="true">
|
||||
@if (f.n !== null && f.n > 0) { <i [style.width.%]="ancho(f.n)"></i> @if (ancho(f.n) < 2) { <b class="minima" [style.left.%]="ancho(f.n)"></b> } }
|
||||
@if (f.n === 0) { <u class="cero-marca"></u> }
|
||||
</span>
|
||||
<span class="v">@if (f.n === null) { <strong>{{ f.estado === 'Suprimido' ? 'Suprimido' : 'No disponible' }}</strong> }
|
||||
@else { <strong>{{ f.n.toLocaleString('es-MX') }}</strong>{{ ' ' }}@if (c.den !== null) { <small>{{ pct(f.n) }}</small> } @else { <small>% no disponible</small> } }</span>
|
||||
</li>
|
||||
</ng-template>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; container-type: inline-size; }
|
||||
.den, .seleccion, .titulo-eje { margin: 0 0 .4rem; font-size: .85rem; color: var(--issste-text-secondary); }
|
||||
.den strong, .seleccion strong { color: var(--issste-text); }
|
||||
.titulo-eje { margin: .15rem 0 0; font-size: .75rem; }
|
||||
ul { margin: 0; padding: 0; list-style: none; }
|
||||
.filas { display: grid; gap: .3rem; }
|
||||
.fila { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; align-items: center; gap: .5rem; transition: opacity .15s; }
|
||||
.fila.atenuada { opacity: .45; }
|
||||
.et { font-size: .85rem; line-height: 1.2; overflow-wrap: anywhere; }
|
||||
.pista { position: relative; height: 1rem; background: linear-gradient(90deg, var(--issste-border) 1px, transparent 1px) 0 0 / 50% 100% repeat-x, linear-gradient(270deg, var(--issste-border) 1px, transparent 1px); }
|
||||
.pista i { position: absolute; inset: 0 auto 0 0; background: var(--c); border-radius: 0 2px 2px 0; }
|
||||
.minima { position: absolute; top: 50%; width: .5rem; height: .5rem; box-sizing: border-box; border: 2px solid var(--c); border-radius: 50%; background: var(--issste-surface); transform: translate(-50%, -50%); }
|
||||
.cero-marca { position: absolute; inset: .15rem auto .15rem 0; border-left: 2px dotted var(--c); }
|
||||
.nd .pista { background: repeating-linear-gradient(45deg, var(--issste-border) 0 4px, var(--issste-surface) 4px 8px); }
|
||||
.v { text-align: end; font-variant-numeric: tabular-nums; font-size: .85rem; white-space: nowrap; }
|
||||
.v small { margin-inline-start: .3rem; color: var(--issste-text-secondary); font-size: .8rem; }
|
||||
.grupo { margin-top: .5rem; }
|
||||
.cabecera { font-weight: 600; }
|
||||
.cabecera .pista { height: .4rem; background: var(--issste-border); }
|
||||
.cabecera .pista i { opacity: .45; border-radius: 0; }
|
||||
.marca-grupo { display: inline-block; margin-inline-end: .25rem; padding: 0 .3rem; border: 1px solid currentColor; border-radius: 3px; font-size: .65rem; font-weight: 500; color: var(--issste-text-secondary); text-transform: uppercase; }
|
||||
.hijas { margin: .25rem 0 0; padding-inline-start: .75rem; border-inline-start: 3px solid var(--c); }
|
||||
.eje { display: grid; grid-template-columns: minmax(0, min(17rem, 35%)) minmax(0, 1fr) 7.6rem; gap: .5rem; margin-top: .25rem; font-size: .7rem; color: var(--issste-text-secondary); }
|
||||
.marcas { display: flex; justify-content: space-between; }
|
||||
@container (max-width: 25rem) {
|
||||
.fila, .eje { grid-template-columns: minmax(0, 1fr) auto; row-gap: .1rem; }
|
||||
.fila .pista { grid-column: 1 / -1; grid-row: 2; }
|
||||
.eje > span:first-child, .eje > span:last-child { display: none; }
|
||||
.eje { grid-template-columns: 1fr; }
|
||||
.hijas { padding-inline-start: .5rem; }
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class BarrasHorizontales {
|
||||
readonly conjunto = input.required<ConjuntoBarras>();
|
||||
/** Accessible name of the whole chart. */
|
||||
readonly titulo = input.required<string>();
|
||||
readonly limite = computed(() => limiteEscala(maximoDelConjunto(this.conjunto())));
|
||||
readonly seleccionado = computed(() => sumaActivas(this.conjunto()));
|
||||
ancho(n: number) { return 100 * n / this.limite(); }
|
||||
pct(n: number) { const d = this.conjunto().den; return d ? shareText(n, d) : ''; }
|
||||
/** With a selection, what is not selected is dimmed, as the donut did. */
|
||||
atenuado(x: FilaBarra | GrupoBarras) {
|
||||
const a = this.conjunto().activas;
|
||||
if (!a) return false;
|
||||
return 'filas' in x ? !x.filas.some(f => a.has(f.id)) : !a.has(x.id);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,43 @@
|
||||
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; }
|
||||
import { RutaResumen } from './ruta-tamizaje/ruta-tamizaje';
|
||||
export type ProbabilidadClave = 'lieag' | 'cancer' | 'supervivencia';
|
||||
export type OrdenSeguimiento = 'reciente' | ProbabilidadClave;
|
||||
export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; orden?: OrdenSeguimiento; horizonte?: number; grupo_edad?: string; mchat?: string; css?: string; estado_caso?: string; alteracion?: string;
|
||||
/** CaCu: partial identifier search, applied by the server before it counts and paginates. */
|
||||
q?: string;
|
||||
/** CaCu: asks for the screening route block of each row. */
|
||||
incluir?: 'ruta_tamizaje';
|
||||
/** CaCu: inclusive age range at the cut-off date, applied by the server. */
|
||||
edad_min?: number; edad_max?: number;
|
||||
page: number; page_size: number; }
|
||||
export interface SeguimientoStatus { codigo: string; etiqueta: string; }
|
||||
// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`.
|
||||
export interface SeguimientoPaciente {
|
||||
pac_id?: string;
|
||||
id_seudonimo?: string;
|
||||
grupo_edad: string;
|
||||
/** CaCu: her age in whole years at the cut-off date (`edad_al_corte`), when the service gives it. */
|
||||
edad_al_corte?: number | null;
|
||||
estatus: SeguimientoStatus;
|
||||
ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null;
|
||||
ultimo_vph: { fecha: string; resultado: string; genotipo_16_18: boolean | null } | null;
|
||||
dias_toma_diagnostico: number | null;
|
||||
/** CaCu: her latest biopsy reported by the cut-off, with its grade. */
|
||||
ultima_biopsia?: { fecha: string; grado: string | null } | null;
|
||||
/** CaCu: her current probability of LIEAG+, of cancer and (a case's) of surviving at each horizon, from the confirmed batches. */
|
||||
probabilidades?: Partial<Record<ProbabilidadClave, ProbabilidadHorizonte[]>> | null;
|
||||
prioridad: SeguimientoStatus | null;
|
||||
/** CaCu: present only when the list was asked `incluir=ruta_tamizaje`; null when the row has no selected cytology. */
|
||||
ruta_tamizaje?: RutaResumen | null;
|
||||
}
|
||||
export interface ProbabilidadHorizonte { horizonte_anios: number; probabilidad: number; ic_bajo: number | null; ic_alto: number | null; }
|
||||
export interface SeguimientoResponse {
|
||||
simulado: boolean;
|
||||
corte: string;
|
||||
ventana: { meses: 1 | 3 | 6 | 12; desde: string; hasta: string };
|
||||
filtros: { estatus: string | null };
|
||||
/** `q`, `edad_min` and `edad_max` are the parameters the server applied (null: none); older servers omit them. */
|
||||
filtros: { estatus: string | null; orden?: OrdenSeguimiento; horizonte?: number; q?: string | null; edad_min?: number | null; edad_max?: number | null };
|
||||
/** The horizons the models give, in years, for ordering and showing the probabilities. */
|
||||
horizontes_disponibles?: number[];
|
||||
estatus_disponibles: SeguimientoStatus[];
|
||||
reglas: { clave: string; valor: unknown; estado: 'provisional' | 'confirmado' }[];
|
||||
paginacion: { page: number; page_size: number; total_items: number; total_pages: number };
|
||||
@@ -26,6 +48,50 @@ export function isoDate(value: unknown): value is string {
|
||||
const date = new Date(value + 'T00:00:00Z');
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
|
||||
}
|
||||
/** Her exact age in whole years; null when the service does not give one. It is never derived from the age group. */
|
||||
export function edadAnios(item: Pick<SeguimientoPaciente, 'edad_al_corte'>): number | null {
|
||||
const edad = item.edad_al_corte;
|
||||
return typeof edad === 'number' && Number.isInteger(edad) && edad >= 0 ? edad : null;
|
||||
}
|
||||
export function edadTexto(item: Pick<SeguimientoPaciente, 'edad_al_corte'>): string {
|
||||
const edad = edadAnios(item);
|
||||
return edad === null ? 'No disponible' : `${edad} ${edad === 1 ? 'año' : 'años'}`;
|
||||
}
|
||||
/** The search text as sent: trimmed, inner whitespace collapsed; empty means no search. */
|
||||
export function normalizarConsulta(texto: string | undefined): string { return (texto ?? '').trim().replace(/\s+/g, ' '); }
|
||||
/** The search text WebApi admits, in characters, once normalized. */
|
||||
export const CONSULTA_MAXIMA = 100;
|
||||
/** A bound is a whole number of years, 0 or more (as WebApi admits); the range needs min <= max. */
|
||||
export function rangoEdadValido(min: number | undefined, max: number | undefined): boolean {
|
||||
const entero = (n: number | undefined) => n === undefined || (Number.isInteger(n) && n >= 0);
|
||||
return entero(min) && entero(max) && (min === undefined || max === undefined || min <= max);
|
||||
}
|
||||
/** True when a returned row breaks the query it answers: the server did not apply the search or the age range. */
|
||||
export function incumpleConsulta(q: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'>, id: string, item: Pick<SeguimientoPaciente, 'edad_al_corte'>): boolean {
|
||||
const texto = normalizarConsulta(q.q).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase();
|
||||
if (texto && !id.normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().includes(texto)) return true;
|
||||
const edad = edadAnios(item);
|
||||
// Under an age range a row with no age is outside the contract: WebApi leaves those out.
|
||||
if (q.edad_min === undefined && q.edad_max === undefined) return false;
|
||||
return edad === null || (q.edad_min !== undefined && edad < q.edad_min) || (q.edad_max !== undefined && edad > q.edad_max);
|
||||
}
|
||||
/** The search and age range the server says it applied, against the ones asked: every active parameter must come back equal. */
|
||||
export function filtrosConfirmados(q: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'>, filtros: SeguimientoResponse['filtros']): boolean {
|
||||
const texto = normalizarConsulta(q.q);
|
||||
return (!texto || filtros.q === texto) && (q.edad_min === undefined || filtros.edad_min === q.edad_min) && (q.edad_max === undefined || filtros.edad_max === q.edad_max);
|
||||
}
|
||||
export function latestStudy(item: SeguimientoPaciente): string | null {
|
||||
return [item.ultima_citologia?.fecha, item.ultimo_vph?.fecha].filter(isoDate).sort().at(-1) ?? null;
|
||||
}
|
||||
/** Her probability of `clave` at `horizonte`, or `undefined` when no model gives it. */
|
||||
export function probabilidadAl(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number): ProbabilidadHorizonte | undefined {
|
||||
return item.probabilidades?.[clave]?.find(h => h.horizonte_anios === horizonte);
|
||||
}
|
||||
/** CaCu: the probability columns a follow-up status shows, the ones its scenario's models give (a case: survival).
|
||||
* Every patient or an unknown status shows none: each scenario has its own models. */
|
||||
export const COLUMNAS_DE_PROBABILIDAD: Readonly<Record<string, readonly ProbabilidadClave[]>> = {
|
||||
CASO: ['supervivencia'], PRE_COLPOSCOPIA: ['lieag', 'cancer'], POST_COLPOSCOPIA: ['lieag'], POST_TRATAMIENTO: ['lieag'],
|
||||
};
|
||||
export const ETIQUETA_PROBABILIDAD: Readonly<Record<ProbabilidadClave, string>> = {
|
||||
lieag: 'Probabilidad a LIEAG+', cancer: 'Probabilidad a cáncer', supervivencia: 'Probabilidad de supervivencia',
|
||||
};
|
||||
|
||||
@@ -1,42 +1,70 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { CONSULTA_MAXIMA, isoDate, normalizarConsulta, rangoEdadValido, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||
import { RutaDetalle, rutaDetalleValida, rutaResumenValida, urlDetalleValida } from './ruta-tamizaje/ruta-tamizaje';
|
||||
import { PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string';
|
||||
const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const ORDENES = ['reciente', 'lieag', 'cancer', 'supervivencia'];
|
||||
// The exact age is optional: an API that does not give it still validates, and the table says so.
|
||||
const edad = (v: unknown) => v === undefined || v === null || typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && v <= 130;
|
||||
const anios = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
|
||||
const prob = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
|
||||
// CaCu's biopsy and probabilities are optional: an API that doesn't give them still validates.
|
||||
const biopsia = (b: unknown) => b === undefined || b === null || record(b) && isoDate(b['fecha']) && (b['grado'] === null || typeof b['grado'] === 'string');
|
||||
const probabilidades = (p: unknown) => p === undefined || p === null || record(p) && Object.entries(p).every(([k, hs]) =>
|
||||
['lieag', 'cancer', 'supervivencia'].includes(k) && Array.isArray(hs) && hs.every(h => record(h) && anios(h['horizonte_anios']) && prob(h['probabilidad'])
|
||||
&& (h['ic_bajo'] === null || prob(h['ic_bajo'])) && (h['ic_alto'] === null || prob(h['ic_alto']))));
|
||||
export function validSeguimientoQuery(q: SeguimientoQuery) {
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX;
|
||||
return (!q.corte || isoDate(q.corte)) && [1,3,6,12].includes(q.meses) && integer(q.page, 1) && integer(q.page_size, 1) && q.page_size <= PAGE_SIZE_MAX
|
||||
&& rangoEdadValido(q.edad_min, q.edad_max) && normalizarConsulta(q.q).length <= CONSULTA_MAXIMA;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
// before passing any item to the component; real-patient activation is separate.
|
||||
if (!record(v) || v['simulado'] !== true) throw new Error('Esta vista solo admite datos de demostración.');
|
||||
if (!record(v) || typeof v['simulado'] !== 'boolean') throw new Error('Respuesta de seguimiento inválida');
|
||||
const p = v['paginacion'], window = v['ventana'], filters = v['filtros'];
|
||||
if (!isoDate(v['corte']) || !record(window) || ![1,3,6,12].includes(window['meses'] as number) || !isoDate(window['desde']) || !isoDate(window['hasta'])
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| (filters['q'] !== undefined && filters['q'] !== null && typeof filters['q'] !== 'string')
|
||||
|| !edad(filters['edad_min']) || !edad(filters['edad_max'])
|
||||
|| (filters['orden'] !== undefined && !ORDENES.includes(filters['orden'] as string))
|
||||
|| (v['horizontes_disponibles'] !== undefined && !(Array.isArray(v['horizontes_disponibles']) && v['horizontes_disponibles'].every(anios)))
|
||||
|| !Array.isArray(v['estatus_disponibles']) || !v['estatus_disponibles'].every(status)
|
||||
|| !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string))
|
||||
|| !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > PAGE_SIZE_MAX || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => {
|
||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false;
|
||||
if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !edad(item['edad_al_corte']) || !status(item['estatus'])) return false;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string'))
|
||||
&& (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean'))
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']));
|
||||
&& (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad']))
|
||||
&& biopsia(item['ultima_biopsia']) && probabilidades(item['probabilidades'])
|
||||
&& (item['ruta_tamizaje'] === undefined || item['ruta_tamizaje'] === null || rutaResumenValida(item['ruta_tamizaje']));
|
||||
}) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida');
|
||||
return v as unknown as SeguimientoResponse;
|
||||
}
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class CacuSeguimientoService {
|
||||
private readonly http = inject(HttpClient);
|
||||
/** The detail of one route, from the `detalle_url` of the list; only a path of this service's own routes is requested. */
|
||||
detalleRuta(url: string) {
|
||||
if (!urlDetalleValida(url)) throw new Error('Ruta de detalle inválida');
|
||||
return this.http.get<unknown>(url).pipe(map((v): RutaDetalle => { if (!rutaDetalleValida(v)) throw new Error('Detalle de ruta inválido'); return v; }));
|
||||
}
|
||||
consultar(query: SeguimientoQuery) {
|
||||
if (!validSeguimientoQuery(query)) 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);
|
||||
if (query.estatus) params = params.set('estatus', query.estatus);
|
||||
if (query.orden && query.orden !== 'reciente') params = params.set('orden', query.orden);
|
||||
if (query.horizonte !== undefined) params = params.set('horizonte', query.horizonte);
|
||||
const q = normalizarConsulta(query.q);
|
||||
if (q) params = params.set('q', q);
|
||||
if (query.edad_min !== undefined) params = params.set('edad_min', query.edad_min);
|
||||
if (query.edad_max !== undefined) params = params.set('edad_max', query.edad_max);
|
||||
if (query.incluir) params = params.set('incluir', query.incluir);
|
||||
return this.http.get<unknown>('/cacu/seguimiento', { params }).pipe(map(seguimientoResponse));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import fixtureData from './fixtures/cacu_seguimiento.json';
|
||||
import { CacuSeguimientoService, seguimientoResponse } from './cacu-seguimiento.service';
|
||||
import { latestStudy } from './cacu-seguimiento.models';
|
||||
import { tablaExportacionCaCu } from './export/cacu-tracking-export';
|
||||
import { IndicadoresTracking } from './indicadores-tracking';
|
||||
|
||||
describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
@@ -24,10 +25,10 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(Array.from(fixture.nativeElement.querySelectorAll('tbody tr td:first-child')).map(e => (e as HTMLElement).textContent)).toEqual(order);
|
||||
fixture.componentInstance.apply();
|
||||
let req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']);
|
||||
req.flush(fixtureData); fixture.detectChanges();
|
||||
fixture.componentInstance.navigate(2); req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'meses', 'page', 'page_size']);
|
||||
expect(req.request.params.keys().sort()).toEqual(['corte', 'incluir', 'meses', 'page', 'page_size']);
|
||||
expect(req.request.params.get('page')).toBe('2');
|
||||
req.flush({ ...fixtureData, paginacion: { ...fixtureData.paginacion, page: 2 } });
|
||||
});
|
||||
@@ -42,7 +43,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: 'SATISFACTORIO' })).toBe('Sin resultado al corte');
|
||||
expect(fixture.componentInstance.cytologyLabel({ bethesda: null, calidad: null })).toBe('Sin resultado al corte');
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(8);
|
||||
expect(root.querySelectorAll('tbody tr')).toHaveLength(10); expect(root.querySelectorAll('thead th')).toHaveLength(9);
|
||||
expect(root.querySelector('form input[name="corte"]')).not.toBeNull();
|
||||
expect(root.querySelector('form select[name="meses"]')).not.toBeNull();
|
||||
expect(root.querySelector('nav[aria-label="Paginación de seguimiento"]')).not.toBeNull();
|
||||
@@ -78,6 +79,243 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
fixture.componentRef.setInput('active',false); fixture.detectChanges(); fixture.componentRef.setInput('active',true); fixture.detectChanges(); http.expectNone(()=>true);
|
||||
expect(fixture.componentInstance.data?.paginacion.page).toBe(2);
|
||||
});
|
||||
// API-01: the search and the age range are the server's; WebApp sends them, shows what comes back and nothing else.
|
||||
describe('búsqueda global y rango de edad', () => {
|
||||
const consultas = () => http.match(r => r.url === '/cacu/seguimiento');
|
||||
const escribir = (texto: string) => {
|
||||
const input = fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement;
|
||||
input.value = texto; input.dispatchEvent(new Event('input', { bubbles: true })); fixture.detectChanges();
|
||||
};
|
||||
const filas = () => [...fixture.nativeElement.querySelectorAll('tr[data-paciente]')].map((tr: Element) => tr.getAttribute('data-paciente'));
|
||||
const respuesta = (ids: string[], extra: object = {}) => ({ ...fixtureData, ...extra,
|
||||
items: ids.map((id, i) => ({ ...fixtureData.items[i], id_seudonimo: id, edad_al_corte: 45 })), paginacion: { ...fixtureData.paginacion, total_items: ids.length, total_pages: 1, ...((extra as { paginacion?: object }).paginacion ?? {}) } });
|
||||
// The server echoes the parameters it applied in `filtros`, as WebApi does.
|
||||
const eco = (req: { request: { params: { get(k: string): string | null } } }) => { const n = (k: string) => req.request.params.get(k) === null ? null : Number(req.request.params.get(k)); return { q: req.request.params.get('q'), edad_min: n('edad_min'), edad_max: n('edad_max') }; };
|
||||
const responder = (req: { request: { params: { get(k: string): string | null } }; flush(b: unknown): void }, ids: string[], extra: Record<string, unknown> = {}) =>
|
||||
req.flush(respuesta(ids, { ...extra, filtros: { ...((extra['filtros'] as object) ?? fixtureData.filtros), ...eco(req) } }));
|
||||
beforeEach(() => { vi.useFakeTimers(); });
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
it('espera tras la última tecla, pide la página 1 con q normalizada y muestra solo lo que devuelve el servidor', () => {
|
||||
respond();
|
||||
escribir('a'); escribir(' a4 2 ');
|
||||
vi.advanceTimersByTime(399); expect(consultas()).toHaveLength(0);
|
||||
vi.advanceTimersByTime(2);
|
||||
const [req] = consultas(); expect(consultas()).toHaveLength(0);
|
||||
expect(req.request.params.get('q')).toBe('a4 2'); expect(req.request.params.get('page')).toBe('1');
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.textContent).toContain('Cargando seguimiento');
|
||||
responder(req, ['PRUEBA-A4 2', 'PRUEBA-A4 25']); fixture.detectChanges();
|
||||
expect(filas()).toEqual(['PRUEBA-A4 2', 'PRUEBA-A4 25']);
|
||||
expect(fixture.nativeElement.querySelector('#alcance-busqueda-cacu').textContent).toContain('2 registros coinciden');
|
||||
// The input keeps its text and focus target while the list reloads.
|
||||
expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe(' a4 2 ');
|
||||
});
|
||||
it('conserva la búsqueda al paginar, reinicia a la página 1 al cambiarla y se puede limpiar', () => {
|
||||
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 120, total_pages: 3 } }); fixture.detectChanges();
|
||||
fixture.componentInstance.navigate(2);
|
||||
let [req] = consultas(); expect(req.request.params.get('q')).toBe('P'); expect(req.request.params.get('page')).toBe('2');
|
||||
responder(req, ['P-2'], { paginacion: { page: 2, total_items: 120, total_pages: 3 } }); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('nav').textContent).toContain('120 registros');
|
||||
escribir('PR'); vi.advanceTimersByTime(401);
|
||||
[req] = consultas(); expect(req.request.params.get('page')).toBe('1'); expect(req.request.params.get('q')).toBe('PR');
|
||||
responder(req, ['PR-1']); fixture.detectChanges();
|
||||
([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click();
|
||||
[req] = consultas(); expect(req.request.params.has('q')).toBe(false); expect(req.request.params.get('page')).toBe('1');
|
||||
responder(req, ['X-1']); fixture.detectChanges();
|
||||
expect((fixture.nativeElement.querySelector('input[type="search"]') as HTMLInputElement).value).toBe('');
|
||||
});
|
||||
// Why: a slow answer to an old search must never replace the answer to the current one.
|
||||
it('una respuesta obsoleta se cancela y no sustituye a la vigente', () => {
|
||||
respond(); escribir('ab'); vi.advanceTimersByTime(401);
|
||||
const [vieja] = consultas();
|
||||
escribir('abc'); vi.advanceTimersByTime(401);
|
||||
const [nueva] = consultas();
|
||||
expect(vieja.cancelled).toBe(true);
|
||||
responder(nueva, ['ABC-1']); fixture.detectChanges();
|
||||
expect(filas()).toEqual(['ABC-1']);
|
||||
});
|
||||
it('sin coincidencias lo dice y no cae en la lista local', () => {
|
||||
respond(); escribir('zzz'); vi.advanceTimersByTime(401);
|
||||
const [vacia] = consultas(); vacia.flush({ ...respuesta([]), filtros: { ...fixtureData.filtros, ...eco(vacia) }, paginacion: { ...fixtureData.paginacion, total_items: 0, total_pages: 0 } }); fixture.detectChanges();
|
||||
expect(filas()).toEqual([]); expect(fixture.nativeElement.textContent).toContain('No hay coincidencias para la búsqueda y el rango de edad.');
|
||||
});
|
||||
it('el rango de edad se envía con uno o ambos límites, se limpia y no pide nada si es inválido', () => {
|
||||
respond();
|
||||
const c = fixture.componentInstance;
|
||||
c.draft.edad_min = 40; c.apply();
|
||||
let [req] = consultas(); expect(req.request.params.get('edad_min')).toBe('40'); expect(req.request.params.has('edad_max')).toBe(false);
|
||||
responder(req, ['E-1']); fixture.detectChanges();
|
||||
c.draft.edad_max = 49; c.apply();
|
||||
[req] = consultas(); expect([req.request.params.get('edad_min'), req.request.params.get('edad_max')]).toEqual(['40', '49']);
|
||||
responder(req, ['E-2']); fixture.detectChanges();
|
||||
c.draft.edad_min = 60; c.apply(); fixture.detectChanges();
|
||||
expect(consultas()).toHaveLength(0); expect(fixture.nativeElement.querySelector('#error-edad').textContent).toContain('desde 0');
|
||||
for (const malo of [-1, 40.5]) { c.draft.edad_min = malo; c.draft.edad_max = undefined; c.apply(); expect(consultas()).toHaveLength(0); }
|
||||
c.limpiarRangoEdad();
|
||||
[req] = consultas(); expect(req.request.params.has('edad_min') || req.request.params.has('edad_max')).toBe(false);
|
||||
responder(req, ['E-3']); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#error-edad')).toBeNull();
|
||||
});
|
||||
it('el rango de edad se combina con la búsqueda y con los filtros existentes sin cambiar el orden ni el horizonte', () => {
|
||||
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||
responder(consultas()[0], ['P-1'], { filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 }, horizontes_disponibles: [1, 3, 5] }); fixture.detectChanges();
|
||||
const c = fixture.componentInstance; c.draft.edad_max = 50; c.apply();
|
||||
const [req] = consultas();
|
||||
expect(['q', 'edad_max', 'estatus', 'orden', 'horizonte', 'page'].map(k => req.request.params.get(k))).toEqual(['P', '50', 'PRE_COLPOSCOPIA', 'lieag', '3', '1']);
|
||||
});
|
||||
// Why: an older server ignores the new parameters; a partial local result must not pass as a global search.
|
||||
it('si el servidor no aplica la búsqueda o la edad, no presenta resultados parciales', () => {
|
||||
respond(); escribir('a42'); vi.advanceTimersByTime(401);
|
||||
consultas()[0].flush(respuesta(['OTRO-1', 'A42-2'])); fixture.detectChanges();
|
||||
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó la búsqueda');
|
||||
([...fixture.nativeElement.querySelectorAll('button')] as HTMLButtonElement[]).find(b => b.textContent === 'Limpiar búsqueda')!.click();
|
||||
responder(consultas()[0], ['OTRO-1']); fixture.detectChanges();
|
||||
const c = fixture.componentInstance; c.draft.edad_min = 40; c.apply();
|
||||
responder(consultas()[0], ['OTRO-1'], {}); fixture.detectChanges();
|
||||
expect(filas()).toEqual(['OTRO-1']);
|
||||
c.draft.edad_min = 40; c.apply();
|
||||
const conEdad = respuesta(['E-1']); (conEdad.items[0] as { edad_al_corte?: number }).edad_al_corte = 30;
|
||||
{ const [r] = consultas(); r.flush({ ...conEdad, filtros: { ...conEdad.filtros, ...eco(r) } }); } fixture.detectChanges();
|
||||
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó');
|
||||
// A row without age under an age range is outside the contract too.
|
||||
c.draft.edad_min = 40; c.apply(); const sinEdad = respuesta(['E-2']); (sinEdad.items[0] as { edad_al_corte?: number | null }).edad_al_corte = null;
|
||||
{ const [r] = consultas(); r.flush({ ...sinEdad, filtros: { ...sinEdad.filtros, ...eco(r) } }); } fixture.detectChanges();
|
||||
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('no confirmó');
|
||||
});
|
||||
// Why: WebApi answers 400 over 100 characters; WebApp does not send it, and a backend 400 shows its message and no rows.
|
||||
it('q admite 100 caracteres: más no se envía; un 400 del servidor se anuncia sin filas', () => {
|
||||
respond(); escribir('1'.repeat(101)); vi.advanceTimersByTime(401);
|
||||
expect(consultas()).toHaveLength(0); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('hasta 100 caracteres');
|
||||
escribir('1'.repeat(100)); vi.advanceTimersByTime(401);
|
||||
const [req] = consultas(); expect(req.request.params.get('q')).toHaveLength(100);
|
||||
req.flush({ error: 'x' }, { status: 400, statusText: 'Bad Request' }); fixture.detectChanges();
|
||||
expect(filas()).toEqual([]); expect(fixture.nativeElement.querySelector('[role=alert]').textContent).toContain('Revisa');
|
||||
});
|
||||
// Why: the file must hold the query the server confirms, not the one WebApp hoped for.
|
||||
it('la exportación valida y usa los filtros efectivos que el servidor confirma', () => {
|
||||
respond();
|
||||
const pedir = (filtros: Record<string, string>) => {
|
||||
let tabla: { filtros: Record<string, string | null> } | undefined, error: unknown;
|
||||
fixture.componentInstance.origenExportacionCaCu.consultar('cacu', { corte: fixtureData.corte, meses: 12, page: 1, page_size: 200, filtros } as never).subscribe({ next: t => tabla = t as never, error: e => error = e });
|
||||
return { req: http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200'), get tabla() { return tabla; }, get error() { return error; } };
|
||||
};
|
||||
const sinEco = pedir({ q: 'P', edad_min: '30' });
|
||||
expect(sinEco.req.request.params.get('incluir')).toBeNull();
|
||||
sinEco.req.flush(respuesta(['P-1']));
|
||||
expect(sinEco.error).toBeInstanceOf(Error); expect(sinEco.tabla).toBeUndefined();
|
||||
const conEco = pedir({ q: 'P', edad_min: '30' });
|
||||
responder(conEco.req, ['P-1']);
|
||||
expect(conEco.tabla!.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: null });
|
||||
const sinFiltros = pedir({}); sinFiltros.req.flush(respuesta(['X-1']));
|
||||
expect(sinFiltros.tabla).toBeDefined();
|
||||
});
|
||||
it('la exportación lleva la consulta completa: q, edad_min, edad_max y los demás filtros, y dice qué se aplicó', () => {
|
||||
respond(); escribir('P'); vi.advanceTimersByTime(401);
|
||||
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges();
|
||||
const c = fixture.componentInstance; c.draft.edad_min = 30; c.draft.edad_max = 60; c.apply();
|
||||
responder(consultas()[0], ['P-1'], { paginacion: { total_items: 201, total_pages: 5 } }); fixture.detectChanges();
|
||||
const tabla = c.exportacionCaCu!;
|
||||
expect(tabla.filtros).toMatchObject({ q: 'P', edad_min: '30', edad_max: '60' });
|
||||
expect(tabla.filtros_disponibles.filter(f => ['q', 'edad_min', 'edad_max'].includes(f.clave)).map(f => f.opciones[0].etiqueta)).toEqual(['P', '30', '60']);
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
([...root.querySelectorAll('app-seguimiento-exportar button')] as HTMLButtonElement[]).find(x => x.textContent!.includes('Excel'))!.click();
|
||||
const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200');
|
||||
expect(['q', 'edad_min', 'edad_max', 'page'].map(k => exportacion.request.params.get(k))).toEqual(['P', '30', '60', '1']);
|
||||
responder(exportacion, ['P-1'], { paginacion: { total_items: 1, total_pages: 1 } });
|
||||
});
|
||||
});
|
||||
it('sin edad exacta ni identificador demográfico muestra los estados correspondientes', () => {
|
||||
respond();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector<HTMLElement>('tr[data-paciente]')!;
|
||||
expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad');
|
||||
expect(fila.querySelector('td:nth-child(2)')?.textContent).toContain('No disponible');
|
||||
expect(fila.querySelector('td:nth-child(2)')?.textContent?.trim()).toBe('No disponible');
|
||||
expect(root.textContent).not.toContain('Grupo de edad');
|
||||
fila.querySelector('button')!.click();
|
||||
fixture.detectChanges();
|
||||
const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento');
|
||||
expect(nacimiento?.nextElementSibling?.textContent?.trim()).toBe('No se pudo cargar');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('muestra en la ficha la fecha recuperada para el paciente seleccionado', () => {
|
||||
open().flush({ ...fixtureData, items: [{ ...fixtureData.items[0], pac_id: '42' }] });
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
root.querySelector<HTMLElement>('tr[data-paciente] button')!.click();
|
||||
fixture.detectChanges();
|
||||
http.expectOne(r => r.url === '/cacu/fhir/RiskAssessment').flush({}, { status: 404, statusText: 'Not Found' });
|
||||
const nacimiento = [...root.querySelectorAll('app-paciente-detalle dt')].find(dt => dt.textContent === 'Fecha de nacimiento')!;
|
||||
expect(nacimiento.nextElementSibling?.textContent).toContain('Cargando');
|
||||
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush({ pac_id: '42', fecha_nacimiento: '1980-01-02' });
|
||||
fixture.detectChanges();
|
||||
expect(nacimiento.nextElementSibling?.textContent?.trim()).toBe('02/01/1980');
|
||||
});
|
||||
// Why: the exact age is shown only when the service gives it, as whole years, and never estimated from the age group.
|
||||
it('muestra la edad exacta en años y distingue la edad ausente de una edad de 0 años', () => {
|
||||
const items = [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], edad_al_corte: 1 }, { ...fixtureData.items[2], edad_al_corte: 0 },
|
||||
{ ...fixtureData.items[3], edad_al_corte: null, grupo_edad: '40-49' }, { ...fixtureData.items[4], grupo_edad: '40-49' }];
|
||||
open().flush({ ...fixtureData, items, paginacion: { ...fixtureData.paginacion, total_items: 5 } });
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect([...root.querySelectorAll('tbody tr')].map(tr => tr.querySelector('td:nth-child(2)')!.textContent!.trim()))
|
||||
.toEqual(['42 años', '1 año', '0 años', 'No disponible', 'No disponible']);
|
||||
expect(root.querySelector('thead th:nth-child(2)')?.textContent).toBe('Edad');
|
||||
expect(root.textContent).not.toContain('Grupo de edad');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('la edad exacta solo se acepta como años enteros no negativos', () => {
|
||||
const con = (edad: unknown) => () => seguimientoResponse({ ...fixtureData, items: [{ ...fixtureData.items[0], edad_al_corte: edad }] });
|
||||
for (const valida of [0, 1, 42, null]) expect(con(valida)).not.toThrow();
|
||||
for (const invalida of [-1, 41.5, '42', 131, Number.NaN]) expect(con(invalida)).toThrow();
|
||||
});
|
||||
it('el listado no tiene la columna «Estudio más reciente» y conserva su opción de orden', () => {
|
||||
open().flush({ ...fixtureData, filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5] });
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect([...root.querySelectorAll('thead th')].map(th => th.textContent)).not.toContain('Estudio más reciente');
|
||||
expect(fixture.componentInstance.ordenes().map(o => o.etiqueta)).toContain('Estudio más reciente');
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(9 + fixture.componentInstance.columnasProbabilidad().length);
|
||||
});
|
||||
// Why: the exports must list the same columns as the screen; the study stays only as an ordering option.
|
||||
it('la tabla de exportación coincide con el listado: Edad exacta, sin «Estudio más reciente» y con su opción de orden', () => {
|
||||
const respuesta = seguimientoResponse({ ...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 }, horizontes_disponibles: [5],
|
||||
items: [{ ...fixtureData.items[0], edad_al_corte: 42 }, { ...fixtureData.items[1], grupo_edad: '40-49' }] });
|
||||
const tabla = tablaExportacionCaCu(respuesta, () => 'Citología', () => null);
|
||||
const claves = tabla.columnas.map(c => c.clave);
|
||||
expect(claves).toContain('edad'); expect(claves).not.toContain('grupo_edad'); expect(claves).not.toContain('reciente');
|
||||
expect(tabla.columnas.map(c => c.etiqueta)).not.toContain('Estudio más reciente');
|
||||
expect(tabla.items.map(item => item['edad'])).toEqual(['42 años', null]);
|
||||
expect(tabla.items.every(item => !('reciente' in item))).toBe(true);
|
||||
expect(tabla.filtros_disponibles.find(f => f.clave === 'orden')!.opciones.map(o => o.etiqueta)).toContain('Estudio más reciente');
|
||||
});
|
||||
it.each(['Excel', 'PDF'])('la exportación %s usa el contrato y los filtros aplicados de CaCu, con los filtros de la consulta', formato => {
|
||||
const pagina = {
|
||||
...fixtureData, filtros: { estatus: 'PRE_COLPOSCOPIA', orden: 'lieag', horizonte: 3 },
|
||||
paginacion: { ...fixtureData.paginacion, total_items: 201 },
|
||||
};
|
||||
open().flush(pagina);
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} });
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const botones = () => [...root.querySelectorAll<HTMLButtonElement>('app-seguimiento-exportar button')];
|
||||
botones().find(button => button.textContent!.includes(formato))!.click();
|
||||
const exportacion = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page_size') === '200');
|
||||
expect(exportacion.request.params.get('estatus')).toBe('PRE_COLPOSCOPIA');
|
||||
expect(exportacion.request.params.get('orden')).toBe('lieag');
|
||||
expect(exportacion.request.params.get('horizonte')).toBe('3');
|
||||
expect(exportacion.request.params.get('corte')).toBe(pagina.corte);
|
||||
expect(exportacion.request.params.get('page')).toBe('1');
|
||||
const items = Array.from({ length: 200 }, (_, i) => ({ ...pagina.items[0], id_seudonimo: `PRUEBA-${i}` }));
|
||||
exportacion.flush({ ...pagina, items, paginacion: { page: 1, page_size: 200, total_items: 201, total_pages: 2 } });
|
||||
const siguiente = http.expectOne(r => r.url === '/cacu/seguimiento' && r.params.get('page') === '2');
|
||||
fixture.detectChanges();
|
||||
botones().find(button => button.textContent === 'Cancelar')!.click();
|
||||
expect(siguiente.cancelled).toBe(true);
|
||||
});
|
||||
it.each([404,400,0,503])('HTTP %s no introduce registros ficticios; reintento conserva consulta', code => {
|
||||
const req=open(); if(code===0) req.error(new ProgressEvent('error')); else req.flush({error:'private'}, {status:code,statusText:'Failure'});
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).toBeNull(); expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
@@ -86,15 +324,66 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({}, {status:404,statusText:'Absent'}); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.textContent).toContain('No hay registros');
|
||||
});
|
||||
it('no activa registros reales ni acepta respuestas malformadas', () => {
|
||||
expect(()=>seguimientoResponse({...fixtureData,simulado:false})).toThrow();
|
||||
it('acepta ambas marcas de simulación y rechaza respuestas malformadas', () => {
|
||||
expect(seguimientoResponse({...fixtureData,simulado:false}).simulado).toBe(false);
|
||||
expect(tablaExportacionCaCu(seguimientoResponse({...fixtureData,simulado:false}), () => '', () => null).simulado).toBe(false);
|
||||
expect(seguimientoResponse({...fixtureData,simulado:true}).simulado).toBe(true);
|
||||
expect(()=>seguimientoResponse({...fixtureData,simulado:'false'})).toThrow();
|
||||
expect(()=>seguimientoResponse({...fixtureData,items:[{...fixtureData.items[0],ultimo_vph:{fecha:'bad'}}]})).toThrow();
|
||||
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();
|
||||
open().flush({...fixtureData,simulado:false});
|
||||
http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({categorias:{}});
|
||||
fixture.detectChanges(); expect(fixture.nativeElement.querySelector('tbody')).not.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();
|
||||
http.expectNone(()=>true);
|
||||
});
|
||||
// Fails if the list stops showing each patient's biopsy and probabilities at the horizon chosen, or the order and the
|
||||
// horizon stop reaching the API (the list is paginated, so ordering happens there).
|
||||
it('con Pre colposcopia muestra la biopsia y las probabilidades de LIEAG+ y cáncer al horizonte elegido, y pide el orden al servidor', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, ultima_biopsia: { fecha: '2025-10-01', grado: 'LIEAG' },
|
||||
probabilidades: { lieag: [{ horizonte_anios: 1, probabilidad: 0.08, ic_bajo: 0.05, ic_alto: 0.12 },
|
||||
{ horizonte_anios: 5, probabilidad: 0.34, ic_bajo: 0.26, ic_alto: 0.44 }],
|
||||
cancer: [{ horizonte_anios: 5, probabilidad: 0.015, ic_bajo: null, ic_alto: null }] },
|
||||
} : item);
|
||||
const data = { ...fixtureData, items, horizontes_disponibles: [1, 5], filtros: { ...fixtureData.filtros, estatus: 'PRE_COLPOSCOPIA', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(data); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const fila = root.querySelector('tbody tr')!;
|
||||
expect(fila.textContent).toContain('LIEAG'); expect(fila.textContent).toContain('34 % (26 – 44 %)'); expect(fila.textContent).toContain('1.5 %');
|
||||
expect(root.querySelector('thead')!.textContent).toContain('Probabilidad a LIEAG+ a 5 años (%)');
|
||||
expect([...root.querySelectorAll('select[name="horizonte"] option')].map(o => o.textContent!.trim())).toEqual(['1 año', '5 años']);
|
||||
|
||||
fixture.componentInstance.draft.orden = 'lieag'; fixture.componentInstance.draft.horizonte = 1;
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.get('orden')).toBe('lieag'); expect(req.request.params.get('horizonte')).toBe('1');
|
||||
req.flush({ ...data, filtros: { ...data.filtros, orden: 'lieag', horizonte: 1 } }); fixture.detectChanges();
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('8 % (5 – 12 %)');
|
||||
});
|
||||
|
||||
// Fails if the columns stop following the status filtered: each scenario has its own models.
|
||||
it('las columnas de probabilidad siguen al estatus: un caso muestra supervivencia y todas las pacientes, ninguna', () => {
|
||||
const items = fixtureData.items.map((item: any, i: number) => i === 0 ? {
|
||||
...item, estatus: { codigo: 'CASO', etiqueta: 'Caso (cáncer)' },
|
||||
probabilidades: { supervivencia: [{ horizonte_anios: 5, probabilidad: 0.7, ic_bajo: 0.55, ic_alto: 0.8 }] } } : item);
|
||||
const caso = { ...fixtureData, items, horizontes_disponibles: [5], filtros: { ...fixtureData.filtros, estatus: 'CASO', orden: 'reciente', horizonte: 5 } };
|
||||
open().flush(caso); http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement, encabezados = () => [...root.querySelectorAll('thead th')].map(t => t.textContent!.trim());
|
||||
expect(encabezados()).toContain('Probabilidad de supervivencia a 5 años (%)');
|
||||
expect(encabezados().some(t => t.includes('LIEAG+'))).toBe(false);
|
||||
expect(root.querySelector('tbody tr')!.textContent).toContain('70 % (55 – 80 %)');
|
||||
expect(fixture.componentInstance.ordenes().map(o => o.codigo)).toEqual(['reciente', 'supervivencia']);
|
||||
|
||||
fixture.componentInstance.draft.estatus = undefined; fixture.componentInstance.draft.orden = 'supervivencia';
|
||||
fixture.componentInstance.apply();
|
||||
const req = http.expectOne(r => r.url === '/cacu/seguimiento');
|
||||
expect(req.request.params.has('orden')).toBe(false);
|
||||
req.flush({ ...caso, filtros: { ...caso.filtros, estatus: null } }); fixture.detectChanges();
|
||||
expect(encabezados().some(t => t.startsWith('Probabilidad'))).toBe(false);
|
||||
expect(root.querySelector('select[name="orden"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { COLUMNAS_DE_PROBABILIDAD, edadAnios, edadTexto, ETIQUETA_PROBABILIDAD, normalizarConsulta, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse } from '../cacu-seguimiento.models';
|
||||
import { ETIQUETA_IDENTIDAD, identidadDe } from '../paciente-identidad';
|
||||
import { SeguimientoTablaQuery, SeguimientoTablaResponse } from '../seguimiento-tabla.service';
|
||||
|
||||
const ORDEN_RECIENTE = { codigo: 'reciente', etiqueta: 'Estudio más reciente' };
|
||||
|
||||
export function consultaExportacionCaCu(q: SeguimientoTablaQuery): SeguimientoQuery {
|
||||
const { corte, meses, page, page_size, filtros } = q;
|
||||
if (meses === 0) throw new Error('Ventana de seguimiento CaCu inválida');
|
||||
const orden = filtros?.['orden'];
|
||||
return {
|
||||
corte, meses, page, page_size, estatus: filtros?.['estatus'],
|
||||
orden: orden === 'lieag' || orden === 'cancer' || orden === 'supervivencia' ? orden : 'reciente',
|
||||
horizonte: filtros?.['horizonte'] === undefined ? undefined : Number(filtros['horizonte']),
|
||||
// The whole query: the file holds every record the search and the age range select, not the page on screen.
|
||||
q: normalizarConsulta(filtros?.['q']) || undefined,
|
||||
edad_min: filtros?.['edad_min'] === undefined ? undefined : Number(filtros['edad_min']),
|
||||
edad_max: filtros?.['edad_max'] === undefined ? undefined : Number(filtros['edad_max']),
|
||||
};
|
||||
}
|
||||
|
||||
/** Adapts the validated CaCu list to the shared export table. */
|
||||
export function tablaExportacionCaCu(
|
||||
respuesta: SeguimientoResponse,
|
||||
citologia: (estudio: NonNullable<SeguimientoPaciente['ultima_citologia']>) => string,
|
||||
probabilidad: (item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte: number) => string | null,
|
||||
consulta: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'> = {},
|
||||
): SeguimientoTablaResponse {
|
||||
// The effective query is the one the server confirms; the one asked fills in for servers that do not say.
|
||||
const q = normalizarConsulta(respuesta.filtros.q ?? consulta.q);
|
||||
const edadMin = respuesta.filtros.edad_min ?? consulta.edad_min, edadMax = respuesta.filtros.edad_max ?? consulta.edad_max;
|
||||
const identidad = (respuesta.items[0] && identidadDe(respuesta.items[0]))?.campo ?? 'id_seudonimo';
|
||||
const { estatus, orden, horizonte } = respuesta.filtros;
|
||||
const probabilidades = estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
const horizonteMostrado = horizonte ?? 5;
|
||||
return {
|
||||
simulado: respuesta.simulado,
|
||||
corte: respuesta.corte,
|
||||
ventana: respuesta.ventana,
|
||||
paginacion: respuesta.paginacion,
|
||||
filtros: { estatus, orden: orden ?? 'reciente', horizonte: horizonte?.toString() ?? null,
|
||||
q: q || null, edad_min: edadMin?.toString() ?? null, edad_max: edadMax?.toString() ?? null },
|
||||
filtros_disponibles: [
|
||||
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento', opciones: respuesta.estatus_disponibles },
|
||||
{ clave: 'orden', etiqueta: 'Orden', opciones: [ORDEN_RECIENTE, ...probabilidades.map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))] },
|
||||
{ clave: 'horizonte', etiqueta: 'Horizonte de la probabilidad', opciones: (respuesta.horizontes_disponibles ?? [0, 1, 3, 5])
|
||||
.map(h => ({ codigo: String(h), etiqueta: `${h} ${h === 1 ? 'año' : 'años'}` })) },
|
||||
// Free values: the only option is the value applied, so the files say what was searched.
|
||||
{ clave: 'q', etiqueta: 'Identificador contiene', opciones: q ? [{ codigo: q, etiqueta: q }] : [] },
|
||||
{ clave: 'edad_min', etiqueta: 'Edad mínima (años)', opciones: edadMin == null ? [] : [{ codigo: String(edadMin), etiqueta: String(edadMin) }] },
|
||||
{ clave: 'edad_max', etiqueta: 'Edad máxima (años)', opciones: edadMax == null ? [] : [{ codigo: String(edadMax), etiqueta: String(edadMax) }] },
|
||||
],
|
||||
columnas: [
|
||||
{ clave: identidad, etiqueta: ETIQUETA_IDENTIDAD[identidad] },
|
||||
{ clave: 'edad', etiqueta: 'Edad' },
|
||||
{ clave: 'estatus', etiqueta: 'Estatus de seguimiento' },
|
||||
{ clave: 'citologia', etiqueta: 'Última citología', detalles: [{ clave: 'fecha_citologia', etiqueta: 'Fecha' }, { clave: 'calidad', etiqueta: 'Calidad' }] },
|
||||
{ clave: 'vph', etiqueta: 'Último resultado de VPH', detalles: [{ clave: 'fecha_vph', etiqueta: 'Fecha' }, { clave: 'genotipo', etiqueta: 'Genotipo 16/18' }] },
|
||||
{ clave: 'biopsia', etiqueta: 'Última biopsia', detalles: [{ clave: 'fecha_biopsia', etiqueta: 'Fecha' }] },
|
||||
...probabilidades.map(clave => ({ clave, etiqueta: `${ETIQUETA_PROBABILIDAD[clave]} a ${horizonteMostrado} años (%)` })),
|
||||
{ clave: 'dias', etiqueta: 'Días de toma a diagnóstico' },
|
||||
{ clave: 'prioridad', etiqueta: 'Prioridad' },
|
||||
],
|
||||
items: respuesta.items.map(item => ({
|
||||
[identidad]: identidadDe(item)!.id,
|
||||
edad: edadAnios(item) === null ? null : edadTexto(item),
|
||||
estatus: item.estatus.etiqueta,
|
||||
citologia: item.ultima_citologia ? citologia(item.ultima_citologia) : null,
|
||||
fecha_citologia: item.ultima_citologia?.fecha ?? null,
|
||||
calidad: item.ultima_citologia?.calidad ?? null,
|
||||
vph: item.ultimo_vph?.resultado ?? null,
|
||||
fecha_vph: item.ultimo_vph?.fecha ?? null,
|
||||
genotipo: item.ultimo_vph?.genotipo_16_18 == null ? null : item.ultimo_vph.genotipo_16_18 ? 'Presente' : 'No detectado',
|
||||
biopsia: item.ultima_biopsia ? item.ultima_biopsia.grado ?? 'Sin grado' : null,
|
||||
fecha_biopsia: item.ultima_biopsia?.fecha ?? null,
|
||||
...Object.fromEntries(probabilidades.map(c => [c, probabilidad(item, c, horizonteMostrado)])),
|
||||
dias: item.dias_toma_diagnostico,
|
||||
prioridad: item.prioridad?.etiqueta ?? null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const pad = (n: number) => String(n).padStart(2, '0');
|
||||
* Name of a downloaded file. It carries the report kind, the cut-off date and the moment it was made, and never a
|
||||
* patient identifier, because file names end up in download lists, backups and mail attachments.
|
||||
*/
|
||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||
export function exportFilename(kind: 'seguimiento-cancer-de-mama' | 'seguimiento-cancer-de-mama-seleccion' | 'ficha-cancer-de-mama' | 'seguimiento-cancer-cervicouterino' | 'ficha-cancer-cervicouterino', corte: string, extension: 'xlsx' | 'pdf', now = new Date()): string {
|
||||
const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
|
||||
return `${kind}_corte-${corte.replace(/[^0-9-]/g, '')}_${stamp}.${extension}`;
|
||||
}
|
||||
|
||||
@@ -57,9 +57,11 @@ export class TrackingExportBar {
|
||||
readonly habilitado = input(true);
|
||||
/** How the analysis named the selection this answer belongs to; it travels into the files. */
|
||||
readonly seleccion = input<string | undefined>(undefined);
|
||||
readonly origen = input<Pick<SeguimientoTablaService, 'consultar'> | undefined>();
|
||||
|
||||
private readonly service = inject(SeguimientoTablaService);
|
||||
private subscription?: Subscription;
|
||||
private exportacion = 0;
|
||||
readonly formatos: readonly ExportFormat[] = ['xlsx', 'pdf'];
|
||||
readonly label = FORMAT_LABEL;
|
||||
readonly limits = EXPORT_LIMITS;
|
||||
@@ -80,14 +82,14 @@ export class TrackingExportBar {
|
||||
});
|
||||
|
||||
constructor() {
|
||||
inject(DestroyRef).onDestroy(() => this.subscription?.unsubscribe());
|
||||
inject(DestroyRef).onDestroy(() => this.detenerExportacion());
|
||||
// A result message belongs to the query it was made for: it goes away when another query is shown. An export still
|
||||
// being read belongs to a query that is no longer on screen: it is cancelled, never downloaded as the current one.
|
||||
effect(() => {
|
||||
this.queryKey();
|
||||
untracked(() => {
|
||||
if (this.estado() === 'working') {
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
this.estado.set('error'); this.listo.set(''); this.mensaje.set('La consulta cambió; se canceló la exportación. Vuelve a exportar.');
|
||||
} else { this.listo.set(''); this.mensaje.set(''); if (this.estado() === 'error') this.estado.set('idle'); }
|
||||
});
|
||||
@@ -101,35 +103,44 @@ export class TrackingExportBar {
|
||||
exportar(formato: ExportFormat) {
|
||||
if (!this.available(formato)) return;
|
||||
this.estado.set('working'); this.mensaje.set(''); this.listo.set(''); this.progress.set({ fetched: 0, total: 0 });
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
const exportacion = this.exportacion;
|
||||
const clave = this.queryKey(), seleccion = this.seleccion();
|
||||
this.subscription = fetchAllTracking(this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||
const esCaCu = this.dominio() === 'cacu';
|
||||
this.subscription = fetchAllTracking(this.origen() ?? this.service, this.dominio(), queryOf(this.respuesta()), EXPORT_LIMITS[formato]).subscribe({
|
||||
next: event => {
|
||||
if (event.kind === 'progress') this.progress.set({ fetched: event.fetched, total: event.total });
|
||||
else void this.generar(formato, seleccion ? { ...event.snapshot, seleccion } : event.snapshot, clave);
|
||||
else void this.generar(formato, { ...event.snapshot, seleccion, titulo: esCaCu ? 'Cáncer cervicouterino' : undefined }, clave, exportacion, esCaCu);
|
||||
},
|
||||
error: error => this.fallar(error),
|
||||
});
|
||||
}
|
||||
|
||||
cancelar() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.detenerExportacion();
|
||||
this.estado.set('idle');
|
||||
}
|
||||
|
||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string) {
|
||||
private detenerExportacion() {
|
||||
this.exportacion++;
|
||||
this.subscription?.unsubscribe();
|
||||
}
|
||||
|
||||
private async generar(formato: ExportFormat, snapshot: TrackingSnapshot, clave: string, exportacion: number, esCaCu: boolean) {
|
||||
try {
|
||||
// Each generator (and its library) downloads only when its button is used.
|
||||
const blob = formato === 'xlsx'
|
||||
? await (await import('./tracking-xlsx')).buildTrackingXlsx(snapshot)
|
||||
: await (await import('./tracking-pdf')).buildTrackingPdf(snapshot);
|
||||
// The query on screen changed while the file was being made: it is not the one that was asked for.
|
||||
if (clave !== this.queryKey()) return;
|
||||
downloadBlob(blob, exportFilename(snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama', snapshot.corte, formato));
|
||||
if (exportacion !== this.exportacion || clave !== this.queryKey()) return;
|
||||
const nombre = esCaCu ? 'seguimiento-cancer-cervicouterino'
|
||||
: snapshot.seleccion ? 'seguimiento-cancer-de-mama-seleccion' : 'seguimiento-cancer-de-mama';
|
||||
downloadBlob(blob, exportFilename(nombre, snapshot.corte, formato));
|
||||
this.estado.set('idle');
|
||||
this.listo.set(`Se generó el archivo con ${snapshot.items.length} registros.`);
|
||||
} catch {
|
||||
this.fallar(new Error('generation'));
|
||||
if (exportacion === this.exportacion && clave === this.queryKey()) this.fallar(new Error('generation'));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const sameQuery = consultaAplicada;
|
||||
* Reads every row a follow-up query matches, page by page, with the cut-off fixed by the first answer.
|
||||
* Unsubscribing cancels the pending requests. It fails instead of returning a partial or unstable list.
|
||||
*/
|
||||
export function fetchAllTracking(service: SeguimientoTablaService, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||
export function fetchAllTracking(service: Pick<SeguimientoTablaService, 'consultar'>, dominio: Dominio, query: SeguimientoTablaQuery, limit: number): Observable<TrackingExportEvent> {
|
||||
const ask = (q: SeguimientoTablaQuery) => defer(() => service.consultar(dominio, q));
|
||||
return ask({ ...query, page: 1, page_size: PAGE_SIZE_MAX }).pipe(
|
||||
switchMap(first => {
|
||||
|
||||
@@ -8,6 +8,7 @@ export type TrackingRow = Record<string, SeguimientoValor>;
|
||||
|
||||
/** Everything one export needs: the first answer (columns, filters, window) and all the rows it announced. */
|
||||
export interface TrackingSnapshot {
|
||||
titulo?: string;
|
||||
/** How the analysis named the selection this list opens, when it does; the files carry it so they say where they come from. */
|
||||
seleccion?: string;
|
||||
corte: string;
|
||||
|
||||
@@ -48,7 +48,7 @@ function dataTable(snapshot: TrackingSnapshot) {
|
||||
|
||||
/** The document definition of a follow-up report. Exported so its content can be checked without rendering. */
|
||||
export function trackingDocument(snapshot: TrackingSnapshot, now: Date, logo?: string): PdfDefinition {
|
||||
return institutionalDocument({ title: TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||
return institutionalDocument({ title: snapshot.titulo ?? TRACKING_TITLE, logo, now, orientation: 'landscape' }, [
|
||||
{ text: 'Resultados de seguimiento', style: 'h1' },
|
||||
parameters(snapshot),
|
||||
{ text: 'Pacientes', style: 'h2' },
|
||||
|
||||
@@ -48,7 +48,7 @@ export function parameterRows(snapshot: TrackingSnapshot, now: Date): SheetData
|
||||
});
|
||||
return [
|
||||
[header('Parámetro'), header('Valor')],
|
||||
row('Reporte', 'Cáncer de mama'),
|
||||
row('Reporte', snapshot.titulo ?? 'Cáncer de mama'),
|
||||
...(snapshot.seleccion ? [row('Selección del análisis', snapshot.seleccion)] : []),
|
||||
row('Fecha de corte', snapshot.corte),
|
||||
row('Ventana consultada', ventanaConsultada(snapshot)),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "searchset",
|
||||
"total": 7,
|
||||
"total": 9,
|
||||
"link": [
|
||||
{
|
||||
"relation": "self",
|
||||
@@ -297,6 +297,123 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-DIAGNOSTICO-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_diagnostico_tratamiento",
|
||||
"title": "Tiempo de diagnóstico a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales del diagnóstico que resuelve cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Solo entran las citologías que un diagnóstico resolvió; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. Dos citologías que resuelve el mismo diagnóstico cuentan cada una. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_diagnostico_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-DIAGNOSTICO",
|
||||
"resource": {
|
||||
@@ -414,6 +531,123 @@
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"resource": {
|
||||
"resourceType": "Measure",
|
||||
"id": "CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
|
||||
"valueCode": "C3r"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "semestre"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
|
||||
"valueCode": "mes"
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/figuras",
|
||||
"valueString": "fig_c3r_caja"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-DIAS-TOMA-TRATAMIENTO",
|
||||
"version": "0.1.0",
|
||||
"name": "cacu_dias_toma_tratamiento",
|
||||
"title": "Tiempo de tamizaje a tratamiento",
|
||||
"status": "active",
|
||||
"subjectCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
|
||||
"code": "examen"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Días naturales de la toma de cada citología del periodo al primer tratamiento posterior: una nota médica con un CIE-10 de tratamiento después de la primera colposcopia de la paciente, dentro del horizonte y a la fecha de corte. Entran todas las citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma. El tratamiento se infiere de la nota: no distingue el indicado del realizado.",
|
||||
"scoring": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
|
||||
"code": "continuous-variable"
|
||||
}
|
||||
]
|
||||
},
|
||||
"improvementNotation": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
|
||||
"code": "decrease"
|
||||
}
|
||||
]
|
||||
},
|
||||
"group": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
|
||||
"code": "TOTAL"
|
||||
}
|
||||
]
|
||||
},
|
||||
"population": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "initial-population"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades del periodo",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-observation"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades con valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
|
||||
"code": "measure-population-exclusion"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": "Unidades sin valor",
|
||||
"criteria": {
|
||||
"language": "text/x-dbt-metric",
|
||||
"expression": "cacu_dias_toma_tratamiento"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"search": {
|
||||
"mode": "match"
|
||||
}
|
||||
},
|
||||
{
|
||||
"fullUrl": "http://webapi/cacu/fhir/Measure/CACU-EU-TIEMPO-REPORTE",
|
||||
"resource": {
|
||||
|
||||
@@ -0,0 +1,835 @@
|
||||
{
|
||||
"resourceType": "Bundle",
|
||||
"type": "collection",
|
||||
"entry": [
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "ados2-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2",
|
||||
"display": "ADOS-2"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo",
|
||||
"display": "Módulo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.modulo.MODULO_2"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.css",
|
||||
"display": "Puntaje de severidad (CSS)"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 8
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion",
|
||||
"display": "Clasificación"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueCodeableConcept": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.clasificacion.AUTISMO"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "SA",
|
||||
"display": "Afecto social"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 10
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio",
|
||||
"code": "RRB",
|
||||
"display": "Comportamiento restringido y repetitivo"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 4
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_a4",
|
||||
"display": "Uso estereotipado o idiosincrásico de palabras o frases"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d2",
|
||||
"display": "Manierismos de manos y dedos y otros manierismos complejos"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.rrb_d4",
|
||||
"display": "Intereses inusualmente repetitivos o comportamientos estereotipados"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "RRB"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a6",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_a7",
|
||||
"display": "Señalar"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b1",
|
||||
"display": "Contacto visual inusual"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b12",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b2",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b3",
|
||||
"display": "Expresiones faciales dirigidas a otros"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 0,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b5",
|
||||
"display": "Disfrute compartido durante la interacción"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 2,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 2
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b6",
|
||||
"display": "Iniciación espontánea de la atención conjunta"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "ados2.sa_b8",
|
||||
"display": "Características de las iniciaciones sociales"
|
||||
}
|
||||
]
|
||||
},
|
||||
"valueInteger": 1,
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/puntaje-algoritmo",
|
||||
"valueInteger": 1
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/dominio",
|
||||
"valueCode": "SA"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Procedure",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "completed",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"performedDateTime": "1985-01-01",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "DiagnosticReport",
|
||||
"id": "eeg-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo",
|
||||
"code": "eeg",
|
||||
"display": "Electroencefalograma"
|
||||
}
|
||||
]
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"result": [
|
||||
{
|
||||
"reference": "Observation/calidad-bad-scalp-triage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-clean-windows-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-internal-coverage-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-line-noise-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-triage-level-vista-previa"
|
||||
},
|
||||
{
|
||||
"reference": "Observation/calidad-usable-scalp-vista-previa"
|
||||
}
|
||||
],
|
||||
"conclusionCode": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/calidad",
|
||||
"code": "MALO"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "not-valid"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"extension": [
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/duracion-min",
|
||||
"valueDecimal": 2.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/edad-meses",
|
||||
"valueDecimal": 30.0
|
||||
},
|
||||
{
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/canales",
|
||||
"valueInteger": 24
|
||||
}
|
||||
],
|
||||
"conclusion": "EEG de mala calidad: no es válido para el estudio (nivel de triaje: no_analizable).",
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-bad-scalp-triage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "bad-scalp-triage",
|
||||
"display": "bad-scalp-triage"
|
||||
}
|
||||
],
|
||||
"text": "bad-scalp-triage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 0.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 2.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-clean-windows-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "clean-windows",
|
||||
"display": "clean-windows"
|
||||
}
|
||||
],
|
||||
"text": "clean-windows"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 100.0,
|
||||
"unit": "%"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 60.0,
|
||||
"unit": "%"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-internal-coverage-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "internal-coverage",
|
||||
"display": "internal-coverage"
|
||||
}
|
||||
],
|
||||
"text": "internal-coverage"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 1.0,
|
||||
"unit": "fraction"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 0.9,
|
||||
"unit": "fraction"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-line-noise-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "line-noise",
|
||||
"display": "line-noise"
|
||||
}
|
||||
],
|
||||
"text": "line-noise"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 9.231034526452635,
|
||||
"unit": "dB"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"high": {
|
||||
"value": 45.0,
|
||||
"unit": "dB"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": false
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-triage-level-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "triage-level",
|
||||
"display": "triage-level"
|
||||
}
|
||||
],
|
||||
"text": "triage-level"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "A"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueString": "no_analizable",
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"resource": {
|
||||
"resourceType": "Observation",
|
||||
"id": "calidad-usable-scalp-vista-previa",
|
||||
"status": "final",
|
||||
"code": {
|
||||
"coding": [
|
||||
{
|
||||
"system": "urn:tea:validation",
|
||||
"code": "usable-scalp",
|
||||
"display": "usable-scalp"
|
||||
}
|
||||
],
|
||||
"text": "usable-scalp"
|
||||
},
|
||||
"subject": {
|
||||
"reference": "Patient/vista-previa"
|
||||
},
|
||||
"effectiveDateTime": "1985-01-01",
|
||||
"interpretation": [
|
||||
{
|
||||
"coding": [
|
||||
{
|
||||
"system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation",
|
||||
"code": "N"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"valueQuantity": {
|
||||
"value": 19.0,
|
||||
"unit": "electrodes"
|
||||
},
|
||||
"referenceRange": [
|
||||
{
|
||||
"low": {
|
||||
"value": 12.0,
|
||||
"unit": "electrodes"
|
||||
}
|
||||
}
|
||||
],
|
||||
"component": [
|
||||
{
|
||||
"code": {
|
||||
"text": "decisive"
|
||||
},
|
||||
"valueBoolean": true
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"tag": [
|
||||
{
|
||||
"system": "https://isssteleon.org/fhir/CodeSystem/etiqueta",
|
||||
"code": "simulado",
|
||||
"display": "Datos simulados"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Covers the round "?" help of TEA's cards: hover or focus shows the text, a click keeps it until the next click.
|
||||
// Fixture: a host component that projects one line of text into the button.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
|
||||
@Component({ imports: [IndicadorAyuda], template: `<app-indicador-ayuda etiqueta="Cómo leer: prueba" (opened)="aperturas = aperturas + 1">Texto de ayuda</app-indicador-ayuda>` })
|
||||
class Host { aperturas = 0; }
|
||||
|
||||
describe('Ayuda redonda', () => {
|
||||
function crear() {
|
||||
const fixture = TestBed.createComponent(Host);
|
||||
fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
const boton = () => root.querySelector<HTMLButtonElement>('.ayuda-boton')!;
|
||||
const texto = () => root.querySelector('.ayuda-texto')?.textContent?.trim();
|
||||
const ayuda = root.querySelector('.ayuda')!;
|
||||
return { fixture, boton, texto, ayuda };
|
||||
}
|
||||
|
||||
it('muestra el texto al pasar el cursor y lo oculta al salir', () => {
|
||||
// Fails if hovering stops showing the guide or leaving leaves it open when it was not pinned.
|
||||
const { fixture, texto, ayuda } = crear();
|
||||
expect(texto()).toBeUndefined();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('un clic fija el texto hasta el siguiente clic', () => {
|
||||
// Fails if the click stops pinning the text, if leaving closes a pinned text, or if a second click does not close it.
|
||||
const { fixture, boton, texto, ayuda } = crear();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseenter')); boton().click(); fixture.detectChanges();
|
||||
ayuda.dispatchEvent(new MouseEvent('mouseleave')); fixture.detectChanges();
|
||||
expect(texto()).toBe('Texto de ayuda');
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('true');
|
||||
boton().click(); fixture.detectChanges();
|
||||
expect(texto()).toBeUndefined();
|
||||
expect(boton().getAttribute('aria-expanded')).toBe('false');
|
||||
});
|
||||
|
||||
it('avisa solo al abrirse con un clic y nombra el botón', () => {
|
||||
// Fails if closing also reports an opening (the metadata would be requested again) or the accessible name is lost.
|
||||
const { fixture, boton } = crear();
|
||||
boton().click(); boton().click(); boton().click(); fixture.detectChanges();
|
||||
expect(fixture.componentInstance.aperturas).toBe(2);
|
||||
expect(boton().getAttribute('aria-label')).toBe('Cómo leer: prueba');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Component, input, output, signal } from '@angular/core';
|
||||
|
||||
// Round "?" button at the top right of a card. Hover or focus shows its text; a click keeps it open until the next click.
|
||||
@Component({
|
||||
selector: 'app-indicador-ayuda',
|
||||
template: `
|
||||
<div class="ayuda" (mouseenter)="sobre.set(true)" (mouseleave)="sobre.set(false)" (focusin)="sobre.set(true)" (focusout)="sobre.set(false)">
|
||||
<button type="button" class="ayuda-boton" [attr.aria-label]="etiqueta()" [attr.aria-expanded]="visible()"
|
||||
[attr.aria-controls]="visible() ? idPanel : null" (click)="alternar()"><span aria-hidden="true">?</span></button>
|
||||
@if (visible()) {
|
||||
<div class="ayuda-texto" role="tooltip" [id]="idPanel"><ng-content /></div>
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
:host { position: absolute; top: .5rem; right: .5rem; z-index: 2; }
|
||||
.ayuda { position: relative; }
|
||||
.ayuda-boton { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; padding: 0; border: 0;
|
||||
border-radius: 50%; background: transparent; box-shadow: inset 0 0 0 1.5px var(--issste-text-secondary); color: var(--issste-text); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
|
||||
.ayuda-boton:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.ayuda-texto { position: absolute; top: calc(100% + .375rem); right: 0; width: min(22rem, 80vw); box-sizing: border-box; padding: var(--issste-space-3) var(--issste-space-4);
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-inline-start: 3px solid var(--issste-accent);
|
||||
border-radius: var(--issste-radius); box-shadow: 0 4px 16px rgb(0 0 0 / .18); font: var(--mat-sys-body-small); line-height: 1.5; text-align: start; overflow-wrap: anywhere; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorAyuda {
|
||||
readonly etiqueta = input('Cómo leer');
|
||||
readonly opened = output<void>();
|
||||
readonly sobre = signal(false);
|
||||
readonly fijo = signal(false);
|
||||
private static contador = 0;
|
||||
readonly idPanel = 'ayuda-' + ++IndicadorAyuda.contador;
|
||||
visible() { return this.sobre() || this.fijo(); }
|
||||
alternar() {
|
||||
const abre = !this.fijo();
|
||||
this.fijo.set(abre);
|
||||
if (abre) this.opened.emit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, SimpleChanges } from '@angular/core';
|
||||
import { catchError, of, Subscription } from 'rxjs';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } from './indicadores.models';
|
||||
import { describePeriods, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorVphGenotipo } from './indicador-vph-genotipo';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
|
||||
// Three independent CaCu distributions sharing the general period filter.
|
||||
@Component({
|
||||
selector: 'app-indicador-cacu-donas',
|
||||
imports: [IndicadorEu7Escenario, IndicadorVphGenotipo, IndicadorConfirmacionCitologia],
|
||||
template: `
|
||||
<p class="filtro">Filtro general aplicado: {{ filtro }}</p>
|
||||
<div class="donas">
|
||||
<app-indicador-eu7-escenario [mostrarFiltro]="false" [permitirSeleccion]="false" [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="metadataRequested.emit()" />
|
||||
<app-indicador-vph-genotipo [mostrarFiltro]="vphFiltroPropio" [dominio]="dominio" [indicador]="vph" [tema]="tema" [applied]="vphApplied" [visible]="visible" />
|
||||
@if (confirmacion && confirmacionApplied) {
|
||||
<app-indicador-confirmacion-citologia vista="dona" [mostrarFiltro]="filtroPropio" [permitirSeleccion]="false" [dominio]="dominio" [indicador]="confirmacion" [tema]="tema" [applied]="confirmacionApplied" [visible]="visible" [metadata]="confirmacionMetadata" (metadataRequested)="loadConfirmacionMetadata()" />
|
||||
}
|
||||
</div>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.filtro { margin: 0 0 var(--issste-space-2); color: var(--issste-text-secondary); }
|
||||
.donas { display: flex; flex-direction: column; }
|
||||
.donas > * { display: block; min-width: 0; padding-block: var(--issste-space-3); }
|
||||
.donas > * + * { border-top: 1px solid var(--issste-border); }
|
||||
`,
|
||||
})
|
||||
export class IndicadorCacuDonas 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;
|
||||
// The biopsy donut belongs to the histopathological confirmation indicator.
|
||||
@Input() confirmacion?: Indicador;
|
||||
@Input() confirmacionApplied?: GlobalApplied;
|
||||
// HPV by genotype: its Measure, when the server publishes it.
|
||||
@Input() vph?: Indicador;
|
||||
@Input() vphApplied?: GlobalApplied;
|
||||
readonly metadataRequested = output<void>();
|
||||
get filtro() { return describePeriods(this.applied.tipo, this.applied.selection); }
|
||||
get vphFiltroPropio() { return !!this.vphApplied && describePeriods(this.vphApplied.tipo, this.vphApplied.selection) !== this.filtro; }
|
||||
// A donut whose effective period differs from the card's keeps its own line.
|
||||
get filtroPropio() { return !!this.confirmacionApplied && describePeriods(this.confirmacionApplied.tipo, this.confirmacionApplied.selection) !== this.filtro; }
|
||||
confirmacionMetadata?: IndicadorMetadatos;
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private metadataSubscription?: Subscription;
|
||||
private metadataKey = '';
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (changes['confirmacion'] && this.metadataKey !== '') {
|
||||
this.metadataSubscription?.unsubscribe(); this.metadataKey = ''; this.confirmacionMetadata = undefined;
|
||||
}
|
||||
}
|
||||
loadConfirmacionMetadata() {
|
||||
if (!this.confirmacion) return;
|
||||
const key = JSON.stringify([this.dominio, this.confirmacion.id]);
|
||||
if (this.metadataKey === key) return;
|
||||
this.metadataKey = key;
|
||||
this.metadataSubscription?.unsubscribe();
|
||||
this.metadataSubscription = this.indicators.metadatos(this.dominio, this.confirmacion.id)
|
||||
.pipe(catchError(() => of(undefined))).subscribe(value => {
|
||||
if (this.metadataKey !== key) return;
|
||||
if (!value) this.metadataKey = '';
|
||||
this.confirmacionMetadata = value;
|
||||
this.changeDetector.markForCheck();
|
||||
});
|
||||
}
|
||||
ngOnDestroy() { this.metadataSubscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { filterCompatibility } from './indicadores-memory';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorCacuDonas } from './indicador-cacu-donas';
|
||||
import { IndicadorTiemposPareados } from './indicador-tiempos-pareados';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
@@ -24,16 +24,18 @@ import { parTiempos } from './indicadores-tiempos-pareados';
|
||||
import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
||||
import { parConteos } from './indicadores-conteos-pareados';
|
||||
|
||||
const DOBLE_ANCHO_TEA: readonly string[] = ['M28_casos_por_estado', 'M23_pacientes_evaluados'];
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-catalog-card',
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || isHistopatologia || !!tiempos || !!conteos', '[class.doble]': 'ocupaDos' },
|
||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorCacuDonas, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||
template: `
|
||||
<mat-card>
|
||||
@if (!conteos) {
|
||||
<header>
|
||||
<div class="card-identity">
|
||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||
<h2 [id]="titleId" tabindex="-1" [class.con-ayuda]="dominio === 'tea'">{{ titulo }}</h2>
|
||||
</div>
|
||||
</header>
|
||||
}
|
||||
@@ -48,7 +50,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
||||
@if (isEu7) {
|
||||
<div #visibilityRegion class="eu7-region">
|
||||
<app-indicador-eu7-escenario [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
||||
<app-indicador-cacu-donas [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" [confirmacion]="companion" [confirmacionApplied]="companionApplied" [vph]="vph" [vphApplied]="vphApplied" (metadataRequested)="loadMetadata()" />
|
||||
</div>
|
||||
} @else if (isConfirmacion) {
|
||||
<div #visibilityRegion class="confirmacion-region">
|
||||
@@ -81,12 +83,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
`,
|
||||
styles: `
|
||||
:host { display: flex; min-width: 0; margin: 0; }
|
||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
mat-card { position: relative; flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface);
|
||||
color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
header { display: grid; grid-template-columns: minmax(0, 1fr); align-items: start; gap: var(--issste-space-3); }
|
||||
.catalog-content { display: flex; flex-direction: column; flex: 1; min-width: 0; }
|
||||
.graphic-region { flex: 1; min-width: 0; }
|
||||
:host(.dual-card) { grid-column: 1 / -1; }
|
||||
:host(.doble) { grid-column: span 2; }
|
||||
.graphic-region { display: grid; grid-template-columns: minmax(0, 1fr); }
|
||||
.representation-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr); }
|
||||
.representation-panel > h3 { margin: 1rem 0 0; overflow-wrap: anywhere; }
|
||||
@@ -108,6 +111,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
||||
.card-identity { min-width: 0; }
|
||||
h2, p { overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; }
|
||||
h2.con-ayuda { padding-right: 2.5rem; }
|
||||
.pin-toggle { align-self: start; margin-top: var(--issste-space-1); max-width: 100%; height: auto;
|
||||
min-width: 48px; min-height: 48px; color: var(--issste-text); }
|
||||
.pin-toggle mat-icon { flex-shrink: 0; }
|
||||
@@ -137,7 +141,11 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
}
|
||||
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
|
||||
get sobrio() { return true; }
|
||||
// TEA's stacked case charts span two columns of its three-column grid.
|
||||
get ocupaDos() { return this.dominio === 'tea' && DOBLE_ANCHO_TEA.includes(this.indicador.id); }
|
||||
get pair() { return dualFigures(this.indicador); }
|
||||
// CaCu's first card gathers the three donuts, so it carries its own name.
|
||||
get titulo() { return this.isEu7 ? 'Resultados de citología, VPH y biopsia' : this.indicador.titulo; }
|
||||
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
|
||||
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
|
||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||
@@ -169,6 +177,12 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
// The histopathological confirmation indicator, whose biopsy donut sits on the EU7 card.
|
||||
@Input() companion?: Indicador;
|
||||
@Input() companionApplied?: GlobalApplied;
|
||||
// The HPV-by-genotype indicator, whose donut sits on the same card.
|
||||
@Input() vph?: Indicador;
|
||||
@Input() vphApplied?: GlobalApplied;
|
||||
@Input() pinned = false;
|
||||
// Draws the indicator alone even when it belongs to a connected pair.
|
||||
@Input() individual = false;
|
||||
|
||||
@@ -1,51 +1,67 @@
|
||||
<section class="confirmacion" aria-label="Confirmación histopatológica por resultado de la citología">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<section class="confirmacion" [class.vista-dona]="vista === 'dona'" [attr.aria-label]="vista === 'dona' ? 'Resultado de la biopsia' : 'Confirmación histopatológica por resultado de la citología'">
|
||||
<div class="encabezado">
|
||||
@if (mostrarFiltro) { <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) {
|
||||
@if (!permitirSeleccion && vista === 'dona') {
|
||||
<p>Cada barra muestra mujeres por grado de biopsia y su porcentaje del total con biopsia. Los encabezados reúnen los grados en grupos clínicos. Los casos sin biopsia o sin grado se informan fuera de la distribución.</p>
|
||||
} @else 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> }
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para {{ vista === 'dona' ? 'esta figura' : '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 ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando citologías y biopsias" /><p role="status">{{ vista === 'dona' ? 'Cargando resultados de biopsia…' : 'Cargando tasas de confirmación…' }}</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>
|
||||
<nav class="periods" [attr.aria-label]="vista === 'dona' ? 'Periodos del resultado de la biopsia' : 'Periodos de la confirmación histopatológica'">
|
||||
<button type="button" [attr.aria-label]="vista === 'dona' ? 'Periodo anterior del resultado de la biopsia' : 'Periodo anterior de la confirmación'" [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 la confirmación" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
<button type="button" [attr.aria-label]="vista === 'dona' ? 'Periodo siguiente del resultado de la biopsia' : '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 (permitirSeleccion) { <p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}@if (vista === 'tasas') { . {{ 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">
|
||||
@else if (permitirSeleccion) {
|
||||
<div class="legend" role="group" [attr.aria-label]="vista === 'dona' ? 'Seleccionar resultado de biopsia en la gráfica' : 'Seleccionar resultado de biopsia para las tasas'">
|
||||
<div class="tab-bar"><div class="tabs" 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>
|
||||
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" 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="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (g of m.grupos; track g.id) {
|
||||
<div class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||
@for (c of m.grados; track c.id; let i = $index) {
|
||||
@if (c.grupo === g.id) {
|
||||
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="cuerpo">
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (model; as m) {
|
||||
@if (status() !== 'empty') {
|
||||
@if (vista === 'tasas') {
|
||||
<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" />
|
||||
@@ -54,24 +70,47 @@
|
||||
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
|
||||
</ul>
|
||||
</section>
|
||||
} @else {
|
||||
<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> }
|
||||
@if (m.conBiopsia === 0) { <p role="status">Sin mujeres con biopsia en el periodo.</p> }
|
||||
@else {
|
||||
@if (m.conBiopsia === null) { <p role="status">Total no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial ni porcentajes.</p> }
|
||||
@if (barras) { <app-barras-horizontales [conjunto]="barras" [titulo]="'Resultado de la biopsia, ' + m.periodo + (permitirSeleccion ? ', selección: ' + selectionLabel : '')" /> }
|
||||
}
|
||||
@if (totales; as t) {
|
||||
<p class="aparte">Fuera de la distribución:
|
||||
@for (a of t.aparte; track a.id; let last = $last) { {{ a.etiqueta }}: {{ a.n === null ? a.estado : a.n.toLocaleString('es-MX') }}{{ last ? '.' : ';' }} }
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@if (vista === 'tasas') {
|
||||
@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 contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</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>
|
||||
</details>
|
||||
} @else if (totales; as t) {
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de resultados de biopsia" tabindex="0">
|
||||
<table><caption>Mujeres por resultado de la biopsia, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Resultado</th><th scope="col">Mujeres</th></tr></thead>
|
||||
<tbody>
|
||||
@for (g of t.grados; track g.id) { <tr><th scope="row">{{ g.etiqueta }}</th><td>{{ g.n === null ? g.estado : g.n.toLocaleString('es-MX') }}</td></tr> }
|
||||
@for (a of t.aparte; track a.id) { <tr><th scope="row">{{ a.etiqueta }}</th><td>{{ a.n === null ? a.estado : a.n.toLocaleString('es-MX') }}</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
@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 contingencia de citología y biopsia" tabindex="0">
|
||||
<table><caption>Tabla de contingencia de mujeres, {{ m.periodo }}</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>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -23,7 +23,6 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse
|
||||
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; }
|
||||
@@ -59,8 +58,20 @@ caption { text-align: start; font-weight: 600; }
|
||||
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). */
|
||||
.aparte { color: var(--issste-text-secondary); }
|
||||
@media (min-width: 1100px) {
|
||||
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
|
||||
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
|
||||
}
|
||||
|
||||
|
||||
.confirmacion:not(.histo) .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||
.confirmacion:not(.histo) .legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||
.confirmacion:not(.histo) .tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||
.confirmacion:not(.histo) .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||
.confirmacion:not(.histo) .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||
.confirmacion:not(.histo) .tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||
.confirmacion:not(.histo) .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||
.confirmacion:not(.histo) .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||
.confirmacion:not(.histo) .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||
.confirmacion:not(.histo) .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||
.confirmacion:not(.histo) .tab .swatch, .confirmacion:not(.histo) .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||
|
||||
@@ -4,20 +4,25 @@ 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 { BarrasHorizontales } from './barras-horizontales';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
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,
|
||||
import { clicConfirmacion, barrasBiopsia, ConfirmacionIncompatible, ESTRATO_CITOLOGIA, estadoTasa, figuraTasas, ID_CONFIRMACION,
|
||||
lectura, ModeloConfirmacion, modeloConfirmacion, periodosConfirmacion, SeleccionConfirmacion, seleccionBase, seleccionEtiqueta,
|
||||
Celda, tasas } from './indicadores-confirmacion-citologia';
|
||||
Celda, tasas, totalesPublicados } 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;
|
||||
// Figure of the kit whose "Cómo leer" describes each view of this indicator.
|
||||
const FIGURAS = {
|
||||
dona: [['fig_c2_donas', 'Grados de biopsia']],
|
||||
tasas: [['fig_c2_barras', 'Tasas por resultado de la citología']],
|
||||
} as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-confirmacion-citologia',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, BarrasHorizontales],
|
||||
templateUrl: './indicador-confirmacion-citologia.html',
|
||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||
})
|
||||
@@ -27,6 +32,11 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
// False when the card above already says the general filter this view follows.
|
||||
@Input() mostrarFiltro = true;
|
||||
@Input() permitirSeleccion = true;
|
||||
// The indicator has two views with their own selection: the biopsy donut and the rates by cytology.
|
||||
@Input() vista: 'dona' | 'tasas' = 'tasas';
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
@@ -35,7 +45,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloConfirmacion;
|
||||
donutFigure?: PlotlyFigure;
|
||||
barras?: ConjuntoBarras;
|
||||
ratesFigure?: PlotlyFigure;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
@@ -48,6 +58,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
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 totales() { return this.model ? totalesPublicados(this.model) : undefined; }
|
||||
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;
|
||||
@@ -55,7 +66,7 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
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]) => {
|
||||
return FIGURAS[this.vista].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);
|
||||
@@ -73,12 +84,12 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
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();
|
||||
else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) 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;
|
||||
this.barras = undefined; this.ratesFigure = undefined;
|
||||
}
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
@@ -123,17 +134,16 @@ export class IndicadorConfirmacionCitologia implements OnChanges, OnDestroy {
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || !this.selection || this.status() !== 'ready') return;
|
||||
if (!this.permitirSeleccion || !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);
|
||||
if (this.vista === 'dona') {
|
||||
const barras = barrasBiopsia(this.model, this.selection);
|
||||
this.barras = this.permitirSeleccion ? barras : { ...barras, activas: null };
|
||||
}
|
||||
else this.ratesFigure = figuraTasas(this.model, this.selection, this.tema);
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
|
||||
@@ -1,64 +1,74 @@
|
||||
<section class="eu7" aria-label="Resultados citológicos por escenario clínico">
|
||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
||||
<section class="eu7" aria-label="Resultados citológicos">
|
||||
<div class="encabezado">
|
||||
@if (mostrarFiltro) { <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) {
|
||||
@if (!permitirSeleccion) {
|
||||
<p>Cada barra muestra pacientes por resultado citológico y su porcentaje del total con resultado disponible. Los encabezados reúnen las categorías en grupos clínicos. «Sin dato» se informa fuera de la distribución.</p>
|
||||
} @else 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> }
|
||||
} @empty { <p>El servicio no publica instrucciones de lectura para esta figura.</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 resultados citológicos y escenarios" /><p role="status">Cargando el mismo periodo para dona y barras…</p> }
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando resultados citológicos" /><p role="status">Cargando resultados citológicos…</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" aria-label="Periodos de resultados citológicos">
|
||||
<button type="button" aria-label="Periodo anterior de resultados citológicos" [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 de resultados citológicos" [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 (permitirSeleccion) { <p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}</p> }
|
||||
@if (status() === 'empty') { <p role="status">No hay pacientes publicados para este periodo.</p> }
|
||||
@else {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de EU7">
|
||||
<button type="button" (click)="select('centro')" [disabled]="!selection.grupo && !selection.categoria" aria-label="Volver en la selección de EU7">Volver</button>
|
||||
<div class="keys" role="group" aria-label="Grupos del anillo interior">
|
||||
@else if (permitirSeleccion) {
|
||||
<div class="legend" role="group" aria-label="Explorar grupos y categorías de resultados citológicos">
|
||||
<div class="tab-bar"><div class="tabs" 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>
|
||||
<button type="button" class="tab" [style.--swatch]="g.color" [attr.aria-pressed]="selection.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
|
||||
}
|
||||
</div>
|
||||
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
<button type="button" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
</div></div>
|
||||
<div class="child-groups" role="group" aria-label="Categorías del anillo exterior">
|
||||
@for (g of m.grupos; track g.id) {
|
||||
<div class="tab-panel" role="group" [attr.aria-label]="g.etiqueta">
|
||||
@for (c of m.categorias; track c.id; let i = $index) {
|
||||
@if (c.grupo === g.id) {
|
||||
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection.categoria === c.id" [disabled]="!!selection.grupo && selection.grupo !== c.grupo" (click)="select('categorias', i)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<div class="figures">
|
||||
<section class="figure"><h3>Distribución de resultados, {{ m.periodo }}</h3>
|
||||
@if (m.total !== null && m.total > 0 && donutFigure) {
|
||||
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'EU7, dona de dos anillos, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
|
||||
} @else { <p role="status">{{ m.total === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado 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>
|
||||
@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" />
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<div class="cuerpo">
|
||||
@if (status() === 'ready' || status() === 'empty') {
|
||||
@if (model; as m) {
|
||||
@if (status() !== 'empty') {
|
||||
<section class="figure"><h3>Distribución de resultados citológicos, {{ m.periodo }}</h3>
|
||||
@if (m.total === 0) { <p role="status">Sin pacientes con resultado disponible.</p> }
|
||||
@else {
|
||||
@if (m.total === null) { <p role="status">Total no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial ni porcentajes.</p> }
|
||||
@if (barras) { <app-barras-horizontales [conjunto]="barras" [titulo]="'Resultados citológicos, ' + m.periodo + (permitirSeleccion ? ', selección: ' + selectionLabel : '')" /> }
|
||||
}
|
||||
<p>{{ sinDatoNote }}</p>
|
||||
</section>
|
||||
}
|
||||
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
@@ -75,4 +85,5 @@
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@use './indicadores-cacu-botones';
|
||||
:host { display: block; min-width: 0; }
|
||||
.eu7 { min-width: 0; padding-top: var(--issste-space-3); }
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
@@ -14,10 +15,8 @@ button[aria-pressed=true] { border-color: var(--issste-accent); box-shadow: inse
|
||||
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; }
|
||||
@@ -26,7 +25,6 @@ summary { cursor: pointer; padding-block: .75rem; }
|
||||
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; }
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
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';
|
||||
@@ -8,15 +7,9 @@ import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||
import { IndicadoresSnapshots } from './indicadores-snapshots';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub {
|
||||
figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>();
|
||||
plotClick = output<unknown>();
|
||||
}
|
||||
describe('EU7 integración Angular y caché compartida', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const indicador: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||
@@ -27,7 +20,6 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
let data: typeof fixtureData;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorEu7Escenario, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorEu7Escenario, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); data = structuredClone(fixtureData);
|
||||
f = TestBed.createComponent(IndicadorEu7Escenario);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', indicador);
|
||||
@@ -46,23 +38,33 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
const kpi = TestBed.inject(IndicadoresSnapshots).datos('cacu', indicador.id, 'semestre', ['2025-S2'], indicador.version).subscribe();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
flush(); expect(f.componentInstance.model!.total).toBe(946);
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => (chart.componentInstance as ChartStub).animated())).toEqual([true, true]);
|
||||
const scenarioFigure = f.nativeElement.querySelectorAll('.figure')[1] as HTMLElement;
|
||||
expect(scenarioFigure.querySelectorAll('p')).toHaveLength(1);
|
||||
expect((f.componentInstance.barsFigure!.layout['annotations'] as { text: string }[])[0].text).toBe('682');
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||
expect(f.nativeElement.querySelector('app-barras-horizontales .den').textContent).toContain('946');
|
||||
const general = data.general; const original = structuredClone(applied);
|
||||
const anormal = Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>).find(b => b.textContent!.includes('Anormal'))!;
|
||||
anormal.click(); f.detectChanges(); expect(f.componentInstance.selection.grupo).toBe('ANORMAL');
|
||||
const chart = f.debugElement.queryAll(By.directive(ChartStub))[0].componentInstance as ChartStub;
|
||||
chart.plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 4 }] }); f.detectChanges();
|
||||
f.componentInstance.select('categorias', 4); f.detectChanges();
|
||||
expect(f.componentInstance.selection.categoria).toBe('LIEAG');
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('LIEAG');
|
||||
f.componentInstance.select('centro'); f.componentInstance.select('centro'); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({});
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||
expect(applied).toEqual(original); expect(data.general).toEqual(general); http.expectNone(() => true); kpi.unsubscribe();
|
||||
});
|
||||
it('desde TOTAL, elegir un hijo activa y abre su grupo sin volver a pedir datos', () => {
|
||||
f.detectChanges(); flush();
|
||||
const button = (name: string) => Array.from(f.nativeElement.querySelectorAll('button') as NodeListOf<HTMLButtonElement>)
|
||||
.find(item => item.textContent?.trim() === name)!;
|
||||
const child = button('LIEAG'), parent = button('Anormal');
|
||||
expect(parent.getAttribute('aria-pressed')).toBe('false');
|
||||
child.click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||
expect(parent.getAttribute('aria-pressed')).toBe('true');
|
||||
expect(child.getAttribute('aria-pressed')).toBe('true');
|
||||
expect([...f.componentInstance.barras!.activas!]).toEqual(['LIEAG']);
|
||||
child.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
parent.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({});
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('dos periodos en una petición por alcance; navegación coordinada limpia selección sin GET', () => {
|
||||
const periods: [string, string] = ['2025-S1', '2025-S2'];
|
||||
for (const d of [data.general, data.estatus_seguimiento]) {
|
||||
@@ -71,15 +73,26 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
}
|
||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: periods } }); f.detectChanges(); flush();
|
||||
expect(f.componentInstance.model!.total).toBe(1892); expect(f.componentInstance.model!.escenarios[0].den).toBe(1364);
|
||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance as ChartStub);
|
||||
const barrasAntes = f.nativeElement.querySelectorAll('app-barras-horizontales')[0];
|
||||
f.componentInstance.select('grupos', 1); f.componentInstance.changePeriod(1); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({}); expect(f.componentInstance.model!.periodo).toBe('2025-S2');
|
||||
expect(f.componentInstance.model!.total).toBe(946); expect(f.componentInstance.model!.escenarios[0].den).toBe(682);
|
||||
expect(f.componentInstance.barsFigure!.layout['annotations']).toBeDefined();
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub)).map(chart => chart.componentInstance)).toEqual(charts);
|
||||
expect(charts.map(chart => chart.animated())).toEqual([true, true]);
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')[0]).toBe(barrasAntes);
|
||||
expect(f.nativeElement.querySelectorAll('h3')[0].textContent).toContain('2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('h3')[1].textContent).toContain('2025-S2'); http.expectNone(() => true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
// The card draws one donut whatever is selected: no scenario bars in any selection state, and the scenario values stay in the table.
|
||||
it('no dibuja barras por escenario en ningún estado de selección y conserva sus valores en la tabla', () => {
|
||||
f.detectChanges(); flush();
|
||||
const estados: [string, number][] = [['grupos', 1], ['categorias', 4], ['centro', 0]];
|
||||
for (const [traza, indice] of [['', 0] as [string, number], ...estados]) {
|
||||
if (traza) f.componentInstance.select(traza, indice);
|
||||
f.detectChanges();
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||
expect((f.componentInstance as unknown as { barsFigure?: unknown }).barsFigure).toBeUndefined();
|
||||
expect(f.nativeElement.textContent).not.toContain('por escenario clínico,');
|
||||
}
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de valores EU7"]').textContent).toContain('Denominador válido');
|
||||
});
|
||||
it('HTTP 500 estratificado conserva error y reintenta solo el alcance fallido', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.flush(data.general);
|
||||
@@ -99,7 +112,7 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
it('error de red permite reintento sin figuras engañosas', () => {
|
||||
f.detectChanges(); const r = requests(); r.general.error(new ProgressEvent('error')); f.detectChanges();
|
||||
expect(r.escenarios.cancelled).toBe(true); expect(f.componentInstance.status()).toBe('error');
|
||||
expect(f.componentInstance.donutFigure).toBeUndefined();
|
||||
expect(f.componentInstance.barras).toBeUndefined();
|
||||
f.componentInstance.retry(); flush(); expect(f.componentInstance.status()).toBe('ready');
|
||||
});
|
||||
it('cambio de aplicado cancela solicitudes obsoletas aun fuera del viewport', () => {
|
||||
@@ -112,12 +125,12 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
});
|
||||
it('respuesta incompatible se anuncia y nunca dibuja datos mezclados', () => {
|
||||
data.estatus_seguimiento.categorias.NORMAL.color = '#FFFFFF'; f.detectChanges(); flush();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||
});
|
||||
it('estado empty conserva navegación, notas y tabla sin dona ficticia', () => {
|
||||
data.general.filas = []; data.estatus_seguimiento.filas = []; data.estatus_seguimiento.totales_estrato = [];
|
||||
f.detectChanges(); flush(); expect(f.componentInstance.status()).toBe('empty');
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||
expect(f.nativeElement.textContent).toContain('No hay pacientes publicados');
|
||||
});
|
||||
it('tabla accesible distingue supresión y no muestra cifras marcadas como ocultas', () => {
|
||||
@@ -134,13 +147,13 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
});
|
||||
it('visibilidad y metadatos conservan referencias de figuras y selección sin renderizado nuevo', () => {
|
||||
f.detectChanges(); flush(); f.componentInstance.select('grupos', 1); f.detectChanges();
|
||||
const donut = f.componentInstance.donutFigure, bars = f.componentInstance.barsFigure;
|
||||
const barras = f.componentInstance.barras;
|
||||
f.componentRef.setInput('visible', false); f.componentRef.setInput('metadata', { descripcion: 'Descripción publicada' }); f.detectChanges();
|
||||
f.componentRef.setInput('visible', true); f.detectChanges();
|
||||
expect(f.componentInstance.donutFigure).toBe(donut); expect(f.componentInstance.barsFigure).toBe(bars);
|
||||
expect(f.componentInstance.barras).toBe(barras);
|
||||
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', () => {
|
||||
it('«Cómo leer» muestra solo la descripción y el como_leer publicados de la dona, 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;
|
||||
@@ -159,11 +172,10 @@ describe('EU7 integración Angular y caché compartida', () => {
|
||||
}); 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.map(g => g.querySelector('h3')!.textContent)).toEqual(['Distribución de resultados citológicos']);
|
||||
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('Lee las barras así.');
|
||||
for (const absent of ['Barras por escenario', '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();
|
||||
|
||||
@@ -3,21 +3,23 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { BarrasHorizontales } from './barras-horizontales';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
import { Dominio, Indicador, IndicadorMetadatos, Tema } 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 { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
import { barrasCitologia, Celda, clic, 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;
|
||||
// Only the donut is drawn; the scenario figure has no entry in the reading guide.
|
||||
const EU7_FIGURES = [['fig_c2_donas', 'Distribución de resultados citológicos']] as const;
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-eu7-escenario',
|
||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales],
|
||||
templateUrl: './indicador-eu7-escenario.html',
|
||||
styleUrl: './indicador-eu7-escenario.scss',
|
||||
})
|
||||
@@ -27,6 +29,9 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
// False when the card above already says the general filter this view follows.
|
||||
@Input() mostrarFiltro = true;
|
||||
@Input() permitirSeleccion = true;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
readonly metadataRequested = output<void>();
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
@@ -35,8 +40,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: Modelo;
|
||||
donutFigure?: PlotlyFigure;
|
||||
barsFigure?: PlotlyFigure;
|
||||
barras?: ConjuntoBarras;
|
||||
helpOpen = false;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
@@ -51,9 +55,9 @@ 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;
|
||||
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.`;
|
||||
return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la distribución.`
|
||||
: m.total === null ? `Fuera de la distribución: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la distribución no disponible.`
|
||||
: `Fuera de la distribución: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`;
|
||||
}
|
||||
get generalCells() {
|
||||
const m = this.model;
|
||||
@@ -86,18 +90,18 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
if (key !== this.key) {
|
||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
||||
this.pages = []; this.periods = []; this.model = undefined;
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.selection = {}; this.barras = 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();
|
||||
else if (this.model && (changes['tema'] || changes['permitirSeleccion'])) this.draw();
|
||||
// Visibility and metadata changes must not restart Plotly rendering.
|
||||
}
|
||||
retry() { if (this.visible) this.load(); }
|
||||
private load() {
|
||||
this.subscription?.unsubscribe();
|
||||
this.loaded = true; this.model = undefined; this.pages = []; this.periods = [];
|
||||
this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.selection = {}; this.barras = undefined;
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
@@ -125,7 +129,7 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
});
|
||||
}
|
||||
private failure(error: unknown) {
|
||||
this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined;
|
||||
this.model = undefined; this.barras = undefined;
|
||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
||||
: error instanceof Eu7Incompatible ? error.message
|
||||
: httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit'
|
||||
@@ -142,17 +146,12 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
this.periodIndex += step; this.activatePeriod();
|
||||
}
|
||||
select(trace: string, index = 0) {
|
||||
if (!this.model || this.status() !== 'ready') return;
|
||||
if (!this.permitirSeleccion || !this.model || this.status() !== 'ready') return;
|
||||
this.selection = clic(this.model, this.selection, trace, index); this.draw();
|
||||
}
|
||||
plotClicked(event: unknown) {
|
||||
const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0];
|
||||
if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber);
|
||||
}
|
||||
private draw() {
|
||||
if (!this.model) return;
|
||||
this.donutFigure = dona(this.model, this.selection, this.tema);
|
||||
this.barsFigure = barras(this.model, this.selection, this.tema);
|
||||
this.barras = barrasCitologia(this.model, this.permitirSeleccion ? this.selection : {});
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
<mat-card class="figure-card" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected) {
|
||||
<mat-card class="figure-card" [class.sin-marco]="ayudaRedonda" [class.dark]="tema === 'oscuro'" [attr.data-render-source]="state.source" [attr.aria-label]="dominio + ', ' + selected?.id + ', ' + figuraId" [attr.aria-busy]="state.status === 'loading'">
|
||||
@if (selected && ayudaRedonda) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + selected.titulo" (opened)="!metadata && metadataRequested.emit()">
|
||||
<ul class="ayuda-lista">@for (line of interpretation; track $index) { <li>{{ line }}</li> }</ul>
|
||||
@if (state.status === 'ready' && state.footnotes?.length) {
|
||||
@for (note of state.footnotes; track $index) { <p class="ayuda-nota">{{ note }}</p> }
|
||||
}
|
||||
</app-indicador-ayuda>
|
||||
} @else if (selected) {
|
||||
<section class="interpretation" [class.expanded]="methodologyExpanded()">
|
||||
<button mat-stroked-button type="button" class="methodology-toggle"
|
||||
[attr.aria-label]="'Cómo leer esta figura: ' + selected.titulo + ', ' + dominio + ', ' + figuraId"
|
||||
@@ -37,8 +44,10 @@
|
||||
@if (hasNoVisibleValues(figure)) {
|
||||
<p class="state" role="status">{{ state.emptyMessage ?? 'No hay valores visibles para la selección. No se puede determinar la causa a partir de la figura recibida.' }}</p>
|
||||
}
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
@if (!ayudaRedonda) {
|
||||
<h2 class="figure-title" [innerHTML]="figureTitle(figure, selected?.titulo ?? '')"></h2>
|
||||
<p class="figure-id">Figura: {{ figureDisplayName(figuraId, selected?.figuras ?? []) }}</p>
|
||||
}
|
||||
} @else {
|
||||
<p class="state" role="status">{{ !selected?.figuras?.length ? 'El indicador no tiene figuras disponibles.' : 'Completa una selección válida para consultar la figura.' }}</p>
|
||||
}
|
||||
@@ -84,7 +93,7 @@
|
||||
</div>
|
||||
}
|
||||
@if (state.status === 'ready' && state.highlight; as h) {
|
||||
<div class="highlight-legend" role="group" aria-label="Resaltar partes de la figura">
|
||||
<div class="highlight-legend" [class.sin-estado]="ayudaRedonda" role="group" aria-label="Resaltar partes de la figura">
|
||||
<p class="highlight-status" role="status" aria-live="polite">Selección: {{ highlightStatus }}</p>
|
||||
<button type="button" class="highlight-back" (click)="highlightBack()" [disabled]="!highlightSelection.group && !highlightSelection.item">Volver</button>
|
||||
@for (row of highlightRows(h); track row.group?.id ?? '') {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
.methodology-toggle:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
||||
.figure-card { display: grid; grid-template-rows: auto auto auto minmax(0, 1fr) auto auto;
|
||||
overflow: visible; min-width: 0; border: 1px solid var(--issste-border); }
|
||||
.figure-card.sin-marco { position: static; border: 0; box-shadow: none; background: transparent; --mat-card-outlined-outline-width: 0; --mat-card-elevated-container-elevation: none; }
|
||||
.figure-heading { grid-row: 2; min-width: 0; padding-bottom: .5rem; }
|
||||
.interpretation { grid-row: 1; }
|
||||
.figure-legend { grid-row: 3; min-width: 0; }
|
||||
@@ -117,6 +118,7 @@
|
||||
.highlight-legend { display: grid; gap: .5rem; padding: .5rem .75rem .75rem; color: var(--issste-text); }
|
||||
.dark .highlight-legend { color: #eef1f7; }
|
||||
.highlight-status { margin: 0; font-weight: 600; }
|
||||
.sin-estado .highlight-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
.highlight-back { justify-self: start; }
|
||||
.highlight-keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||
.highlight-legend button { display: inline-flex; align-items: center; gap: .4rem; min-height: 36px; padding: .3rem .75rem; text-align: start;
|
||||
@@ -126,3 +128,6 @@
|
||||
.highlight-legend button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.highlight-legend .legend-swatch { border-radius: 50%; }
|
||||
.highlight-legend .highlight-group { font-weight: 600; }
|
||||
|
||||
.ayuda-lista { margin: 0; padding-left: 1.1rem; }
|
||||
.ayuda-nota { margin: .5rem 0 0; }
|
||||
|
||||
@@ -515,4 +515,14 @@ describe('IndicadorFigureCard', () => {
|
||||
expect(JSON.stringify(original)).toBe(snapshot); expect(JSON.stringify(copy)).toBe(copySnapshot);
|
||||
});
|
||||
|
||||
it('con la ayuda redonda no repite el título ni el nombre de la figura', () => {
|
||||
// Fails if TEA's cards bring back the heading box with the title and «Figura: …» under the card's own title.
|
||||
fixture.componentRef.setInput('ayudaRedonda', true);
|
||||
ready({ data: [{ y: [1] }], layout: {} });
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('.figure-title')).toBeNull();
|
||||
expect(root.querySelector('.figure-id')).toBeNull();
|
||||
expect(root.querySelector('.ayuda-boton')).not.toBeNull();
|
||||
expect(root.querySelector('.interpretation')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +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 { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
||||
@@ -41,7 +42,7 @@ export interface FigureState {
|
||||
selector: 'app-indicador-figure-card',
|
||||
standalone: true,
|
||||
host: { '[class.methodology-expanded]': 'methodologyExpanded()' },
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatIconModule, MatCardModule, MatProgressBarModule, MatTooltipModule, PlotlyChart, IndicadorAyuda],
|
||||
templateUrl: './indicador-figure-card.html',
|
||||
styleUrl: './indicador-figure-card.scss',
|
||||
})
|
||||
@@ -142,6 +143,8 @@ export class IndicadorFigureCard implements OnChanges {
|
||||
if (point?.curveNumber === (this.activeParent ? 1 : 0) && typeof point.label === 'string') this.expandParent(point.label);
|
||||
else if (this.activeParent && point?.curveNumber === 0 && typeof point.label === 'string') this.selectCategory(point.label);
|
||||
}
|
||||
// A round "?" button with the reading guide instead of the «Cómo leer» box.
|
||||
@Input() ayudaRedonda = false;
|
||||
@Input() selected?: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
|
||||
@@ -33,6 +33,8 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture.componentRef.setInput('dominio', 'tea');
|
||||
fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1');
|
||||
// These tests cover the «Cómo leer» box shared by the domains; TEA's round help has its own spec.
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('tema', 'claro');
|
||||
state = TestBed.inject(IndicadoresMemory).restoreGlobal('tea', ['semestre']);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
@@ -373,6 +375,7 @@ describe('IndicadorFigurePanel', () => {
|
||||
fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
fixture.componentRef.setInput('dominio', 'tea'); fixture.componentRef.setInput('indicador', catalog[0]);
|
||||
fixture.componentRef.setInput('figuraId', 'f1'); fixture.componentRef.setInput('tema', 'claro');
|
||||
fixture.componentRef.setInput('ayudaRedonda', false);
|
||||
fixture.componentRef.setInput('applied', state.applied);
|
||||
page = fixture.componentInstance; load(); figure().flush({ data: [], layout: {} });
|
||||
expect(JSON.stringify(state)).toBe(snapshot);
|
||||
|
||||
@@ -23,9 +23,10 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicador-figure-panel',
|
||||
host: { '[class.ayuda-externa]': 'conAyudaRedonda' },
|
||||
imports: [IndicadorFigureCard, MatTooltipModule],
|
||||
template: `
|
||||
<section class="figure-panel" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<section class="figure-panel" [class.sin-linea]="conAyudaRedonda" [class.with-sidebar]="sidebar" [attr.aria-labelledby]="titleId">
|
||||
<h3 class="visually-hidden" [id]="titleId">{{ dominio }}, {{ indicador.id }}, {{ indicador.titulo }}, {{ figuraId }}</h3>
|
||||
@if (sidebar) {
|
||||
<aside class="strata-sidebar" aria-label="Estratificación">
|
||||
@@ -110,7 +111,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
</nav>
|
||||
}
|
||||
</header>
|
||||
<app-indicador-figure-card [state]="result()" [selected]="indicador"
|
||||
<app-indicador-figure-card [ayudaRedonda]="conAyudaRedonda" [state]="result()" [selected]="indicador"
|
||||
[metadata]="metadata" [figuraId]="figuraId" [dominio]="dominio" [tema]="tema" (metadataRequested)="metadataRequested.emit()" (hierarchySelected)="selectHierarchy($event)" (retry)="requestFigure()" (plotWidthChanged)="updatePlotWidth($event)" />
|
||||
<div class="stratified-detail">
|
||||
@if (dimension && result().status === 'ready') {
|
||||
@@ -130,6 +131,7 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
:host { display: grid; min-width: 0; }
|
||||
.figure-panel { display: grid; min-width: 0; grid-template-rows: auto minmax(0, 1fr) auto; }
|
||||
.panel-controls { min-width: 0; padding-block: var(--issste-space-3); border-top: 1px solid var(--issste-border); }
|
||||
.sin-linea .panel-controls { border-top: 0; padding-block: 0; }
|
||||
.applied-summary { margin: 0; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
|
||||
.selection-status { display: inline-flex; align-items: center; min-height: 44px; white-space: nowrap;
|
||||
font: var(--mat-sys-body-small); color: var(--issste-text-secondary); cursor: help; }
|
||||
@@ -166,6 +168,8 @@ import { MatTooltipModule } from '@angular/material/tooltip';
|
||||
/* Many stratifiers: a list beside the bars while the panel is wide, above them when it isn't. The rows stay
|
||||
shared with the neighbouring panel, so the bars line up with the donut. */
|
||||
:host { container-type: inline-size; }
|
||||
// A container is a containing block for absolute children; the round help must reach the outer card.
|
||||
:host(.ayuda-externa) { container-type: normal; }
|
||||
.figure-panel.with-sidebar { grid-template-columns: minmax(10rem, 13rem) minmax(0, 1fr); column-gap: var(--issste-space-4); }
|
||||
.with-sidebar > :not(.strata-sidebar) { grid-column: 2; }
|
||||
.strata-sidebar { grid-column: 1; grid-row: 1 / -1; align-self: start; position: sticky; top: var(--issste-header-clearance, 0);
|
||||
@@ -198,6 +202,9 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
@Input({ required: true }) indicador!: Indicador;
|
||||
@Input() metadata?: IndicadorMetadatos;
|
||||
@Input({ required: true }) figuraId!: string;
|
||||
// Round "?" help instead of the «Cómo leer» box; TEA draws it unless told otherwise.
|
||||
@Input() ayudaRedonda?: boolean;
|
||||
get conAyudaRedonda() { return this.ayudaRedonda ?? this.dominio === 'tea'; }
|
||||
@Input({ required: true }) tema!: Tema;
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@@ -290,7 +297,7 @@ export class IndicadorFigurePanel implements OnChanges {
|
||||
this.estratos = stratumOptions(data);
|
||||
const publicados = new Set(this.estratos.map(e => e.valor));
|
||||
if ([...this.ocultos].some(v => !publicados.has(v))) this.ocultos = new Set([...this.ocultos].filter(v => publicados.has(v)));
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos);
|
||||
const adapted = stratifiedBars(data, this.dimension as DimensionEstrato, data.periodos[0], this.tema, local, this.medida, this.ocultos, this.dominio);
|
||||
this.cells = adapted.cells;
|
||||
return { ...this.present(adapted.figure, { dominio: this.dominio, indicador: this.indicador.id,
|
||||
tipoPeriodo: this.applied.tipo, figura: this.figuraId, tema: this.tema, periodos: data.periodos }),
|
||||
|
||||
@@ -8,12 +8,7 @@
|
||||
}
|
||||
@if (model(); as m) {
|
||||
<div class="controls">
|
||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||
<mat-label>Periodo</mat-label>
|
||||
<mat-select [value]="m.period" (selectionChange)="selectPeriod($event.value)" aria-label="Periodo de la ruta del tamizaje">
|
||||
@for (period of m.periods; track period) { <mat-option [value]="period">{{ periodLabel(period) }}</mat-option> }
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
@if (m.period) { <p class="period">Periodo: {{ periodLabel(m.period) }}</p> }
|
||||
<mat-button-toggle-group [value]="view()" (change)="selectView($event.value)" aria-label="Vista de los tiempos">
|
||||
<mat-button-toggle value="cumulative">Acumulado desde la toma</mat-button-toggle>
|
||||
<mat-button-toggle value="steps">Por pasos</mat-button-toggle>
|
||||
@@ -22,15 +17,17 @@
|
||||
@if (status() === 'empty') { <p role="status">No hay tiempos publicados para esta ruta.</p> }
|
||||
@else if (figure(); as figure) {
|
||||
<app-plotly-chart [figure]="figure" [showNotes]="false" label="Días desde la toma de muestra hasta cada evento de la ruta del tamizaje" />
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Cada barra es la mediana de días desde la toma de muestra hasta ese evento y el bigote va de Q1 a Q3. Cada fila cuenta solo a quienes llegaron a ese evento.
|
||||
El diagnóstico incluye a quienes lo recibieron tras el tamizaje, en la colposcopía o tras la biopsia, por eso su barra puede salir antes que la de biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior y empieza donde termina el tramo previo; la de color es el tramo más lento. Cada tramo cuenta solo a quienes llegaron a sus dos eventos.
|
||||
Las medianas de los tramos no tienen que sumar el tiempo acumulado.
|
||||
}
|
||||
</p>
|
||||
<details class="how-to-read"><summary>Cómo leer</summary>
|
||||
<p class="note">
|
||||
@if (view() === 'cumulative') {
|
||||
Barra: mediana de días desde la toma hasta el evento; bigote: Q1 a Q3. Cada evento cuenta solo a quienes llegaron a él.
|
||||
El diagnóstico también se da tras el tamizaje o la colposcopía, por eso puede quedar antes que la biopsia.
|
||||
} @else {
|
||||
Cada barra es el tramo desde el evento anterior; en color, el más lento. Cuenta a quienes llegaron a sus dos eventos,
|
||||
y las medianas de los tramos no suman el acumulado.
|
||||
}
|
||||
</p>
|
||||
</details>
|
||||
}
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de tiempos de la ruta del tamizaje" tabindex="0">
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
p, h3, summary { overflow-wrap: anywhere; }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 1rem 1.5rem; align-items: center; margin-block: .75rem; }
|
||||
.how-to-read summary { cursor: pointer; color: var(--issste-text-secondary); }
|
||||
.note { color: var(--issste-text-secondary); max-width: 70ch; }
|
||||
app-plotly-chart { --plot-height: 360px; }
|
||||
summary { cursor: pointer; padding-block: .75rem; }
|
||||
|
||||
@@ -64,8 +64,10 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeUndefined();
|
||||
f.componentInstance.selectView('steps'); f.detectChanges();
|
||||
expect((f.componentInstance.figure()!.data[0] as Record<string, unknown>)['base']).toBeDefined();
|
||||
f.componentInstance.selectPeriod('2025-S1'); f.detectChanges();
|
||||
// the period follows the page's filter, with no request of its own
|
||||
f.componentRef.setInput('periodos', ['2025-S1']); f.detectChanges();
|
||||
expect(f.componentInstance.model()!.period).toBe('2025-S1');
|
||||
expect(f.nativeElement.querySelector('mat-select')).toBeNull();
|
||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
||||
expect(f.componentInstance.figure()!.layout['paper_bgcolor']).toBe('#081839');
|
||||
http.expectNone(() => true);
|
||||
@@ -79,6 +81,17 @@ describe('Ruta del tamizaje: componente', () => {
|
||||
expect(text).toContain('mediana 35.7');
|
||||
expect(text).toContain('Suprimido');
|
||||
});
|
||||
it('la lectura de la gráfica es breve y va plegada en «Cómo leer»', () => {
|
||||
// Fails if the reading note goes back to an open paragraph under the chart.
|
||||
f.detectChanges();
|
||||
responder(id => payload(id));
|
||||
const guia = f.nativeElement.querySelector('details.how-to-read') as HTMLDetailsElement;
|
||||
expect(guia.querySelector('summary')!.textContent).toBe('Cómo leer');
|
||||
expect(guia.open).toBe(false);
|
||||
expect(guia.textContent).toContain('bigote: Q1 a Q3');
|
||||
expect(f.nativeElement.querySelector('section > p.note')).toBeNull();
|
||||
});
|
||||
|
||||
it('sin ninguna caja publicada muestra estado vacío y no dibuja', () => {
|
||||
// Fails if an empty route draws a chart or hides the reason.
|
||||
f.detectChanges();
|
||||
|
||||
@@ -3,9 +3,7 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { forkJoin, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSelectModule } from '@angular/material/select';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { Dominio, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { etiquetaPeriodo } from './indicadores-historico-figures';
|
||||
@@ -16,7 +14,7 @@ import { ROUTE_IDS, RouteIncompatible, RouteView, routeCellText, routeFigure, ro
|
||||
/** Days along the screening route, from the sample to each event, as horizontal bars: cumulative or step by step. */
|
||||
@Component({
|
||||
selector: 'app-indicador-screening-route',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatProgressBarModule, PlotlyChart],
|
||||
templateUrl: './indicador-screening-route.html',
|
||||
styleUrl: './indicador-screening-route.scss',
|
||||
})
|
||||
@@ -24,17 +22,18 @@ export class IndicadorScreeningRoute {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly tipo = input<TipoPeriodo>('semestre');
|
||||
/** The periods of the page's filter: the chart shows the newest of them with data, and has no period filter of its own. */
|
||||
readonly periodos = input<readonly string[] | undefined>(undefined);
|
||||
/** The measures load once the region is visible. */
|
||||
readonly visible = input(true);
|
||||
|
||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||
readonly message = signal('');
|
||||
readonly view = signal<RouteView>('cumulative');
|
||||
readonly requestedPeriod = signal<string | undefined>(undefined);
|
||||
private readonly payloads = signal<Record<string, IndicadorDatos> | undefined>(undefined);
|
||||
readonly model = computed(() => {
|
||||
const data = this.payloads();
|
||||
return data ? routeModel(data, this.tipo(), this.requestedPeriod()) : undefined;
|
||||
return data ? routeModel(data, this.tipo(), this.periodos()) : undefined;
|
||||
});
|
||||
readonly figure = computed(() => {
|
||||
const model = this.model();
|
||||
@@ -56,7 +55,6 @@ export class IndicadorScreeningRoute {
|
||||
}
|
||||
|
||||
retry() { this.load(this.dominio(), this.tipo()); }
|
||||
selectPeriod(period: string) { this.requestedPeriod.set(period); }
|
||||
selectView(view: RouteView) { this.view.set(view); }
|
||||
|
||||
private load(dominio: Dominio, tipo: TipoPeriodo) {
|
||||
@@ -67,7 +65,7 @@ export class IndicadorScreeningRoute {
|
||||
this.subscription = forkJoin(requests).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: data => {
|
||||
try {
|
||||
const model = routeModel(data, tipo, this.requestedPeriod());
|
||||
const model = routeModel(data, tipo, this.periodos());
|
||||
this.payloads.set(data);
|
||||
this.status.set(routeHasData(model) ? 'ready' : 'empty');
|
||||
} catch (error) { this.failure(error); }
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, 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 { BarrasHorizontales } from './barras-horizontales';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
import { Dominio, Indicador, Tema } from './indicadores.models';
|
||||
import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { barrasVph, ModeloVph, modeloVph, periodosVph, porcentajeVph, VphIncompatible } from './indicadores-vph-genotipo';
|
||||
|
||||
/**
|
||||
* HPV result by genotype, on its own: no selection, no link to the cytology or biopsy donuts, its own request, states
|
||||
* and errors. Without the Measure (an older server) it says so and nothing else changes.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-indicador-vph-genotipo',
|
||||
imports: [MatButtonModule, MatProgressBarModule, BarrasHorizontales],
|
||||
template: `
|
||||
<div class="encabezado">
|
||||
@if (mostrarFiltro && indicador) { <p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p> }
|
||||
@switch (status()) {
|
||||
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando VPH por genotipo" /><p role="status">Cargando resultados de VPH…</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 (periods.length > 1 && (status() === 'ready')) {
|
||||
<nav class="periods" aria-label="Periodos de VPH por genotipo">
|
||||
<button type="button" aria-label="Periodo anterior de VPH por genotipo" [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 VPH por genotipo" [disabled]="periodIndex === periods.length - 1" (click)="changePeriod(1)">›</button>
|
||||
</nav>
|
||||
}
|
||||
</div>
|
||||
<section class="vph" aria-label="Resultados de VPH por genotipo">
|
||||
<h3>Resultados de VPH por genotipo@if (model) {, {{ model.periodo }}}</h3>
|
||||
@if (!indicador) { <p class="estado" role="status">No disponible: el servicio todavía no publica este indicador. No se muestran valores.</p> }
|
||||
@else if (status() === 'deferred') { <p class="estado" role="status">La vista se cargará al acercarse a esta región.</p> }
|
||||
@else if (model; as m) {
|
||||
@switch (m.estado) {
|
||||
@case ('ausente') { <p class="estado" role="status">Sin reporte publicado para {{ m.periodo }}.</p> }
|
||||
@case ('cero') { <p class="estado" role="status">Sin reportes de VPH elegibles en {{ m.periodo }}: no hay distribución que mostrar.</p> }
|
||||
@default {
|
||||
<app-barras-horizontales [conjunto]="barras!" [titulo]="'VPH por genotipo, ' + m.periodo" />
|
||||
}
|
||||
}
|
||||
@if (m.estado === 'datos') {
|
||||
<details class="published-values"><summary>Valores publicados</summary>
|
||||
<div class="table-scroll" role="region" aria-label="Tabla de VPH por genotipo" tabindex="0">
|
||||
<table><caption>Reportes de VPH por categoría, {{ m.periodo }}</caption>
|
||||
<thead><tr><th scope="col">Categoría</th><th scope="col">Reportes</th><th scope="col">Porcentaje</th></tr></thead>
|
||||
<tbody>@for (c of m.categorias; track c.id) { <tr><th scope="row">{{ c.etiqueta }}</th><td>{{ c.n.toLocaleString('es-MX') }}</td><td>{{ pct(c.n, m.total!) }}</td></tr> }</tbody>
|
||||
<tfoot><tr><th scope="row">Total de reportes</th><td>{{ m.total!.toLocaleString('es-MX') }}</td><td></td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
`,
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
.vph { min-width: 0; border-top: 1px solid var(--issste-border); }
|
||||
.encabezado { padding-top: var(--issste-space-3); }
|
||||
h3 { font-size: 1rem; line-height: 1.5; }
|
||||
h3, p, summary, li { overflow-wrap: anywhere; }
|
||||
.applied-summary, .nota { color: var(--issste-text-secondary); }
|
||||
.estado { display: flex; align-items: center; justify-content: center; box-sizing: border-box; margin: 0; padding: 1rem; text-align: center;
|
||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); color: var(--issste-text-secondary); }
|
||||
.periods { display: flex; align-items: center; justify-content: center; gap: .75rem; }
|
||||
button { min-height: 44px; padding: .5rem .8rem; border: 1px solid var(--issste-border); border-radius: 999px; color: var(--issste-text); background: var(--issste-surface); font: inherit; cursor: pointer; }
|
||||
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; }
|
||||
.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; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorVphGenotipo implements OnChanges, OnDestroy {
|
||||
@Input() dominio: Dominio = 'cacu';
|
||||
/** The published indicator; absent when the server does not publish the Measure. */
|
||||
@Input() indicador?: Indicador;
|
||||
@Input() tema: Tema = 'claro';
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() visible = true;
|
||||
@Input() mostrarFiltro = true;
|
||||
readonly status = signal<'idle' | 'deferred' | 'loading' | 'ready' | 'error' | 'incompatible'>('idle');
|
||||
message = '';
|
||||
periods: string[] = [];
|
||||
periodIndex = 0;
|
||||
model?: ModeloVph;
|
||||
barras?: ConjuntoBarras;
|
||||
readonly pct = porcentajeVph;
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||
private subscription?: Subscription;
|
||||
private key = '';
|
||||
private loaded = false;
|
||||
private pages: ModeloVph[] = [];
|
||||
get appliedSummary() { return this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : ''; }
|
||||
|
||||
ngOnChanges(changes: SimpleChanges) {
|
||||
if (!this.indicador || !this.applied) { this.subscription?.unsubscribe(); this.clear(); this.key = ''; this.status.set('idle'); return; }
|
||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||
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.barras = undefined; }
|
||||
private load() {
|
||||
const indicador = this.indicador!, applied = this.applied!;
|
||||
this.subscription?.unsubscribe(); this.loaded = true; this.clear();
|
||||
const compatibility = filterCompatibility(applied, indicador.tipos_periodo);
|
||||
if (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, periods = applied.selection.mode === 'explicit' ? [...applied.selection.periodos] : undefined;
|
||||
this.status.set('loading');
|
||||
this.subscription = this.snapshots.datos(this.dominio, indicador.id, applied.tipo, periods, indicador.version).pipe(timeout({ first: 40000 })).subscribe({
|
||||
next: datos => {
|
||||
if (key !== this.key) return;
|
||||
try {
|
||||
this.periods = periodosVph(datos, applied.tipo, periods);
|
||||
this.pages = this.periods.map(p => modeloVph(datos, p));
|
||||
this.periodIndex = this.periods.length ? this.periods.length - 1 : 0; this.activate();
|
||||
} 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 VphIncompatible ? error.message
|
||||
: httpMessage(error);
|
||||
this.status.set(error instanceof VphIncompatible || (error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)) ? 'incompatible' : 'error');
|
||||
this.changeDetector.markForCheck();
|
||||
}
|
||||
private activate() { this.model = this.pages[this.periodIndex]; this.draw(); this.status.set('ready'); this.changeDetector.markForCheck(); }
|
||||
changePeriod(step: number) {
|
||||
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
|
||||
this.periodIndex += step; this.activate();
|
||||
}
|
||||
private draw() { this.barras = this.model?.estado === 'datos' ? barrasVph(this.model) : undefined; this.changeDetector.markForCheck(); }
|
||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Data shape of the horizontal bars that show the CaCu results (cytology, HPV by genotype, biopsy): one bar per
|
||||
// category, optional clinical groups as headers with their subtotal, absolute counts as the scale and the
|
||||
// percentage of the published denominator beside each count. A group is a header, not a category of the distribution.
|
||||
export type EstadoCelda = 'Publicado' | 'Suprimido' | 'No disponible';
|
||||
export interface FilaBarra { id: string; etiqueta: string; n: number | null; estado: EstadoCelda; color: string; }
|
||||
export interface GrupoBarras {
|
||||
/** Null for a flat distribution (HPV): no header. */
|
||||
id: string | null; etiqueta: string | null; color: string;
|
||||
/** Sum of its categories; null when any of them is unknown. */
|
||||
subtotal: number | null; filas: FilaBarra[];
|
||||
}
|
||||
export interface ConjuntoBarras {
|
||||
grupos: GrupoBarras[];
|
||||
/** The published denominator the percentages use; null when it is not available. */
|
||||
den: number | null;
|
||||
/** What the denominator counts: «pacientes con resultado», «reportes de VPH elegibles»… */
|
||||
unidad: string;
|
||||
/** The ids of the categories the selection highlights; null when nothing is selected. */
|
||||
activas: ReadonlySet<string> | null;
|
||||
}
|
||||
|
||||
const BASES = [2, 4, 6, 8, 10, 12, 16, 20, 24, 30, 40, 50, 60, 80, 100];
|
||||
/** The upper limit of the count scale: the smallest round, even number that holds the largest bar or subtotal. */
|
||||
export function limiteEscala(maximo: number): number {
|
||||
if (!(maximo > 0)) return 2;
|
||||
for (let potencia = 1; ; potencia *= 10) for (const base of BASES) if (base * potencia / 10 >= maximo && Number.isInteger(base * potencia / 10 / 2)) return base * potencia / 10;
|
||||
}
|
||||
export function maximoDelConjunto(c: ConjuntoBarras): number {
|
||||
return Math.max(0, ...c.grupos.flatMap(g => [g.subtotal ?? 0, ...g.filas.map(f => f.n ?? 0)]));
|
||||
}
|
||||
/** Sum of the categories the selection highlights, or null when there is no selection or any of them is unknown. */
|
||||
export function sumaActivas(c: ConjuntoBarras): number | null {
|
||||
if (!c.activas) return null;
|
||||
const filas = c.grupos.flatMap(g => g.filas).filter(f => c.activas!.has(f.id));
|
||||
return filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0);
|
||||
}
|
||||
@@ -59,8 +59,8 @@ describe('Dona de dos anillos para C1', () => {
|
||||
expect(result.highlight.items.map(i => i.label)).toEqual(['16 a 23 meses', '24 a 29 meses', '30 a 36 meses']);
|
||||
expect(result.highlight.items[0].center).toBe('<b>34.8 %</b><br>16 a 23 meses');
|
||||
});
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, sin verde ni rojo', () => {
|
||||
const colores = ['#2F6DB3', '#E0A526', '#A23E8C'];
|
||||
it('cada grupo de edad tiene el mismo color en la dona de M21 y las barras de M22, tomado de la paleta compartida', () => {
|
||||
const colores = ['#A8C243', '#42C29C', '#9C42C2'];
|
||||
const dona = c1DonutFigure(datos(), { ...selection, figura: 'fig_c1_dona_edad' });
|
||||
if (dona.status !== 'supported') throw new Error('sin figura');
|
||||
expect((dona.figure.data[0] as { marker: { colors: string[] } }).marker.colors).toEqual(colores);
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
|
||||
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Color, C2_PALETTE, recolorFigure, seriesColors } from './indicadores-c2-palette';
|
||||
import { c2Fixture } from './indicadores-c2-adapter.testing';
|
||||
import { FigureSelection } from './indicadores.models';
|
||||
import { FigureSelection, IndicadorDatos } from './indicadores.models';
|
||||
import { donutFixture } from './indicadores-donut-drilldown.testing';
|
||||
import { donutLegend, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||
import { figurePresentation } from './indicadores.presentation';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { stratifiedBars } from './indicadores-stratified';
|
||||
|
||||
const selection: FigureSelection = { dominio: 'tea', indicador: 'i1', figura: 'fig_c2_donas', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] };
|
||||
function supported(data = c2Fixture(), s = selection) {
|
||||
@@ -13,6 +15,32 @@ function supported(data = c2Fixture(), s = selection) {
|
||||
return result;
|
||||
}
|
||||
describe('C2: datos publicados a Plotly', () => {
|
||||
it('comparte el color de LIEBG entre dona, barras, estratos e histórico solo para CaCu', () => {
|
||||
const data: IndicadorDatos = { ...c2Fixture(), id: 'cacu_eu7' };
|
||||
const original = data['categorias'] as Record<string, object>;
|
||||
data['categorias'] = { LIEBG: { ...original['A'], color: '#E8C28E' }, B: original['B'], C: original['C'] };
|
||||
data.filas[0]['categoria'] = 'LIEBG';
|
||||
const cacu = { ...selection, dominio: 'cacu' as const, indicador: data.id };
|
||||
const pie = supported(data, cacu).figure;
|
||||
const bars = supported(data, { ...cacu, figura: 'fig_c2_barras' }).figure;
|
||||
const history = historicoFigura(data, 'claro').figure;
|
||||
const stratum = { ...data, estrato: 'grupo_edad', valores_estrato: ['estrato'], etiquetas_estrato: { estrato: 'Estrato' },
|
||||
filas: data.filas.map(row => ({ ...row, estrato: 'estrato' as const })) };
|
||||
const chart = (domain: 'cacu' | 'tea' | 'cama') => stratifiedBars(stratum, 'grupo_edad', '2025-S2', 'claro', {}, 'conteo', new Set(), domain);
|
||||
expect(pie.data[0]['marker']).toMatchObject({ colors: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(bars.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(history.data[0]['marker']).toMatchObject({ color: '#AD8F20' });
|
||||
expect(chart('cacu').figure.data[0]['marker']).toMatchObject({ color: expect.arrayContaining(['#AD8F20']) });
|
||||
expect(chart('cacu').figure.data[0]['marker']).not.toHaveProperty('pattern');
|
||||
expect(chart('cacu').cells).toEqual(chart('tea').cells);
|
||||
for (const domain of ['tea', 'cama'] as const) {
|
||||
expect(chart(domain).figure.data[0]['marker']).toHaveProperty('pattern.shape', '');
|
||||
expect(chart(domain).figure.data[0]['marker']).toMatchObject({ color: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||
expect(supported(data, { ...selection, indicador: data.id, dominio: domain }).figure.data[0]['marker']).toMatchObject({ colors: [C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]] });
|
||||
}
|
||||
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bars)).toBe(bars);
|
||||
expect(recolorFigure(history)).toBe(history);
|
||||
});
|
||||
it('equivale a los dos anillos publicados: valores, orden, relaciones, periodo y total', () => {
|
||||
const data = c2Fixture(), before = structuredClone(data), result = supported(data), server = donutFixture().figure;
|
||||
expect(result.figure.data.map(t => [t['labels'], t['values'], t['name']])).toEqual(server.data.map(t => [t['labels'], t['values'], t['name']]));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
||||
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor, cacuGroupColor } from './indicadores-cacu-palette';
|
||||
|
||||
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
||||
@@ -81,8 +82,13 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
|
||||
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
|
||||
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
|
||||
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||
const isCaCu = selection.dominio === 'cacu';
|
||||
const defaults = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
|
||||
const cacuColors = isCaCu ? categories.map(c => cacuCategoryColor(c.id)) : [];
|
||||
const colors = defaults.map((color, i) => cacuColors[i] ?? color);
|
||||
const bases = basesPorGrupo(parentIds);
|
||||
const groupColors = parentIds.map(id => (isCaCu ? cacuGroupColor(id) : undefined) ?? bases.get(id) ?? C2_PALETTE.series[0]);
|
||||
const edge = cacuColors.some(Boolean) ? { color: theme.background, width: 1.5 } : { color: theme.outline, width: 0.7 };
|
||||
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
|
||||
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
|
||||
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
|
||||
@@ -94,7 +100,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
const figure: PlotlyFigure = { data: [], layout };
|
||||
if (selection.figura === 'fig_c2_barras') {
|
||||
if (rows.length) figure.data = [{ type: 'bar', orientation: 'h', name: period, x: values, y: labels,
|
||||
marker: { color: colors, line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { color: colors, line: edge },
|
||||
hovertemplate: '%{y}<br>%{x} ' + model.unit + '<extra></extra>' }];
|
||||
layout['xaxis'] = { title: { text: 'Conteo (' + model.unit + ')' }, rangemode: 'tozero', showgrid: true,
|
||||
gridcolor: theme.grid, zeroline: false, tickformat: ',d', showline: true, linecolor: '#AEB7C2', linewidth: 1,
|
||||
@@ -105,12 +111,12 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
|
||||
} else if (total > 0) {
|
||||
layout['annotations'] = [{ x: 0.5, y: 0.5, xref: 'paper', yref: 'paper', showarrow: false,
|
||||
text: '<b>' + total + '</b>', font: { color: theme.text, size: 18 } }];
|
||||
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: { color: theme.outline, width: 0.7 } },
|
||||
figure.data = [{ type: 'pie', labels, values, marker: { colors, line: edge },
|
||||
hole: 0.62, sort: false, name: period, textinfo: 'none', legendgroup: 'categorias', domain: { x: [0, 0.72], y: [0, 1] },
|
||||
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
|
||||
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
|
||||
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
|
||||
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
|
||||
marker: { colors: groupColors, line: edge },
|
||||
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
|
||||
}
|
||||
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
|
||||
|
||||
@@ -13,8 +13,8 @@ export const C2_PALETTE = Object.freeze({
|
||||
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||
]),
|
||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
||||
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
|
||||
// Age groups of the EEG indicators (M21, M22): the same lime, teal and purple the other domains' series use.
|
||||
edades: Object.freeze(['#A8C243', '#42C29C', '#9C42C2']),
|
||||
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
|
||||
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
|
||||
claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }),
|
||||
|
||||
@@ -20,7 +20,7 @@ describe('estrategia C2 /datos y respaldo /figuras', () => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorFigurePanel], providers: [provideHttpClient(),provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(IndicadorFigurePanel);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied })) fixture.componentRef.setInput(name,value);
|
||||
for (const [name,value] of Object.entries({ dominio: 'tea', indicador: item, figuraId: 'fig_c2_donas', tema: 'claro', applied, ayudaRedonda: false })) fixture.componentRef.setInput(name,value);
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); });
|
||||
const dataRequest = () => http.expectOne(r => r.url.endsWith('/datos'));
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
|
||||
.legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
|
||||
.legend > button { align-self: flex-start; margin-bottom: .4rem; }
|
||||
.tab-bar { display: flex; align-items: flex-end; border-bottom: 1px solid var(--issste-border); }
|
||||
.tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
|
||||
.tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
|
||||
.tabs .tab[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
|
||||
.child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
|
||||
.tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
|
||||
.tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); text-align: start; overflow-wrap: anywhere; }
|
||||
.tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); box-shadow: inset 0 0 0 1px var(--swatch); }
|
||||
.tab .swatch, .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
|
||||
@@ -67,6 +67,19 @@ describe('Identificadores de CaCu entre FHIR y la página', () => {
|
||||
});
|
||||
|
||||
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
|
||||
it('rechaza una categoría EU7 publicada que no figura en la Measure, sin descartar su conteo', () => {
|
||||
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
|
||||
const cod = (value: string) => ({ coding: [{ code: value }] });
|
||||
const report = { resourceType: 'MeasureReport', period: { start: '2025-01-01', end: '2025-06-30' }, group: [{
|
||||
code: cod('TOTAL'), population: [{ code: cod('initial-population'), count: 2 }],
|
||||
stratifier: [{ code: [cod('estatus_seguimiento'), cod('resultado')], stratum: [{
|
||||
component: [{ code: cod('estatus_seguimiento'), value: cod('PRE_COLPOSCOPIA') },
|
||||
{ code: cod('resultado'), value: cod('NEGATIVO') }], population: [{ count: 2 }],
|
||||
}] }],
|
||||
}] } as unknown as Report;
|
||||
expect(() => datosDeReportes(measure, [report], 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrow('Categoría no declarada en el estrato');
|
||||
});
|
||||
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
|
||||
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
|
||||
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
|
||||
@@ -107,13 +120,14 @@ const reporteDe = (m: Measure, conteos: number[]): Report => ({
|
||||
|
||||
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
|
||||
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
|
||||
// Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none
|
||||
// Pins down: C2 measures offer the donut and the bars, the C3r the box plot, and the C1 and the risk bands none
|
||||
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
|
||||
// checked against the renderer.
|
||||
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
|
||||
expect(figuras).toEqual({
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_diagnostico_tratamiento: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
|
||||
cacu_dias_toma_tratamiento: ['fig_c3r_caja'], cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
|
||||
cacu_riesgo_banda: [], ind1: [],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,5 +18,6 @@ export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
|
||||
'CACU-VPH-GENOTIPO': 'cacu_vph_genotipo',
|
||||
'IND1': 'ind1',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { isCoffeeColor } from './indicadores-c2-palette';
|
||||
|
||||
// Exact codes from the CaCu catalog. Cytology and biopsy keep their own groups.
|
||||
// The ochre sits outside the coffee range that the shared Plotly renderer recolors.
|
||||
const CATEGORY_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||
NORMAL: '#438B53',
|
||||
'ASC-US': '#2879BD',
|
||||
LIEBG: '#AD8F20',
|
||||
'ASC-H': '#7959B8',
|
||||
LIEAG: '#D14D78',
|
||||
CIS: '#AE4050',
|
||||
CARCINOMA: '#925078',
|
||||
SIN_DATO: '#C9CDD2',
|
||||
SIN_BIOPSIA: '#C9CDD2',
|
||||
// HPV by genotype: outside the coffee hues, apart from the cytology and biopsy colours; unknown and inconsistent stay grey.
|
||||
NEGATIVO: '#5F9EA0',
|
||||
POSITIVO_16: '#3E6FB0',
|
||||
POSITIVO_18: '#7B5EA7',
|
||||
POSITIVO_16_18: '#B0457A',
|
||||
POSITIVO_SIN_16_18: '#4F7942',
|
||||
POSITIVO_INCOMPLETO: '#9A9A2F',
|
||||
INDETERMINADO: '#8A9199',
|
||||
INCONSISTENTE: '#C9CDD2',
|
||||
});
|
||||
|
||||
const GROUP_COLORS: Readonly<Record<string, string>> = Object.freeze({
|
||||
NO_ANORMAL: '#247A71',
|
||||
ANORMAL: '#656677',
|
||||
SIN_DATO: '#C9CDD2',
|
||||
});
|
||||
|
||||
export function cacuCategoryColor(id: string): string | undefined {
|
||||
return Object.hasOwn(CATEGORY_COLORS, id) ? CATEGORY_COLORS[id] : undefined;
|
||||
}
|
||||
|
||||
export function cacuGroupColor(id: string): string | undefined {
|
||||
return Object.hasOwn(GROUP_COLORS, id) ? GROUP_COLORS[id] : undefined;
|
||||
}
|
||||
|
||||
export function cacuClinicalColor(id: string, published: string | null): string {
|
||||
// A new catalog code can keep a valid published color when the renderer can keep it too.
|
||||
return cacuCategoryColor(id) ?? (published && !isCoffeeColor(published) ? published : '#8A9199');
|
||||
}
|
||||
|
||||
|
||||
export function cacuRgba(hex: string, alpha: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alpha})`;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
// Covers how the Indicadores tab arranges CaCu's figures: the five times of «Tiempo de tamizaje a diagnóstico» under
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures with the
|
||||
// pending «Progresión por grupo de riesgo». Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
// «Indicadores de oportunidad» (pending where the catalog publishes nothing) and the clinical figures. Fixtures: a CaCu catalog shaped like /cacu/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
@@ -40,31 +39,24 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las cinco figuras conservan su orden y las ausentes quedan como pendientes', () => {
|
||||
it('las figuras disponibles conservan su orden sin reservas vacías', () => {
|
||||
// Fails if a time figure changes place, if a missing indicator is drawn as a figure or if the published ones lose
|
||||
// the names of the request.
|
||||
abrir(CACU);
|
||||
expect(root().querySelector('.subsection-title')?.textContent).toBe('Tiempo de tamizaje a diagnóstico');
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
});
|
||||
|
||||
it('con la ruta del tamizaje la gráfica dibuja colposcopía y biopsia y no hay una segunda tarjeta ni una pendiente', () => {
|
||||
// Fails if the measures only the route chart draws get a card (or a «pendiente» slot) next to it, which the route
|
||||
// chart's own page spec forbids.
|
||||
it('con la ruta del tamizaje no hay subsección «Tiempo de tamizaje a diagnóstico»: la gráfica dibuja los tiempos', () => {
|
||||
// Fails if the times the route chart draws also get a figure or a «pendiente» slot of their own next to it.
|
||||
abrir([...CACU, ...RUTA]);
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
expect(root().querySelector('.subsection-title')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([]);
|
||||
expect(root().querySelector('app-indicador-screening-route')).not.toBeNull();
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica',
|
||||
'figura-pendiente: Progresión por grupo de riesgo']);
|
||||
'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
});
|
||||
|
||||
it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => {
|
||||
@@ -73,7 +65,6 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(root().querySelector('app-indicador-screening-route')).toBeNull();
|
||||
expect(titulos('.kpi-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de citología',
|
||||
'figura-pendiente: Tiempo de toma de muestra a resultado de VPH',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de colposcopía',
|
||||
'catalog-card: Tiempo de toma de muestra a resultado de biopsia',
|
||||
'catalog-card: Tiempo de toma de muestra a diagnóstico']);
|
||||
@@ -87,14 +78,13 @@ describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () =
|
||||
expect(titulosKpi).not.toContain('Días de toma a resultado');
|
||||
});
|
||||
|
||||
it('los indicadores clínicos son los dos pedidos más «Progresión por grupo de riesgo» pendiente, sin tarjetas vacías', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card or if the pending
|
||||
// figure is not drawn as such.
|
||||
it('los indicadores clínicos son los dos pedidos, sin tarjetas vacías ni figuras pendientes', () => {
|
||||
// Fails if the time figures stay in the clinical section, if indicators with no figure get a card, or if a pending
|
||||
// figure («Progresión por grupo de riesgo», withdrawn) comes back.
|
||||
abrir(CACU);
|
||||
expect(titulos('.graphic-section .catalog-grid')).toEqual([
|
||||
'catalog-card: Distribución de resultados citológicos', 'catalog-card: Tasa de confirmación histopatológica',
|
||||
'figura-pendiente: Progresión por grupo de riesgo']);
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')?.textContent).toContain('Integración pendiente');
|
||||
'catalog-card: Resultados de citología, VPH y biopsia', 'catalog-card: Tasa de confirmación histopatológica']);
|
||||
expect(root().querySelector('.graphic-section app-indicador-figura-pendiente')).toBeNull();
|
||||
});
|
||||
|
||||
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||
|
||||
@@ -70,7 +70,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||
open('cama', CAMA);
|
||||
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||
expect(nombres).toContain('Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6');
|
||||
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||
});
|
||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
||||
|
||||
@@ -3,17 +3,21 @@ 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 eu7Fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { IndicadorCacuDonas } from './indicador-cacu-donas';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
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 { recolorFigure } from './indicadores-c2-palette';
|
||||
import { clicConfirmacion, ConfirmacionIncompatible, donaConfirmacion, estadoTasa, figuraTasas, lectura, modeloConfirmacion,
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, wilson } from './indicadores-confirmacion-citologia';
|
||||
periodosConfirmacion, rangoTasas, seleccionBase, tasas, totalesPublicados, 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>(); }
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = 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
|
||||
@@ -128,7 +132,16 @@ describe('Confirmación histopatológica: modelo', () => {
|
||||
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\)$/);
|
||||
expect((otra.data[2]['marker'] as { colors: string[] }).colors[2]).toMatch(/,0\.45\)$/);
|
||||
});
|
||||
it('el carcinoma conserva el color del marcador, intervalo y dona al seleccionar', () => {
|
||||
const m = modeloConfirmacion(respuesta(), '2026-S2');
|
||||
const sel = { grupo: 'ANORMAL', categoria: 'CARCINOMA' };
|
||||
const tasa = figuraTasas(m, sel, 'oscuro'), pie = donaConfirmacion(m, sel, 'oscuro');
|
||||
expect(tasa.data[0]).toMatchObject({ marker: { color: '#925078' }, error_x: { color: '#925078' } });
|
||||
const i = m.grados.findIndex(g => g.id === 'CARCINOMA');
|
||||
expect((pie.data[2]['marker'] as { colors: string[] }).colors[i]).toBe('rgba(146,80,120,1)');
|
||||
expect(recolorFigure(tasa)).toBe(tasa); expect(recolorFigure(pie)).toBe(pie);
|
||||
});
|
||||
it('rechaza otro indicador, otro estrato, periodos no solicitados o filas duplicadas', () => {
|
||||
expect(() => periodosConfirmacion({ ...respuesta(), id: 'cacu_eu7' }, 'semestre')).toThrow(ConfirmacionIncompatible);
|
||||
@@ -160,21 +173,22 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
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', () => {
|
||||
it('carga diferida, solo las tasas (la dona vive en otra tarjeta), 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;
|
||||
const figures = [...f.nativeElement.querySelectorAll('.figure')] as HTMLElement[];
|
||||
expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas']);
|
||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
|
||||
expect(f.componentInstance.barras).toBeUndefined();
|
||||
const normal = [...f.nativeElement.querySelectorAll('.legend .child, .legend .tab')].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();
|
||||
([...f.nativeElement.querySelectorAll('.legend .tab')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === 'LIEAG o más')!.click(); 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']);
|
||||
@@ -195,7 +209,7 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
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', () => {
|
||||
it('«Cómo leer» de las tasas muestra solo descripción y como_leer de 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();
|
||||
@@ -206,8 +220,8 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
{ 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);
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']);
|
||||
for (const absent of ['Lee la dona.', '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();
|
||||
@@ -223,3 +237,162 @@ describe('Confirmación histopatológica: componente', () => {
|
||||
card.destroy(); http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Confirmación histopatológica: vista de la dona de biopsia', () => {
|
||||
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], 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('vista', 'dona');
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const flush = (body: IndicadorDatos = respuesta(['2026-S1', '2026-S2'])) => {
|
||||
http.expectOne(req => req.url.endsWith('/datos')).flush(body as Record<string, unknown>); f.detectChanges();
|
||||
};
|
||||
const apartado = () => (f.nativeElement.querySelector('.aparte').textContent as string).replace(/\s+/g, ' ');
|
||||
// Why: the donut moved to the first card; it must draw only itself, answer its own buttons and keep what it leaves out.
|
||||
it('dibuja solo las barras de la biopsia, responde a sus botones y dice qué queda fuera de la distribución', () => {
|
||||
f.detectChanges(); flush();
|
||||
expect(f.componentInstance.ratesFigure).toBeUndefined();
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1); expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||
// Two group headers with their subtotals; the six grades are the bars (a group is not a category).
|
||||
const grupos = [...f.nativeElement.querySelectorAll('.grupo .cabecera')] as HTMLElement[];
|
||||
expect(grupos.map(g => g.textContent!.replace(/\s+/g, ' ').trim())).toEqual(['Grupo Menor que LIEAG 45 41.7 %', 'Grupo LIEAG o más 63 58.3 %']);
|
||||
expect([...f.nativeElement.querySelectorAll('.filas .fila')].map((x: Element) => x.textContent!.replace(/\s+/g, ' ').trim())).toEqual([
|
||||
'NORMAL 22 20.4 %', 'LIEBG 22 20.4 %', 'CIN2 1 0.9 %', 'LIEAG 44 40.7 %', 'Carcinoma in situ 13 12.0 %', 'CARCINOMA 6 5.6 %']);
|
||||
const button = (name: string) => ([...f.nativeElement.querySelectorAll('.legend button')] as HTMLButtonElement[]).find(b => b.textContent!.trim() === name)!;
|
||||
button('NORMAL').click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
expect(f.nativeElement.querySelector('.selection-status').textContent).not.toContain('Falsos positivos');
|
||||
button('LIEAG o más').click(); f.detectChanges();
|
||||
expect(f.componentInstance.selection).toEqual({ grupo: 'ANORMAL' });
|
||||
expect(f.nativeElement.querySelector('.seleccion').textContent.replace(/\s+/g, ' ')).toContain('Selección: 63 de 108 (58.3 %)');
|
||||
expect(apartado()).toContain('Sin biopsia aún: 53; Sin dato: 6.');
|
||||
expect(f.nativeElement.querySelector('[aria-label="Tabla de resultados de biopsia"]').textContent).toContain('Sin biopsia aún');
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('«Cómo leer» muestra solo la guía de la figura de biopsia', () => {
|
||||
f.componentRef.setInput('metadata', { figuras_detalle: [
|
||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] },
|
||||
{ figura: 'fig_c2_donas', descripcion: null, como_leer: ['Lee la dona.'] }] });
|
||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
||||
const help = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
||||
expect([...help.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee la dona.']);
|
||||
});
|
||||
it('una celda fuera de la dona suprimida se dice «Suprimido» y no se convierte en cero', () => {
|
||||
const datos = respuesta(['2026-S1', '2026-S2']);
|
||||
Object.assign(datos.filas.find(r => r['periodo'] === '2026-S2' && r['estrato'] === 'LIEAG' && r['categoria'] === 'SIN_BIOPSIA')!, { n: 987654, suprimido: 1 });
|
||||
f.detectChanges(); flush(datos);
|
||||
expect(apartado()).toContain('Sin biopsia aún: Suprimido'); expect(apartado()).not.toContain('987654');
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||
});
|
||||
it('totalesPublicados suma por grado y deja desconocido lo suprimido', () => {
|
||||
const t = totalesPublicados(modeloConfirmacion(respuesta(['2026-S2']), '2026-S2'));
|
||||
expect(t.grados.map(g => [g.id, g.n])).toEqual([['NORMAL', 22], ['LIEBG', 22], ['LIEAG', 44], ['CIS', 13], ['CARCINOMA', 6], ['CIN2', 1]]);
|
||||
expect(t.aparte.map(a => [a.id, a.n, a.estado])).toEqual([['SIN_BIOPSIA', 53, 'Publicado'], ['SIN_DATO', 6, 'Publicado']]);
|
||||
const datos = respuesta(['2026-S2']);
|
||||
Object.assign(datos.filas.find(r => r['estrato'] === 'CIS' && r['categoria'] === 'SIN_DATO')!, { suprimido: 1 });
|
||||
const s = totalesPublicados(modeloConfirmacion(datos, '2026-S2'));
|
||||
expect(s.aparte.find(a => a.id === 'SIN_DATO')).toMatchObject({ n: null, estado: 'Suprimido' });
|
||||
expect(s.aparte.find(a => a.id === 'SIN_BIOPSIA')!.n).toBe(53);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tres donas de CaCu: independencia y reparto de solicitudes', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const eu7: Indicador = { id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', version: '0.3.0',
|
||||
figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
|
||||
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus de seguimiento', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
|
||||
const confirmacion: 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'] };
|
||||
let http: HttpTestingController;
|
||||
let f: ReturnType<typeof TestBed.createComponent<IndicadorCacuDonas>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCacuDonas], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const component of [IndicadorEu7Escenario, IndicadorConfirmacionCitologia])
|
||||
TestBed.overrideComponent(component, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
f = TestBed.createComponent(IndicadorCacuDonas);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', eu7);
|
||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
f.componentRef.setInput('confirmacion', confirmacion); f.componentRef.setInput('confirmacionApplied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const eu7Requests = () => ({
|
||||
general: http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')),
|
||||
escenarios: http.expectOne(r => r.url.includes('/cacu_eu7/') && r.params.get('estrato') === 'estatus_seguimiento'),
|
||||
});
|
||||
const biopsia = () => http.expectOne(r => r.url.includes('/cacu_confirmacion_citologia/'));
|
||||
const eu7Component = () => f.debugElement.query(By.directive(IndicadorEu7Escenario)).componentInstance as IndicadorEu7Escenario;
|
||||
const biopsiaComponent = () => f.debugElement.query(By.directive(IndicadorConfirmacionCitologia)).componentInstance as IndicadorConfirmacionCitologia;
|
||||
it('muestra las distribuciones completas sin controles ni atenuación en la tarjeta', () => {
|
||||
f.detectChanges();
|
||||
const e = eu7Requests(); const b = biopsia();
|
||||
e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento));
|
||||
b.flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges();
|
||||
expect([...f.nativeElement.querySelectorAll('h3')].map((h: HTMLElement) => h.textContent!.replace(/, 2025-S2$/, ''))).toEqual([
|
||||
'Distribución de resultados citológicos', 'Resultados de VPH por genotipo', 'Resultado de la biopsia']);
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2);
|
||||
expect(f.nativeElement.querySelectorAll('.legend button, .selection-status, .seleccion, .atenuada')).toHaveLength(0);
|
||||
expect(eu7Component().barras!.activas).toBeNull();
|
||||
expect(biopsiaComponent().barras!.activas).toBeNull();
|
||||
eu7Component().select('grupos', 1); biopsiaComponent().select('categorias', 0); f.detectChanges();
|
||||
expect(eu7Component().selection).toEqual({});
|
||||
expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' });
|
||||
expect(f.nativeElement.querySelectorAll('.atenuada, .seleccion')).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales .cabecera').length).toBeGreaterThan(0);
|
||||
expect(f.nativeElement.querySelectorAll('details.published-values')).toHaveLength(2);
|
||||
const vph = f.nativeElement.querySelector('app-indicador-vph-genotipo') as HTMLElement;
|
||||
expect(vph.textContent).toContain('No disponible'); expect(vph.querySelectorAll('button')).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
// Why: the general filter is said once in the card header; a donut with a different effective period keeps its own line.
|
||||
it('dice el filtro general una vez y conserva una indicación propia solo si el periodo efectivo difiere', () => {
|
||||
f.detectChanges();
|
||||
expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelector('.filtro').textContent).toContain('2025-S2');
|
||||
f.componentRef.setInput('confirmacionApplied', { ...applied, selection: { mode: 'explicit', periodos: ['2025-S1'] } });
|
||||
f.detectChanges();
|
||||
expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(1);
|
||||
expect(f.nativeElement.querySelector('app-indicador-confirmacion-citologia .applied-summary').textContent).toContain('2025-S1');
|
||||
http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')).flush({}, { status: 500, statusText: 'x' });
|
||||
http.match(() => true);
|
||||
});
|
||||
// Why: one failing donut must not hide the other two, and its retry repeats only its own request.
|
||||
it('un error en la dona de biopsia no oculta la dona citológica y el reintento solo repite su solicitud', () => {
|
||||
f.detectChanges();
|
||||
const e = eu7Requests(); const b = biopsia();
|
||||
e.general.flush(structuredClone(eu7Fixture.general)); e.escenarios.flush(structuredClone(eu7Fixture.estatus_seguimiento));
|
||||
b.flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(biopsiaComponent().status()).toBe('error');
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||
expect(f.nativeElement.querySelector('app-indicador-eu7-escenario [role=alert]')).toBeNull();
|
||||
expect(f.nativeElement.querySelector('app-indicador-vph-genotipo').textContent).toContain('No disponible');
|
||||
biopsiaComponent().retry(); http.expectNone(r => r.url.includes('/cacu_eu7/'));
|
||||
biopsia().flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges();
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(2);
|
||||
});
|
||||
// Why: the bars and the rates read the same source; a second HTTP request would double the load.
|
||||
it('la dona y las tasas de la confirmación comparten una sola solicitud y conservan selecciones propias', () => {
|
||||
const tasas = TestBed.createComponent(IndicadorConfirmacionCitologia);
|
||||
tasas.componentRef.setInput('dominio', 'cacu'); tasas.componentRef.setInput('indicador', confirmacion);
|
||||
tasas.componentRef.setInput('tema', 'claro'); tasas.componentRef.setInput('applied', applied);
|
||||
f.detectChanges(); tasas.detectChanges();
|
||||
eu7Requests();
|
||||
biopsia().flush(respuesta(['2025-S2']) as Record<string, unknown>); f.detectChanges(); tasas.detectChanges();
|
||||
expect(tasas.componentInstance.status()).toBe('ready');
|
||||
biopsiaComponent().select('grupos', 0); tasas.componentInstance.select('categorias', 0);
|
||||
expect(biopsiaComponent().selection).toEqual({ grupo: 'ANORMAL' });
|
||||
expect(biopsiaComponent().barras!.activas).toBeNull();
|
||||
expect(tasas.componentInstance.selection).toEqual({ grupo: 'NO_ANORMAL', categoria: 'NORMAL' });
|
||||
http.expectNone(() => true); tasas.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
|
||||
// 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
|
||||
@@ -41,6 +43,7 @@ export interface ModeloConfirmacion {
|
||||
}
|
||||
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 interface TotalPublicado { id: string; etiqueta: string; n: number | null; estado: Celda['estado']; }
|
||||
export class ConfirmacionIncompatible extends Error {}
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -69,10 +72,6 @@ function suma(celdas: Celda[]): number | null {
|
||||
function estado(celdas: Celda[]): Celda['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function 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;
|
||||
|
||||
@@ -97,20 +96,15 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
|
||||
const c = cats[a.id];
|
||||
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
|
||||
});
|
||||
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
|
||||
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|
||||
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
|
||||
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
|
||||
return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, c['color'] as string | null), grupo: c['grupo'] };
|
||||
});
|
||||
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
|
||||
const colores = paintByGroup(conColor.map(g => g.grupo));
|
||||
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
|
||||
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
|
||||
const bases = basesPorGrupo(conColor.map(g => g.grupo));
|
||||
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
|
||||
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||
const propios = grados.filter(g => g.grupo === id);
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
|
||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: cacuGroupColor(id) ?? COLOR_RESPALDO,
|
||||
grados: propios.map(g => g.id) };
|
||||
});
|
||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||
@@ -159,6 +153,34 @@ export function seleccionados(m: ModeloConfirmacion, sel: SeleccionConfirmacion)
|
||||
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;
|
||||
}
|
||||
/**
|
||||
* Women per grade (what the donut draws) and per category kept outside it, summed over the cytology rows.
|
||||
* An unknown or suppressed cell makes its total unknown, never zero.
|
||||
*/
|
||||
export function totalesPublicados(m: ModeloConfirmacion): { grados: TotalPublicado[]; aparte: TotalPublicado[] } {
|
||||
return {
|
||||
grados: m.grados.map(g => {
|
||||
const n = m.totales[g.id] ?? null;
|
||||
return { id: g.id, etiqueta: g.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(m.filas.map(f => ({ n: f.den, estado: f.estado }))) };
|
||||
}),
|
||||
aparte: m.aparte.map(a => {
|
||||
const celdas = m.filas.map(f => f.aparte[a.id]), n = suma(celdas);
|
||||
return { id: a.id, etiqueta: a.etiqueta, n, estado: n !== null ? 'Publicado' as const : estado(celdas) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
/** The biopsy bars: the two groups of grades as headers, the grades as bars; what has no biopsy or no grade stays outside. */
|
||||
export function barrasBiopsia(m: ModeloConfirmacion, sel: SeleccionConfirmacion): ConjuntoBarras {
|
||||
const t = totalesPublicados(m);
|
||||
return {
|
||||
grupos: m.grupos.map(g => {
|
||||
const filas = g.grados.map(id => { const grado = m.grados.find(x => x.id === id)!, total = t.grados.find(x => x.id === id)!;
|
||||
return { id, etiqueta: grado.etiqueta, n: total.n, estado: total.estado, color: grado.color }; });
|
||||
return { id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: filas.some(f => f.n === null) ? null : filas.reduce((s, f) => s + f.n!, 0), filas };
|
||||
}),
|
||||
den: m.conBiopsia, unidad: 'mujeres con biopsia', activas: new Set(seleccionados(m, sel)),
|
||||
};
|
||||
}
|
||||
/** 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);
|
||||
@@ -204,7 +226,7 @@ export function figuraTasas(m: ModeloConfirmacion, sel: SeleccionConfirmacion, t
|
||||
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,
|
||||
marker: { size: 12, color, line: { color: p.text, width: 1 } }, 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!)]),
|
||||
@@ -237,10 +259,10 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
|
||||
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)), hovertext: hoverText(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 } } },
|
||||
marker: { colors: m.grupos.map(g => cacuRgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .45)), 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)), hovertext: hoverText(exterior),
|
||||
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
|
||||
marker: { colors: m.grados.map(g => cacuRgba(g.color, activos.has(g.id) ? 1 : .45)), 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 } };
|
||||
}
|
||||
|
||||
@@ -217,7 +217,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
]);
|
||||
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6, por paciente y por mastografía');
|
||||
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
expect(graficas).toHaveLength(2);
|
||||
expect(graficas.map(g => g.label)).toEqual(h3);
|
||||
|
||||
@@ -2,6 +2,7 @@ import fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { barras, clic, dona, modelo, porcentaje, periodosCompatibles, Seleccion } from './indicadores-eu7-escenario';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
import { recolorFigure } from './indicadores-c2-palette';
|
||||
|
||||
function eu7Datos() {
|
||||
return structuredClone({ general: fixture.general as IndicadorDatos, escenarios: fixture.estatus_seguimiento as IndicadorDatos });
|
||||
@@ -19,6 +20,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
expect(f.data[2]['values']).toEqual([798, 62, 46, 17, 19, 4]);
|
||||
expect(data).toEqual(original);
|
||||
});
|
||||
it.each(['claro', 'oscuro'] as const)('conserva colores lisos en dona y barras hasta Plotly, tema %s', tema => {
|
||||
const m = model();
|
||||
const expected = {
|
||||
NORMAL: '#438B53', 'ASC-US': '#2879BD', LIEBG: '#AD8F20', 'ASC-H': '#7959B8', LIEAG: '#D14D78', CIS: '#AE4050',
|
||||
};
|
||||
expect(Object.fromEntries(m.categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||
for (const payload of [data.general, data.escenarios]) {
|
||||
payload['categorias'] = Object.fromEntries(Object.entries(payload['categorias'] as object).reverse());
|
||||
payload.filas.reverse();
|
||||
for (const row of payload.filas) if (typeof row['orden'] === 'number') row['orden'] = 10 - row['orden'];
|
||||
}
|
||||
expect(model().categorias.map(c => c.id)).not.toEqual(m.categorias.map(c => c.id));
|
||||
expect(Object.fromEntries(model().categorias.map(c => [c.id, c.color]))).toEqual(expected);
|
||||
const pie = dona(m, {}, tema), bar = barras(m, {}, tema);
|
||||
expect(recolorFigure(pie)).toBe(pie); expect(recolorFigure(bar)).toBe(bar);
|
||||
expect(pie.data[2]['marker']).not.toHaveProperty('pattern');
|
||||
const i = m.categorias.findIndex(c => c.id === 'LIEBG');
|
||||
expect(pie.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(173,143,32,1)']) });
|
||||
expect(bar.data[i]).toMatchObject({ uid: 'LIEBG', marker: { color: '#AD8F20' } });
|
||||
expect(bar.data[i]['marker']).not.toHaveProperty('pattern');
|
||||
const selected = dona(m, { categoria: 'LIEBG' }, tema);
|
||||
expect(recolorFigure(selected)).toBe(selected);
|
||||
expect(selected.data[2]['marker']).toMatchObject({ colors: expect.arrayContaining(['rgba(121,89,184,0.45)']) });
|
||||
});
|
||||
it('TOTAL → Anormal → LIEAG → grupo → TOTAL y toggles', () => {
|
||||
const m = model(); let s: Seleccion = {};
|
||||
const g = m.grupos.findIndex(g => g.id === 'ANORMAL'), c = m.categorias.findIndex(c => c.id === 'LIEAG');
|
||||
@@ -29,26 +54,33 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
s = clic(m, s, 'centro', 0); expect(s).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'grupos', g)).toEqual({});
|
||||
expect(clic(m, { categoria: 'LIEAG' }, 'centro', 0)).toEqual({});
|
||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: undefined, categoria: 'LIEAG' });
|
||||
expect(clic(m, {}, 'categorias', c)).toEqual({ grupo: 'ANORMAL', categoria: 'LIEAG' });
|
||||
expect(clic(m, {}, 'otra', c)).toEqual({});
|
||||
expect(clic(m, {}, 'grupos', -1)).toEqual({});
|
||||
expect(clic(m, { grupo: 'ANORMAL' }, 'categorias', 0)).toEqual({ grupo: 'ANORMAL' });
|
||||
});
|
||||
it('cada escenario suma 100 % en TOTAL y Anormal conserva 5.0, 24.3, 21.7, 7.8 %', () => {
|
||||
it('barras agrupadas: conteos absolutos por categoría y escenario, sin apilar ni normalizar', () => {
|
||||
const m = model(), f = barras(m, {}, 'claro');
|
||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBeCloseTo(100, 8));
|
||||
expect((f.layout['annotations'] as { text: string }[]).map(a => a.text)).toEqual(m.escenarios.map(s => `${s.den}`));
|
||||
expect(f.layout['barmode']).toBe('group');
|
||||
expect(f.data.map(t => t['uid'])).toEqual(m.categorias.map(c => c.id));
|
||||
f.data.forEach((t, i) => expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[m.categorias[i].id].n)));
|
||||
m.escenarios.forEach((s, i) => expect(f.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(s.den));
|
||||
const labels = (f.layout['yaxis'] as { categoryarray: string[] }).categoryarray;
|
||||
m.escenarios.forEach((s, i) => { expect(labels[i]).toContain(s.etiqueta); expect(labels[i]).not.toContain('Total válido'); });
|
||||
expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Número de pacientes');
|
||||
const todos = f.data.flatMap(t => t['x'] as number[]);
|
||||
expect((f.layout['xaxis'] as { range: number[] }).range[0]).toBe(0);
|
||||
expect((f.layout['xaxis'] as { range: number[] }).range[1]).toBeGreaterThan(Math.max(...todos));
|
||||
const selected = barras(m, { grupo: 'ANORMAL' }, 'claro');
|
||||
expect(m.escenarios.map((s, i) => selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0).toFixed(1)))
|
||||
.toEqual(['5.0', '24.3', '21.7', '7.8']);
|
||||
expect(selected.data.map(t => t['uid'])).toEqual(m.categorias.filter(c => c.grupo === 'ANORMAL').map(c => c.id));
|
||||
const anormales = m.categorias.filter(c => c.grupo === 'ANORMAL');
|
||||
m.escenarios.forEach((s, i) => expect(selected.data.reduce((n, t) => n + (t['x'] as number[])[i], 0)).toBe(anormales.reduce((n, c) => n + s.celdas[c.id].n!, 0)));
|
||||
// The selected scale is common and fits the selected counts, not the whole distribution.
|
||||
expect((selected.layout['xaxis'] as { range: number[] }).range[1]).toBeLessThan((f.layout['xaxis'] as { range: number[] }).range[1]);
|
||||
const category = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
// Same traces in every selection (animation identity); unselected ones are zero-width.
|
||||
expect(category.data.map(t => t['uid'])).toEqual(f.data.map(t => t['uid']));
|
||||
const lieag = category.data.find(t => t['uid'] === 'LIEAG')!;
|
||||
expect(lieag['x']).toEqual(m.escenarios.map(s => 100 * s.celdas['LIEAG'].n! / s.den!));
|
||||
expect(category.data.filter(t => t !== lieag).every(t => (t['x'] as number[]).every(v => v === 0) && t['hoverinfo'] === 'skip')).toBe(true);
|
||||
expect((category.layout['annotations'] as { text: string }[]).map(a => a.text))
|
||||
.toEqual(m.escenarios.map(s => `<b>${percentNumber(100 * s.celdas['LIEAG'].n! / s.den!)} %</b> (${s.celdas['LIEAG'].n}/${s.den})`));
|
||||
expect(category.data).toHaveLength(1);
|
||||
expect(category.data[0]['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n));
|
||||
expect(category.data[0]['text']).toEqual(m.escenarios.map(s => String(s.celdas['LIEAG'].n)));
|
||||
expect(m.escenarios.map(s => s.den)).toEqual([682, 140, 60, 64]);
|
||||
});
|
||||
it.each(['estrato', 'categorias', 'periodos', 'orden', 'duplicado', 'version', 'filtros', 'total', 'diferencia'])('rechaza incompatibilidad de %s', kind => {
|
||||
@@ -71,16 +103,19 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
data.general['reportes'] = [{ periodo, report_id: 1 }]; data.escenarios['reportes'] = [{ periodo, report_id: 2 }];
|
||||
expect(model).toThrow(/reportes distintos/);
|
||||
});
|
||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: todos los puntos son null y no hay denominador inventado', kind => {
|
||||
it.each(['suprimido', 'nulo', 'sin fila', 'sin dato suprimido', 'total suprimido'])('escenario con %s: el estado se dice, nunca se dibuja un cero ni un total inventado', kind => {
|
||||
const row = data.escenarios.filas.find(f => f['estrato'] === 'VIGILANCIA' && f['categoria'] === (kind === 'sin dato suprimido' ? 'SIN_DATO' : 'LIEAG'))!;
|
||||
if (kind === 'sin fila') data.escenarios.filas = data.escenarios.filas.filter(f => f !== row);
|
||||
else if (kind === 'total suprimido') Object.assign((data.escenarios['totales_estrato'] as any[])[0], { n: 123456, suprimido: 1 });
|
||||
else Object.assign(row, { n: kind === 'nulo' ? null : 123456, suprimido: kind === 'nulo' ? 0 : 1 });
|
||||
const m = model(), f = barras(m, { categoria: 'LIEAG' }, 'claro');
|
||||
expect(m.escenarios[0].den).toBeNull(); expect(f.data.find(t => t['uid'] === 'LIEAG')!['x']).toEqual([null, 100 * 9 / 140, 100 * 4 / 60, 100 / 64]);
|
||||
expect(f.data.every(t => (t['x'] as unknown[])[0] === null)).toBe(true);
|
||||
expect(f.data.filter(t => t['uid'] !== 'LIEAG').every(t =>
|
||||
t['hoverinfo'] === 'skip' && (t['customdata'] as unknown[]).length === 0)).toBe(true);
|
||||
expect(m.escenarios[0].den).toBeNull();
|
||||
const t = f.data[0], celda = m.escenarios[0].celdas['LIEAG'];
|
||||
expect(f.data).toHaveLength(1);
|
||||
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n ?? 0));
|
||||
expect(t['text']).toEqual(m.escenarios.map(s => s.celdas['LIEAG'].n === null ? s.celdas['LIEAG'].estado : String(s.celdas['LIEAG'].n)));
|
||||
if (celda.n === null) expect((t['hovertext'] as string[])[0]).toContain('no es cero');
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray[0]).toMatch(/Total (suprimido|no disponible)/);
|
||||
expect(JSON.stringify(f)).not.toContain('123456');
|
||||
expect(porcentaje(m.escenarios[0], 'LIEAG')).toBeNull();
|
||||
});
|
||||
@@ -96,30 +131,30 @@ describe('EU7 modelo de presentación del entregable', () => {
|
||||
const m = model(); expect(m.escenarios.map(s => s.id)).not.toContain('INFO_INSUFICIENTE');
|
||||
expect(barras(m, {}, 'claro').data[0]['x']).toHaveLength(3);
|
||||
});
|
||||
it('escenario vacío y periodo de ceros no producen porcentajes 0/0', () => {
|
||||
it('escenario vacío y periodo de ceros: ceros publicados, sin porcentajes ni totales inventados', () => {
|
||||
data.general.filas.forEach(f => f['n'] = 0); data.escenarios.filas.forEach(f => f['n'] = 0);
|
||||
(data.escenarios['totales_estrato'] as any[]).forEach(t => t.n = 0);
|
||||
const m = model(); expect(m.total).toBe(0); expect(dona(m, {}, 'claro').data).toEqual([]);
|
||||
expect(barras(m, {}, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, { categoria: 'LIEAG' }, 'claro').data.every(t => (t['x'] as null[]).every(v => v === null))).toBe(true);
|
||||
expect(barras(m, {}, 'claro').layout['annotations']).toEqual(expect.arrayContaining([expect.objectContaining({ text: 'Sin pacientes con resultado' })]));
|
||||
for (const sel of [{}, { categoria: 'LIEAG' }]) {
|
||||
const f = barras(m, sel, 'claro');
|
||||
expect(f.data.every(t => (t['x'] as number[]).every(v => v === 0) && (t['text'] as string[]).every(x => x === '0'))).toBe(true);
|
||||
expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray.every(l => l.includes('Sin pacientes con resultado'))).toBe(true);
|
||||
}
|
||||
});
|
||||
it('periodo sin pacientes con filas vacías es empty, sin fabricar celdas cero', () => {
|
||||
data.general.filas = []; data.escenarios.filas = []; data.escenarios['totales_estrato'] = [];
|
||||
const m = model(); expect(m.vacio).toBe(true); expect(m.total).toBe(0); expect(m.escenarios).toEqual([]);
|
||||
expect(m.celdas['NORMAL'].n).toBeNull();
|
||||
});
|
||||
it('selección jerárquica y Volver conservan UID, orden, denominadores y datos fuente', () => {
|
||||
it('selección jerárquica y Volver conservan orden, denominadores y datos fuente; las barras solo eligen categorías', () => {
|
||||
const original = structuredClone(data), m = model(), snapshot = structuredClone(m);
|
||||
const ids = m.categorias.map(c => c.id);
|
||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, {}]) {
|
||||
const esperadas = (s: Seleccion) => m.categorias.filter(c => s.categoria ? c.id === s.categoria : s.grupo ? c.grupo === s.grupo : true).map(c => c.id);
|
||||
for (const selection of [{}, { grupo: 'ANORMAL' }, { grupo: 'ANORMAL', categoria: 'LIEAG' }, { categoria: 'LIEAG' }, { grupo: 'NO_ANORMAL' }, {}]) {
|
||||
const f = barras(m, selection, 'claro');
|
||||
expect(f.data.map(t => t['uid'])).toEqual(ids);
|
||||
expect(new Set(f.data.map(t => t['uid'])).size).toBe(ids.length);
|
||||
f.data.forEach((t, i) => {
|
||||
if (t['hoverinfo'] === 'skip') {
|
||||
expect(t['customdata']).toEqual([]); expect(t['text']).toEqual(m.escenarios.map(() => ''));
|
||||
} else expect(t['x']).toEqual(m.escenarios.map(s => porcentaje(s, ids[i])));
|
||||
expect(f.data.map(t => t['uid'])).toEqual(esperadas(selection));
|
||||
f.data.forEach(t => {
|
||||
expect(t['x']).toEqual(m.escenarios.map(s => s.celdas[t['uid'] as string].n));
|
||||
expect(t['marker']).toMatchObject({ color: m.categorias.find(c => c.id === t['uid'])!.color });
|
||||
});
|
||||
dona(m, selection, 'claro');
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
|
||||
import { c2Theme } from './indicadores-c2-palette';
|
||||
import { cacuClinicalColor, cacuGroupColor, cacuRgba } from './indicadores-cacu-palette';
|
||||
import { percentNumber, shareText } from './indicadores-format';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
|
||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||
// This boundary is intentionally specific to EU7. Unknown cells never become zero.
|
||||
@@ -39,10 +41,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
|
||||
return celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido'
|
||||
: celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado';
|
||||
}
|
||||
function rgba(hex: string, alfa: number): string {
|
||||
const v = parseInt(hex.slice(1), 16);
|
||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
||||
}
|
||||
function catalogo(data: IndicadorDatos): Categoria[] {
|
||||
const cats = data['categorias'], grupos = data['grupos_de_categoria'];
|
||||
if (!registro(cats) || !registro(grupos) || !Object.hasOwn(cats, SIN_DATO)) return fail('Catálogo EU7 incompleto.');
|
||||
@@ -129,11 +127,10 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
|
||||
const claves = baseCategorias.map(c => c.grupo);
|
||||
const bases = basesPorGrupo(claves);
|
||||
const colores = paintByGroup(claves);
|
||||
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
|
||||
const categorias = baseCategorias.map(c => ({ ...c, color: cacuClinicalColor(c.id, c.color) }));
|
||||
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({
|
||||
id, etiqueta: nombres[id], color: cacuGroupColor(id) ?? '#8A9199',
|
||||
}));
|
||||
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||
const totals = porEscenario['totales_estrato'];
|
||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||
@@ -167,6 +164,15 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
const nGrupo = (m: Modelo, grupo: string) => suma(hijas(m, grupo).map(c => m.celdas[c.id]));
|
||||
/** The cytology bars: the groups of the inner ring as headers, the categories of the outer ring as bars; «Sin dato» stays outside. */
|
||||
export function barrasCitologia(m: Modelo, sel: Seleccion): ConjuntoBarras {
|
||||
return {
|
||||
grupos: m.grupos.map(g => ({ id: g.id, etiqueta: g.etiqueta, color: g.color, subtotal: nGrupo(m, g.id),
|
||||
filas: hijas(m, g.id).map(c => ({ id: c.id, etiqueta: c.etiqueta, n: m.celdas[c.id].n, estado: m.celdas[c.id].estado, color: c.color })) })),
|
||||
den: m.total, unidad: 'pacientes con resultado',
|
||||
activas: sel.categoria ? new Set([sel.categoria]) : sel.grupo ? new Set(hijas(m, sel.grupo).map(c => c.id)) : null,
|
||||
};
|
||||
}
|
||||
export function seleccionEtiqueta(m: Modelo, sel: Seleccion): string {
|
||||
return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta
|
||||
: sel.grupo ? m.grupos.find(g => g.id === sel.grupo)!.etiqueta : 'TOTAL';
|
||||
@@ -181,7 +187,7 @@ export function clic(m: Modelo, sel: Seleccion, traza: string, indice: number):
|
||||
if (traza !== 'categorias') return sel;
|
||||
const c = m.categorias[indice];
|
||||
if (!c || (sel.grupo && c.grupo !== sel.grupo)) return sel;
|
||||
return sel.categoria === c.id ? { grupo: sel.grupo } : { grupo: sel.grupo, categoria: c.id };
|
||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||
}
|
||||
export function porcentaje(s: Escenario, categoria: string): number | null {
|
||||
const n = s.celdas[categoria]?.n;
|
||||
@@ -193,6 +199,7 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const interior = m.grupos.map(g => !sel.grupo || sel.grupo === g.id ? nGrupo(m, g.id)! : 0);
|
||||
const exterior = m.categorias.map(c => !sel.grupo || sel.grupo === c.grupo ? m.celdas[c.id].n! : 0);
|
||||
const alpha = (id: string) => sel.categoria && id !== sel.categoria ? .45 : 1;
|
||||
const centro = sel.categoria ? m.celdas[sel.categoria].n! : sel.grupo ? nGrupo(m, sel.grupo)! : m.total;
|
||||
const rotulos = (values: number[], labels: string[], pct: boolean) => {
|
||||
const total = values.reduce((s, n) => s + n, 0);
|
||||
@@ -209,45 +216,44 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
|
||||
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
|
||||
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
|
||||
textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
hovertext: hoverText(interior),
|
||||
marker: { colors: m.grupos.map(g => cacuRgba(g.color, sel.categoria ? .45 : 1)), line: { color: p.background, width: 2 } } },
|
||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
||||
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
|
||||
textfont: { size: 11 }, hovertext: hoverText(exterior),
|
||||
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
|
||||
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||
marker: { colors: m.categorias.map(c => cacuRgba(c.color, alpha(c.id))), 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 } };
|
||||
}
|
||||
/** Selection never changes the original denominator or renormalizes a subset. */
|
||||
/** Absolute counts, one independent bar per category inside each clinical scenario. The selection only chooses which
|
||||
* categories are drawn; it never renormalizes anything and every scenario shares one horizontal scale. */
|
||||
export function barras(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
|
||||
const p = c2Theme(tema);
|
||||
const visibles = sel.categoria ? [sel.categoria] : sel.grupo ? hijas(m, sel.grupo).map(c => c.id) : m.categorias.map(c => c.id);
|
||||
const y = m.escenarios.map(s => escapar(s.etiqueta));
|
||||
const sumas = m.escenarios.map(s => s.den === null || s.den === 0 ? null : visibles.reduce((n, c) => n + porcentaje(s, c)!, 0));
|
||||
// Every category keeps its trace (same uid and count) so a selection animates;
|
||||
// an unselected category is a zero-width bar without text or hover, never data.
|
||||
return { data: m.categorias.map(c => {
|
||||
const visible = visibles.includes(c.id);
|
||||
const x = m.escenarios.map(s => {
|
||||
const value = porcentaje(s, c.id);
|
||||
return value === null ? null : visible ? value : 0;
|
||||
});
|
||||
const visibles = m.categorias.filter(c => sel.categoria ? c.id === sel.categoria : sel.grupo ? c.grupo === sel.grupo : true);
|
||||
// The valid total of each scenario travels with its name; an unknown total is said, never drawn as zero.
|
||||
const y = m.escenarios.map(s => `${escapar(s.etiqueta)}${s.den === null ? `<br>Total ${s.estado === 'Suprimido' ? 'suprimido' : 'no disponible'}`
|
||||
: s.den === 0 ? '<br>Sin pacientes con resultado' : ''}`);
|
||||
const traces = visibles.map(c => {
|
||||
const celdas = m.escenarios.map(s => s.celdas[c.id]);
|
||||
// An unknown cell draws no bar (width 0) and says its state instead of a number; a published zero says «0».
|
||||
const x = celdas.map(v => v.n ?? 0);
|
||||
return { type: 'bar', orientation: 'h', uid: c.id, name: escapar(c.etiqueta), y, x,
|
||||
marker: { color: c.color, line: { color: p.background, width: visible ? 1 : 0 } },
|
||||
text: x.map(v => visible && v !== null && v >= 6 ? `${percentNumber(v)} %` : ''), textposition: 'inside', insidetextanchor: 'middle',
|
||||
customdata: visible ? m.escenarios.map(s => s.den === null ? [s.estado, 'No disponible'] : [s.celdas[c.id].n, s.den]) : [],
|
||||
...(visible ? { hovertemplate: `%{y}<br>${escapar(c.etiqueta)}: %{x:.1f} % (%{customdata[0]}/%{customdata[1]})<extra></extra>` }
|
||||
: { hoverinfo: 'skip' }) };
|
||||
}), layout: { barmode: 'stack', autosize: true, height: Math.max(440, 130 + m.escenarios.length * 65),
|
||||
marker: { color: c.color, line: { color: p.background, width: 1 } },
|
||||
text: celdas.map(v => v.n === null ? v.estado : miles(v.n)), textposition: 'outside', cliponaxis: false,
|
||||
textfont: { size: 12, color: p.text },
|
||||
hovertext: celdas.map((v, i) => `${escapar(m.escenarios[i].etiqueta)}<br>${escapar(c.etiqueta)}: ${v.n === null
|
||||
? `${v.estado} (no es cero)` : `${miles(v.n)} ${v.n === 1 ? 'paciente' : 'pacientes'}`}`),
|
||||
hovertemplate: '%{hovertext}<extra></extra>' };
|
||||
});
|
||||
const mayor = Math.max(1, ...traces.flatMap(t => t.x));
|
||||
return { data: traces, layout: { barmode: 'group', bargap: .45, bargroupgap: .08, autosize: true,
|
||||
height: Math.max(360, 110 + m.escenarios.length * (visibles.length * 22 + 36)),
|
||||
paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text },
|
||||
margin: { t: 24, l: 150, r: 72, b: 64 }, showlegend: false,
|
||||
margin: { t: 16, l: 150, r: 24, b: 64 }, showlegend: false,
|
||||
// A thin rule between scenarios so each group reads as one unit.
|
||||
shapes: m.escenarios.slice(1).map((_, i) => ({ type: 'line', xref: 'paper', x0: 0, x1: 1, yref: 'y', y0: i + .5, y1: i + .5, line: { color: p.outline, width: 1, dash: 'dot' } })),
|
||||
yaxis: { type: 'category', autorange: 'reversed', categoryorder: 'array', categoryarray: y, automargin: true },
|
||||
xaxis: { title: { text: '% de pacientes del escenario con resultado' }, ticksuffix: ' %', gridcolor: p.grid,
|
||||
range: sel.grupo || sel.categoria ? [0, Math.max(...sumas.filter((v): v is number => v !== null), 1) * 1.35] : [0, 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,
|
||||
font: { size: 12, color: p.text }, text: s.den === null ? s.estado : s.den === 0 ? 'Sin pacientes con resultado'
|
||||
: sel.grupo || sel.categoria ? `<b>${percentNumber(sumas[i]!)} %</b> (${visibles.reduce((n, c) => n + s.celdas[c].n!, 0)}/${miles(s.den)})`
|
||||
: miles(s.den) })),
|
||||
xaxis: { title: { text: 'Número de pacientes' }, tickformat: ',d', gridcolor: p.grid, zeroline: false,
|
||||
range: [0, mayor * 1.2], ...(mayor <= 8 ? { dtick: 1 } : {}) },
|
||||
}, config: { displayModeBar: false } };
|
||||
}
|
||||
|
||||
@@ -17,9 +17,11 @@ import {
|
||||
import * as fx from './indicadores-fhir.fixtures';
|
||||
import { c1AlterationFigure } from './indicadores-c1-alteraciones';
|
||||
import { c2Figure } from './indicadores-c2-adapter';
|
||||
import { historicoFigura } from './indicadores-historico-figures';
|
||||
import { datosValidos } from './indicadores.service';
|
||||
import { FhirTeaSeguimientoService, mapaDeElectrodos } from './tea-seguimiento-fhir';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import vistaPreviaBundle from './fixtures/tea_vista_previa_bundle.json';
|
||||
|
||||
const measure = (id: string) => resources(fx.measures).find(m => m.id === id) as Measure;
|
||||
|
||||
@@ -35,12 +37,12 @@ const curva = {
|
||||
],
|
||||
};
|
||||
const prediccion = (zona: string, z: number | null) => ({
|
||||
outcome: { coding: [{ system: `${CS}/tea-catalogo`, code: 'ados2.sa_b9', display: 'Mostrar' }] },
|
||||
outcome: { coding: [{ system: `${CS}/tea-ados2-resultado`, code: 'ados2_item_11', display: 'Mostrar' }] },
|
||||
probabilityDecimal: 0.41,
|
||||
extension: [
|
||||
{ url: `${SD}/biomarcador`, valueCoding: { system: `${CS}/tea-eeg-metrica`, code: 'RITMO_POSTERIOR', display: 'Ritmo posterior' } },
|
||||
{ url: `${SD}/zona`, valueCoding: { system: `${CS}/tea-eeg-zona`, code: zona, display: 'Occipital' } },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=2' },
|
||||
{ url: `${SD}/tipo`, valueString: 'item' }, { url: `${SD}/evento`, valueString: '>=1' },
|
||||
...(z === null ? [] : [{ url: `${SD}/valor-z`, valueDecimal: z }]),
|
||||
{ url: `${SD}/odds-ratio`, valueDecimal: 0.5 }, { url: `${SD}/ic-inf`, valueDecimal: 0.3 }, { url: `${SD}/ic-sup`, valueDecimal: 0.8 },
|
||||
{ url: `${SD}/q`, valueDecimal: 0.01 }, { url: `${SD}/probabilidad-referencia`, valueDecimal: 0.2 }, { url: `${SD}/observado`, valueInteger: 2 },
|
||||
@@ -146,6 +148,24 @@ describe('Indicadores sobre FHIR', () => {
|
||||
const dibujo = JSON.stringify(figura.status === 'supported' ? figura.figure : {});
|
||||
for (const etiqueta of ['Bueno', 'No aceptable', 'Sin analizar']) expect(dibujo).toContain(etiqueta);
|
||||
expect(dibujo).not.toContain('Malo');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar']);
|
||||
});
|
||||
|
||||
it('presenta Aceptable en ambas gráficas cuando M29 lo declara como categoría propia', () => {
|
||||
const actual = measure('M29-calidad-eeg');
|
||||
const conAceptable: Measure = {
|
||||
...actual, extension: [...actual.extension ?? [], { url: `${SD}/categoria`, extension: [
|
||||
{ url: 'codigo', valueCode: 'ACEPTABLE' }, { url: 'etiqueta', valueString: 'ACEPTABLE' },
|
||||
] }],
|
||||
};
|
||||
const datos = datosDeReportes(conAceptable, [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
expect(datos.filas.find(fila => fila['categoria'] === 'ACEPTABLE')).toMatchObject({ n: 0 });
|
||||
const figura = c2Figure(datos, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
expect(JSON.stringify(figura.status === 'supported' ? figura.figure : {})).toContain('Aceptable');
|
||||
expect(historicoFigura(datos, 'claro').figure.data.map(traza => traza['name']))
|
||||
.toEqual(['Bueno', 'No aceptable', 'Sin analizar', 'Aceptable']);
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
@@ -329,7 +349,7 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(relacion).toMatchObject({ version: '1.0.0', validado: false, nivel: 'item', n_cohorte: 40 });
|
||||
expect(relacion.filas).toEqual([{
|
||||
biomarcador: 'Ritmo posterior', zona: 'occipital', zona_etiqueta: 'Occipital', valor_z: -2.6, tipo: 'item',
|
||||
resultado: 'ados2.sa_b9', resultado_etiqueta: 'Mostrar', evento: '>=2', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
resultado: 'ados2_item_11', resultado_etiqueta: 'Mostrar', evento: '>=1', or: 0.5, ic_inf: 0.3, ic_sup: 0.8, q: 0.01,
|
||||
probabilidad: 0.41, probabilidad_referencia: 0.2, observado: 2 }]);
|
||||
});
|
||||
|
||||
@@ -356,4 +376,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
|
||||
expect(mapa.regiones.map(r => r.codigo)).toEqual(['occipital', 'parietal']);
|
||||
expect(mapa.regiones[0].valor_z).toBe(-2.6);
|
||||
});
|
||||
|
||||
it('las regiones del mapa son las zonas del análisis del EEG', () => {
|
||||
// Pins down: Fz is its own region (frontal media) and the central region averages C3, Cz and C4 only, as the
|
||||
// EEG analysis's zones do, so a region on the map is the zone the association model names. Fails if Fz goes
|
||||
// back into the central average or the frontal media region disappears.
|
||||
const mapa = mapaDeElectrodos('picos_paroxisticos', 'Picos paroxísticos', { Fz: 3, C3: 1, Cz: 1.5, C4: 2 });
|
||||
expect(mapa.regiones.map(r => [r.codigo, r.etiqueta, r.valor_z])).toEqual([
|
||||
['frontal_media', 'Frontal media', 3], ['central', 'Central', 1.5]]);
|
||||
});
|
||||
|
||||
it('la vista previa de un EDF y su ADOS-2 se lee como la ficha de un paciente guardado', async () => {
|
||||
// The fixture is what `POST /governance/tea/eeg/preview` answered for a short synthetic EDF with an ADOS-2 report.
|
||||
// Pins that the bundle the server builds without storing anything passes the same converter and checks as a
|
||||
// stored patient's summary. Fails if the server's shape and the converter drift apart.
|
||||
const answer = firstValueFrom(service.vistaPrevia(vistaPreviaBundle));
|
||||
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush({ concept: [] });
|
||||
const detalle = await answer;
|
||||
expect(detalle.id_seudonimo).toBe('vista-previa');
|
||||
expect(detalle.ados2?.modulo).toBe('2');
|
||||
expect(detalle.ados2?.dominios.length).toBe(2);
|
||||
expect(detalle.eeg?.calidad).toBe('malo');
|
||||
expect(detalle.eeg?.criterios_calidad.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -62,7 +62,7 @@ const percent = (value: number | null) => value === null ? null : round1(value *
|
||||
// Captions the page shows instead of the ones a Measure publishes; the category codes stay those of the data.
|
||||
// TEA's EEG quality shows its invalid exams as «No aceptable».
|
||||
const ROTULOS_DE_CATEGORIA: Readonly<Record<string, Readonly<Record<string, string>>>> = {
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable' },
|
||||
'M29-calidad-eeg': { MALO: 'No aceptable', ACEPTABLE: 'Aceptable' },
|
||||
};
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Presentation labels for representations confirmed in the published catalog.
|
||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
||||
// from a prefix. Unknown options keep a neutral label in publication order.
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
|
||||
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
|
||||
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||
|
||||
@@ -96,20 +96,16 @@ describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
// the page gives it, and with the contract the panel expects.
|
||||
const catalogo = new Map(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m)]));
|
||||
const activos = HISTORICO_CACU.filter(p => !p.enDesarrollo);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']);
|
||||
expect(activos.map(p => p.id)).toEqual(['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda']);
|
||||
for (const panel of activos) {
|
||||
expect(Object.values(CACU_MEASURE_IDS)).toContain(panel.id);
|
||||
expect(catalogo.get(panel.id)?.contrato).toBe(panel.contrato);
|
||||
}
|
||||
});
|
||||
it('los paneles reservados llevan los ids FHIR esperados y ninguno se activa por estar en el catálogo', () => {
|
||||
const reservados = HISTORICO_CACU.filter(p => p.enDesarrollo);
|
||||
expect(reservados.map(p => [p.id, p.fhir, p.contrato])).toEqual([
|
||||
['cacu_dias_toma_tratamiento', ['CACU-DIAS-TOMA-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_dias_diagnostico_tratamiento', ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'], 'C3r'],
|
||||
['cacu_riesgo_banda', ['CACU-RIESGO-BANDA'], 'C2'],
|
||||
]);
|
||||
// The risk bands are in the catalog and stay reserved.
|
||||
it('ningún panel queda reservado: los nueve leen su medida del catálogo', () => {
|
||||
// Pins down: every CaCu history panel is active, the risk bands included, under the page id of its measure.
|
||||
expect(HISTORICO_CACU.filter(p => p.enDesarrollo)).toEqual([]);
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,8 +19,9 @@ const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStar
|
||||
const SEMESTRES = ['2023-S1', '2023-S2', '2024-S1', '2024-S2', '2025-S1', '2025-S2', '2026-S1'];
|
||||
const CONTRATOS: Record<string, string> = { cacu_eu7: 'C2', ind1: 'C1', cacu_eu13: 'C1', cacu_confirmacion_citologia: 'C2', cacu_eu_tiempo_reporte: 'C3r',
|
||||
cacu_dias_toma_diagnostico: 'C3r', cacu_dias_toma_tratamiento: 'C3r', cacu_dias_diagnostico_tratamiento: 'C3r', cacu_riesgo_banda: 'C2' };
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico'];
|
||||
const RESERVADOS = ['cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const ACTIVOS = ['cacu_eu7', 'ind1', 'cacu_eu13', 'cacu_confirmacion_citologia', 'cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico',
|
||||
'cacu_dias_toma_tratamiento', 'cacu_dias_diagnostico_tratamiento', 'cacu_riesgo_banda'];
|
||||
const RESERVADOS: string[] = [];
|
||||
const item = (id: string): Indicador => ({ id, titulo: id, contrato: CONTRATOS[id], figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
|
||||
// Every measure the catalog could publish, reserved ones included: publishing them must not activate them.
|
||||
const CATALOGO = [...ACTIVOS, ...RESERVADOS].map(item);
|
||||
@@ -75,7 +76,7 @@ describe('Histórico de CaCu', () => {
|
||||
const panelDe = (titulo: string) => paneles().find(p => p.querySelector('h2')?.textContent === titulo)!;
|
||||
const tituloDe = (id: string) => HISTORICO_CACU.find(p => p.id === id)!.titulo;
|
||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Histórico de ' + titulo))!;
|
||||
const graficaDe = (titulo: string) => graficas().find(g => g.label?.startsWith('Trazabilidad de ' + titulo))!;
|
||||
|
||||
it('no pide nada hasta que la pestaña está activa, y entonces solo las medidas activas', () => {
|
||||
// Fails if the tab loads data while hidden, or asks for a reserved panel because the catalog publishes it.
|
||||
@@ -95,21 +96,21 @@ describe('Histórico de CaCu', () => {
|
||||
expect([...vistos].sort()).toEqual([...ACTIVOS].sort());
|
||||
for (const reservado of RESERVADOS) expect(vistos.has(reservado)).toBe(false);
|
||||
});
|
||||
it('dibuja nueve paneles en orden: seis con gráfica y tres reservados sin consultar', () => {
|
||||
it('dibuja los nueve paneles en orden: los activos con gráfica y los reservados sin consultar', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(p => p.titulo));
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(graficas()).toHaveLength(6);
|
||||
const reservados = paneles().slice(6);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
const reservados = paneles().slice(ACTIVOS.length);
|
||||
expect(reservados.every(p => !p.querySelector('app-plotly-chart') && !p.querySelector('mat-progress-bar'))).toBe(true);
|
||||
expect(reservados.map(p => [...p.children].map(n => n.textContent?.trim()))).toEqual(
|
||||
HISTORICO_CACU.slice(6).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
HISTORICO_CACU.slice(ACTIVOS.length).map(p => [p.titulo, 'Trabajo en desarrollo']));
|
||||
});
|
||||
it('un panel reservado sigue reservado con o sin su medida en el catálogo', () => {
|
||||
// Pins down: the state of a reserved panel comes from the config alone.
|
||||
for (const catalogo of [ACTIVOS.map(item), CATALOGO]) {
|
||||
montar(catalogo, true); responder();
|
||||
expect(paneles().slice(6).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(3).fill('Trabajo en desarrollo'));
|
||||
expect(paneles().slice(ACTIVOS.length).map(p => p.querySelector('[role="status"]')?.textContent)).toEqual(Array(RESERVADOS.length).fill('Trabajo en desarrollo'));
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
@@ -122,7 +123,7 @@ describe('Histórico de CaCu', () => {
|
||||
it('al abrir pide solo los últimos cinco periodos de cada medida y no repite la lista', () => {
|
||||
// Pins down the first request: the page asks for the latest five months, not the twelve it could.
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(-5));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
@@ -130,7 +131,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(MESES.slice(0, 7));
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ene 2025 a dic 2025 (12 meses)');
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
@@ -176,7 +177,7 @@ describe('Histórico de CaCu', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
expect(pedidos).toHaveLength(ACTIVOS.length);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
@@ -188,7 +189,7 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="status"]')?.textContent).toBe('Trabajo en desarrollo');
|
||||
expect(pedidos.some(p => p.id === 'cacu_eu13')).toBe(false);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
@@ -196,17 +197,17 @@ describe('Histórico de CaCu', () => {
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(6);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length);
|
||||
});
|
||||
it('una medida que llega con otro contrato es un error del panel, no una gráfica', () => {
|
||||
// Pins down the expected contract: the panel does not draw a C1 where it declared a composition.
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { contrato: 'C1' } : {} });
|
||||
const panel = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Contrato inesperado: se esperaba C2 y llegó C1');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(graficas()).toHaveLength(ACTIVOS.length - 1);
|
||||
});
|
||||
it('el cero válido de un C1 es un valor y un periodo sin población de un C2 es «sin dato»', () => {
|
||||
montar(CATALOGO, true); responder({ datos: id => id === 'cacu_eu7' ? { sinPoblacion: '2025-10' } : {} });
|
||||
@@ -226,7 +227,7 @@ describe('Histórico de CaCu', () => {
|
||||
}
|
||||
});
|
||||
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
|
||||
montar(RESERVADOS.map(item), true);
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
|
||||
@@ -81,13 +81,21 @@ describe('Histórico de CaMa', () => {
|
||||
});
|
||||
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual([
|
||||
'Días de la toma de la mastografía a su resultado',
|
||||
'Días del resultado de la mastografía al diagnóstico',
|
||||
'Días de tamizaje a diagnóstico',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6',
|
||||
'Pacientes con resultado BI-RADS 4, 5 ó 6',
|
||||
'Resultado histopatológico',
|
||||
'Tasa de confirmación histopatológica',
|
||||
]);
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Días del resultado de la mastografía al diagnóstico', 'Resultado histopatológico']);
|
||||
expect(paneles()).toHaveLength(7);
|
||||
const titulo = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6';
|
||||
expect(paneles()[3].querySelector('h2')?.textContent).toBe(titulo);
|
||||
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
|
||||
expect(graficas().some(g => g.label?.startsWith('Trazabilidad de ' + titulo))).toBe(true);
|
||||
expect(graficas()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
});
|
||||
|
||||
@@ -42,7 +42,7 @@ export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
];
|
||||
|
||||
// CaCu's history. The first six read the measures `dev` publishes; the last three are reserved.
|
||||
// CaCu's history. The active panels read the measures the catalog publishes; the reserved ones (`enDesarrollo`) never ask.
|
||||
export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'ind1', titulo: 'Pacientes con citología anómala', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
@@ -50,12 +50,9 @@ export const HISTORICO_CACU: readonly PanelHistorico[] = [
|
||||
{ id: 'cacu_confirmacion_citologia', titulo: 'Resultado de biopsia tras citología de alto grado', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-TOMA-TRATAMIENTO'] },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana',
|
||||
enDesarrollo: true, fhir: ['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO'] },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas',
|
||||
enDesarrollo: true, fhir: ['CACU-RIESGO-BANDA'] },
|
||||
{ id: 'cacu_dias_toma_tratamiento', titulo: 'Tiempo de tamizaje a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_dias_diagnostico_tratamiento', titulo: 'Tiempo de diagnóstico a tratamiento', contrato: 'C3r', grafica: 'linea_mediana' },
|
||||
{ id: 'cacu_riesgo_banda', titulo: 'Riesgo CIN2+ por banda', contrato: 'C2', grafica: 'barras_apiladas' },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
|
||||
@@ -137,22 +137,27 @@ describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en
|
||||
});
|
||||
it('resultado histopatológico y mastografías BI-RADS 4, 5 ó 6 usan el pie de total por categoría', () => {
|
||||
// Fails if the two keep the old sentence, or if the patients' counts (which carry none) or another count gets it.
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría.';
|
||||
const pie = 'Cada barra indica el total de pacientes por periodo en cada categoría';
|
||||
for (const id of ['cama_histopatologia_birads', 'cama_birads_456_mastografia']) expect(figura({ ...base('C2', MESES, cats), id } as IndicadorDatos).comoLeer).toBe(pie);
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'cama_birads_456_paciente' } as IndicadorDatos).comoLeer).toBe('');
|
||||
expect(figura({ ...base('C2', MESES, cats), id: 'otro' } as IndicadorDatos).comoLeer).toContain('Cada barra es el total');
|
||||
});
|
||||
it('M30 muestra la proporción publicada de alteraciones y deja pendiente la clasificación de EEG normal', () => {
|
||||
// Fails if children without an evaluable result are treated as normal through a complement.
|
||||
it('M30 dibuja EEG anormal y EEG normal como dos líneas complementarias', () => {
|
||||
// Fails if the normal line stops mirroring the abnormal one over the same denominator, or if a period without
|
||||
// evaluable children is drawn as normal (it stays a gap), or if the caption changes.
|
||||
const m30 = figura({ ...base('C1', MESES, [fila('2025-01', { valor: 62.5, numerador: 5, denominador: 8, ic_bajo: 30.6, ic_alto: 86.3 }),
|
||||
fila('2025-02', { valor: null, numerador: null, denominador: 0, ic_bajo: null, ic_alto: null })]), id: 'M30_resultado_eeg' } as IndicadorDatos);
|
||||
const f = m30.figure as unknown as Fig;
|
||||
const lineas = f.data.filter(t => t['mode'] === 'lines+markers');
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG con alteración detectada']);
|
||||
expect(lineas.map(t => t['name'])).toEqual(['EEG anormal', 'EEG normal']);
|
||||
expect(lineas[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(lineas[1]['y']).toEqual([37.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 de 8');
|
||||
expect(JSON.stringify(lineas[1]['text'])).toContain('3 de 8');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([86.3, 30.6]);
|
||||
expect(m30.comoLeer).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(f.data.find(t => t['name'] === 'Intervalo de confianza (normal)')!['y']).toEqual([69.4, 13.7]);
|
||||
expect(m30.comoLeer).toBe('La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.');
|
||||
expect(m30.notaMetodologica).toContain('La clasificación de EEG normal está pendiente de validación.');
|
||||
expect(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor } from './indicadores-cacu-palette';
|
||||
import { sortedPeriods } from './indicadores-periodos';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
|
||||
export interface HistoricoFigura {
|
||||
contrato: string;
|
||||
figure: PlotlyFigure;
|
||||
comoLeer: string;
|
||||
notaMetodologica?: string;
|
||||
suprimidos: string[];
|
||||
sinDato: string[];
|
||||
}
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
||||
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
|
||||
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
|
||||
const FONDO_AZUL = '#9DBFE380';
|
||||
@@ -96,32 +95,44 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
|
||||
return { validas, suprimidos, sinDato };
|
||||
}
|
||||
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
|
||||
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
// CaMa's line charts (and TEA's, which follow them) share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
|
||||
function colorDeLinea(id: string, tema: Tema) {
|
||||
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
|
||||
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
if (id.startsWith('cama_') || /^M\d+_/.test(id)) return { linea: MORADO[tema], relleno: FONDO_AZUL };
|
||||
const linea = c2Theme(tema).line;
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
// Normal takes the cool side of the palette and abnormal the warm one, as in the other domains' compositions.
|
||||
const NORMAL_EEG = C2_PALETTE.frios[3], ANORMAL_EEG = C2_PALETTE.calidos[0];
|
||||
|
||||
const PIE_PORCENTAJE: Readonly<Record<string, string>> = {
|
||||
cama_confirmacion_birads45: 'La línea representa el porcentaje de confirmación histopatológica.',
|
||||
[M30_RESULTADO_EEG]: 'Resultado experimental. La línea muestra EEG con alguna alteración detectada. La clasificación de EEG normal está pendiente de validación.',
|
||||
[M30_RESULTADO_EEG]: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
};
|
||||
const PIE_MEDIANA: Readonly<Record<string, string>> = Object.fromEntries(['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico'].map(id => [id,
|
||||
'La línea representa la mediana de los días de tamizaje a diagnóstico en cada periodo analizado. La banda sombreada incluye del primer al tercer cuartil.']));
|
||||
const PIE_CATEGORIAS: Readonly<Record<string, string>> = Object.fromEntries(['cama_histopatologia_birads', 'cama_birads_456_mastografia'].map(id => [id,
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría.']));
|
||||
'Cada barra indica el total de pacientes por periodo en cada categoría']));
|
||||
|
||||
type Trazo = Omit<HistoricoFigura, 'contrato'>;
|
||||
function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data);
|
||||
// A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here.
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0);
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
|
||||
const nombre = data.id === M30_RESULTADO_EEG ? 'EEG con alteración detectada' : 'Porcentaje';
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje');
|
||||
const trazo = data.id === M30_RESULTADO_EEG ? { linea: ANORMAL_EEG, relleno: ANORMAL_EEG + '40' } : colorDeLinea(data.id, tema);
|
||||
const resultadoEeg = data.id === M30_RESULTADO_EEG;
|
||||
const nombre = resultadoEeg ? 'EEG anormal' : 'Porcentaje';
|
||||
const complemento = (llave: string) => campo(validas, llave).map(v => v === null ? null : Math.round(10 * (100 - v)) / 10);
|
||||
// EEG results are two complementary lines; the normal one mirrors the abnormal share and its interval.
|
||||
const normal = data.id === M30_RESULTADO_EEG ? [
|
||||
banda(periodos.map(etiquetaPeriodo), complemento('ic_alto'), complemento('ic_bajo'), 'Intervalo de confianza (normal)', NORMAL_EEG, NORMAL_EEG + '40'),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'EEG normal', x: periodos.map(etiquetaPeriodo), y: complemento('valor'), connectgaps: false,
|
||||
line: { color: NORMAL_EEG, width: 2 }, marker: { color: NORMAL_EEG },
|
||||
text: validas.map(row => row ? `${(row['denominador'] as number) - (row['numerador'] as number)} de ${row['denominador']}` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} %<br>%{text}<extra></extra>' },
|
||||
] : [];
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
@@ -132,8 +143,10 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
...normal,
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: PIE_PORCENTAJE[data.id] ?? 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
...(resultadoEeg ? { notaMetodologica: 'Resultado experimental. La proporción usa el primer EEG de buena calidad de cada niño en el periodo. La clasificación de EEG normal está pendiente de validación.' } : {}),
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -191,6 +204,7 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones =
|
||||
? periodos.filter(p => !suprimidos.includes(p) && (numero(unidades?.[p]) ? unidades![p] === 0 : suma(p) === 0)) : []);
|
||||
const sinDato = periodos.filter(p => sinPoblacion.has(p) || (!suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))));
|
||||
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||
const isCaCu = data.id.startsWith('cacu_');
|
||||
return {
|
||||
figure: { data: orden.map((id, i) => {
|
||||
const meta = record(catalogo[id]) ? catalogo[id] : {};
|
||||
@@ -199,7 +213,8 @@ function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones =
|
||||
const slot = tono === 'neutro' ? i : curso[tono]++;
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) && !sinPoblacion.has(p) ? n : null; });
|
||||
return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores,
|
||||
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
marker: { color: (isCaCu ? cacuCategoryColor(id) : undefined) ?? c2Color(color, slot, tono),
|
||||
...(isCaCu ? { line: { color: c2Theme(tema).background, width: 1 } } : {}) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
|
||||
comoLeer: data.id === 'cama_birads_456_paciente' ? ''
|
||||
: CONTEOS[data.id]?.comoLeer ?? PIE_CATEGORIAS[data.id] ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
@@ -219,25 +234,3 @@ export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: Hist
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
}
|
||||
// The share of the children in the screening at each period's end who hadn't finished it, from M28's stages.
|
||||
export function enProcesoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura {
|
||||
const periodos = validar(data);
|
||||
const n = (periodo: string, categorias: readonly string[]) => {
|
||||
const valores = categorias.map(c => data.filas.find(f => f['periodo'] === periodo && f['categoria'] === c)?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
const puntos = periodos.map(periodo => {
|
||||
const proceso = n(periodo, M28_EN_PROCESO), completo = n(periodo, [M28_COMPLETO]);
|
||||
return proceso === null || completo === null || proceso + completo === 0 ? null : { proceso, base: proceso + completo };
|
||||
});
|
||||
const layout = ejes(data, periodos, [], tema, 'Porcentaje');
|
||||
return {
|
||||
contrato: 'C1',
|
||||
figure: { data: [{ type: 'scatter', mode: 'lines+markers', name: 'En proceso', x: periodos.map(etiquetaPeriodo), connectgaps: false, line: { color: C2_PALETTE.series[1], width: 2 },
|
||||
y: puntos.map(p => p && Math.round(1000 * p.proceso / p.base) / 10), text: puntos.map(p => p ? `${p.proceso} de ${p.base} niños` : ''),
|
||||
hovertemplate: '%{x}<br>%{y} % en proceso<br>%{text}<extra></extra>' }],
|
||||
layout: { ...layout, showlegend: false, margin: { ...layout.margin, b: data.tipo_periodo === 'mes' ? 84 : 64 }, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'De los niños en el tamizaje al cierre de cada periodo, el porcentaje que todavía no lo completaba con un EEG de buena calidad.',
|
||||
suprimidos: [], sinDato: periodos.filter((_, i) => !puntos[i]).map(etiquetaPeriodo),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, and its
|
||||
// Covers the history tab in the page: it sits between Indicadores and the risk analysis tab, and its
|
||||
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
@@ -30,7 +30,7 @@ describe('Pestaña Histórico', () => {
|
||||
|
||||
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -42,14 +42,14 @@ describe('Pestaña Histórico', () => {
|
||||
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
|
||||
it('TEA tiene Trazabilidad y Análisis de Riesgo', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
});
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Covers the series chips of TEA's Trazabilidad: which series a figure offers and how choosing one dims the rest.
|
||||
// Fixture: a figure with two lines, each preceded by its confidence band, as the EEG normal/anormal chart draws it.
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
import { resaltarSerie, seriesDe } from './indicadores-historico';
|
||||
|
||||
const figura = (): PlotlyFigure => ({ layout: {}, data: [
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza' },
|
||||
{ type: 'scatter', name: 'EEG anormal', line: { color: '#a00' }, marker: { color: '#a00' } },
|
||||
{ type: 'scatter', fill: 'toself', name: 'Intervalo de confianza (normal)' },
|
||||
{ type: 'scatter', name: 'EEG normal', line: { color: '#06a' } },
|
||||
] });
|
||||
|
||||
describe('Series de la trazabilidad de TEA', () => {
|
||||
it('ofrece una ficha por línea o barra y ninguna por banda', () => {
|
||||
// Fails if a confidence band becomes a chip of its own or a series loses its colour.
|
||||
expect(seriesDe(figura())).toEqual([{ nombre: 'EEG anormal', color: '#a00' }, { nombre: 'EEG normal', color: '#06a' }]);
|
||||
});
|
||||
|
||||
it('al elegir una serie atenúa las demás y sus bandas, y deja intacta la figura publicada', () => {
|
||||
// Fails if the chosen series is dimmed, if its band is dimmed with the other series, or if the original is mutated.
|
||||
const original = figura();
|
||||
const vista = resaltarSerie(original, 'EEG normal');
|
||||
expect(vista.data.map(t => t['opacity'])).toEqual([.15, .15, undefined, undefined]);
|
||||
expect(original.data.every(t => t['opacity'] === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { Subject } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { enProcesoFigura, etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
@@ -86,22 +86,15 @@ describe('Figuras de histórico', () => {
|
||||
expect(etiquetaPeriodo('2024-03')).toBe('mar 2024');
|
||||
expect(etiquetaPeriodo('2024-S2')).toBe('2024 S2');
|
||||
});
|
||||
it('el porcentaje en proceso suma las etapas antes del EEG sobre todos los niños en el tamizaje', () => {
|
||||
const fila = (periodo: string, categoria: string, n: number) => ({ periodo, categoria, n, suprimido: 0 });
|
||||
const { figure } = enProcesoFigura({ ...base, periodos: ['2024-01', '2024-02'], contrato: 'C2', filas: [
|
||||
fila('2024-01', 'EEG', 10), fila('2024-01', 'SOLO_MCHAT', 10), fila('2024-01', 'PSICOLOGIA', 10), fila('2024-01', 'NEUROPEDIATRIA', 10),
|
||||
fila('2024-02', 'EEG', 30), fila('2024-02', 'SOLO_MCHAT', 5), fila('2024-02', 'PSICOLOGIA', 5), fila('2024-02', 'NEUROPEDIATRIA', 0)] }, 'claro');
|
||||
expect(figure.data[0]['y']).toEqual([75, 25]);
|
||||
expect(figure.data[0]['x']).toEqual(['ene 2024', 'feb 2024']);
|
||||
});
|
||||
it('una escala compartida fija el máximo de las medianas', () => {
|
||||
const data: IndicadorDatos = { ...base, periodos: ['2024-01'], contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] };
|
||||
expect((historicoFigura(data, 'claro', { yMax: 90 }).figure.layout['yaxis'] as { range: number[] }).range).toEqual([0, 90]);
|
||||
expect((historicoFigura(data, 'claro').figure.layout['yaxis'] as { range?: number[] }).range).toBeUndefined();
|
||||
});
|
||||
it('M21 y M22 no usan verde en sus líneas', () => {
|
||||
it('las líneas de M21 y M22 siguen el morado de las de CaMa', () => {
|
||||
// Fails if TEA's lines go back to their own age colours or leave CaMa's purple mark.
|
||||
const color = (id: string) => (historicoFigura({ ...base, id, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure.data[1]['line'] as { color: string }).color;
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#2F6DB3'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#A23E8C');
|
||||
expect(color('M21_diagnosticados_con_eeg')).toBe('#9C42C2'); expect(color('M22_diagnosticados_sin_eeg')).toBe('#9C42C2');
|
||||
});
|
||||
it('rechaza contratos sin representación y filas ambiguas', () => {
|
||||
expect(() => historicoFigura({ ...base, contrato: 'C9', filas: [] }, 'claro')).toThrow('no soportada');
|
||||
@@ -179,23 +172,45 @@ describe('Pestaña Histórico', () => {
|
||||
expect(c.ventana()).toBe(5);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('agrupa los tres pasos de tiempo y añade el porcentaje en proceso tras los casos', () => {
|
||||
const items: Indicador[] = ['M28_casos_por_estado', 'M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico']
|
||||
.map(id => ({ id, titulo: id, contrato: id.startsWith('M28') ? 'C2' : 'C3r', figuras: [], tipos_periodo: ['mes'] }));
|
||||
it('ordena y titula las ocho gráficas de Trazabilidad y agrupa los tres pasos de tiempo', () => {
|
||||
const items: Indicador[] = [
|
||||
{ id: 'M30_resultado_eeg', titulo: 'Porcentaje de EEG normal y anormal', contrato: 'C1' },
|
||||
{ id: 'M29_calidad_eeg', titulo: 'Calidad del EEG', contrato: 'C2' },
|
||||
{ id: 'M28_casos_por_estado', titulo: 'Casos por estatus', contrato: 'C2' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', titulo: 'Días de ADOS-2 a diagnóstico', contrato: 'C3r' },
|
||||
{ id: 'M26_dias_mchat_ados2', titulo: 'Días de M-CHAT a ADOS-2', contrato: 'C3r' },
|
||||
{ id: 'M25_dias_mchat_diagnostico', titulo: 'Días de M-CHAT a diagnóstico positivo', contrato: 'C3r' },
|
||||
{ id: 'M24_confirmacion_diagnostico', titulo: 'Porcentaje de confirmación diagnóstica', contrato: 'C1' },
|
||||
{ id: 'M23_pacientes_evaluados', titulo: 'Pacientes evaluados por resultado diagnóstico', contrato: 'C2' },
|
||||
{ id: 'M22_diagnosticados_sin_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', contrato: 'C1' },
|
||||
{ id: 'M21_diagnosticados_con_eeg', titulo: 'Porcentaje de pacientes con diagnóstico de TEA con EEG', contrato: 'C1' },
|
||||
].map(item => ({ ...item, figuras: [], tipos_periodo: ['mes'] }));
|
||||
fixture.componentRef.setInput('catalog', items); fixture.componentRef.setInput('active', true); render();
|
||||
const pasos = ['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo'];
|
||||
const titulos = () => Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.panel h2'), el => el.textContent?.trim());
|
||||
expect(titulos().slice(0, 3)).toEqual(pasos);
|
||||
for (const { id } of items) http.expectOne(`/tea/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: '2024-01', tipo: 'mes' }] });
|
||||
for (const { id } of items) {
|
||||
const c2 = id.startsWith('M28');
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato: c2 ? 'C2' : 'C3r', tipo_periodo: 'mes', periodos: ['2024-01'],
|
||||
filas: c2 ? [{ periodo: '2024-01', categoria: 'EEG', n: 3, orden: 0, suprimido: 0 }, { periodo: '2024-01', categoria: 'SOLO_MCHAT', n: 1, orden: 1, suprimido: 0 }, { periodo: '2024-01', categoria: 'PSICOLOGIA', n: 0, orden: 2, suprimido: 0 }, { periodo: '2024-01', categoria: 'NEUROPEDIATRIA', n: 0, orden: 3, suprimido: 0 }]
|
||||
: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 }] });
|
||||
for (const { id, contrato } of items) {
|
||||
const periodo = '2024-01';
|
||||
const fila = contrato === 'C1' ? c1(periodo, 50) : contrato === 'C2' ? c2(periodo, 'A', 3, 0)
|
||||
: { periodo, suprimido: 0, n: 9, mediana: 5, q1: 2, q3: id.startsWith('M25') ? 100 : 10 };
|
||||
http.expectOne(r => r.url === `/tea/indicadores/${id}/datos`).flush({ id, contrato, tipo_periodo: 'mes', periodos: [periodo], filas: [fila] });
|
||||
}
|
||||
render();
|
||||
const paneles = fixture.componentInstance.paneles();
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']);
|
||||
expect(titulos()).toEqual([
|
||||
'Tiempos del tamizaje', 'Progresión del proceso diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Flujo del proceso diagnóstico y estudios de EEG', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal',
|
||||
]);
|
||||
const grupo = paneles[0] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(grupo.pasos!.map(p => (p.figura.figure.layout['yaxis'] as { range: number[] }).range[1])).toEqual([105, 105, 105]);
|
||||
expect(fixture.nativeElement.querySelectorAll('.pasos section')).toHaveLength(3);
|
||||
expect(Array.from((fixture.nativeElement as HTMLElement).querySelectorAll('.pasos h3'), el => el.textContent?.trim())).toEqual(pasos);
|
||||
// The notes live in the round help, not as text under the chart.
|
||||
expect((fixture.nativeElement as HTMLElement).querySelector('.panel:last-child p.nota')).toBeNull();
|
||||
const ayuda = (fixture.nativeElement as HTMLElement).querySelector('.panel:last-child app-indicador-ayuda') as HTMLElement;
|
||||
ayuda.querySelector('button')!.click(); fixture.detectChanges();
|
||||
expect(ayuda.querySelector('.ayuda-texto')!.textContent).toContain('Resultado experimental.');
|
||||
});
|
||||
it('TEA ordena sus paneles como se pidió y deja al final lo que la lista no nombra', () => {
|
||||
// Fails if the catalog's own order shows through, if M30 does not close the list or if an unnamed indicator is dropped.
|
||||
|
||||
@@ -7,14 +7,16 @@ import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { defer, map, Subscription } from 'rxjs';
|
||||
import { IndicadorAyuda } from './indicador-ayuda';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura, M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos';
|
||||
import { IndicadoresPeriodos } from './indicadores-periodos';
|
||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema, TipoPeriodo } from './indicadores.models';
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
import { TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD } from './indicadores-kpi';
|
||||
|
||||
export { HISTORICO_CAMA };
|
||||
|
||||
@@ -31,8 +33,11 @@ type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' | 'desarrollo' | 'error' }
|
||||
| { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
class ContratoHistoricoInvalido extends Error {}
|
||||
const TIEMPOS = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
const CASOS = 'M28_casos_por_estado';
|
||||
const TIEMPOS = TEA_FIGURAS_OPORTUNIDAD;
|
||||
const TITULOS_TEA: Readonly<Record<string, string>> = {
|
||||
M23_pacientes_evaluados: 'Progresión del proceso diagnóstico',
|
||||
M28_casos_por_estado: 'Flujo del proceso diagnóstico y estudios de EEG',
|
||||
};
|
||||
const PERSONALIZADO = -1;
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p)));
|
||||
@@ -43,29 +48,46 @@ function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
...(reportes.length ? { reportes } : {}), ...(a['unidades_periodo'] || b['unidades_periodo'] ? { unidades_periodo: unidades } : {}) };
|
||||
}
|
||||
|
||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
|
||||
// Keep the individual cards available for loading, error and empty states.
|
||||
function agruparTiempos(paneles: Panel[]): Panel[] {
|
||||
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
|
||||
const listos = pasos.every(p => p?.estado === 'listo');
|
||||
return paneles.flatMap((panel): Panel[] => {
|
||||
if (listos && panel.item.id === TIEMPOS[0] && panel.estado === 'listo') {
|
||||
const figuras = pasos.map(p => ({ titulo: p!.item.titulo, figura: (p as Extract<Panel, { estado: 'listo' }>).figura }));
|
||||
const notas = (campo: 'suprimidos' | 'sinDato') => [...new Set(figuras.flatMap(f => f.figura[campo]))];
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos de tamizaje por paso', contrato: 'C3r' }, pasos: figuras,
|
||||
return [{ ...panel, item: { id: 'tiempos', titulo: 'Tiempos del tamizaje', contrato: 'C3r' }, pasos: figuras,
|
||||
figura: { ...panel.figura, comoLeer: 'La línea es la mediana de días de cada paso y la banda va del primer al tercer cuartil. Las tres usan la misma escala. Las medianas de los pasos no tienen que sumar la del total.',
|
||||
suprimidos: notas('suprimidos'), sinDato: notas('sinDato') } }];
|
||||
}
|
||||
if (listos && TIEMPOS.includes(panel.item.id)) return [];
|
||||
if (panel.item.id === CASOS && panel.estado === 'listo' && panel.datos) {
|
||||
return [panel, { item: { id: 'en_proceso', titulo: 'Porcentaje de niños en proceso', contrato: 'C1' }, rango: panel.rango, estado: 'listo', figura: enProcesoFigura(panel.datos, tema) }];
|
||||
}
|
||||
return [panel];
|
||||
});
|
||||
}
|
||||
|
||||
interface SerieResaltable { nombre: string; color: string }
|
||||
const nombreDe = (trazo: Record<string, unknown>) => typeof trazo['name'] === 'string' ? trazo['name'] : '';
|
||||
// Bands are drawn with their line: they are not series of their own.
|
||||
const esBanda = (trazo: Record<string, unknown>) => trazo['fill'] === 'toself';
|
||||
function colorDe(trazo: Record<string, unknown>): string {
|
||||
const marca = trazo['marker'] as { color?: unknown } | undefined, linea = trazo['line'] as { color?: unknown } | undefined;
|
||||
const color = typeof marca?.color === 'string' ? marca.color : linea?.color;
|
||||
return typeof color === 'string' ? color : 'currentColor';
|
||||
}
|
||||
export function seriesDe(figura: PlotlyFigure): SerieResaltable[] {
|
||||
return figura.data.filter(trazo => !esBanda(trazo) && nombreDe(trazo)).map(trazo => ({ nombre: nombreDe(trazo), color: colorDe(trazo) }));
|
||||
}
|
||||
// Dims every series but the chosen one; a band follows the line drawn right after it.
|
||||
export function resaltarSerie(figura: PlotlyFigure, elegida: string): PlotlyFigure {
|
||||
const data = figura.data.map((trazo, i) => {
|
||||
const propio = esBanda(trazo) ? nombreDe(figura.data[i + 1] ?? {}) : nombreDe(trazo);
|
||||
return propio === elegida ? trazo : { ...trazo, opacity: .15 };
|
||||
});
|
||||
return { ...figura, data };
|
||||
}
|
||||
|
||||
// TEA's panels in the order of the request; whatever it does not name keeps the catalog's order after them.
|
||||
const ORDEN_TEA = ['tiempos', 'M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg', 'M22_diagnosticados_sin_eeg',
|
||||
CASOS, 'en_proceso', 'M29_calidad_eeg', M30_RESULTADO_EEG];
|
||||
const ORDEN_TEA = [...TIEMPOS, ...TEA_FIGURAS_CLINICAS, M30_RESULTADO_EEG];
|
||||
function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
const lugar = (panel: Panel) => { const i = orden.indexOf(panel.item.id); return i < 0 ? orden.length : i; };
|
||||
return paneles.map((panel, i) => ({ panel, i })).sort((a, b) => lugar(a.panel) - lugar(b.panel) || a.i - b.i).map(({ panel }) => panel);
|
||||
@@ -75,7 +97,7 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||
@Component({
|
||||
selector: 'app-indicadores-historico',
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart, IndicadorAyuda],
|
||||
template: `
|
||||
<div class="controles compacto">
|
||||
<h2>Filtros</h2>
|
||||
@@ -99,6 +121,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="paneles">
|
||||
@for (panel of paneles(); track panel.item.id) {
|
||||
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||
@if (dominio() === 'tea' && panel.estado === 'listo' && panel.figura.comoLeer) {
|
||||
<app-indicador-ayuda [etiqueta]="'Cómo leer: ' + panel.item.titulo"><p class="ayuda-texto">{{ panel.figura.comoLeer }}@if (panel.figura.notaMetodologica) { {{ panel.figura.notaMetodologica }} }</p></app-indicador-ayuda>
|
||||
}
|
||||
<h2>{{ panel.item.titulo }}</h2>
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@if (panel.mensaje) {
|
||||
@@ -117,15 +142,26 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
<div class="pasos">
|
||||
@for (paso of pasos; track paso.titulo) {
|
||||
<section><h3>{{ paso.titulo }}</h3>
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="'Histórico de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
<app-plotly-chart [style.--plot-height]="'340px'" [showNotes]="false" [figure]="paso.figura.figure" [label]="etiquetaVista() + ' de ' + paso.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
} @else {
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
@if (series(panel); as lista) {
|
||||
@if (dominio() === 'tea' && lista.length > 1) {
|
||||
<div class="series" role="group" aria-label="Resaltar una serie">
|
||||
@for (serie of lista; track serie.nombre) {
|
||||
<button type="button" [style.--swatch]="serie.color" [attr.aria-pressed]="resaltados()[panel.item.id] === serie.nombre" (click)="resaltar(panel.item.id, serie.nombre)">
|
||||
<span class="swatch" [style.background]="serie.color" aria-hidden="true"></span>{{ serie.nombre }}
|
||||
</button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="vistas()[panel.item.id] ?? panel.figura.figure"
|
||||
[label]="etiquetaVista() + ' de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
||||
}
|
||||
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.comoLeer && dominio() !== 'tea') { <p class="nota">{{ panel.figura.comoLeer }}</p> }
|
||||
@if (panel.figura.suprimidos.length) {
|
||||
<details class="nota-pie">
|
||||
<summary>Datos suprimidos</summary>
|
||||
@@ -167,9 +203,9 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
|
||||
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
@container dashboard (min-width: 1304px) { .paneles { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
.panel { position: relative; box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
h2 { margin: 0; padding-right: 2.5rem; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.nota-pie { margin-top: var(--issste-space-3); padding-top: var(--issste-space-2); border-top: 1px solid var(--issste-border); color: var(--issste-text-secondary); font-size: 0.8125rem; line-height: 1.4; }
|
||||
@@ -177,6 +213,14 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
.nota-pie summary:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.nota-pie p { margin-top: var(--issste-space-2); font: inherit; }
|
||||
app-plotly-chart { margin-top: var(--issste-space-3); }
|
||||
app-indicador-ayuda p { margin: 0; }
|
||||
.series { display: flex; flex-wrap: wrap; gap: .25rem .75rem; margin-top: var(--issste-space-3); }
|
||||
// The look of CaMa's category chips: rounded, outlined with the series colour, tinted when chosen.
|
||||
.series button { display: inline-flex; align-items: center; gap: .45rem; min-height: 36px; padding: .25rem .75rem; border: 1px solid color-mix(in srgb, var(--swatch) 55%, var(--issste-border));
|
||||
border-radius: .75rem; background: var(--issste-surface); color: inherit; font: inherit; font-size: .875rem; cursor: pointer; }
|
||||
.series button[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); font-weight: 600; }
|
||||
.series button:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
|
||||
.swatch { width: .75rem; height: .75rem; flex-shrink: 0; border: 1px solid currentColor; border-radius: 2px; }
|
||||
.panel.ancho { grid-column: 1 / -1; }
|
||||
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
|
||||
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||
@@ -186,12 +230,30 @@ function ordenar(paneles: Panel[], orden: readonly string[]): Panel[] {
|
||||
})
|
||||
export class IndicadoresHistorico {
|
||||
readonly dominio = input.required<Dominio>();
|
||||
// The series each panel's chart draws, which a chip can highlight; one selection per panel.
|
||||
readonly resaltados = signal<Readonly<Record<string, string>>>({});
|
||||
series(panel: Panel): readonly SerieResaltable[] { return panel.estado === 'listo' ? seriesDe(panel.figura.figure) : []; }
|
||||
resaltar(id: string, nombre: string) {
|
||||
this.resaltados.update(actual => {
|
||||
const { [id]: previo, ...resto } = actual;
|
||||
return previo === nombre ? resto : { ...actual, [id]: nombre };
|
||||
});
|
||||
}
|
||||
// The figure of each panel with a selected series; the others keep their published figure untouched.
|
||||
readonly vistas = computed<Readonly<Record<string, PlotlyFigure>>>(() => {
|
||||
const elegidas = this.resaltados();
|
||||
return Object.fromEntries(this.paneles().flatMap(panel => {
|
||||
const nombre = elegidas[panel.item.id];
|
||||
return nombre && panel.estado === 'listo' ? [[panel.item.id, resaltarSerie(panel.figura.figure, nombre)]] : [];
|
||||
}));
|
||||
});
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
readonly catalogLoading = input(false);
|
||||
readonly catalogError = input('');
|
||||
readonly retryCatalog = output<void>();
|
||||
readonly etiquetaVista = computed(() => 'Trazabilidad');
|
||||
// What the domain declares for its history (`indicadores-historico-config`); none for a domain that draws its catalog.
|
||||
private readonly config = computed(() => historicoDeDominio(this.dominio()));
|
||||
// The indicators the tab draws: the domain's fixed list, where the catalog publishes it and the panel is active;
|
||||
@@ -260,7 +322,7 @@ export class IndicadoresHistorico {
|
||||
const visibles = this.recortar(carga.datos.periodos);
|
||||
return carga.datos.filas.filter(f => visibles.includes(f['periodo'] as string)).map(f => (f['q3'] as number | null) ?? 0);
|
||||
})) * 1.05;
|
||||
const panelDe = (item: Indicador): Panel & { datos?: IndicadorDatos } => {
|
||||
const panelDe = (item: Indicador): Panel => {
|
||||
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
|
||||
const carga = cargas?.[item.id];
|
||||
if (!carga) return { item, estado: 'cargando' };
|
||||
@@ -284,7 +346,7 @@ export class IndicadoresHistorico {
|
||||
if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) {
|
||||
return { item, estado: mensaje ? 'error' : 'vacio', mensaje };
|
||||
}
|
||||
return { item, rango, estado: 'listo', figura, datos, mensaje };
|
||||
return { item, rango, estado: 'listo', figura, mensaje };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
@@ -303,8 +365,10 @@ export class IndicadoresHistorico {
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles;
|
||||
const items = this.catalog().filter(item => item.tipos_periodo.includes(tipo));
|
||||
if (this.dominio() !== 'tea') return items.map(panelDe);
|
||||
const paneles = items.map(item => panelDe({ ...item, titulo: TITULOS_TEA[item.id] ?? item.titulo }));
|
||||
return agruparTiempos(ordenar(paneles, ORDEN_TEA));
|
||||
});
|
||||
|
||||
constructor() {
|
||||
|
||||
@@ -78,8 +78,9 @@ describe('KPI de tratamiento de CaCu', () => {
|
||||
expect(cards[0].querySelector('.value')).toBeNull();
|
||||
expect(cards[1].querySelector('.value')?.firstChild?.textContent).toBe('7.75');
|
||||
expect(cards[1].querySelector('.period')?.textContent).toContain(PERIOD);
|
||||
expect(cards[1].textContent).toContain('El evento de tratamiento se infiere de notas clínicas');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')?.textContent).not.toContain('diagnóstico a tratamiento');
|
||||
// the cards carry no provisional notice: what the measure is lives in its technical sheet
|
||||
expect(cards[1].textContent).not.toContain('Indicador provisional');
|
||||
expect(root.querySelector('.kpi-section .catalog-grid')).toBeNull();
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
|
||||
@@ -22,7 +22,6 @@ const CACU_TRATAMIENTO_C3R = {
|
||||
unit: 'días (mediana)',
|
||||
requiresObservations: true,
|
||||
c3rInfo: (n, q1, q3) => `${n} ${n === 1 ? 'observación' : 'observaciones'}. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
note: 'Indicador provisional. El evento de tratamiento se infiere de notas clínicas, sin confirmación de que se realizó.',
|
||||
} satisfies Omit<KpiDefinition, 'id' | 'title'>;
|
||||
|
||||
export const CACU_TRATAMIENTO_KPIS: readonly KpiDefinition[] = [
|
||||
@@ -50,11 +49,11 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
// cards read the `titulo` that the API already sends.
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
// M28's last stage follows neuropediatrics and requires a good EEG.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
export const M29_MALO = 'MALO';
|
||||
// What only TEA's summary paragraph needs: the children by stage, the time of each screening step and the EEGs by quality.
|
||||
export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
{ id: 'M28_casos_por_estado', title: 'Niños en el tamizaje', contrato: 'C2', unit: 'pacientes' },
|
||||
@@ -67,17 +66,15 @@ export const KPI_RESUMEN_TEA: KpiDefinition[] = [
|
||||
export const TEA_FIGURAS_OPORTUNIDAD: readonly string[] = ['M26_dias_mchat_ados2', 'M27_dias_ados2_diagnostico', 'M25_dias_mchat_diagnostico'];
|
||||
export const TEA_FIGURAS_CLINICAS: readonly string[] = ['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg'];
|
||||
// CaCu's figures under «Indicadores de oportunidad» (section «Tiempo de tamizaje a diagnóstico») in display order. A slot
|
||||
// with no `id` has no published indicator yet and draws as pending; `titulo` is the name the page gives the figure.
|
||||
// CaCu's available figures in display order; titles are assigned when the catalog publishes them.
|
||||
export interface FiguraOportunidad { id?: string; titulo: string; }
|
||||
export const CACU_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Tiempo de toma de muestra a resultado de citología' },
|
||||
{ titulo: 'Tiempo de toma de muestra a resultado de VPH' },
|
||||
{ id: 'cacu_dias_toma_colposcopia', titulo: 'Tiempo de toma de muestra a resultado de colposcopía' },
|
||||
{ id: 'cacu_dias_toma_biopsia', titulo: 'Tiempo de toma de muestra a resultado de biopsia' },
|
||||
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de toma de muestra a diagnóstico' },
|
||||
];
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. Same rules as CaCu's: an entry
|
||||
// CaMa's five times of «Tiempo de tamizaje a diagnóstico», in the order of the request. An entry
|
||||
// with no `id` has no published indicator yet and draws as pending.
|
||||
export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Tiempo de toma de mastografía a interpretación radiológica' },
|
||||
@@ -86,9 +83,8 @@ export const CAMA_FIGURAS_OPORTUNIDAD: readonly FiguraOportunidad[] = [
|
||||
{ titulo: 'Tiempo de diagnóstico a tratamiento' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
|
||||
];
|
||||
// CaCu's clinical figures in display order, and the one still to be implemented.
|
||||
// CaCu's clinical figures in display order.
|
||||
export const CACU_FIGURAS_CLINICAS: readonly string[] = ['cacu_eu7', 'cacu_confirmacion_citologia'];
|
||||
export const CACU_FIGURA_CLINICA_PENDIENTE = 'Progresión por grupo de riesgo';
|
||||
export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
tea: [
|
||||
{ id: 'M23_pacientes_evaluados', title: 'Total de pacientes evaluados', contrato: 'C2', unit: 'pacientes' },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<section class="dashboard" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<section class="dashboard" [class.dominio-tea]="dominio === 'tea'" [class.reporte-impresion]="preparandoReporte()" aria-labelledby="dashboard-title">
|
||||
<header>
|
||||
@if (fichaPacienteAbierta()) {
|
||||
<h1 id="dashboard-title">Ficha del paciente</h1>
|
||||
@@ -126,14 +126,13 @@
|
||||
<span>Incluye el periodo y los indicadores seleccionados. Elige «Guardar como PDF» en el cuadro de impresión.</span>
|
||||
</div>
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" [tipo]="filters?.applied?.tipo ?? 'semestre'" [periodos]="periodosDelFiltro()" /> }
|
||||
<div class="catalog-grid">
|
||||
@for (item of clinicosItems(); track cardIdentity(item)) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||
[pinned]="isPinned(item)" [companion]="companion(item)" [companionApplied]="companionApplied(item)" [vph]="vph(item)" [vphApplied]="vphApplied(item)" (pinChanged)="togglePinned(item)" />
|
||||
}
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@if (dominio === 'cacu') { <app-indicador-figura-pendiente [titulo]="figuraClinicaPendiente" /> }
|
||||
</div>
|
||||
@if (dominio === 'cama') {
|
||||
<div class="kpi-grid" style="--kpi-count: 1">
|
||||
|
||||
@@ -34,6 +34,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
overflow-wrap: anywhere; margin: var(--issste-space-2) 0 var(--issste-space-4); }
|
||||
@container dashboard (min-width: 600px) { .kpi-grid { grid-template-columns: repeat(min(2, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1304px) { .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
// TEA draws three smaller plots per row.
|
||||
.dominio-tea .catalog-grid { --plot-height: 340px; }
|
||||
@container dashboard (min-width: 1000px) { .dominio-tea .catalog-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-flow: dense; } }
|
||||
|
||||
@media (max-width: 550px) {
|
||||
h1 { font-size: 1.5rem; }
|
||||
|
||||
@@ -227,7 +227,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
filters.select([]); filters.year = '2025'; filters.unit = 'S1'; filters.add();
|
||||
const draft = structuredClone(filters.entry.draft), applied = structuredClone(page.filters!.applied);
|
||||
const result = panel.result();
|
||||
const button = fixture.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement;
|
||||
// TEA's reading guide is the round "?" button: its first opening loads the metadata once.
|
||||
const button = fixture.nativeElement.querySelector('.ayuda-boton') as HTMLButtonElement;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
button.click(); fixture.detectChanges();
|
||||
if (i === 0) {
|
||||
@@ -287,7 +288,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
||||
});
|
||||
it('controles permanentes conservan IDs únicos y foco al salir del viewport', () => {
|
||||
load(); toggle(); flushAll();
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .methodology-toggle');
|
||||
const input = fixture.nativeElement.querySelector('app-indicador-catalog-card .ayuda-boton');
|
||||
input.focus(); cards()[0].setVisible(false); fixture.detectChanges(); expect(document.activeElement).toBe(input);
|
||||
const ids = Array.from(fixture.nativeElement.querySelectorAll('[id]') as NodeListOf<HTMLElement>).map(e => e.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -17,13 +17,15 @@ import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { esSocioConteos } from './indicadores-conteos-pareados';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, CACU_FIGURA_CLINICA_PENDIENTE, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, CACU_TRATAMIENTO_KPIS, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, CACU_FIGURAS_CLINICAS, CACU_FIGURAS_OPORTUNIDAD, CAMA_CONFIRMACION_KPI, CAMA_FIGURAS_OPORTUNIDAD, KpiCardSlot, TEA_FIGURAS_CLINICAS, TEA_FIGURAS_OPORTUNIDAD, camaKpiCards } from './indicadores-kpi';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorScreeningRoute } from './indicador-screening-route';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { IndicadorFiguraPendiente } from './indicador-figura-pendiente';
|
||||
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
|
||||
import { ID_VPH } from './indicadores-vph-genotipo';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
@@ -37,6 +39,7 @@ import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { historicoDeDominio } from './indicadores-historico-config';
|
||||
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { M30_RESULTADO_EEG } from './indicadores-historico-figures';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
@@ -44,9 +47,11 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
// TEA and CaMa have enough periods for their history to say anything; the epidemiological analysis is CaMa's,
|
||||
// between its history and its follow-up list.
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, SECTIONS[1], SECTIONS[2]];
|
||||
const SECTIONS_TEA: typeof SECTIONS = [
|
||||
{ id: 'resumen', label: 'Resumen' }, { id: 'historico', label: 'Trazabilidad' }, { id: 'seguimiento', label: 'Análisis de Riesgo' }, SECTIONS[2],
|
||||
];
|
||||
const SECTIONS_CACU: typeof SECTIONS = [SECTIONS[0], { id: 'historico', label: 'Trazabilidad' }, SECTIONS[1], SECTIONS[2]];
|
||||
// Whether CaMa offers the Análisis tab. While off, its panel is a placeholder and the component is not rendered.
|
||||
export const CAMA_ANALYSIS_ENABLED = false;
|
||||
// TEA's figures in the order of its two sections; the indicators the sections do not name keep the catalog's order after them.
|
||||
@@ -56,7 +61,7 @@ function ordenTea(catalog: Indicador[]): Indicador[] {
|
||||
return [...first, ...catalog.filter(item => !named.includes(item.id))];
|
||||
}
|
||||
const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
SECTIONS_WITH_HISTORY[0], SECTIONS_WITH_HISTORY[1],
|
||||
SECTIONS_WITH_HISTORY[0], { id: 'historico', label: 'Trazabilidad' },
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
SECTIONS_WITH_HISTORY[2], SECTIONS_WITH_HISTORY[3]];
|
||||
|
||||
@@ -67,7 +72,11 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
styleUrl: './indicadores-page.scss',
|
||||
})
|
||||
export class IndicadoresPage {
|
||||
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
|
||||
get sections(): typeof SECTIONS {
|
||||
if (this.dominio === 'tea') return SECTIONS_TEA;
|
||||
if (this.dominio === 'cacu') return SECTIONS_CACU;
|
||||
return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS;
|
||||
}
|
||||
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
@@ -319,6 +328,11 @@ export class IndicadoresPage {
|
||||
};
|
||||
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
|
||||
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
|
||||
// The biopsy donut of the histopathological confirmation indicator is drawn on CaCu's EU7 card.
|
||||
companion(item: Indicador) { return this.dominio === 'cacu' && item.id === 'cacu_eu7' ? this.catalog().find(other => other.id === ID_CONFIRMACION) : undefined; }
|
||||
companionApplied(item: Indicador) { const other = this.companion(item); return other ? this.figureApplied(other) : undefined; }
|
||||
vph(item: Indicador) { return this.dominio === 'cacu' && item.id === 'cacu_eu7' ? this.catalog().find(other => other.id === ID_VPH) : undefined; }
|
||||
vphApplied(item: Indicador) { const other = this.vph(item); return other ? this.figureApplied(other) : undefined; }
|
||||
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
|
||||
kpiIndicator(id: string) {
|
||||
const published = this.catalog().find(item => item.id === id);
|
||||
@@ -344,6 +358,12 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
||||
}
|
||||
/** The periods the page's filter applies, for the charts that follow it with no filter of their own (the screening
|
||||
* route); `undefined` when it applies every period. */
|
||||
periodosDelFiltro(): readonly string[] | undefined {
|
||||
const seleccion = this.filters?.applied.selection;
|
||||
return seleccion?.mode === 'explicit' ? seleccion.periodos : undefined;
|
||||
}
|
||||
// CaCu's screening route chart, once the catalog publishes every measure it reads.
|
||||
get screeningRouteAvailable() {
|
||||
return this.dominio === 'cacu' && ROUTE_IDS.every(id => this.catalog().some(item => item.id === id));
|
||||
@@ -386,7 +406,7 @@ export class IndicadoresPage {
|
||||
return this.dominio === 'cacu'
|
||||
? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7' && !route.includes(item.id))]
|
||||
: this.dominio === 'cama' ? this.cardsDeCama(catalog)
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => !item.vistas || item.vistas.includes('resumen')))
|
||||
: this.dominio === 'tea' ? ordenTea(catalog.filter(item => item.id !== M30_RESULTADO_EEG && (!item.vistas || item.vistas.includes('resumen'))))
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
@@ -400,8 +420,9 @@ export class IndicadoresPage {
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
|
||||
});
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary, and CaCu's five times, each a
|
||||
// pending slot while the catalog does not publish its indicator. The rest are the clinical ones.
|
||||
// The figures of «Indicadores de oportunidad»: TEA's time figures under its summary and CaMa's times, each a pending
|
||||
// slot while the catalog does not publish its indicator; CaCu's, only when its screening route chart isn't shown. The
|
||||
// rest are the clinical ones.
|
||||
// The domain is not a signal: each result reads the items first, so a new catalog recomputes it whichever domain it was last for.
|
||||
readonly oportunidadSlots = computed((): { item?: Indicador; titulo: string }[] => {
|
||||
const items = this.searchResults().items;
|
||||
@@ -416,26 +437,25 @@ export class IndicadoresPage {
|
||||
return item ? { item: { ...item, titulo: figura.titulo }, titulo: figura.titulo } : { titulo: figura.titulo };
|
||||
});
|
||||
}
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length) return [];
|
||||
// The screening route chart draws the measures only it uses (ROUTE_ONLY_IDS) and they get no card of their own while
|
||||
// it is shown, so those slots are left to the chart instead of drawn twice or as pending.
|
||||
const delaRuta = this.screeningRouteAvailable ? ROUTE_ONLY_IDS : [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.filter(figura => !figura.id || !delaRuta.includes(figura.id)).map(figura => {
|
||||
const item = figura.id ? items.find(candidate => candidate.id === figura.id) : undefined;
|
||||
return item ? { item, titulo: item.titulo } : { titulo: figura.titulo };
|
||||
// With the screening route chart, CaCu has no separate time figures: the chart shows every time from the sample to
|
||||
// each event. Without it, each time the catalog publishes with a figure keeps its own.
|
||||
if (this.dominio !== 'cacu' || !this.catalog().length || this.screeningRouteAvailable) return [];
|
||||
return CACU_FIGURAS_OPORTUNIDAD.flatMap(figura => {
|
||||
const item = items.find(candidate => candidate.id === figura.id && candidate.figuras.length > 0);
|
||||
return item ? [{ item, titulo: item.titulo }] : [];
|
||||
});
|
||||
});
|
||||
readonly clinicosItems = computed(() => {
|
||||
const items = this.searchResults().items;
|
||||
if (this.dominio === 'cacu') {
|
||||
// The opportunity section already presents the time figures and the treatment KPIs.
|
||||
const clinicos = items.filter(item => item.figuras.length && !this.esKpiTratamientoCacu(item.id)
|
||||
// HPV by genotype is drawn on the donut card, not as a card of its own.
|
||||
const clinicos = items.filter(item => item.figuras.length && item.id !== ID_VPH && !this.esKpiTratamientoCacu(item.id)
|
||||
&& !CACU_FIGURAS_OPORTUNIDAD.some(figura => figura.id === item.id));
|
||||
return [...CACU_FIGURAS_CLINICAS.flatMap(id => clinicos.filter(item => item.id === id)), ...clinicos.filter(item => !CACU_FIGURAS_CLINICAS.includes(item.id))];
|
||||
}
|
||||
return this.dominio === 'tea' ? items.filter(item => !TEA_FIGURAS_OPORTUNIDAD.includes(item.id)) : items;
|
||||
});
|
||||
readonly figuraClinicaPendiente = CACU_FIGURA_CLINICA_PENDIENTE;
|
||||
// CaMa's confirmation rate closes its clinical section: a number card, pending while the catalog does not publish it.
|
||||
readonly confirmacionCama = CAMA_CONFIRMACION_KPI;
|
||||
get confirmacionCamaPendiente() { return !this.catalog().some(item => item.id === CAMA_CONFIRMACION_KPI.id); }
|
||||
|
||||
@@ -163,7 +163,8 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
|
||||
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
|
||||
expect(e.page.seleccionSeguimiento()).toBeUndefined();
|
||||
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
|
||||
['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
dominio === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -33,14 +33,14 @@ describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
const ruta = () => fixture.nativeElement.querySelector('app-indicador-screening-route');
|
||||
const tarjetas = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => (d.componentInstance as IndicadorCatalogCard).indicador.id);
|
||||
|
||||
it('con las siete medidas publicadas aparece la gráfica y sus medidas exclusivas no tienen tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of the five measures only it draws, while the cytology's and the diagnosis'
|
||||
// keep theirs. Fails if the chart stops appearing, or a measure it draws also shows as a card.
|
||||
it('con las siete medidas publicadas aparece la gráfica y ninguna de sus medidas tiene tarjeta', () => {
|
||||
// Pins down: the chart replaces the cards of every time it draws, the cytology's and the diagnosis' included (the
|
||||
// «Tiempo de tamizaje a diagnóstico» figures). Fails if the chart stops appearing, or a time it draws also shows as
|
||||
// a card.
|
||||
abrir('cacu', [item('cacu_eu7', 'C2'), ...ROUTE_IDS.map(id => item(id))]);
|
||||
expect(ruta()).not.toBeNull();
|
||||
const ids = tarjetas();
|
||||
for (const id of ROUTE_ONLY_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu_tiempo_reporte');
|
||||
for (const id of ROUTE_IDS) expect(ids).not.toContain(id);
|
||||
expect(ids).toContain('cacu_eu7');
|
||||
});
|
||||
it('si el catálogo no publica alguna de las siete, no hay gráfica y las medidas conservan sus tarjetas', () => {
|
||||
|
||||
@@ -39,8 +39,8 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA, CaMa and CaCu have Histórico; the follow-up tab is named Análisis de riesgos in every domain.
|
||||
const esperadas = ['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
const esperadas = domain === 'tea' ? ['Resumen', 'Trazabilidad', 'Análisis de Riesgo', 'Datos y definiciones']
|
||||
: ['Indicadores', 'Trazabilidad', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
|
||||
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
|
||||
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
|
||||
@@ -58,6 +58,10 @@ describe('Secciones compartidas por dominio', () => {
|
||||
harness.detectChanges();
|
||||
const tracking = root.querySelector<HTMLElement>('#panel-seguimiento')!;
|
||||
expect(tracking.hidden).toBe(false);
|
||||
if (domain === 'tea') {
|
||||
expect(tracking.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA');
|
||||
expect(tracking.querySelector('select[name="estatus"]')?.closest('label')?.firstChild?.textContent?.trim()).toBe('Estatus de EEG');
|
||||
}
|
||||
expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible');
|
||||
if (domain === 'cama') {
|
||||
// An unavailable cohort has no table and offers a retry.
|
||||
|
||||
@@ -36,7 +36,8 @@ describe('Seguimiento de CaMa: ficha del paciente', () => {
|
||||
// Fails if the export buttons leave the title row or come back under the table.
|
||||
it('has the export buttons in the row of the section title, and nothing after the pagination', () => {
|
||||
const row = root().querySelector('.title-row')!;
|
||||
expect(row.querySelector('h2')!.textContent).toContain('Seguimiento de');
|
||||
// Fails if the section heading goes back to «Seguimiento de …» instead of the name of the section tab.
|
||||
expect(row.querySelector('h2')!.textContent).toBe('Análisis de riesgos');
|
||||
expect([...row.querySelectorAll('button')].map(b => b.textContent!.trim())).toEqual(['Exportar Excel (.xlsx)', 'Exportar PDF']);
|
||||
expect(root().querySelector('nav')!.nextElementSibling).toBeNull();
|
||||
expect(root().textContent).not.toContain('Exportar resultados');
|
||||
|
||||
@@ -48,7 +48,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
}
|
||||
<div [hidden]="!!ficha()">
|
||||
<div class="title-row">
|
||||
<h2>Seguimiento de {{ domainLabel }}</h2>
|
||||
<h2>Análisis de riesgos</h2>
|
||||
@if (data(); as respuesta) {
|
||||
<app-seguimiento-exportar [dominio]="dominio" [respuesta]="respuesta" [habilitado]="estado() === 'ready' && !diferencia()" [seleccion]="etiquetaDatos()" />
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DimensionEstrato, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { DimensionEstrato, Dominio, Indicador, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
||||
import { DonutSelection } from './indicadores-donut-drilldown';
|
||||
import { c2Theme, seriesColors } from './indicadores-c2-palette';
|
||||
import { cacuCategoryColor } from './indicadores-cacu-palette';
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
@@ -39,7 +40,7 @@ export function stratumOptions(data: IndicadorDatos): StratumOption[] {
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; percent: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
/** The bars of one period broken down by `dimension`; the strata in `hidden` are left out of the figure and the cells,
|
||||
* unless that would leave none. */
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set()): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}, medida: MedidaEstrato = 'conteo', hidden: ReadonlySet<string> = new Set(), dominio?: Dominio): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||
|| !record(data['categorias']) || !record(data['grupos_de_categoria']) || !record(data['grupos'])
|
||||
|| Object.keys(data['grupos']).length !== 1
|
||||
@@ -73,7 +74,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
||||
const cells: StratifiedCell[] = [];
|
||||
const theme = c2Theme(tema);
|
||||
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const defaults = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
|
||||
const palette = dominio === 'cacu' ? categories.map(([id], i) => cacuCategoryColor(id) ?? defaults[i]) : defaults;
|
||||
// The stratum's total: the one published, or else the sum of its cells when every one is published. A share is
|
||||
// only drawn over a known total; a suppressed or missing total leaves the stratum without percentages.
|
||||
const totales = Array.isArray(data['totales_estrato']) ? data['totales_estrato'] as Record<string, unknown>[] : [];
|
||||
@@ -100,7 +102,8 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
||||
const x = selected.map(v => porcentaje ? v.percent : v.value);
|
||||
return { type: 'bar', orientation: 'h', name: escape(labels[s] as string), x, y: categories.map(([, c]) => escape(c.label)),
|
||||
customdata: selected.map(v => [v.value ?? 'sin valor', v.total ?? 'sin total']),
|
||||
marker: { color: palette, pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] }, line: { color: theme.text, width: .5 } },
|
||||
marker: { color: palette, line: { color: theme.text, width: .5 },
|
||||
...(dominio === 'cacu' ? {} : { pattern: { shape: ['', '/', '\\', 'x', '.', '-', '+'][series % 7] } }) },
|
||||
hovertemplate: porcentaje ? '%{y}<br>%{x:.1f} % (%{customdata[0]} de %{customdata[1]})<extra>%{fullData.name}</extra>' : '%{y}<br>%{x}<extra>%{fullData.name}</extra>' };
|
||||
}), layout: { title: { text: (porcentaje ? 'Porcentaje en cada estrato, ' : 'Distribución estratificada, ') + period }, barmode: 'group', autosize: true,
|
||||
height: Math.max(620, 160 + categories.length * strata.length * 18), paper_bgcolor: theme.background, plot_bgcolor: theme.background,
|
||||
|
||||
@@ -48,16 +48,16 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
const titles = (selector: string) => [...root().querySelectorAll(selector + ' app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('las figuras de tiempo van en oportunidad y las clínicas en su orden, sin duplicarse', () => {
|
||||
// Fails if a figure is drawn in both sections, if either order changes, or if M30 (not named by the sections)
|
||||
// disappears instead of following the clinical ones.
|
||||
// M30 belongs to Trazabilidad even when the catalog publishes it.
|
||||
open('tea', TEA);
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de ADOS-2 a diagnóstico', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section')).toEqual([
|
||||
'Pacientes evaluados por resultado diagnóstico', 'Porcentaje de confirmación diagnóstica',
|
||||
'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG',
|
||||
'Casos por estatus', 'Calidad del EEG', 'Porcentaje de EEG normal y anormal']);
|
||||
'Casos por estatus', 'Calidad del EEG']);
|
||||
expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
expect(fixture.componentInstance.catalogOrder().map(item => item.id)).not.toContain('M30_resultado_eeg');
|
||||
});
|
||||
|
||||
it('un indicador no publicado deja el resto en su orden', () => {
|
||||
@@ -73,12 +73,12 @@ describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
expect(root().querySelector('app-tea-resumen-periodo')).toBeNull();
|
||||
});
|
||||
|
||||
it('la primera pestaña se llama Indicadores en los tres dominios', () => {
|
||||
// Fails if the first tab goes back to «Resumen» in any domain, or changes its section id.
|
||||
it('la primera pestaña se llama Resumen en TEA e Indicadores en CaCu y CaMa', () => {
|
||||
// Fails if TEA's first tab loses its name, if CaCu or CaMa take it, or if the section id changes.
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) {
|
||||
open(domain, [item(domain + '_x', 'Indicador', 'C2', ['fig_c2_barras'])]);
|
||||
const first = root().querySelector('[role="tab"]') as HTMLElement;
|
||||
expect(first.textContent?.trim()).toBe('Indicadores');
|
||||
expect(first.textContent?.trim()).toBe(domain === 'tea' ? 'Resumen' : 'Indicadores');
|
||||
expect(first.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
@if (pacienteDetalle.estado().tipo !== 'cerrado') {
|
||||
<app-paciente-detalle [estado]="pacienteDetalle.estado()" [categorias]="categories"
|
||||
<app-paciente-detalle [estado]="pacienteDetalle.estado()" [nacimiento]="pacienteDetalle.nacimiento()" [categorias]="categories"
|
||||
[registrosTemporales]="pacienteDetalle.registrosTemporales()"
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
@if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (teaFicha) {
|
||||
<section class="ficha-tea" aria-label="Resumen del paciente">
|
||||
<button type="button" (click)="volverDeTea()">Volver a Seguimiento</button>
|
||||
<h2>Paciente {{ teaFicha }}</h2>
|
||||
<app-tea-paciente-resumen [id]="teaFicha" modo="resumen" />
|
||||
</section>
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado' || !!teaFicha">
|
||||
@if (dominio === 'cacu') {
|
||||
<div class="title-row">
|
||||
<h2>{{ titulo }}</h2>
|
||||
@if (exportacionCaCu; as respuesta) {
|
||||
<app-seguimiento-exportar dominio="cacu" [respuesta]="respuesta" [origen]="origenExportacionCaCu" [habilitado]="active && pacienteDetalle.estado().tipo === 'cerrado'" />
|
||||
}
|
||||
</div>
|
||||
} @else if (dominio !== 'cama') { <h2>{{ titulo }}</h2> }
|
||||
@if (dominio === 'cama') {
|
||||
<app-seguimiento-tabla [dominio]="dominio" [domainLabel]="domainLabel" [active]="active" [seleccion]="seleccion" (fichaAbierta)="cambiaFichaCama($event)"
|
||||
(volverAlAnalisis)="volverAlAnalisis.emit()" />
|
||||
@@ -48,9 +62,35 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<label>Edad mínima (años) <input name="edad_min" type="number" min="0" step="1" inputmode="numeric" [(ngModel)]="draft.edad_min" aria-describedby="error-edad" /></label>
|
||||
<label>Edad máxima (años) <input name="edad_max" type="number" min="0" step="1" inputmode="numeric" [(ngModel)]="draft.edad_max" aria-describedby="error-edad" /></label>
|
||||
<button type="button" [disabled]="status === 'loading' || (draft.edad_min == null && draft.edad_max == null && !rangoEdadAplicado)" (click)="limpiarRangoEdad()">Limpiar rango de edad</button>
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Horizonte de la probabilidad <select name="horizonte" [(ngModel)]="draft.horizonte">
|
||||
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} {{ h === 1 ? 'año' : 'años' }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
@if (columnasDelEstatus(draft.estatus).length) {
|
||||
<label>Ordenar por <select name="orden" [(ngModel)]="draft.orden">
|
||||
@for (o of ordenes(); track o.codigo) { <option [value]="o.codigo">{{ o.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" [max]="tamanoMaximo" required [(ngModel)]="draft.page_size" (change)="draft.page_size = acotar(draft.page_size)" /></label>
|
||||
<button type="submit" [disabled]="status === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@if (errorBusqueda) { <p role="alert">{{ errorBusqueda }}</p> }
|
||||
@if (errorEdad) { <p id="error-edad" role="alert">{{ errorEdad }}</p> }
|
||||
@if (dominio === 'cacu') {
|
||||
<div class="page-search">
|
||||
<label>Buscar identificador
|
||||
<input type="search" [attr.maxlength]="consultaMaxima + 20" [value]="busquedaCaCu" (input)="escribirBusqueda($any($event.target).value)" (keydown.enter)="buscar($any($event.target).value)"
|
||||
placeholder="Identificador completo o parcial" aria-describedby="alcance-busqueda-cacu" />
|
||||
</label>
|
||||
<button type="button" [disabled]="!busquedaCaCu && !buscandoCaCu" (click)="limpiarBusqueda()">Limpiar búsqueda</button>
|
||||
</div>
|
||||
}
|
||||
@if (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
|
||||
@if (status === 'pending') { <p role="status">El seguimiento aún no está disponible para esta consulta. Funcionalidad pendiente de publicación.</p> }
|
||||
@if (message && status !== 'pending') { <p role="alert">{{ message }}</p> }
|
||||
@@ -88,7 +128,8 @@
|
||||
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<td><button class="row-toggle" type="button" [attr.aria-expanded]="teaAbierto === item.id_seudonimo" [attr.aria-controls]="'tea-detalle-' + item.id_seudonimo"
|
||||
[attr.aria-label]="(teaAbierto === item.id_seudonimo ? 'Ocultar' : 'Ver') + ' resumen del paciente ' + item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
<span class="chevron" aria-hidden="true"></span>{{ item.id_seudonimo }}</button></td>
|
||||
<span class="chevron" aria-hidden="true"></span></button>
|
||||
<button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + item.id_seudonimo" (click)="abrirTea(item.id_seudonimo, $event)">{{ item.id_seudonimo }}</button></td>
|
||||
<td>{{ item.grupo_edad }}</td>
|
||||
<td><span class="estado-caso" [attr.data-estado]="item.estado_caso">{{ etiquetaEstado[item.estado_caso] }}</span>
|
||||
@if (item.pendientes.length) { <small>Falta: {{ item.pendientes.join(', ') }}</small> }</td>
|
||||
@@ -97,26 +138,40 @@
|
||||
<td>{{ item.css_ados2 ?? 'No disponible' }}@if (item.modulo_ados2) { <small>Módulo {{ item.modulo_ados2 }}</small> }</td>
|
||||
<td>@if (item.alteraciones_eeg; as eeg) { <span class="eeg" [class.eeg-anormal]="eeg === 'anormal'">{{ eeg === 'anormal' ? 'Anormal' : 'Normal' }}</span> } @else { No disponible }</td></tr>
|
||||
@if (teaAbierto === item.id_seudonimo) {
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" /></td></tr>
|
||||
<tr class="tea-detalle" [id]="'tea-detalle-' + item.id_seudonimo"><td colspan="7"><app-tea-paciente-resumen [id]="item.id_seudonimo" (completo)="abrirTea($event)" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td colspan="7">No hay registros para los filtros aplicados.</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
} @else if (data; as response) {
|
||||
<p id="alcance-busqueda-cacu" role="status">
|
||||
@if (buscandoCaCu || rangoEdadAplicado) { {{ response.paginacion.total_items }} {{ response.paginacion.total_items === 1 ? 'registro coincide' : 'registros coinciden' }} con la búsqueda y el rango de edad en toda la consulta. }
|
||||
Los archivos de exportación incluyen toda la consulta.
|
||||
</p>
|
||||
<app-etapas-leyenda />
|
||||
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
|
||||
<table>
|
||||
<caption>Resultados disponibles por paciente</caption>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Grupo de edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Estudio más reciente</th><th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th></tr></thead>
|
||||
<thead><tr><th scope="col">{{ etiquetaIdentidad(response) }}</th><th scope="col">Edad</th><th scope="col">Estatus de seguimiento</th><th scope="col">Última citología</th><th scope="col">Último resultado de VPH</th><th scope="col">Última biopsia</th>@for (c of columnasProbabilidad(); track c) {<th scope="col">{{ etiquetaProbabilidad[c] }} a {{ horizonteMostrado() }} años (%)</th>}<th scope="col">Días de toma a diagnóstico</th><th scope="col">Prioridad</th><th scope="col">Etapas</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track identidad(item).id) {
|
||||
<tr tabindex="-1" (click)="abrirPaciente(item, $event)" [attr.data-paciente]="identidad(item).id">
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td><td>{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td><button class="patient-link" type="button" [attr.aria-label]="'Ver ficha del paciente ' + identidad(item).id" (click)="abrirPaciente(item, $event)">{{ identidad(item).id }}</button></td>
|
||||
<td>{{ edadTexto(item) }}</td><td>{{ item.estatus.etiqueta }}</td>
|
||||
<td>@if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}<small>Fecha: {{ c.fecha }}</small><small>Calidad: {{ c.calidad ?? '—' }}</small> } @else { No disponible }</td>
|
||||
<td>@if (item.ultimo_vph; as v) { {{ v.resultado }}<small>Fecha: {{ v.fecha }}</small><small>Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }}</small> } @else { No disponible }</td>
|
||||
<td>{{ latestStudy(item) ?? 'No disponible' }}</td><td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
<td>@if (item.ultima_biopsia; as b) { {{ b.grado ?? 'Sin grado' }}<small>Fecha: {{ b.fecha }}</small> } @else { No disponible }</td>
|
||||
@for (c of columnasProbabilidad(); track c) { <td class="probabilidad">{{ probabilidad(item, c) ?? 'No disponible' }}</td> }
|
||||
<td>{{ item.dias_toma_diagnostico ?? 'No disponible' }}</td><td>{{ item.prioridad?.etiqueta ?? 'No disponible' }}</td>
|
||||
<td><app-etapas-compacta [ruta]="item.ruta_tamizaje" [paciente]="identidad(item).id" [abierta]="rutaAbierta === identidad(item).id" [controla]="'etapas-' + identidad(item).id" (alternar)="alternarRuta(identidad(item).id)" /></td>
|
||||
</tr>
|
||||
} @empty { <tr><td colspan="8">No hay registros para los filtros aplicados.</td></tr> }
|
||||
@if (rutaAbierta === identidad(item).id && item.ruta_tamizaje; as ruta) {
|
||||
<tr class="detalle-ruta" [id]="'etapas-' + identidad(item).id"><td [attr.colspan]="9 + columnasProbabilidad().length"><app-etapas-detalle [ruta]="ruta" [paciente]="identidad(item).id" (actualizar)="retry()" /></td></tr>
|
||||
}
|
||||
} @empty { <tr><td [attr.colspan]="9 + columnasProbabilidad().length">
|
||||
{{ buscandoCaCu || rangoEdadAplicado ? 'No hay coincidencias para la búsqueda y el rango de edad.' : 'No hay registros para los filtros aplicados.' }}
|
||||
</td></tr> }
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
:host { display: block; min-width: 0; padding: var(--issste-space-4); overflow-wrap: anywhere;
|
||||
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
h2 { font-size: 1.5rem; margin-top: 0; }
|
||||
.title-row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem 1rem; margin-bottom: 1rem; }
|
||||
.title-row h2 { margin: 0; margin-inline-end: auto; }
|
||||
.page-search { display: flex; flex-wrap: wrap; align-items: end; gap: .5rem 1rem; }
|
||||
p { color: var(--issste-text-secondary); }
|
||||
form { display: flex; flex-wrap: wrap; align-items: end; gap: 1rem; margin-bottom: 1rem; }
|
||||
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
|
||||
@@ -29,7 +32,7 @@ nav { display: flex; flex-wrap: wrap; align-items: center; gap: 1rem; margin-top
|
||||
tbody tr[data-paciente] { cursor: pointer; transition: background-color 120ms ease; }
|
||||
tbody tr[data-paciente]:hover { background-color: color-mix(in srgb, var(--issste-accent) 7%, transparent); }
|
||||
tbody tr[data-paciente]:focus-within { outline: 2px solid var(--issste-accent); outline-offset: -2px; }
|
||||
.patient-link { min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link { display: inline-flex; align-items: center; min-height: 44px; padding: .35rem .5rem; border: 0; border-radius: var(--issste-radius); background: transparent; color: var(--issste-accent); font: inherit; font-weight: 600; text-align: left; text-decoration: underline; text-underline-offset: .15em; cursor: pointer; }
|
||||
.patient-link:focus-visible { outline: 2px solid var(--issste-accent); outline-offset: 2px; }
|
||||
.eeg { display: inline-block; padding: .15rem .6rem; border-radius: 999px; border: 1px solid var(--issste-border); font-weight: 600; }
|
||||
.eeg-anormal { border-color: var(--issste-accent); color: var(--issste-accent); }
|
||||
@@ -42,3 +45,6 @@ tbody tr.tea-row:hover, tbody tr.tea-row.abierta { background-color: color-mix(i
|
||||
@media (prefers-reduced-motion: reduce) { .chevron, tbody tr.tea-row { transition: none; } }
|
||||
tbody tr.tea-detalle > td { padding: 1rem; border-top: 0; background: var(--issste-background); }
|
||||
// TEA patient window (mock: odd-numbered patients), laid out like CaCu's patient page.
|
||||
.ficha-tea > button { margin-bottom: .5rem; }
|
||||
|
||||
tr.detalle-ruta > td { padding: 1rem; background: var(--issste-background); }
|
||||
|
||||
@@ -2,10 +2,13 @@ import { afterNextRender, ChangeDetectorRef, Component, DestroyRef, inject, Inje
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { catchError, debounceTime, defer, map, of, Subject, switchMap } from 'rxjs';
|
||||
import { CacuSeguimientoService, validSeguimientoQuery } from './cacu-seguimiento.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX } from './seguimiento-tabla.service';
|
||||
import { latestStudy, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { acotarTamano, PAGE_SIZE_MAX, SeguimientoTablaResponse, SeguimientoTablaService } from './seguimiento-tabla.service';
|
||||
import { EtapasCompacta, EtapasLeyenda } from './ruta-tamizaje/etapas-compacta';
|
||||
import { EtapasDetalle } from './ruta-tamizaje/etapas-detalle';
|
||||
import { COLUMNAS_DE_PROBABILIDAD, edadTexto, ETIQUETA_PROBABILIDAD, filtrosConfirmados, CONSULTA_MAXIMA, incumpleConsulta, normalizarConsulta, probabilidadAl, rangoEdadValido, ProbabilidadClave, SeguimientoPaciente, SeguimientoQuery, SeguimientoResponse, SeguimientoStatus } from './cacu-seguimiento.models';
|
||||
import { porcentaje } from './paciente-detalle/paciente-riesgo.presentacion';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
@@ -15,10 +18,13 @@ import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-i
|
||||
import { IndicadoresService } from './indicadores.service';
|
||||
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
|
||||
import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
import { TrackingExportBar } from './export/tracking-export-bar';
|
||||
import { consultaExportacionCaCu, tablaExportacionCaCu } from './export/cacu-tracking-export';
|
||||
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-tracking',
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla],
|
||||
imports: [FormsModule, MatButtonModule, PacienteDetalleComponent, TeaPacienteResumen, IndicadoresSeguimientoTabla, TrackingExportBar, EtapasCompacta, EtapasDetalle, EtapasLeyenda],
|
||||
providers: [PacienteDetalleState],
|
||||
templateUrl: './indicadores-tracking.html',
|
||||
styleUrl: './indicadores-tracking.scss',
|
||||
@@ -57,15 +63,90 @@ export class IndicadoresTracking implements OnChanges {
|
||||
status: 'idle' | 'loading' | 'ready' | 'pending' | 'error' = 'idle';
|
||||
message = '';
|
||||
data?: SeguimientoResponse;
|
||||
exportacionCaCu?: SeguimientoTablaResponse;
|
||||
readonly origenExportacionCaCu: Pick<SeguimientoTablaService, 'consultar'> = {
|
||||
// The file is built from the query the server confirms; an answer that does not confirm it is not exported.
|
||||
consultar: (_dominio, q) => {
|
||||
const consulta = consultaExportacionCaCu(q);
|
||||
return this.service.consultar(consulta).pipe(map(respuesta => {
|
||||
if (!filtrosConfirmados(consulta, respuesta.filtros)) throw new Error('El servicio no confirmó la búsqueda o el rango de edad de la exportación.');
|
||||
return this.tablaExportacion(respuesta, consulta);
|
||||
}));
|
||||
},
|
||||
};
|
||||
// The identifier search is the server's: the text waits a moment after the last key, then asks for page 1 of the
|
||||
// whole query. The rows shown are exactly the ones the server returns; nothing filters them again here.
|
||||
busquedaCaCu = '';
|
||||
private readonly busquedas = new Subject<string>();
|
||||
/** The search applied to the answer on screen. */
|
||||
get buscandoCaCu() { return !!this.applied.q; }
|
||||
/** Set when the age range typed is not valid; no request goes out until it is. */
|
||||
errorEdad = '';
|
||||
errorBusqueda = '';
|
||||
get rangoEdadAplicado() { return this.applied.edad_min !== undefined || this.applied.edad_max !== undefined; }
|
||||
readonly consultaMaxima = CONSULTA_MAXIMA;
|
||||
escribirBusqueda(texto: string) { this.busquedaCaCu = texto; this.busquedas.next(texto); }
|
||||
limpiarBusqueda() { this.busquedaCaCu = ''; this.buscar(''); }
|
||||
buscar(texto: string) {
|
||||
const q = normalizarConsulta(texto) || undefined;
|
||||
if (this.dominio !== 'cacu' || q === this.applied.q) return;
|
||||
if (q && q.length > CONSULTA_MAXIMA) { this.errorBusqueda = `La búsqueda admite hasta ${CONSULTA_MAXIMA} caracteres.`; this.changeDetector.markForCheck(); return; }
|
||||
this.errorBusqueda = '';
|
||||
this.load({ ...this.applied, q, page: 1 });
|
||||
}
|
||||
limpiarRangoEdad() { this.draft.edad_min = undefined; this.draft.edad_max = undefined; this.apply(); }
|
||||
private tablaExportacion(respuesta: SeguimientoResponse, consulta?: Pick<SeguimientoQuery, 'q' | 'edad_min' | 'edad_max'>) {
|
||||
return tablaExportacionCaCu(respuesta, estudio => this.cytologyLabel(estudio), (item, clave, horizonte) => this.probabilidad(item, clave, horizonte), consulta);
|
||||
}
|
||||
// An older server ignores `q`, `edad_min` and `edad_max`. If a returned row breaks the query asked, the answer is not
|
||||
// shown as a search of the whole list: the user is told, and no partial result is presented.
|
||||
private respuestaDeLaConsulta(q: SeguimientoQuery, data: SeguimientoResponse) {
|
||||
const consulta = { q: q.q, edad_min: q.edad_min, edad_max: q.edad_max };
|
||||
const filtrada = !!(q.q || q.edad_min !== undefined || q.edad_max !== undefined);
|
||||
// The server must say the parameters it applied (`filtros`); the rows are a second check, never the only one.
|
||||
if (filtrada && (!filtrosConfirmados(q, data.filtros) || data.items.some(item => incumpleConsulta(q, this.identidad(item).id, item)))) {
|
||||
return { data: undefined, consulta, status: 'error' as const,
|
||||
message: 'El servicio no confirmó la búsqueda o el rango de edad, así que no se muestran resultados parciales. Quita la búsqueda y el rango, o actualiza el servicio.' };
|
||||
}
|
||||
return { data, consulta, message: '', status: 'ready' as const };
|
||||
}
|
||||
teaData?: TeaSeguimientoResponse;
|
||||
// One open summary at a time, like an accordion.
|
||||
teaAbierto?: string;
|
||||
/** The TEA patient whose whole record shows in place of the list. */
|
||||
teaFicha?: string;
|
||||
private controlTea?: HTMLElement;
|
||||
statuses: SeguimientoStatus[] = [];
|
||||
private metadataLoaded = false;
|
||||
categories: Record<string, { etiqueta: string; color?: string | null }> = {};
|
||||
draft: SeguimientoQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
/** CaCu: the horizons the models give (years), for the probability columns and the order; 5 until the list says. */
|
||||
horizontes(): number[] { return this.data?.horizontes_disponibles?.length ? this.data.horizontes_disponibles : [0, 1, 3, 5]; }
|
||||
horizonteMostrado(): number { return this.data?.filtros.horizonte ?? this.draft.horizonte ?? 5; }
|
||||
readonly etiquetaProbabilidad = ETIQUETA_PROBABILIDAD;
|
||||
/** The probability columns of a follow-up status (its scenario's models); none for every patient. */
|
||||
columnasDelEstatus(estatus: string | null | undefined): readonly ProbabilidadClave[] {
|
||||
return estatus ? COLUMNAS_DE_PROBABILIDAD[estatus] ?? [] : [];
|
||||
}
|
||||
/** The probability columns of the list shown: those of the status it was filtered by. */
|
||||
columnasProbabilidad(): readonly ProbabilidadClave[] { return this.columnasDelEstatus(this.data?.filtros.estatus); }
|
||||
/** "Ordenar por": the most recent study, or one of the columns of the status chosen in the form. */
|
||||
ordenes(): { codigo: string; etiqueta: string }[] {
|
||||
return [{ codigo: 'reciente', etiqueta: 'Estudio más reciente' },
|
||||
...this.columnasDelEstatus(this.draft.estatus).map(c => ({ codigo: c, etiqueta: ETIQUETA_PROBABILIDAD[c] }))];
|
||||
}
|
||||
/** A probability cell: "12.5 % (8.1 – 18 %)", or `null` when no model gives it at the horizon shown. */
|
||||
probabilidad(item: SeguimientoPaciente, clave: ProbabilidadClave, horizonte = this.horizonteMostrado()): string | null {
|
||||
const h = probabilidadAl(item, clave, horizonte);
|
||||
if (!h) return null;
|
||||
const ic = h.ic_bajo !== null && h.ic_alto !== null ? ` (${porcentaje(h.ic_bajo)} – ${porcentaje(h.ic_alto)} %)` : '';
|
||||
return `${porcentaje(h.probabilidad)} %${ic}`;
|
||||
}
|
||||
private applied: SeguimientoQuery = { ...this.draft };
|
||||
readonly latestStudy = latestStudy;
|
||||
readonly edadTexto = edadTexto;
|
||||
/** The patient whose route detail is open; one at a time, and any new list closes it. */
|
||||
rutaAbierta?: string;
|
||||
alternarRuta(id: string) { this.rutaAbierta = this.rutaAbierta === id ? undefined : id; }
|
||||
readonly gruposEdad = GRUPOS_EDAD_TEA;
|
||||
readonly rangosMchat = RANGOS_MCHAT;
|
||||
readonly rangosCss = RANGOS_CSS;
|
||||
@@ -79,15 +160,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
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.'
|
||||
: error instanceof HttpErrorResponse && error.status === 404 ? 'El seguimiento aún no está disponible para esta consulta.' : 'No se pudo consultar el seguimiento. Intenta nuevamente.' });
|
||||
this.busquedas.pipe(debounceTime(400), takeUntilDestroyed(this.destroy)).subscribe(texto => this.buscar(texto));
|
||||
this.requests.pipe(switchMap(q => q ? defer(() => this.service.consultar(q)).pipe(
|
||||
map(data => ({ data, message: '', status: 'ready' as const })), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
map(data => this.respuestaDeLaConsulta(q, data)), catchError(error => failure(error, q))) : of(null)), takeUntilDestroyed(this.destroy)).subscribe(result => {
|
||||
if (!result) return;
|
||||
this.changeDetector.markForCheck();
|
||||
this.status = result.status; this.data = result.data; this.message = result.message;
|
||||
this.exportacionCaCu = result.data && this.tablaExportacion(result.data, result.consulta);
|
||||
if (result.data) {
|
||||
const data = result.data;
|
||||
this.statuses = data.estatus_disponibles;
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
|
||||
this.applied = { corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.estatus ?? undefined, orden: data.filtros.orden, horizonte: data.filtros.horizonte, page: data.paginacion.page, page_size: data.paginacion.page_size,
|
||||
q: result.consulta?.q, edad_min: result.consulta?.edad_min, edad_max: result.consulta?.edad_max };
|
||||
this.draft = { ...this.applied };
|
||||
if (!this.metadataLoaded) {
|
||||
this.metadataLoaded = true;
|
||||
@@ -118,8 +202,11 @@ export class IndicadoresTracking implements OnChanges {
|
||||
// Changing domain removes the table that holds CaMa's record, so the page is told here that no record shows.
|
||||
if (this.pacienteDetalle.estado().tipo !== 'cerrado' || this.camaFichaAbierta()) this.fichaPacienteAbierta.emit(false);
|
||||
this.camaFichaAbierta.set(false);
|
||||
if (this.teaFicha) this.fichaPacienteAbierta.emit(false);
|
||||
this.teaFicha = undefined; this.controlTea = undefined;
|
||||
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.exportacionCaCu = undefined; this.busquedaCaCu = ''; this.errorEdad = '';
|
||||
this.status = 'idle'; this.statuses = []; this.initialized = false; this.draft = { meses: 3, page: 1, page_size: 50 }; this.applied = { ...this.draft };
|
||||
}
|
||||
if (this.dominio === 'cacu' && this.active && !this.initialized) { this.initialized = true; this.load(this.applied); }
|
||||
@@ -128,10 +215,27 @@ export class IndicadoresTracking implements OnChanges {
|
||||
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 ${PAGE_SIZE_MAX}).`; return; }
|
||||
this.changeDetector.markForCheck();
|
||||
this.rutaAbierta = undefined;
|
||||
this.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
this.exportacionCaCu = undefined;
|
||||
// CaCu's rows come with their screening route summary; the detail is asked only when a row opens.
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(this.dominio === 'cacu' ? { ...q, incluir: 'ruta_tamizaje' } : q);
|
||||
}
|
||||
apply() {
|
||||
this.draft.page_size = acotarTamano(this.draft.page_size);
|
||||
// an order by a column the chosen status doesn't show goes back to the most recent study
|
||||
if (this.draft.orden && this.draft.orden !== 'reciente' && !this.columnasDelEstatus(this.draft.estatus).includes(this.draft.orden)) this.draft.orden = 'reciente';
|
||||
for (const clave of ['edad_min', 'edad_max'] as const) {
|
||||
const valor = this.draft[clave] as number | null | undefined;
|
||||
this.draft[clave] = valor === null || valor === undefined || (valor as unknown) === '' ? undefined : Number(valor);
|
||||
}
|
||||
if (this.dominio === 'cacu' && !rangoEdadValido(this.draft.edad_min, this.draft.edad_max)) {
|
||||
this.errorEdad = 'Las edades son años enteros desde 0 y la mínima no puede superar a la máxima.'; this.changeDetector.markForCheck(); return;
|
||||
}
|
||||
this.errorEdad = ''; this.changeDetector.markForCheck();
|
||||
this.load({ ...this.draft, q: this.applied.q, page: 1 });
|
||||
}
|
||||
apply() { this.draft.page_size = acotarTamano(this.draft.page_size); this.load({ ...this.draft, page: 1 }); }
|
||||
retry() { this.load(this.applied); }
|
||||
navigate(page: number) {
|
||||
if (!this.response || page < 1 || page > this.response.paginacion.total_pages) return;
|
||||
@@ -160,6 +264,18 @@ export class IndicadoresTracking implements OnChanges {
|
||||
if (evento.currentTarget instanceof HTMLTableRowElement && evento.target instanceof HTMLElement && evento.target.closest('button, a, input, select, textarea')) return;
|
||||
this.teaAbierto = this.teaAbierto === id ? undefined : id;
|
||||
}
|
||||
abrirTea(id: string, evento?: Event) {
|
||||
evento?.stopPropagation();
|
||||
this.controlTea = evento?.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined;
|
||||
this.teaFicha = id;
|
||||
this.fichaPacienteAbierta.emit(true);
|
||||
}
|
||||
volverDeTea() {
|
||||
this.teaFicha = undefined;
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
const control = this.controlTea;
|
||||
afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector });
|
||||
}
|
||||
volverASeguimiento() {
|
||||
this.pacienteDetalle.cerrar();
|
||||
this.fichaPacienteAbierta.emit(false);
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
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 eu7Fixture from './fixtures/eu7-c2-ejemplos.json';
|
||||
import { IndicadorVphGenotipo } from './indicador-vph-genotipo';
|
||||
import { IndicadorCacuDonas } from './indicador-cacu-donas';
|
||||
import { IndicadorEu7Escenario } from './indicador-eu7-escenario';
|
||||
import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { datosDeReportes, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { Indicador, IndicadorDatos } from './indicadores.models';
|
||||
import { barrasVph, modeloVph, periodosVph, VphIncompatible } from './indicadores-vph-genotipo';
|
||||
import { isCoffeeColor } from './indicadores-c2-palette';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
||||
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
|
||||
|
||||
// The Measure and reports follow the shapes WebApi publishes for CACU-VPH-GENOTIPO (synthetic counts written for these tests).
|
||||
const CATEGORIAS = [['NEGATIVO', 'Negativo', '#9DBFE3'], ['POSITIVO_16', 'Positivo 16 exclusivamente', '#2F6DB3'], ['POSITIVO_18', 'Positivo 18 exclusivamente', '#E8C28E'],
|
||||
['POSITIVO_16_18', 'Positivo 16 y 18', '#D98E4A'], ['POSITIVO_SIN_16_18', 'Positivo sin detección de 16/18', '#B55A1F'],
|
||||
['POSITIVO_INCOMPLETO', 'Positivo con genotipificación incompleta', '#7A2E0E'], ['INDETERMINADO', 'Indeterminado', '#A0A0A0'], ['INCONSISTENTE', 'No clasificable o inconsistente', '#C9CDD2']];
|
||||
const MEASURE = {
|
||||
resourceType: 'Measure', id: 'CACU-VPH-GENOTIPO', url: 'https://isssteleon.org/fhir/Measure/CACU-VPH-GENOTIPO', version: '0.1.0', title: 'Resultados de VPH por genotipo',
|
||||
subjectCodeableConcept: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/unidad', code: 'examen' }] },
|
||||
extension: [
|
||||
{ url: 'https://isssteleon.org/fhir/StructureDefinition/contrato', valueCode: 'C2' },
|
||||
{ url: 'https://isssteleon.org/fhir/StructureDefinition/tipos-periodo', valueCode: 'semestre' }, { url: 'https://isssteleon.org/fhir/StructureDefinition/tipos-periodo', valueCode: 'mes' },
|
||||
{ url: 'https://isssteleon.org/fhir/StructureDefinition/figuras', valueString: 'fig_c2_donas' },
|
||||
...CATEGORIAS.map(([codigo, etiqueta, color]) => ({ url: 'https://isssteleon.org/fhir/StructureDefinition/categoria',
|
||||
extension: [{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: etiqueta }, { url: 'color', valueString: color }] })),
|
||||
],
|
||||
group: [{ code: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/grupo-medida', code: 'TOTAL' }] } }],
|
||||
} as unknown as Measure;
|
||||
const informe = (inicio: string, fin: string, total: number, estratos: [string, number][]): Report => ({
|
||||
resourceType: 'MeasureReport', status: 'complete', period: { start: inicio, end: fin },
|
||||
group: [{ code: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/grupo-medida', code: 'TOTAL' }] },
|
||||
population: [{ code: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/measure-population', code: 'initial-population' }] }, count: total }],
|
||||
stratifier: [{ code: [{ coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/estratificador', code: 'categoria' }] }],
|
||||
stratum: estratos.map(([codigo, n]) => ({ value: { coding: [{ system: 'https://isssteleon.org/fhir/CodeSystem/categoria', code: codigo }] },
|
||||
population: [{ code: { coding: [{ system: 'http://terminology.hl7.org/CodeSystem/measure-population', code: 'initial-population' }] }, count: n }] })) }] }],
|
||||
}) as unknown as Report;
|
||||
const SEMESTRAL = informe('2025-01-01', '2025-06-30', 2, [['POSITIVO_16', 1], ['POSITIVO_SIN_16_18', 1]]);
|
||||
const MENSUAL_CERO = informe('2025-03-01', '2025-03-31', 0, []);
|
||||
const datos = (reportes: Report[], tipo: 'semestre' | 'mes' = 'semestre') => datosDeReportes(MEASURE, reportes, tipo);
|
||||
const indicador: Indicador = indicadorDeMeasure(MEASURE);
|
||||
|
||||
describe('VPH por genotipo: modelo', () => {
|
||||
it('el Measure se publica con el id de WebApp y sus ocho categorías en el orden publicado', () => {
|
||||
expect(indicador.id).toBe('cacu_vph_genotipo'); expect(indicador.contrato).toBe('C2'); expect(indicador.tipos_periodo).toEqual(['semestre', 'mes']);
|
||||
const m = modeloVph(datos([SEMESTRAL]), '2025-S1');
|
||||
expect(m.categorias.map(c => c.id)).toEqual(CATEGORIAS.map(c => c[0]));
|
||||
expect(m.categorias.map(c => c.etiqueta)).toEqual(CATEGORIAS.map(c => c[1]));
|
||||
});
|
||||
it('distribución válida: total de reportes, conteos y ceros publicados, sin convertir lo incompleto o indeterminado en negativo', () => {
|
||||
const m = modeloVph(datos([SEMESTRAL]), '2025-S1');
|
||||
expect(m.estado).toBe('datos'); expect(m.total).toBe(2);
|
||||
expect(Object.fromEntries(m.categorias.map(c => [c.id, c.n]))).toEqual({ NEGATIVO: 0, POSITIVO_16: 1, POSITIVO_18: 0, POSITIVO_16_18: 0, POSITIVO_SIN_16_18: 1, POSITIVO_INCOMPLETO: 0, INDETERMINADO: 0, INCONSISTENTE: 0 });
|
||||
expect(m.categorias.reduce((s, c) => s + c.n, 0)).toBe(m.total);
|
||||
});
|
||||
it('población cero no es una distribución; un periodo sin reporte es ausencia', () => {
|
||||
const cero = modeloVph(datos([MENSUAL_CERO], 'mes'), '2025-03');
|
||||
expect(cero.estado).toBe('cero'); expect(cero.total).toBe(0); expect(barrasVph(cero).den).toBe(0);
|
||||
const ausente = modeloVph(datos([SEMESTRAL]), '2025-S2');
|
||||
expect(ausente.estado).toBe('ausente'); expect(ausente.total).toBeNull(); expect(barrasVph(ausente).grupos[0].filas).toEqual([]);
|
||||
});
|
||||
it('rechaza lo que no puede dibujar: otro indicador, categorías que no suman, población no publicada', () => {
|
||||
expect(() => periodosVph({ ...datos([SEMESTRAL]), id: 'cacu_eu7' } as IndicadorDatos, 'semestre')).toThrow(VphIncompatible);
|
||||
expect(() => modeloVph(datos([informe('2025-01-01', '2025-06-30', 3, [['POSITIVO_16', 1]])]), '2025-S1')).toThrow(VphIncompatible);
|
||||
expect(() => modeloVph({ ...datos([SEMESTRAL]), unidades_periodo: {} } as IndicadorDatos, '2025-S1')).toThrow(VphIncompatible);
|
||||
});
|
||||
it('periodos: los solicitados en su orden o, sin pedirlos, los reportados', () => {
|
||||
const d = datos([SEMESTRAL]);
|
||||
expect(periodosVph(d, 'semestre', ['2025-S2', '2025-S1'])).toEqual(['2025-S2', '2025-S1']); expect(periodosVph(d, 'semestre')).toEqual(['2025-S1']);
|
||||
});
|
||||
it('las barras: ocho categorías planas en el orden publicado, sin grupos, y colores de CaCu fuera de los cafés', () => {
|
||||
const m = modeloVph(datos([SEMESTRAL]), '2025-S1'), b = barrasVph(m);
|
||||
expect(b.grupos).toHaveLength(1); expect(b.grupos[0].etiqueta).toBeNull(); expect(b.den).toBe(2); expect(b.unidad).toBe('reportes de VPH elegibles'); expect(b.activas).toBeNull();
|
||||
expect(b.grupos[0].filas.map(f => [f.id, f.n])).toEqual(CATEGORIAS.map(c => [c[0], c[0] === 'POSITIVO_16' || c[0] === 'POSITIVO_SIN_16_18' ? 1 : 0]));
|
||||
const colores = m.categorias.map(c => c.color);
|
||||
expect(new Set(colores).size).toBe(8); expect(colores.filter(c => isCoffeeColor(c))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('VPH por genotipo: componente', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 1 };
|
||||
let http: HttpTestingController, f: ReturnType<typeof TestBed.createComponent<IndicadorVphGenotipo>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorVphGenotipo], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
TestBed.overrideComponent(IndicadorVphGenotipo, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); f = TestBed.createComponent(IndicadorVphGenotipo);
|
||||
f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('applied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.verify(); });
|
||||
const pedir = () => http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos'));
|
||||
const texto = () => (f.nativeElement as HTMLElement).textContent!.replace(/\s+/g, ' ');
|
||||
|
||||
it('una solicitud; dona, categorías con conteos y porcentajes, total de reportes y la definición provisional', () => {
|
||||
f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
||||
const r = pedir(); expect(r.request.params.get('periodos')).toBe('2025-S1'); r.flush(datos([SEMESTRAL]) as never); f.detectChanges();
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(1);
|
||||
expect(texto()).toContain('Resultados de VPH por genotipo, 2025-S1');
|
||||
expect(texto()).toContain('Positivo 16 exclusivamente 1 50.0 %'); expect(texto()).toContain('Positivo 16 y 18 0 0.0 %');
|
||||
expect(f.nativeElement.querySelectorAll('.filas .fila')).toHaveLength(8); expect(f.nativeElement.querySelectorAll('.grupo')).toHaveLength(0);
|
||||
expect(texto()).toContain('Total: 2 reportes de VPH elegibles');
|
||||
expect(texto()).not.toContain('Definición provisional, pendiente de ratificación clínica');
|
||||
expect(texto()).not.toContain('no identifica otro genotipo específico');
|
||||
expect((f.nativeElement as HTMLElement).querySelectorAll('button')).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('población cero y ausencia de reporte se dicen y no dibujan dona', () => {
|
||||
f.detectChanges(); pedir().flush(datos([MENSUAL_CERO], 'mes') as never);
|
||||
f.componentRef.setInput('applied', { ...applied, tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-03', '2025-04'] } }); f.detectChanges();
|
||||
http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush(datos([MENSUAL_CERO], 'mes') as never); f.detectChanges();
|
||||
// The most recent requested period (2025-04) has no report; the previous one has zero units.
|
||||
expect(texto()).toContain('Sin reporte publicado para 2025-04'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||
f.componentInstance.changePeriod(-1); f.detectChanges();
|
||||
expect(texto()).toContain('Sin reportes de VPH elegibles en 2025-03'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||
expect(texto()).not.toContain('Total de reportes');
|
||||
});
|
||||
it('cambiar de periodo no pide datos y cambiar el periodo aplicado pide los nuevos', () => {
|
||||
const dos = datos([SEMESTRAL, informe('2025-07-01', '2025-12-31', 3, [['NEGATIVO', 3]])]);
|
||||
f.componentRef.setInput('applied', { ...applied, selection: { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] } }); f.detectChanges();
|
||||
pedir().flush(dos as never); f.detectChanges();
|
||||
expect(texto()).toContain('2025-S2, 2 de 2'); expect(texto()).toContain('Negativo 3 100.0 %');
|
||||
f.componentInstance.changePeriod(-1); f.detectChanges(); expect(texto()).toContain('Positivo 16 exclusivamente 1 50.0 %'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('applied', { ...applied, revision: 2, selection: { mode: 'explicit', periodos: ['2025-S2'] } }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('loading'); pedir();
|
||||
});
|
||||
it('un error de servicio se anuncia y el reintento repite la solicitud; una respuesta que no suma es incompatible', () => {
|
||||
f.detectChanges(); pedir().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('error'); expect((f.nativeElement as HTMLElement).querySelector('[role=alert]')).not.toBeNull();
|
||||
f.componentInstance.retry(); pedir().flush(datos([informe('2025-01-01', '2025-06-30', 5, [['POSITIVO_16', 1]])]) as never); f.detectChanges();
|
||||
expect(f.componentInstance.status()).toBe('incompatible'); expect(f.nativeElement.querySelectorAll('app-barras-horizontales')).toHaveLength(0);
|
||||
});
|
||||
// Why: a server without the Measure keeps working; the section says so and asks for nothing.
|
||||
it('sin el Measure (servidor anterior) dice «No disponible» y no hace solicitudes', () => {
|
||||
f.componentRef.setInput('indicador', undefined); f.detectChanges();
|
||||
expect(texto()).toContain('No disponible: el servicio todavía no publica este indicador'); http.expectNone(() => true);
|
||||
});
|
||||
it('fuera de vista no pide datos hasta ser visible', () => {
|
||||
f.componentRef.setInput('visible', false); f.detectChanges(); expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
||||
f.componentRef.setInput('visible', true); f.detectChanges(); pedir();
|
||||
});
|
||||
});
|
||||
|
||||
describe('VPH por genotipo en la tarjeta de tres donas', () => {
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 1 };
|
||||
const eu7: Indicador = { id: 'cacu_eu7', titulo: 'EU7', contrato: 'C2', version: '0.3.0', figuras: ['fig_c2_barras', 'fig_c2_donas'], tipos_periodo: ['semestre', 'mes'],
|
||||
filtros: [{ estrato: 'estatus_seguimiento', etiqueta: 'Estatus', valores: [{ valor: 'VIGILANCIA', etiqueta: 'Vigilancia' }] }] };
|
||||
let http: HttpTestingController, f: ReturnType<typeof TestBed.createComponent<IndicadorCacuDonas>>;
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ imports: [IndicadorCacuDonas], providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const c of [IndicadorEu7Escenario, IndicadorConfirmacionCitologia, IndicadorVphGenotipo]) TestBed.overrideComponent(c, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
http = TestBed.inject(HttpTestingController); f = TestBed.createComponent(IndicadorCacuDonas);
|
||||
f.componentRef.setInput('dominio', 'cacu'); f.componentRef.setInput('indicador', eu7); f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||
f.componentRef.setInput('vph', indicador); f.componentRef.setInput('vphApplied', applied);
|
||||
});
|
||||
afterEach(() => { f.destroy(); http.match(() => true); });
|
||||
// Why: HPV must never touch the cytology and biopsy donuts: its own request, its own failure.
|
||||
it('un error de VPH no afecta las barras citológicas y el filtro común se dice una vez', () => {
|
||||
f.detectChanges();
|
||||
http.expectOne(r => r.url.includes('/cacu_eu7/') && !r.params.has('estrato')).flush(structuredClone(eu7Fixture.general));
|
||||
http.expectOne(r => r.url.includes('/cacu_eu7/') && r.params.get('estrato') === 'estatus_seguimiento').flush(structuredClone(eu7Fixture.estatus_seguimiento));
|
||||
http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
||||
const vph = f.nativeElement.querySelector('app-indicador-vph-genotipo') as HTMLElement;
|
||||
expect(vph.querySelector('[role=alert]')).not.toBeNull();
|
||||
expect(f.nativeElement.querySelectorAll('app-barras-horizontales').length).toBe(1);
|
||||
expect(f.nativeElement.querySelectorAll('.applied-summary')).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelectorAll('app-indicador-eu7-escenario .legend button')).toHaveLength(0);
|
||||
expect(f.nativeElement.querySelectorAll('app-indicador-eu7-escenario .atenuada')).toHaveLength(0);
|
||||
expect(vph.querySelector('[role=alert]')).not.toBeNull(); expect(vph.querySelectorAll('button').length).toBe(1);
|
||||
});
|
||||
it('VPH con datos comparte la fila del cuerpo y no pide más de una solicitud', () => {
|
||||
f.detectChanges();
|
||||
const d = datos([informe('2025-07-01', '2025-12-31', 3, [['NEGATIVO', 3]])]);
|
||||
http.expectOne(r => r.url.endsWith('/cacu_vph_genotipo/datos')).flush(d as never); f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('app-indicador-vph-genotipo h3').textContent).toContain('Resultados de VPH por genotipo, 2025-S2');
|
||||
expect(f.nativeElement.querySelectorAll('app-indicador-vph-genotipo .filas .fila')).toHaveLength(8);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import { cacuClinicalColor } from './indicadores-cacu-palette';
|
||||
import { shareText } from './indicadores-format';
|
||||
import { ConjuntoBarras } from './indicadores-barras';
|
||||
|
||||
// HPV result by genotype (CACU-VPH-GENOTIPO, a C2 composition): the unit is the eligible HPV report linked to a
|
||||
// sample, not the patient, so one patient may contribute several; the period is the sample's. The definition is
|
||||
// provisional, pending clinical ratification. A category with no reports in a period is a zero, and a period whose
|
||||
// units are zero is not a distribution.
|
||||
export const ID_VPH = 'cacu_vph_genotipo';
|
||||
export class VphIncompatible extends Error {}
|
||||
|
||||
export interface CategoriaVph { id: string; etiqueta: string; color: string; n: number; }
|
||||
export type EstadoVph = 'ausente' | 'cero' | 'datos';
|
||||
export interface ModeloVph { periodo: string; estado: EstadoVph; total: number | null; categorias: CategoriaVph[]; }
|
||||
|
||||
const registro = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const fail = (message: string): never => { throw new VphIncompatible(message); };
|
||||
|
||||
function validar(datos: IndicadorDatos, tipo: string) {
|
||||
if (datos.id !== ID_VPH || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || !Array.isArray(datos.periodos)
|
||||
|| datos.periodos.some(p => typeof p !== 'string')) return fail('Los datos no corresponden a VPH por genotipo o al periodo aplicado.');
|
||||
}
|
||||
|
||||
/** The periods to offer: the requested ones in order (one without a report is shown as absent) or, with none requested, the reported ones. */
|
||||
export function periodosVph(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] {
|
||||
validar(datos, tipo);
|
||||
return solicitados ? [...solicitados] : [...datos.periodos].sort();
|
||||
}
|
||||
|
||||
/** One period of the response: absent (no report), zero units, or the distribution of its eligible reports. */
|
||||
export function modeloVph(datos: IndicadorDatos, periodo: string): ModeloVph {
|
||||
validar(datos, datos.tipo_periodo);
|
||||
const cats = datos['categorias'];
|
||||
if (!registro(cats) || !Object.keys(cats).length) return fail('Catálogo de categorías de VPH incompleto.');
|
||||
const definidas = Object.entries(cats).map(([id, c]) => {
|
||||
if (!registro(c) || typeof c['etiqueta'] !== 'string' || !c['etiqueta'].trim()) return fail('Categoría de VPH incompatible.');
|
||||
return { id, etiqueta: c['etiqueta'], color: cacuClinicalColor(id, typeof c['color'] === 'string' ? c['color'] : null) };
|
||||
});
|
||||
if (!datos.periodos.includes(periodo)) return { periodo, estado: 'ausente', total: null, categorias: [] };
|
||||
const unidades = registro(datos['unidades_periodo']) ? datos['unidades_periodo'][periodo] : undefined;
|
||||
if (typeof unidades !== 'number' || !Number.isSafeInteger(unidades) || unidades < 0) return fail('La población del periodo no se publica.');
|
||||
const filas = new Map<string, number>();
|
||||
for (const f of datos.filas.filter(r => r['periodo'] === periodo)) {
|
||||
const categoria = f['categoria'], n = f['n'];
|
||||
if (typeof categoria !== 'string' || !definidas.some(d => d.id === categoria) || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) return fail('Fila de VPH inválida.');
|
||||
filas.set(categoria, n);
|
||||
}
|
||||
const categorias = definidas.map(d => ({ ...d, n: filas.get(d.id) ?? 0 }));
|
||||
// Categories that do not add up to the report's units cannot be drawn as a partition: say so, never undercount.
|
||||
if (categorias.reduce((s, c) => s + c.n, 0) !== unidades) return fail('Los conteos por categoría no suman los reportes del periodo.');
|
||||
return { periodo, estado: unidades === 0 ? 'cero' : 'datos', total: unidades, categorias };
|
||||
}
|
||||
|
||||
export const porcentajeVph = (n: number, total: number) => shareText(n, total);
|
||||
|
||||
/** The HPV bars: the eight categories in the published order, flat, with no selection. */
|
||||
export function barrasVph(m: ModeloVph): ConjuntoBarras {
|
||||
return { grupos: [{ id: null, etiqueta: null, color: '#8A9199', subtotal: m.total,
|
||||
filas: m.categorias.map(c => ({ id: c.id, etiqueta: c.etiqueta, n: c.n, estado: 'Publicado' as const, color: c.color })) }],
|
||||
den: m.total, unidad: 'reportes de VPH elegibles', activas: null };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { cacuPatientDocument, buildCacuPatientPdf } from './cacu-patient-pdf';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { RegistroTemporal } from './paciente-registro.models';
|
||||
|
||||
const estado: Extract<PacienteDetalleEstado, { tipo: 'disponible' }> = {
|
||||
tipo: 'disponible', resumen: { identidad: { campo: 'id_seudonimo', id: 'PACIENTE-SINTETICO' }, grupoEdad: '40-49', estatus: 'Seguimiento', estatusCodigo: null, corte: '2026-10-20', origen: 'seguimiento-demostracion', citologia: { fecha: '2026-01-01', resultado: 'NORMAL', calidad: null }, vph: null, diasTomaDiagnostico: 0, prioridad: null },
|
||||
detalle: { id_seudonimo: 'PACIENTE-SINTETICO', origen: 'sintetico', historial: [{ descripcion: 'Antecedente sintético', fecha: null }], procedimientos: [], pruebas: null },
|
||||
};
|
||||
const registros: RegistroTemporal[] = [];
|
||||
const now = new Date('2026-11-12T21:30:00Z');
|
||||
|
||||
describe('Ficha CaCu: PDF individual', () => {
|
||||
it('usa el formato institucional y refleja datos, ceros y estados no disponibles', () => {
|
||||
const doc = cacuPatientDocument(estado, registros, { tipo: 'no-disponible' }, { NORMAL: { etiqueta: 'Normal' } }, now);
|
||||
const body = JSON.stringify(doc['content']);
|
||||
expect(doc['pageOrientation']).toBe('portrait');
|
||||
for (const value of ['PACIENTE-SINTETICO', 'Antecedente sintético', 'Normal', 'Riesgo individual no disponible', 'No disponible', 'Sin registros.', '"0"']) expect(body).toContain(value);
|
||||
expect(JSON.stringify(doc['info'])).not.toContain('PACIENTE-SINTETICO');
|
||||
});
|
||||
it('produce un PDF real', async () => {
|
||||
const blob = await buildCacuPatientPdf(estado, registros, { tipo: 'no-disponible' }, {}, now);
|
||||
const bytes = new TextDecoder('latin1').decode(await blob.arrayBuffer());
|
||||
expect(bytes.startsWith('%PDF-')).toBe(true);
|
||||
expect(bytes.trimEnd().endsWith('%%EOF')).toBe(true);
|
||||
}, 30000);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { PdfDefinition, renderPdf } from '../export/pdf-engine';
|
||||
import { COLORS, institutionalDocument, loadLogo } from '../export/pdf-template';
|
||||
import { ETIQUETA_IDENTIDAD } from '../paciente-identidad';
|
||||
import { PacienteDetalleEstado } from './paciente-detalle.models';
|
||||
import { RegistroTemporal } from './paciente-registro.models';
|
||||
import { etiquetaRegistro, etiquetaResultado } from './paciente-registros-sesion';
|
||||
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { columnasRiesgo, conIntervalo, covariables, delEstatus, filasRiesgo } from './paciente-riesgo.presentacion';
|
||||
|
||||
type EstadoAbierto = Exclude<PacienteDetalleEstado, { tipo: 'cerrado' }>;
|
||||
type Categorias = Record<string, { etiqueta: string }>;
|
||||
const rule = { hLineWidth: () => 0.5, vLineWidth: () => 0, hLineColor: () => COLORS.rule, paddingTop: () => 4, paddingBottom: () => 4 };
|
||||
const valor = (v: string | number | null | undefined) => v == null ? 'No disponible' : String(v);
|
||||
const section = (title: string, rows: [string, string | number | null | undefined][]) => [
|
||||
{ text: title, style: 'h2' },
|
||||
{ table: { widths: [170, '*'], body: rows.map(([label, v]) => [{ text: label, bold: true }, { text: valor(v) }]) }, layout: rule },
|
||||
];
|
||||
|
||||
/** Instantánea de la ficha mostrada, incluidos los registros de demostración aún sin guardar. */
|
||||
export function cacuPatientDocument(estado: EstadoAbierto, registros: readonly RegistroTemporal[], riesgo: PacienteRiesgoEstado,
|
||||
categorias: Categorias, now: Date, logo?: string): PdfDefinition {
|
||||
const r = estado.resumen;
|
||||
const detalle = estado.tipo === 'disponible' ? estado.detalle : null;
|
||||
const temporal = (tipo: RegistroTemporal['tipo']) => registros.filter(item => item.tipo === tipo);
|
||||
const filas = (items: [string, string][], disponible: boolean): [string, string][] => items.length ? items : [['Estado', disponible ? 'Sin registros.' : 'Información no disponible.']];
|
||||
const condiciones: [string, string][] = detalle?.historial?.map(x => [x.descripcion, [x.fecha ?? 'No disponible', x.notas].filter(Boolean).join(' — ')]) ?? [];
|
||||
const procedimientos: [string, string][] = detalle?.procedimientos?.map(x => [x.nombre, [x.fecha ?? 'No disponible', x.resultado ? `Resultado: ${x.resultado}` : null].filter(Boolean).join(' — ')]) ?? [];
|
||||
for (const item of temporal('condicion')) condiciones.push([etiquetaRegistro(item), `${item.fecha} — Agregado en esta sesión, sin guardar`]);
|
||||
for (const item of temporal('procedimiento')) procedimientos.push([etiquetaRegistro(item), `${item.fecha} — Agregado en esta sesión, sin guardar`]);
|
||||
const pruebas: [string, string][] = detalle?.pruebas?.map(x => [x.nombre, `Fecha: ${valor(x.fecha)} — Resultado: ${valor(x.resultado)}`]) ?? [];
|
||||
for (const item of temporal('resultado')) pruebas.push([etiquetaRegistro(item), `Fecha: ${item.fecha} — Resultado: ${etiquetaResultado(item)} — Agregado en esta sesión, sin guardar`]);
|
||||
const citologia = r.citologia;
|
||||
const resultadoCitologia = citologia?.resultado != null ? categorias[citologia.resultado]?.etiqueta ?? citologia.resultado
|
||||
: citologia?.calidad?.trim().toUpperCase() === 'INSATISFACTORIO' ? 'Insatisfactoria' : 'Sin resultado al corte';
|
||||
let riesgos: [string, string][];
|
||||
if (riesgo.tipo === 'disponible') {
|
||||
const columnas = columnasRiesgo(riesgo.datos.riesgos, 'cacu', r.estatusCodigo);
|
||||
const filasDeRiesgo = filasRiesgo(columnas.map(c => c.lote?.horizontes.length ? c.lote : null));
|
||||
riesgos = filasDeRiesgo.flatMap(f => columnas.map((c, i): [string, string] => [
|
||||
`${c.encabezado} — ${f.horizonte_anios} ${c.lote?.estimando?.horizons_unit ?? 'años'}`,
|
||||
c.vacia ?? (f.celdas[i] ? conIntervalo(f.celdas[i]!) : '—'),
|
||||
]));
|
||||
if (!riesgos.length) riesgos = [['Estado', 'Sin horizontes evaluados en el lote vigente.']];
|
||||
const visibles = delEstatus(riesgo.datos.riesgos, r.estatusCodigo);
|
||||
for (const lote of visibles.filter(x => x.horizontes.length)) riesgos.push([`Fecha índice — ${lote.modelo_nombre}`, lote.fecha_indice]);
|
||||
const cov = covariables(visibles); if (cov) riesgos.push(['Covariables', cov]);
|
||||
} else riesgos = [['Estado', riesgo.tipo === 'cargando' ? 'Cargando riesgo individual.' : riesgo.tipo === 'error' ? 'No se pudo validar o cargar el riesgo individual.' : 'Riesgo individual no disponible para esta paciente.']];
|
||||
return institutionalDocument({ title: 'Ficha de paciente — Cáncer cervicouterino', logo, now, orientation: 'portrait' }, [
|
||||
{ text: `Paciente ${r.identidad.id}`, style: 'h1' }, { text: `Fecha de corte: ${r.corte}`, style: 'muted' },
|
||||
...section('Resumen', [[ETIQUETA_IDENTIDAD[r.identidad.campo], r.identidad.id], ['Fecha de nacimiento', null], ['Grupo de edad', r.grupoEdad], ['Estatus de seguimiento', r.estatus], ['Días de toma a diagnóstico', r.diasTomaDiagnostico], ['Prioridad', r.prioridad]]),
|
||||
...(estado.tipo === 'cargando' ? [{ text: 'Cargando información de la ficha.', style: 'muted' }] : estado.tipo === 'error' ? [{ text: 'No se pudo cargar la información de este paciente.', style: 'muted' }] : []),
|
||||
...section('Condiciones', filas(condiciones, detalle?.historial != null)),
|
||||
...section('Procedimientos', filas(procedimientos, detalle?.procedimientos != null)),
|
||||
...section('Últimos resultados', [
|
||||
['Última citología', citologia ? `Fecha: ${citologia.fecha} — Resultado: ${resultadoCitologia} — Calidad: ${valor(citologia.calidad)}` : null],
|
||||
['Último resultado de VPH', r.vph ? `Fecha: ${r.vph.fecha} — Resultado: ${r.vph.resultado} — Genotipo 16/18: ${r.vph.genotipo16y18 === null ? 'No disponible' : r.vph.genotipo16y18 ? 'Presente' : 'No detectado'}` : null],
|
||||
]),
|
||||
...section('Pruebas y resultados adicionales', filas(pruebas, detalle?.pruebas != null)),
|
||||
...section('Riesgo individual CaCu', riesgos),
|
||||
{ text: 'Recomendaciones no disponibles.', style: 'muted' },
|
||||
{ text: '“No disponible” indica dato no registrado, no ausencia clínica.', style: 'small', margin: [0, 10, 0, 0] },
|
||||
]);
|
||||
}
|
||||
|
||||
export async function buildCacuPatientPdf(estado: EstadoAbierto, registros: readonly RegistroTemporal[], riesgo: PacienteRiesgoEstado,
|
||||
categorias: Categorias, now = new Date(), logo?: string): Promise<Blob> {
|
||||
return renderPdf(cacuPatientDocument(estado, registros, riesgo, categorias, now, logo ?? await loadLogo()));
|
||||
}
|
||||
+4
-9
@@ -4,16 +4,11 @@
|
||||
@if (r === undefined) { <p role="status">Buscando el análisis de recurrencia…</p> }
|
||||
@if (r === null) { <p role="status">Todavía no hay un modelo de recurrencia en producción.</p> }
|
||||
@if (r) {
|
||||
@if (r.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos de recurrencia para mostrar.</p> }
|
||||
@if (escenarios().length === 0) { <p role="status">La paciente no cumple las condiciones de ningún escenario clínico de recurrencia.</p> }
|
||||
@else {
|
||||
<label class="selector">Cohorte
|
||||
<select [value]="cohorte()" (change)="elegirCohorte($any($event.target).value)">
|
||||
@for (c of cohortes; track c.id) { <option [value]="c.id" [selected]="c.id === cohorte()">{{ c.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()?.escenario" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track f.escenario) { <option [value]="f.escenario" [selected]="f.escenario === escenario()?.escenario">{{ f.escenario }}</option> }
|
||||
<select [value]="escenario() ? clave(escenario()!) : ''" (change)="elegirEscenario($any($event.target).value)">
|
||||
@for (f of escenarios(); track clave(f)) { <option [value]="clave(f)" [selected]="f === escenario()">{{ f.escenario }} ({{ f.cohorte_nombre }})</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (figura(); as figure) { <app-plotly-chart [figure]="figure" [showNotes]="false" [label]="'Recurrencia: ' + escenario()?.escenario + ', ' + escenario()?.cohorte_nombre" /> }
|
||||
@@ -22,7 +17,7 @@
|
||||
</section>
|
||||
<section aria-labelledby="factores-recurrencia-titulo">
|
||||
<h5 id="factores-recurrencia-titulo">Factores de riesgo</h5>
|
||||
@if (r && r.escenarios.length) {
|
||||
@if (escenario()) {
|
||||
<label class="selector horizons">Horizonte
|
||||
<select [value]="horizonte()" (change)="elegirHorizonte(+$any($event.target).value)">
|
||||
@for (h of horizontes(); track h) { <option [value]="h" [selected]="h === horizonte()">{{ h }} meses</option> }
|
||||
|
||||
+16
-18
@@ -4,15 +4,14 @@ import { switchMap } from 'rxjs';
|
||||
import { PlotlyChart } from '../../../../shared/plotly/plotly-chart';
|
||||
import { CamaFactoresRiesgo } from './cama-factores-riesgo.component';
|
||||
import { figuraRecurrencia } from './cama-recurrencia-figura';
|
||||
import { CamaRecurrenciaService } from './cama-recurrencia.service';
|
||||
import { CamaRecurrenciaService, FiguraRecurrencia } from './cama-recurrencia.service';
|
||||
|
||||
export const COHORTES: { id: string; nombre: string }[] = [{ id: 'metabric', nombre: 'METABRIC' }, { id: 'scanb', nombre: 'SCAN-B' }];
|
||||
export const HORIZONTE_PREDETERMINADO = 60;
|
||||
|
||||
/**
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo»: two chained menus, the cohort (METABRIC or SCAN-B) and then its clinical
|
||||
* scenarios; the scenario chosen decides the curve and the label at once, one at a time, and the cohorts are never mixed. The label has
|
||||
* a horizon (12, 36 or 60 months, 60 by default). The menu opens on the scenario the patient's covariates place her in, when one does.
|
||||
* «Análisis de recurrencia» and its «Factores de riesgo» for one patient: the clinical scenarios her own age, tumor size, grade and
|
||||
* receptors place her in, from either external cohort (METABRIC or SCAN-B, named with each scenario and never mixed in one figure).
|
||||
* The scenario chosen decides the curve and the label at once; the label has a horizon (12, 36 or 60 months, 60 by default).
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-recurrencia',
|
||||
@@ -23,29 +22,28 @@ export const HORIZONTE_PREDETERMINADO = 60;
|
||||
export class CamaAnalisisRecurrencia {
|
||||
readonly pacId = input.required<string>();
|
||||
private readonly service = inject(CamaRecurrenciaService);
|
||||
readonly cohortes = COHORTES;
|
||||
/** The analysis; `undefined` while it loads, `null` when there is no recurrence model in production. */
|
||||
readonly respuesta = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.recurrencia(id))));
|
||||
private readonly cohorteElegida = signal<string | null>(null);
|
||||
private readonly escenarioElegido = signal<string | null>(null);
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
readonly horizonte = signal<number>(HORIZONTE_PREDETERMINADO);
|
||||
readonly cohorte = computed(() => this.cohorteElegida() ?? this.respuesta()?.predeterminado?.cohorte
|
||||
?? COHORTES.find(c => this.respuesta()?.escenarios.some(f => f.cohorte === c.id))?.id ?? null);
|
||||
/** The scenarios of the cohort chosen, from the list of that cohort only. */
|
||||
readonly escenarios = computed(() => this.respuesta()?.escenarios.filter(f => f.cohorte === this.cohorte()) ?? []);
|
||||
readonly escenario = computed(() => {
|
||||
const lista = this.escenarios();
|
||||
const pedido = this.escenarioElegido() ?? (this.respuesta()?.predeterminado?.cohorte === this.cohorte() ? this.respuesta()?.predeterminado?.escenario : null);
|
||||
return lista.find(f => f.escenario === pedido) ?? lista[0] ?? null;
|
||||
/** The figures of her scenarios, in the order the server ranked them. */
|
||||
readonly escenarios = computed(() => {
|
||||
const r = this.respuesta();
|
||||
if (!r) return [];
|
||||
return r.deLaPaciente.map(s => r.escenarios.find(f => f.cohorte === s.cohorte && f.escenario === s.escenario))
|
||||
.filter((f): f is FiguraRecurrencia => !!f);
|
||||
});
|
||||
readonly escenario = computed(() => this.escenarios().find(f => clave(f) === this.elegido()) ?? this.escenarios()[0] ?? null);
|
||||
readonly figura = computed(() => { const f = this.escenario(); return f ? figuraRecurrencia(f) : null; });
|
||||
readonly horizontes = computed(() => this.respuesta()?.horizontes ?? []);
|
||||
readonly factores = computed(() => {
|
||||
const f = this.escenario();
|
||||
return f ? this.respuesta()?.resumen.find(r => r.cohorte === f.cohorte && r.escenario === f.escenario && r.horizonte_meses === this.horizonte()) ?? null : null;
|
||||
});
|
||||
readonly clave = clave;
|
||||
|
||||
elegirCohorte(id: string): void { this.cohorteElegida.set(id); this.escenarioElegido.set(null); }
|
||||
elegirEscenario(nombre: string): void { this.escenarioElegido.set(nombre); }
|
||||
elegirEscenario(valor: string): void { this.elegido.set(valor); }
|
||||
elegirHorizonte(meses: number): void { this.horizonte.set(meses); }
|
||||
}
|
||||
|
||||
function clave(f: FiguraRecurrencia): string { return `${f.cohorte}|${f.escenario}`; }
|
||||
|
||||
+9
-6
@@ -4,13 +4,16 @@
|
||||
@if (m === undefined) { <p role="status">Buscando los escenarios clínicos…</p> }
|
||||
@if (m === null) { <p role="status">Todavía no hay un modelo de supervivencia en producción.</p> }
|
||||
@if (m) {
|
||||
@if (m.escenarios.length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@if (opciones().length === 0) { <p role="status">Todavía no hay escenarios clínicos con pacientes suficientes para mostrar.</p> }
|
||||
@else {
|
||||
<label class="selector">Escenario clínico
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of m.escenarios; track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
@if (opciones().length === 1) { <p class="selector">Escenario clínico de la paciente: <strong>{{ escenario() }}</strong></p> }
|
||||
@else {
|
||||
<label class="selector">Escenarios clínicos de la paciente
|
||||
<select [value]="escenario()" (change)="elegir($any($event.target).value)">
|
||||
@for (e of opciones(); track e.nombre) { <option [value]="e.nombre" [selected]="e.nombre === escenario()">{{ e.nombre }}</option> }
|
||||
</select>
|
||||
</label>
|
||||
}
|
||||
@let l = lectura();
|
||||
@if (l?.tipo === 'cargando') { <p role="status">Calculando con los datos más recientes…</p> }
|
||||
@if (l?.tipo === 'rechazada') { <p role="status">{{ $any(l).motivo }}</p> }
|
||||
|
||||
+5
-3
@@ -9,9 +9,9 @@ import { figuraSupervivencia } from './cama-supervivencia-figura';
|
||||
type Lectura = { tipo: 'cargando' } | { tipo: 'rechazada'; motivo: string } | { tipo: 'error' } | { tipo: 'lista'; datos: EscenarioConFactores };
|
||||
|
||||
/**
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo»: a menu of clinical scenarios; the one chosen decides the curve and the label
|
||||
* at once, one scenario at a time. The curve is computed from the data ingested so far with the model in production; the menu opens on
|
||||
* the scenario the patient belongs to.
|
||||
* «Análisis de supervivencia» and its «Factores de riesgo» of the clinical scenario the patient's own data place her in; when they place
|
||||
* her in several, a menu of those. The scenario decides the curve and the label at once, computed from the data ingested so far with the
|
||||
* model in production.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-cama-analisis-supervivencia',
|
||||
@@ -25,6 +25,8 @@ export class CamaAnalisisSupervivencia {
|
||||
/** The menu; `undefined` while it loads, `null` when there is no model in production. */
|
||||
readonly menu = toSignal(toObservable(this.pacId).pipe(switchMap(id => this.service.escenarios(id))));
|
||||
private readonly elegido = signal<string | null>(null);
|
||||
/** Her scenarios; every scenario only if the server could not place her. */
|
||||
readonly opciones = computed(() => { const m = this.menu(); return m ? (m.deLaPaciente.length ? m.deLaPaciente : m.escenarios) : []; });
|
||||
readonly escenario = computed(() => this.elegido() ?? this.menu()?.predeterminado ?? null);
|
||||
readonly lectura = toSignal(toObservable(this.escenario).pipe(switchMap(nombre => nombre === null ? of<Lectura | null>(null) : this.service.consulta(nombre).pipe(
|
||||
map((datos): Lectura => ({ tipo: 'lista', datos })),
|
||||
|
||||
+36
-16
@@ -78,7 +78,8 @@ describe('Análisis de supervivencia', () => {
|
||||
beforeEach(() => {
|
||||
consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: nombre === 'Estadio I' ? null : fila(nombre) }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }, { nombre: 'Estadio IV', n: 30 }],
|
||||
deLaPaciente: [{ nombre: 'Estadio I', n: 80 }, { nombre: '< 45 años', n: 100 }], predeterminado: 'Estadio I' }), consulta } }] });
|
||||
});
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -89,12 +90,12 @@ describe('Análisis de supervivencia', () => {
|
||||
return f;
|
||||
};
|
||||
|
||||
// Fails if the menu does not open on the patient's scenario, or offers anything but the scenarios the API listed.
|
||||
it('opens on the patient\'s scenario with the menu the API gave', () => {
|
||||
// Fails if the menu does not open on the patient's scenario, or offers a scenario her data do not place her in.
|
||||
it('opens on the patient\'s scenario and offers only hers', () => {
|
||||
const f = montar();
|
||||
const opciones = [...(f.nativeElement as HTMLElement).querySelectorAll('option')].map(o => o.textContent!.trim());
|
||||
|
||||
expect(opciones).toEqual(['< 45 años', 'Estadio I']);
|
||||
expect(opciones).toEqual(['Estadio I', '< 45 años']);
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Estadio I');
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('h5')].map(h => h.textContent!.trim())).toEqual(['Análisis de supervivencia', 'Factores de riesgo']);
|
||||
});
|
||||
@@ -104,7 +105,7 @@ describe('Análisis de supervivencia', () => {
|
||||
const f = montar();
|
||||
expect(texto(f)).toContain('Sin factores de riesgo identificados'); // Estadio I has no row
|
||||
|
||||
elegir(f, 'Escenario clínico', '< 45 años');
|
||||
elegir(f, 'Escenarios clínicos de la paciente', '< 45 años');
|
||||
|
||||
expect(consulta).toHaveBeenLastCalledWith('< 45 años');
|
||||
expect(texto(f)).toContain('Grado=G3 (robusto, 97%)');
|
||||
@@ -112,6 +113,25 @@ describe('Análisis de supervivencia', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de supervivencia de una paciente con un solo escenario', () => {
|
||||
// Fails if a patient whose data place her in one scenario is asked to choose: the scenario is named and drawn, with no menu.
|
||||
it('names her one scenario and draws it without a menu', () => {
|
||||
const consulta = vi.fn((nombre: string) => of({ respuesta: respuestaCurvas(curvas(nombre)), factores: null }));
|
||||
TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaCurvasService, useValue: {
|
||||
escenarios: () => of({ escenarios: [{ nombre: '< 45 años', n: 100 }, { nombre: 'Estadio I', n: 80 }],
|
||||
deLaPaciente: [{ nombre: 'Toda la cohorte', n: 500 }], predeterminado: 'Toda la cohorte' }), consulta } }] });
|
||||
const f = TestBed.createComponent(CamaAnalisisSupervivencia);
|
||||
f.componentRef.setInput('pacId', '9');
|
||||
f.detectChanges();
|
||||
f.detectChanges();
|
||||
|
||||
expect((f.nativeElement as HTMLElement).querySelector('select')).toBeNull();
|
||||
expect(texto(f)).toContain('Escenario clínico de la paciente: Toda la cohorte');
|
||||
expect(consulta).toHaveBeenCalledExactlyOnceWith('Toda la cohorte');
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Análisis de recurrencia', () => {
|
||||
// Fails if the y axis is scaled by follow-up the axis does not show: a curve that stays above 0.8 in the 72 months drawn must not start its axis at 0.2.
|
||||
it('scales the y axis to the months it draws', () => {
|
||||
@@ -130,7 +150,8 @@ describe('Análisis de recurrencia', () => {
|
||||
const respuesta = () => respuestaRecurrencia({ modelo: { nombre: 'cama-recurrence', version: '1' }, horizontes: [12, 36, 60],
|
||||
escenarios: [figura('metabric', '< 45 años'), figura('metabric', 'Tumor >50 mm'), figura('scanb', '< 45 años'), figura('scanb', 'Grado 3')],
|
||||
resumen: ['metabric', 'scanb'].flatMap(c => [12, 36, 60].flatMap(h => [resumen(c, '< 45 años', h), resumen(c, 'Tumor >50 mm', h), resumen(c, 'Grado 3', h)])),
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' } });
|
||||
predeterminado: { cohorte: 'scanb', escenario: 'Grado 3' },
|
||||
de_la_paciente: [{ cohorte: 'scanb', escenario: 'Grado 3' }, { cohorte: 'metabric', escenario: '< 45 años' }] });
|
||||
beforeEach(() => TestBed.configureTestingModule({ providers: [plotly(), { provide: CamaRecurrenciaService, useValue: { recurrencia: () => of(respuesta()) } }] }));
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
const montar = () => {
|
||||
@@ -143,24 +164,23 @@ describe('Análisis de recurrencia', () => {
|
||||
const opciones = (f: { nativeElement: unknown }, etiqueta: string) => [...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].find(l => l.textContent!.includes(etiqueta))!
|
||||
.querySelectorAll('option');
|
||||
|
||||
// Fails if the menus do not open on the patient's cohort and scenario, or the scenario list is not that of the cohort chosen.
|
||||
it('opens on the patient\'s cohort and scenario, with only that cohort\'s scenarios', () => {
|
||||
// Fails if the menu offers a cohort selector or scenarios the patient's covariates do not place her in, or does not open on the first.
|
||||
it('offers only the patient\'s scenarios, each with its cohort, and opens on the first', () => {
|
||||
const f = montar();
|
||||
|
||||
expect([...opciones(f, 'Cohorte')].map(o => o.textContent!.trim())).toEqual(['METABRIC', 'SCAN-B']);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Grado 3']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her scenario, the label at 60 months
|
||||
expect([...(f.nativeElement as HTMLElement).querySelectorAll('label.selector')].some(l => l.textContent!.includes('Cohorte'))).toBe(false);
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['Grado 3 (SCAN-B)', '< 45 años (METABRIC)']);
|
||||
expect(texto(f)).toContain('Marca=scanb-60'); // her first scenario, the label at 60 months
|
||||
});
|
||||
|
||||
// Fails if a change of cohort leaves the other cohort's scenarios, curve or label on screen: the cohorts are never mixed.
|
||||
it('reloads the scenarios, the curve and the label when the cohort changes, and keeps one curve', () => {
|
||||
// Fails if choosing another of her scenarios leaves the previous curve or label on screen: the cohorts are never mixed.
|
||||
it('changes the curve and the label together when she has another scenario chosen, and keeps one curve', () => {
|
||||
const f = montar();
|
||||
|
||||
elegir(f, 'Cohorte', 'metabric');
|
||||
elegir(f, 'Escenario clínico', 'metabric|< 45 años');
|
||||
|
||||
expect([...opciones(f, 'Escenario clínico')].map(o => o.textContent!.trim())).toEqual(['< 45 años', 'Tumor >50 mm']);
|
||||
expect(texto(f)).toContain('Marca=metabric-60');
|
||||
expect(texto(f)).not.toContain('scanb');
|
||||
expect(texto(f)).not.toContain('Marca=scanb');
|
||||
expect(f.nativeElement.querySelectorAll('app-plotly-chart')).toHaveLength(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export interface CurvasSupervivencia {
|
||||
n: number; events: number; median_follow_up_months: number;
|
||||
horizons_months: number[]; months_max: number; bootstrap_replicas: number;
|
||||
km: { months: number[]; S: number[]; low: number[]; high: number[] };
|
||||
km_adjusted: { months: number[]; S: number[] };
|
||||
km_adjusted?: { months: number[]; S: number[] };
|
||||
weibull: { t: number[]; S: number[] };
|
||||
weibull_fractional: { t: number[]; S: number[] };
|
||||
points: { LR: SerieDeSupervivencia; HBN: SerieDeSupervivencia; COMB: SerieDeSupervivencia };
|
||||
@@ -50,7 +50,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
const km = c['km'], adjusted = c['km_adjusted'], weibull = c['weibull'], fractional = c['weibull_fractional'], points = c['points'];
|
||||
if (!record(km) || !numbers(km['months']) || !probabilities(km['S'], (km['months'] as number[]).length)
|
||||
|| !probabilities(km['low'], (km['months'] as number[]).length) || !probabilities(km['high'], (km['months'] as number[]).length)) invalid();
|
||||
if (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length)) invalid();
|
||||
if (adjusted !== undefined && (!record(adjusted) || !numbers(adjusted['months']) || !probabilities(adjusted['S'], (adjusted['months'] as number[]).length))) invalid();
|
||||
for (const curve of [weibull, fractional]) {
|
||||
if (!record(curve) || !numbers(curve['t']) || !probabilities(curve['S'], (curve['t'] as number[]).length)) invalid();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ export function respuestaCurvas(v: unknown): RespuestaCurvas {
|
||||
escenario: typeof c['escenario'] === 'string' ? c['escenario'] : undefined,
|
||||
n: c['n'] as number, events: c['events'] as number, median_follow_up_months: c['median_follow_up_months'] as number,
|
||||
horizons_months: horizons as number[], months_max: c['months_max'] as number, bootstrap_replicas: c['bootstrap_replicas'] as number,
|
||||
km: km as CurvasSupervivencia['km'], km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'],
|
||||
km: km as CurvasSupervivencia['km'], ...(adjusted !== undefined ? { km_adjusted: adjusted as CurvasSupervivencia['km_adjusted'] } : {}),
|
||||
weibull: weibull as CurvasSupervivencia['weibull'], weibull_fractional: fractional as CurvasSupervivencia['weibull_fractional'],
|
||||
points: { LR: serie(p['LR'], h), HBN: serie(p['HBN'], h), COMB: serie(p['COMB'], h) }, etiquetas,
|
||||
},
|
||||
@@ -87,7 +87,7 @@ export function filaFactores(v: unknown): FilaFactores {
|
||||
}
|
||||
|
||||
/** The scenarios the menu offers, and the one the patient belongs to first. */
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
export interface MenuEscenarios { escenarios: { nombre: string; n: number }[]; deLaPaciente: { nombre: string; n: number }[]; predeterminado: string | null; }
|
||||
/** A scenario's figure with its risk factors (`null`: it has no summary row). */
|
||||
export interface EscenarioConFactores { respuesta: RespuestaCurvas; factores: FilaFactores | null; }
|
||||
/** The selection was refused with a reason (a 422): a scenario with too few patients, or one that does not exist. */
|
||||
@@ -97,13 +97,13 @@ export class SeleccionRechazada extends Error {}
|
||||
export class CamaCurvasService {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** The scenarios the menu offers and the patient's default, or `null` when there is no model in production or no cohort yet. */
|
||||
/** The scenarios the menu offers, the patient's own and her default, or `null` when there is no model in production or no cohort yet. */
|
||||
escenarios(pacId: string): Observable<MenuEscenarios | null> {
|
||||
return this.http.get<unknown>('/cama/modelo/escenarios', { params: { paciente: pacId } }).pipe(
|
||||
map(r => {
|
||||
if (!record(r) || !Array.isArray(r['escenarios'])) invalid();
|
||||
const lista = (r['escenarios'] as unknown[]).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: lista, predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
const leer = (v: unknown) => (Array.isArray(v) ? v : []).map(e => { if (!record(e) || typeof e['nombre'] !== 'string' || !Number.isFinite(e['n'])) invalid(); return { nombre: e['nombre'] as string, n: e['n'] as number }; });
|
||||
return { escenarios: leer(r['escenarios']), deLaPaciente: leer(r['de_la_paciente']), predeterminado: typeof r['predeterminado'] === 'string' ? r['predeterminado'] : null };
|
||||
}),
|
||||
catchError(() => of(null)),
|
||||
);
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface RespuestaRecurrencia {
|
||||
resumen: FilaFactores[];
|
||||
/** The cohort and scenario the patient's own covariates place her in first, if any. */
|
||||
predeterminado: { cohorte: string; escenario: string } | null;
|
||||
/** Every scenario her covariates place her in, the larger first within each cohort; empty when none or no patient was asked. */
|
||||
deLaPaciente: { cohorte: string; escenario: string }[];
|
||||
}
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -48,9 +50,12 @@ export function respuestaRecurrencia(v: unknown): RespuestaRecurrencia {
|
||||
if (typeof m['nombre'] !== 'string' || typeof m['version'] !== 'string') invalid();
|
||||
if (!Array.isArray(v['resumen'])) invalid();
|
||||
const d = v['predeterminado'];
|
||||
const suyos = Array.isArray(v['de_la_paciente']) ? (v['de_la_paciente'] as unknown[]) : [];
|
||||
return { modelo: { nombre: m['nombre'] as string, version: m['version'] as string }, horizontes: v['horizontes'] as number[],
|
||||
escenarios: (v['escenarios'] as unknown[]).map(e => figura(e, h)), resumen: (v['resumen'] as unknown[]).map(filaFactores),
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null };
|
||||
predeterminado: record(d) && typeof d['cohorte'] === 'string' && typeof d['escenario'] === 'string' ? { cohorte: d['cohorte'], escenario: d['escenario'] } : null,
|
||||
deLaPaciente: suyos.filter((e): e is Record<string, string> => record(e) && typeof e['cohorte'] === 'string' && typeof e['escenario'] === 'string')
|
||||
.map(e => ({ cohorte: e['cohorte'], escenario: e['escenario'] })) };
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
@if (estado.tipo !== 'cerrado') {
|
||||
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
|
||||
<div class="toolbar">
|
||||
<button class="back-button" mat-stroked-button type="button" (click)="volver.emit()"><mat-icon aria-hidden="true">arrow_back</mat-icon><span>Regresar</span></button>
|
||||
<button class="export-button" mat-stroked-button type="button" [disabled]="generandoPdf()" (click)="exportarPdf()"><mat-icon aria-hidden="true">picture_as_pdf</mat-icon><span>Exportar ficha PDF</span></button>
|
||||
@if (generandoPdf()) { <p class="toolbar-message" role="status">Generando PDF…</p> }
|
||||
@if (errorPdf()) { <p class="toolbar-message" role="alert">No se pudo generar el PDF. Intenta nuevamente.</p> }
|
||||
</div>
|
||||
<header>
|
||||
<h2 #titulo tabindex="-1">Paciente {{ estado.resumen.identidad.id }}</h2>
|
||||
<p>Fecha de corte: {{ estado.resumen.corte }}.</p>
|
||||
<dl class="summary">
|
||||
<div><dt>{{ etiquetaIdentidad }}</dt><dd>{{ estado.resumen.identidad.id }}</dd></div>
|
||||
<div><dt>Fecha de nacimiento</dt><dd>
|
||||
@if (nacimiento.tipo === 'cargando') { <span role="status">Cargando…</span> }
|
||||
@else if (nacimiento.tipo === 'error') { <span role="alert">No se pudo cargar</span> }
|
||||
@else { {{ nacimiento.valor ?? 'No disponible' }} }
|
||||
</dd></div>
|
||||
<div><dt>Grupo de edad</dt><dd>{{ estado.resumen.grupoEdad ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Estatus de seguimiento</dt><dd>{{ estado.resumen.estatus ?? 'No disponible' }}</dd></div>
|
||||
<div><dt>Días de toma a diagnóstico</dt><dd>{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}</dd></div>
|
||||
@@ -79,7 +89,7 @@
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" /></mat-card-content>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [pacId]="pacId" [estatus]="estatusCodigo" /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface PacienteResumen {
|
||||
identidad: IdentidadPaciente;
|
||||
grupoEdad: string | null;
|
||||
estatus: string | null;
|
||||
/** The follow-up status code (`CASO`, `PRE_COLPOSCOPIA`…): it decides which probabilities the record shows. */
|
||||
estatusCodigo: string | null;
|
||||
corte: string;
|
||||
origen: 'seguimiento-demostracion';
|
||||
citologia: { fecha: string; resultado: string | null; calidad: string | null } | null;
|
||||
|
||||
@@ -5,6 +5,9 @@ h3 { margin-block: 0 1rem; font-size: 1.2rem; }
|
||||
h4 { font: inherit; font-weight: 600; }
|
||||
.back-button { display: inline-flex; align-items: center; gap: .35rem; min-height: 40px; padding-inline: .65rem; }
|
||||
.back-button mat-icon { width: 1.15rem; height: 1.15rem; font-size: 1.15rem; }
|
||||
.toolbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem 1rem; }
|
||||
.toolbar-message { flex: 0 0 100%; margin: 0; }
|
||||
.export-button { margin-inline-start: auto; }
|
||||
.availability { margin-block: .75rem; color: var(--issste-text-secondary); }
|
||||
.pending-changes { margin-block: .75rem; color: var(--issste-text-secondary); font-size: .9rem; }
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 1.25rem 2rem; }
|
||||
|
||||
@@ -46,10 +46,30 @@ describe('Proveedor de detalle sintético', () => {
|
||||
|
||||
describe('Estado de selección del paciente', () => {
|
||||
function setup(provider: PacienteDetalleProvider) {
|
||||
TestBed.configureTestingModule({ providers: [PacienteDetalleState, { provide: PACIENTE_DETALLE_PROVIDER, useValue: provider }] });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), PacienteDetalleState, { provide: PACIENTE_DETALLE_PROVIDER, useValue: provider }] });
|
||||
return TestBed.inject(PacienteDetalleState);
|
||||
}
|
||||
|
||||
it('carga la fecha del paciente seleccionado y distingue nulo, error y respuestas cruzadas', () => {
|
||||
const state = setup({ obtener: () => of(null) });
|
||||
const http = TestBed.inject(HttpTestingController);
|
||||
const paciente = { ...pacientes[0], pac_id: '42' };
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
expect(state.nacimiento().tipo).toBe('cargando');
|
||||
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush({ pac_id: '42', fecha_nacimiento: '1980-01-02' });
|
||||
expect(state.nacimiento()).toEqual({ tipo: 'disponible', valor: '02/01/1980' });
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush({ pac_id: '42', fecha_nacimiento: null });
|
||||
expect(state.nacimiento()).toEqual({ tipo: 'disponible', valor: null });
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush({ pac_id: '43', fecha_nacimiento: '1980-01-02' });
|
||||
expect(state.nacimiento().tipo).toBe('error');
|
||||
state.abrir(paciente, fixtureData.corte);
|
||||
http.expectOne('/cacu/seguimiento/pacientes/42/demografia').flush('error', { status: 500, statusText: 'Error' });
|
||||
expect(state.nacimiento().tipo).toBe('error');
|
||||
http.verify();
|
||||
});
|
||||
|
||||
it('entrega el seudónimo sin conversión y toma una instantánea independiente de la fila', () => {
|
||||
const obtener = vi.fn(() => of(null));
|
||||
const state = setup({ obtener });
|
||||
@@ -128,6 +148,23 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
function abrir(index = 0) { accion(index).click(); fixture.detectChanges(); return root.querySelector<HTMLElement>('app-paciente-detalle')!; }
|
||||
function volver() { root.querySelector<HTMLButtonElement>('app-paciente-detalle button')!.click(); fixture.detectChanges(); }
|
||||
|
||||
it('exporta la ficha seleccionada a un PDF sin identificarla en el nombre del archivo', async () => {
|
||||
const pdf = await import('./cacu-patient-pdf');
|
||||
const build = vi.spyOn(pdf, 'buildCacuPatientPdf').mockResolvedValue(new Blob(['pdf']));
|
||||
const descargas: string[] = [];
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:test');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); });
|
||||
const ficha = abrir();
|
||||
const boton = [...ficha.querySelectorAll('button')].find(b => b.textContent?.includes('Exportar ficha PDF'))!;
|
||||
boton.click();
|
||||
for (let i = 0; i < 50 && !descargas.length; i++) await new Promise(resolve => setTimeout(resolve, 20));
|
||||
expect(build).toHaveBeenCalledOnce();
|
||||
expect(descargas[0]).toMatch(/^ficha-cancer-cervicouterino_corte-[\d-]+_\d{8}-\d{4}\.pdf$/);
|
||||
expect(descargas[0]).not.toContain(pacientes[0].id_seudonimo);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('abre por acción nativa accesible, enfoca la ficha y restaura el foco sin HTTP adicional', () => {
|
||||
const button = accion();
|
||||
expect(button.type).toBe('button');
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user