feat(indicadores): consolidar Histórico CaCu y ajustes TEA/CaCu/CaMa #20
@@ -3,11 +3,12 @@ import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map } from 'rxjs';
|
||||
import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models';
|
||||
import { identidadDe, identidadesDe } from './paciente-identidad';
|
||||
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;
|
||||
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 <= 200;
|
||||
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;
|
||||
}
|
||||
export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
// The current authorization covers demonstration records only. Validate this
|
||||
@@ -18,7 +19,7 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse {
|
||||
|| !record(filters) || (filters['estatus'] !== null && typeof filters['estatus'] !== 'string')
|
||||
|| !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) > 200 || !integer(p['total_items']) || !integer(p['total_pages'])
|
||||
|| !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;
|
||||
const c = item['ultima_citologia'], h = item['ultimo_vph'];
|
||||
|
||||
@@ -36,6 +36,7 @@ describe('Seguimiento CaCu con contrato de demostración', () => {
|
||||
const root:HTMLElement=fixture.nativeElement;
|
||||
expect(root.textContent).not.toContain('Datos simulados — uso de demostración');
|
||||
expect(root.textContent).not.toContain('Las reglas de selección son provisionales');
|
||||
expect(root.querySelector('h2')?.textContent).toBe('Modelos de riesgo asociados a cáncer cervicouterino');
|
||||
expect(root.textContent).toContain('Ventana consultada:');
|
||||
expect(root.textContent).toContain('INSATISFACTORIO'); expect(root.textContent).toContain('Normal'); expect(root.textContent).toContain('No detectado');
|
||||
expect(root.textContent).toContain('Insatisfactoria');
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface Resource {
|
||||
}
|
||||
export interface Bundle extends Resource {
|
||||
total?: number;
|
||||
link?: { relation: string; url: string }[];
|
||||
entry?: { fullUrl?: string; resource: Resource; search?: { mode?: string } }[];
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,10 @@
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 1
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -662,6 +666,10 @@
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 89
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -747,6 +755,10 @@
|
||||
"version": "0.1.0",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"unidades_periodo": {
|
||||
"2021-S1": 0,
|
||||
"2025-S2": 0
|
||||
},
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
@@ -2256,7 +2268,7 @@
|
||||
"grupo": null
|
||||
},
|
||||
"MALO": {
|
||||
"etiqueta": "Malo",
|
||||
"etiqueta": "No aceptable",
|
||||
"color": "#B8433A",
|
||||
"grupo": null
|
||||
},
|
||||
@@ -2291,7 +2303,7 @@
|
||||
"grupo": null
|
||||
},
|
||||
"MALO": {
|
||||
"etiqueta": "Malo",
|
||||
"etiqueta": "No aceptable",
|
||||
"color": "#B8433A",
|
||||
"grupo": null
|
||||
},
|
||||
|
||||
@@ -143,7 +143,7 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
// CaMa's histopathology by BI-RADS has its own coordinated view, as the cytology confirmation has in CaCu.
|
||||
get isHistopatologia() { return this.dominio === 'cama' && this.indicador.id === ID_HISTOPATOLOGIA; }
|
||||
// Connected time pairs replace the diagnosis card with one coordinated box plot.
|
||||
get tiempos() { return parTiempos(this.dominio, this.indicador.id); }
|
||||
get tiempos() { return this.individual ? undefined : parTiempos(this.dominio, this.indicador.id); }
|
||||
// Exams and patients of the same finding, drawn together on the exams' card.
|
||||
get conteos() { return parConteos(this.dominio, this.indicador.id); }
|
||||
get isDual() { return this.pair.includes(this.selectedFigure ?? ''); }
|
||||
@@ -170,6 +170,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
|
||||
@Input({ required: true }) applied!: GlobalApplied;
|
||||
@Input() independentPeriods = false;
|
||||
@Input() pinned = false;
|
||||
// Draws the indicator alone even when it belongs to a connected pair.
|
||||
@Input() individual = false;
|
||||
@Input() visualProfile: FigureVisualProfile = READABLE_VISUAL_PROFILE;
|
||||
readonly pinChanged = output<void>();
|
||||
@ViewChild('visibilityRegion') visibilityRegion?: ElementRef<HTMLElement>;
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
||||
}
|
||||
@if (status() === 'ready' && model; as m) {
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||
@let tituloMastografias = 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||
@let tituloPacientes = 'Porcentaje de pacientes con resultados BI-RADS 4, 5 ó 6 en ' + m.periodo;
|
||||
@if (pages.length > 1) {
|
||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
|
||||
/** A figure the catalog does not publish yet: it keeps its place and title, with no figure and no number. */
|
||||
@Component({
|
||||
selector: 'app-indicador-figura-pendiente',
|
||||
imports: [MatCardModule],
|
||||
template: `
|
||||
<mat-card>
|
||||
<h2>{{ titulo }}</h2>
|
||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> {{ detalle }}</p>
|
||||
<div class="vacio">Sin datos publicados</div>
|
||||
</mat-card>
|
||||
`,
|
||||
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); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
||||
.estado { color: var(--issste-text-secondary); }
|
||||
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
||||
`,
|
||||
})
|
||||
export class IndicadorFiguraPendiente {
|
||||
@Input({ required: true }) titulo!: string;
|
||||
@Input() detalle = 'Este indicador aún no está publicado por el catálogo institucional.';
|
||||
}
|
||||
@@ -182,12 +182,12 @@ describe('KPI integración con autoridad global', () => {
|
||||
// CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator.
|
||||
req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] }));
|
||||
fixture.detectChanges();
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||
const cards = [...fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')];
|
||||
expect(cards).toHaveLength(5);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', undefined, undefined]);
|
||||
expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu'
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible']
|
||||
? ['Disponible', 'Selección no consolidable', 'Disponible', 'Integración pendiente', 'Integración pendiente']
|
||||
: ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'),
|
||||
|
||||
@@ -19,8 +19,8 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
|
||||
imports: [IndicadorKpiCard, MatButtonModule],
|
||||
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
|
||||
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="true"
|
||||
[showPeriod]="false" />
|
||||
[loading]="result().loading ?? false" [notes]="notes" [quietWhenAvailable]="true"
|
||||
[showPeriod]="showPeriod" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
@@ -37,6 +37,7 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input() applied?: GlobalApplied;
|
||||
@Input() availability?: PeriodAvailability;
|
||||
@Input() initialPresentation = false;
|
||||
@Input() showPeriod = false;
|
||||
private readonly queries = inject(IndicadoresKpiQueries);
|
||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
@@ -44,6 +45,10 @@ export class IndicadorKpiPanel implements OnChanges {
|
||||
private key = '';
|
||||
readonly usedPeriod = signal<string | undefined>(undefined);
|
||||
readonly result = signal<KpiDisplay>({ state: 'Esperando catálogo' });
|
||||
get notes(): string[] {
|
||||
const notes = this.dominio === 'tea' ? this.result().notes ?? [] : [];
|
||||
return this.definition.note ? [this.definition.note, ...notes] : notes;
|
||||
}
|
||||
get temporalReference() {
|
||||
if (this.result().earlier) return 'Último dato visible, ' + this.usedPeriod();
|
||||
return this.usedPeriod() ?? (this.applied ? describePeriods(this.applied.tipo, this.applied.selection) : 'Sin filtro aplicado');
|
||||
|
||||
@@ -8,10 +8,12 @@ export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
|
||||
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
|
||||
'CACU-DIAS-BIOPSIA-DIAGNOSTICO': 'cacu_dias_biopsia_diagnostico',
|
||||
'CACU-DIAS-COLPOSCOPIA-BIOPSIA': 'cacu_dias_colposcopia_biopsia',
|
||||
'CACU-DIAS-DIAGNOSTICO-TRATAMIENTO': 'cacu_dias_diagnostico_tratamiento',
|
||||
'CACU-DIAS-RESULTADO-COLPOSCOPIA': 'cacu_dias_resultado_colposcopia',
|
||||
'CACU-DIAS-TOMA-BIOPSIA': 'cacu_dias_toma_biopsia',
|
||||
'CACU-DIAS-TOMA-COLPOSCOPIA': 'cacu_dias_toma_colposcopia',
|
||||
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
|
||||
'CACU-DIAS-TOMA-TRATAMIENTO': 'cacu_dias_toma_tratamiento',
|
||||
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
|
||||
'CACU-EU13': 'cacu_eu13',
|
||||
'CACU-EU7': 'cacu_eu7',
|
||||
|
||||
@@ -19,7 +19,7 @@ import { figureApplied } from './indicadores-figure-selection';
|
||||
class ChartStub {}
|
||||
const item = (id: string, titulo = id, contrato: Indicador['contrato'] = 'C1'): Indicador => ({
|
||||
id, titulo, contrato, tipos_periodo: ['semestre', 'mes'],
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : [], version: '1',
|
||||
figuras: contrato === 'C1' ? ['fig_c1_puntos'] : contrato === 'C2' ? ['fig_c2_barras'] : [], version: '1',
|
||||
});
|
||||
const catalog = [
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica'),
|
||||
@@ -67,7 +67,8 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
const cards = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
// The clinical section only: CaCu's time figures sit in the opportunity section.
|
||||
const cards = () => fixture.debugElement.query(By.css('.graphic-section')).queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard);
|
||||
const card = (id: string) => cards().find(c => c.indicador.id === id)!;
|
||||
const panel = (id: string) => fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel))
|
||||
.map(e => e.componentInstance as IndicadorFigurePanel).find(p => p.indicador.id === id)!;
|
||||
@@ -84,11 +85,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
|
||||
expect(root.querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
const kpis = Array.from(root.querySelectorAll('.kpi-section app-indicador-kpi-card'));
|
||||
expect(kpis.map(k => k.querySelector('h3')?.textContent)).toEqual([
|
||||
'Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
'Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
for (const kpi of kpis.slice(3)) {
|
||||
expect(kpi.querySelectorAll('p')).toHaveLength(1);
|
||||
expect(kpi.querySelector('p')?.textContent).toBe('Indicador no disponible');
|
||||
expect(kpi.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(kpi.textContent).toContain('aún no está publicado');
|
||||
expect(kpi.querySelector('.value, .period')).toBeNull();
|
||||
}
|
||||
expect(root.querySelector('.kpi-grid')?.getAttribute('style')).toContain('--kpi-count: 5');
|
||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel))).toHaveLength(3);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// 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.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const CACU = [
|
||||
item('cacu_eu13', 'Tasa de detección histopatológica', 'C1', []),
|
||||
item('cacu_eu7', 'Distribución de resultados citológicos', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
||||
item('cacu_eu_tiempo_reporte', 'Días de la toma de la citología a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||
item('cacu_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('cacu_confirmacion_citologia', 'Tasa de confirmación histopatológica', 'C2', ['fig_c2_donas']),
|
||||
item('ind1', 'Pacientes con citología anómala', 'C1', []),
|
||||
];
|
||||
|
||||
// The route measures besides the cytology and diagnosis ones in CACU; with all of them the screening route chart appears.
|
||||
const RUTA = ['cacu_dias_resultado_colposcopia', 'cacu_dias_toma_colposcopia', 'cacu_dias_colposcopia_biopsia', 'cacu_dias_toma_biopsia', 'cacu_dias_biopsia_diagnostico']
|
||||
.map(id => item(id, id, 'C3r', ['fig_c3r_caja']));
|
||||
|
||||
describe('Indicadores de CaCu: tiempos de oportunidad y figuras clínicas', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
const abrir = (catalogo: ReturnType<typeof item>[]) => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges();
|
||||
http.expectOne('/cacu/indicadores').flush(catalogo); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
};
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
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', () => {
|
||||
// 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.
|
||||
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('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']);
|
||||
});
|
||||
|
||||
it('sin la gráfica de la ruta, colposcopía y biopsia publicadas son figuras con su nombre', () => {
|
||||
// Fails if a published measure of the route stays a pending slot while the chart that would draw it is not there.
|
||||
abrir([...CACU, ...RUTA.filter(medida => medida.id === 'cacu_dias_toma_colposcopia' || medida.id === 'cacu_dias_toma_biopsia')]);
|
||||
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']);
|
||||
});
|
||||
|
||||
it('el resultado de laboratorio se llama «Tiempo desde la toma de muestra al resultado»', () => {
|
||||
// Fails if the opportunity card goes back to «Días de toma a resultado».
|
||||
abrir(CACU);
|
||||
const titulosKpi = [...root().querySelectorAll('.kpi-section app-indicador-kpi-card h3')].map(h => h.textContent?.trim());
|
||||
expect(titulosKpi).toContain('Tiempo desde la toma de muestra al resultado');
|
||||
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.
|
||||
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');
|
||||
});
|
||||
|
||||
it('Datos y definiciones conserva todo el catálogo', () => {
|
||||
// Fails if moving the time figures or hiding figure-less indicators removes them from the definitions tab.
|
||||
abrir(CACU);
|
||||
const definiciones = root().querySelector('#panel-datos')!.textContent!;
|
||||
for (const titulo of ['Tasa de detección histopatológica', 'Pacientes con citología anómala', 'Tiempo de toma de muestra a diagnóstico']) expect(definiciones).toContain(titulo);
|
||||
});
|
||||
});
|
||||
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
|
||||
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
|
||||
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
|
||||
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
|
||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
|
||||
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.', numerador: 0, denominador: 1 });
|
||||
});
|
||||
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
|
||||
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
@@ -143,8 +143,8 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
|
||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
||||
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
|
||||
.toEqual([['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Resultado histopatológico', 'dibujado']]);
|
||||
expect(graficas().map(g => g.figure!.data.length)).toEqual([2, 6]);
|
||||
});
|
||||
it('el panel C3r avisa el periodo suprimido y la matriz CAM-03 sigue visible', () => {
|
||||
montar(false);
|
||||
@@ -199,15 +199,15 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
return pedidos;
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const kpis = () => [...root().querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
||||
const kpis = () => [...root().querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const tarjetas = () => [...root().querySelectorAll('.graphic-section .catalog-grid > *')] as HTMLElement[];
|
||||
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
||||
|
||||
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||
const pedidos = cargar(completo());
|
||||
expect(kpis()).toHaveLength(5);
|
||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
expect(root().querySelector('.kpi-section .kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
|
||||
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
|
||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
|
||||
@@ -215,10 +215,11 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
||||
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
|
||||
expect(kpis()[4].querySelector('.value')).toBeNull();
|
||||
});
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
it('CAM-03 ocupa el lugar de la tarjeta pendiente, después de los conteos y con su vista especializada; no se consulta mientras no es visible', () => {
|
||||
const pedidos = cargar(completo());
|
||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
||||
const primera = tarjetas()[0];
|
||||
// The exams' and patients' counts go first; the histopathology card is the last of the grid (the confirmation rate follows it).
|
||||
const primera = tarjetas().at(-1)!;
|
||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||
expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS');
|
||||
|
||||
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
|
||||
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
|
||||
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
|
||||
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
|
||||
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.', numerador: 3, denominador: 20 });
|
||||
});
|
||||
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
|
||||
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
@@ -205,13 +205,15 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-section .kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
||||
|
||||
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
||||
// Fails if any card without a published measure makes a request or displays a value.
|
||||
const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||
// Fails if any card without a published measure makes a request or displays a value. The confirmation rate of the
|
||||
// clinical section is a published measure with its own panel, so it is requested too.
|
||||
const publicados = [...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI];
|
||||
const urls = load(publicados, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
expect([...new Set(urls)].sort()).toEqual(publicados.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
|
||||
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
|
||||
@@ -260,7 +262,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
});
|
||||
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
|
||||
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||
load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
load([...KPI_BY_DOMAIN.cama, CAMA_CONFIRMACION_KPI], { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) });
|
||||
const ids = fixture.componentInstance.searchResults().items.map(item => item.id);
|
||||
expect(ids).not.toContain('cama_biopsias');
|
||||
expect(ids).toContain('cama_birads_456_mastografia');
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const section = () => root().querySelector('.graphic-section') as HTMLElement;
|
||||
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
const titles = () => [...root().querySelectorAll('.graphic-section .catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
||||
|
||||
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
|
||||
// Fails if the heading goes back to the whole catalog while a card is not drawn.
|
||||
@@ -62,7 +62,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
|
||||
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
||||
open('cama', CAMA);
|
||||
for (const titulo of ['Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||
for (const titulo of ['Tiempo de tamizaje a diagnóstico', 'Días de la toma de la mastografía a su resultado']) {
|
||||
expect(section().textContent).not.toContain(titulo);
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||
}
|
||||
@@ -82,8 +82,23 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
||||
// It follows the exams' and patients' counts, as the request orders them, and is not counted as a published indicator.
|
||||
expect(root().querySelector('.graphic-section .catalog-grid')!.lastElementChild).toBe(tarjeta);
|
||||
});
|
||||
it('CaMa: el orden clínico es mastografías, pacientes, histopatología y tasa de confirmación', () => {
|
||||
// Fails if the clinical figures change order, if the confirmation rate leaves the clinical section or if the two
|
||||
// counts lose the titles of the request (BI-RADS 4, 5 ó 6, with the period).
|
||||
open('cama', CAMA);
|
||||
const orden = [...section().querySelectorAll('.catalog-grid > *, .kpi-grid > *')].map(e => e.tagName.toLowerCase());
|
||||
expect(orden).toEqual(['app-indicador-catalog-card', 'app-indicador-histopatologia-pendiente', 'app-indicador-kpi-panel']);
|
||||
expect(section().querySelector('.kpi-grid h3')?.textContent?.trim()).toBe('Tasa de confirmación histopatológica');
|
||||
});
|
||||
it('CaMa: sin la tasa de confirmación en el catálogo queda como pendiente al final', () => {
|
||||
// Fails if a missing indicator is dropped silently or drawn with numbers.
|
||||
open('cama', CAMA.filter(medida => medida.id !== 'cama_confirmacion_birads45'));
|
||||
const ultima = section().querySelector('.kpi-grid app-indicador-kpi-card') as HTMLElement;
|
||||
expect(ultima.textContent).toContain('Tasa de confirmación histopatológica');
|
||||
expect(ultima.textContent).toContain('Integración pendiente');
|
||||
});
|
||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// Covers CaMa's «Tiempo de tamizaje a diagnóstico» in Indicadores de oportunidad: the five figures in the order of the
|
||||
// request, each pending while the catalog does not publish its indicator. Fixtures: a CaMa catalog shaped like /cama/indicadores.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const CAMA = [
|
||||
item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas']),
|
||||
item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja']),
|
||||
item('cama_dias_resultado_diagnostico', 'Tiempo de resultado a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
];
|
||||
|
||||
describe('Indicadores de CaMa: tiempos de oportunidad', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
function abrir(catalogo: ReturnType<typeof item>[]) {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(catalogo); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
}
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const titulos = (selector: string) => [...root().querySelectorAll(selector + ' > *')]
|
||||
.map(e => e.tagName.toLowerCase().replace('app-indicador-', '') + ': ' + e.querySelector('h2')?.textContent?.trim());
|
||||
|
||||
it('las cinco figuras van en su orden con los nombres pedidos; las no publicadas quedan pendientes', () => {
|
||||
// Fails if a time figure changes place, keeps the catalog's own title, or a missing indicator is drawn as a figure.
|
||||
abrir(CAMA);
|
||||
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 mastografía a interpretación radiológica',
|
||||
'catalog-card: Tiempo de interpretación radiológica a diagnóstico',
|
||||
'figura-pendiente: Tiempo de interpretación radiológica a resultado de biopsia',
|
||||
'figura-pendiente: Tiempo de diagnóstico a tratamiento',
|
||||
'catalog-card: Tiempo de tamizaje a diagnóstico']);
|
||||
});
|
||||
|
||||
it('un indicador de tiempo que el catálogo no publica queda pendiente sin dejar de ocupar su lugar', () => {
|
||||
// Fails if a missing measure shifts the order or disappears instead of showing as pending.
|
||||
abrir(CAMA.filter(medida => medida.id !== 'cama_dias_resultado_diagnostico'));
|
||||
expect(titulos('.kpi-section .catalog-grid').slice(0, 2)).toEqual([
|
||||
'catalog-card: Tiempo de toma de mastografía a interpretación radiológica',
|
||||
'figura-pendiente: Tiempo de interpretación radiológica a diagnóstico']);
|
||||
});
|
||||
|
||||
it('las figuras de tiempo no se repiten en Indicadores clínicos ni salen del catálogo de Datos y definiciones', () => {
|
||||
// Fails if a time figure gets a second card in the clinical section or loses its definition entry.
|
||||
abrir(CAMA);
|
||||
expect(root().querySelector('.graphic-section')!.textContent).not.toContain('Tiempo de tamizaje a diagnóstico');
|
||||
expect(root().querySelector('#panel-datos')!.textContent).toContain('Días de la toma de la mastografía a su resultado');
|
||||
});
|
||||
});
|
||||
@@ -213,8 +213,8 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
||||
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
|
||||
expect(h3).toEqual([
|
||||
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
|
||||
'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6 en 2025-S2',
|
||||
'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');
|
||||
|
||||
@@ -130,6 +130,24 @@ describe('Indicadores sobre FHIR', () => {
|
||||
expect(figure.status).toBe('supported');
|
||||
});
|
||||
|
||||
it('la calidad del EEG muestra «No aceptable» en lugar de «Malo» sin cambiar los códigos de la categoría', () => {
|
||||
// Pins down: the caption is a presentation choice; the rows, the category catalog and the Measure keep MALO, and no
|
||||
// category is invented for «aceptable». Fails if the caption leaks into the codes, if «Malo» is drawn again or if a
|
||||
// fourth category appears.
|
||||
const datos = datosDeReportes(measure('M29-calidad-eeg'), reports(fx.m29Semestres), 'semestre');
|
||||
const s1 = datos.filas.filter(f => f['periodo'] === '2025-S1');
|
||||
expect(s1.map(f => f['categoria'])).toEqual(['BUENO', 'MALO', 'SIN_ANALIZAR']);
|
||||
const categorias = datos['categorias'] as Record<string, { etiqueta: string }>;
|
||||
expect(Object.entries(categorias).map(([codigo, c]) => [codigo, c.etiqueta]))
|
||||
.toEqual([['BUENO', 'Bueno'], ['MALO', 'No aceptable'], ['SIN_ANALIZAR', 'Sin analizar']]);
|
||||
const unPeriodo = datosDeReportes(measure('M29-calidad-eeg'), [reports(fx.m29Semestres)[0]], 'semestre');
|
||||
const figura = c2Figure(unPeriodo, { indicador: 'M29_calidad_eeg', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', dominio: 'tea' });
|
||||
expect(figura.status).toBe('supported');
|
||||
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');
|
||||
});
|
||||
|
||||
it('una duración da mediana, cuartiles y unidad en días, y su caja por periodo', () => {
|
||||
// Pins down: the median and quartile extensions, `dias` (what the KPI card requires) and the box plot built here
|
||||
// instead of by the server. Fails if the quartiles are lost or the box plot stops having one box per period.
|
||||
@@ -171,6 +189,36 @@ describe('Servicios FHIR de indicadores', () => {
|
||||
expect((await answer).filas.length).toBe(2);
|
||||
});
|
||||
|
||||
it('sigue next para recuperar 201 periodos sin cambiar de endpoint ni de selección', async () => {
|
||||
// The links can contain the upstream origin. The second request must stay on the application's FHIR route.
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const periodos = periodosDesde('2009-01-01', 'mes', 201);
|
||||
const report = reports(fx.m21Semestres)[0];
|
||||
const entry = periodos.map(p => ({ resource: { ...report, period: { start: p + '-01', end: p + '-28' } } }));
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'mes', periodos));
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
const page = http.expectOne(r => r.url === '/tea/fhir/MeasureReport');
|
||||
page.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(0, 200),
|
||||
link: [{ relation: 'next', url: 'http://webapi:5050/tea/fhir/MeasureReport?_offset=200' }] });
|
||||
const next = http.expectOne(r => r.url === '/tea/fhir/MeasureReport' && r.params.get('_offset') === '200');
|
||||
expect(next.request.params.get('measure')).toBe(page.request.params.get('measure'));
|
||||
expect(next.request.params.get('periodo')).toBe(periodos.join(','));
|
||||
expect(next.request.params.get('_count')).toBe('200');
|
||||
next.flush({ resourceType: 'Bundle', total: 201, entry: entry.slice(200) });
|
||||
expect((await answer).periodos).toHaveLength(201);
|
||||
});
|
||||
|
||||
it('rechaza un next que repite el offset sin volver a solicitar reportes', async () => {
|
||||
const service = TestBed.inject(FhirIndicadoresService);
|
||||
const answer = firstValueFrom(service.datos('tea', 'M21_diagnosticados_con_eeg', 'semestre'));
|
||||
const error = expect(answer).rejects.toThrow('Paginación FHIR inválida');
|
||||
http.expectOne('/tea/fhir/Measure').flush(fx.measures);
|
||||
http.expectOne(r => r.url === '/tea/fhir/MeasureReport').flush({ ...fx.m21Semestres,
|
||||
link: [{ relation: 'next', url: '?_offset=0' }] });
|
||||
await error;
|
||||
http.expectNone(r => r.url === '/tea/fhir/MeasureReport');
|
||||
});
|
||||
|
||||
it('el inventario de periodos sale de dos búsquedas de un solo reporte', async () => {
|
||||
// Pins down: one report of each type and the search's total, shared by every measure of the domain. Fails if each
|
||||
// measure computes its own periods or every period is evaluated to list them.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { map, Observable, shareReplay, switchMap } from 'rxjs';
|
||||
import { EMPTY, expand, map, Observable, reduce, shareReplay, switchMap } from 'rxjs';
|
||||
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
||||
import { periodLabel } from './measure-report';
|
||||
import {
|
||||
@@ -59,12 +59,19 @@ const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
|
||||
const percent = (value: number | null) => value === null ? null : round1(value * 100);
|
||||
|
||||
// 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' },
|
||||
};
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
export function categorias(measure: Measure): Record<string, Categoria> {
|
||||
const rotulos = ROTULOS_DE_CATEGORIA[measure.id ?? ''] ?? {};
|
||||
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta: rotulos[codigo] ?? etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||
}));
|
||||
}
|
||||
@@ -238,6 +245,8 @@ function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly
|
||||
// The `/datos` answer for `measure`, from one report per period.
|
||||
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
||||
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||
const cacu = measure.id !== undefined && Object.hasOwn(CACU_MEASURE_IDS, measure.id);
|
||||
const unidadesPeriodo: Record<string, number> = {};
|
||||
const declaradas = categorias(measure);
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
@@ -308,6 +317,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
|
||||
throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
if (cacu && units !== null) unidadesPeriodo[periodo] = units;
|
||||
Object.keys(cats).forEach((categoria, orden) =>
|
||||
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
||||
continue;
|
||||
@@ -340,6 +350,7 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
estrato: estrato ?? null,
|
||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||
...(cacu && kind === 'C2' ? { unidades_periodo: unidadesPeriodo } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||
@@ -408,6 +419,29 @@ export class FhirMeasures {
|
||||
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
||||
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
||||
}
|
||||
|
||||
allReports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Report[]> {
|
||||
const path = `/${requireDominio(dominio)}/fhir/MeasureReport`;
|
||||
return this.reports(dominio, measure, params).pipe(
|
||||
map(bundle => ({ bundle, offset: 0 })),
|
||||
expand(({ bundle, offset }) => {
|
||||
const next = bundle.link?.find(link => link.relation === 'next');
|
||||
if (!next) return EMPTY;
|
||||
// A reverse proxy may expose the API's own origin in the link. Keep the request on the original endpoint
|
||||
// with the same measure and filters, advancing only by the offset that the server supplied.
|
||||
const url = new URL(next.url, `http://localhost${path}`);
|
||||
const raw = url.searchParams.get('_offset');
|
||||
const nextOffset = raw === null ? NaN : Number(raw);
|
||||
if (url.pathname !== path || !Number.isSafeInteger(nextOffset) || nextOffset <= offset) {
|
||||
throw new Error('Paginación FHIR inválida');
|
||||
}
|
||||
return this.reports(dominio, measure, params.set('_offset', nextOffset)).pipe(
|
||||
map(page => ({ bundle: page, offset: nextOffset })),
|
||||
);
|
||||
}, 1),
|
||||
reduce((reports, { bundle }) => reports.concat(resources(bundle, 'MeasureReport') as Report[]), [] as Report[]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -425,8 +459,8 @@ export class FhirIndicadoresService extends IndicadoresService {
|
||||
let params = new HttpParams().set('_count', MAX_COUNT);
|
||||
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
||||
return this.measures.one(dominio, indicador).pipe(
|
||||
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
|
||||
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
|
||||
switchMap(measure => this.measures.allReports(dominio, measure, params).pipe(
|
||||
map(reports => datosValidos(datosDeReportes(measure, reports, tipo, scope), indicador, tipo, periodos, scope)))));
|
||||
}
|
||||
override figura(selection: FigureSelection) {
|
||||
const dominio = requireDominio(selection.dominio ?? 'tea');
|
||||
|
||||
@@ -26,8 +26,13 @@ export function percentText(value: number | null | undefined, fallback = 'No dis
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${percentNumber(value)} %` : fallback;
|
||||
}
|
||||
|
||||
/** «12.3» from a count over its denominator. */
|
||||
export function shareNumber(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return value > 0 && value < 0.1 ? String(value) : value.toFixed(1);
|
||||
}
|
||||
|
||||
/** «12.3 %» from a count over its denominator. */
|
||||
export function shareText(k: number, n: number): string {
|
||||
const value = sharePercent(k, n);
|
||||
return `${value > 0 && value < 0.1 ? String(value) : value.toFixed(1)} %`;
|
||||
return `${shareNumber(k, n)} %`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
// What this module covers: how CaCu's FHIR measures, as the WebApi publishes them, reach the history figures: the
|
||||
// primary group of a proportion (`principal`), the page ids, the unit labels, the reconciliation of a composition and
|
||||
// the periods without units. The Measures are the catalog fixture (`fixtures/cacu_fhir_measures.json`); the reports
|
||||
// are synthetic and carry what the WebApi serialises, `group.code` included: the older bundle fixtures name the group
|
||||
// with `group.id` only, which hides the `principal` / `TOTAL` mismatch this spec pins down.
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { Measure, Report, datosDeReportes, indicadorDeMeasure } from './indicadores-fhir';
|
||||
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
|
||||
import { HISTORICO_CACU, historicoDeDominio } from './indicadores-historico-config';
|
||||
import { historicoFigura, HistoricoOpciones } from './indicadores-historico-figures';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import camaMeasuresData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
|
||||
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const medida = (id: string) => publicadas.find(m => m.id === id)!;
|
||||
const cod = (c: string) => ({ coding: [{ code: c }] });
|
||||
const pob = (c: string, count: number) => ({ code: cod(c), count });
|
||||
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
|
||||
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
|
||||
const SEMESTRE = { start: '2025-01-01', end: '2025-06-30' };
|
||||
const SEMESTRE_2 = { start: '2025-07-01', end: '2025-12-31' };
|
||||
|
||||
// A proportion as the WebApi serialises it: group `principal`, a score only when the denominator is positive.
|
||||
const c1 = (period: { start: string; end: string }, numerador: number, denominador: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('principal'), population: [pob('initial-population', denominador), pob('denominator', denominador), pob('numerator', numerador)],
|
||||
...(denominador > 0 ? { measureScore: { value: numerador / denominador } } : {}) }],
|
||||
} as unknown as Report);
|
||||
// A composition: the categories as the first stratifier, the units as the initial population.
|
||||
const c2 = (m: Measure, period: { start: string; end: string }, conteos: Record<string, number>, unidades?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', unidades ?? Object.values(conteos).reduce((a, b) => a + b, 0))],
|
||||
stratifier: [{ code: [cod('categoria')], stratum: Object.entries(conteos).map(([c, n]) => ({ value: cod(c), population: [pob('initial-population', n)] })) }] }],
|
||||
} as unknown as Report);
|
||||
// A duration: the median and the quartiles as extensions of the score.
|
||||
const c3r = (period: { start: string; end: string }, n: number, mediana?: number): Report => ({
|
||||
resourceType: 'MeasureReport', id: 'r', period,
|
||||
group: [{ code: cod('TOTAL'), population: [pob('initial-population', n + 1), pob('measure-observation', n), pob('measure-population-exclusion', 1)],
|
||||
...(mediana === undefined ? {} : { measureScore: { value: mediana, unit: 'd', extension: [
|
||||
{ url: `${STRUCTURE}/q1`, valueDecimal: mediana - 2 }, { url: `${STRUCTURE}/q3`, valueDecimal: mediana + 3 }] } }) }],
|
||||
} as unknown as Report);
|
||||
const traza = (datos: ReturnType<typeof datosDeReportes>, i: number, opciones?: HistoricoOpciones) =>
|
||||
historicoFigura(datos, 'claro', opciones).figure.data[i] as Record<string, unknown[]> & { x: unknown[]; y: unknown[] };
|
||||
const CACU: HistoricoOpciones = { unidades: historicoDeDominio('cacu')!.unidades, conciliarC2: true, c2SinPoblacionSinDato: true };
|
||||
|
||||
describe('Histórico de CaCu: grupo principal e identificadores reales', () => {
|
||||
it('EU13 con el grupo `principal` que publica el WebApi: el cero es un valor y el panel no queda vacío', () => {
|
||||
// Pins down: the proportion's group reaches the history as the total. Fails if `principal` stays as it is and the
|
||||
// selector of the total drops every row, which left EU13's panel empty.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 4, valor: 0 });
|
||||
expect(Object.keys(datos['grupos'] as object)).toEqual(['total']);
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(traza(datos, 1).y).toEqual([0]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('IND1 se publica como `ind1` y conserva su valor', () => {
|
||||
const datos = datosDeReportes(medida('IND1'), [c1(SEMESTRE, 1, 4), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.id).toBe('ind1');
|
||||
expect(traza(datos, 1).y).toEqual([25, 25]);
|
||||
});
|
||||
it('el intervalo de Wilson publicado usa la misma escala porcentual que el valor', () => {
|
||||
// Fails if the history drops the FHIR bounds or scales them a second time.
|
||||
for (const id of ['CACU-EU13', 'IND1']) {
|
||||
const reporte = c1(SEMESTRE, 1, 4);
|
||||
reporte.group![0].measureScore!.extension = [
|
||||
{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 },
|
||||
{ url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 },
|
||||
];
|
||||
const datos = datosDeReportes(medida(id), [reporte], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
|
||||
expect(traza(datos, 0).y).toEqual([69.9, 4.6]);
|
||||
}
|
||||
});
|
||||
it('un denominador cero es «sin dato», no un cero', () => {
|
||||
// The WebApi omits the score when there is no denominator: the period is listed as missing, not drawn at zero.
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 0, 0), c1(SEMESTRE_2, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ valor: null, denominador: 0 });
|
||||
expect(traza(datos, 1).y).toEqual([null, 25]);
|
||||
expect(historicoFigura(datos, 'claro').sinDato).toEqual(['2025 S1']);
|
||||
});
|
||||
it('sin intervalo publicado la banda queda vacía: el cliente no lo calcula ni lo inventa', () => {
|
||||
const datos = datosDeReportes(medida('CACU-EU13'), [c1(SEMESTRE, 1, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ ic_bajo: null, ic_alto: null });
|
||||
expect(traza(datos, 0)).toMatchObject({ name: 'Intervalo de confianza', x: [], y: [] });
|
||||
});
|
||||
it('en CaMa el grupo principal sigue siendo `total`', () => {
|
||||
// Regression: the normalisation CaCu shares with CaMa keeps CaMa's own result.
|
||||
const cama = (resources(camaMeasuresData as unknown as Bundle, 'Measure') as Measure[]).find(m => m.id === 'CAMA-CONFIRMACION-BIRADS45')!;
|
||||
const datos = datosDeReportes(cama, [c1(SEMESTRE, 2, 4)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ grupo: 'total', valor: 50 });
|
||||
});
|
||||
it('los paneles activos usan ids de página y contratos que el catálogo publica', () => {
|
||||
// Pins down the compatibility of the identifiers: every active panel is a measure `dev` publishes, under the id
|
||||
// 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']);
|
||||
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.
|
||||
expect(indicadorDeMeasure(medida('CACU-RIESGO-BANDA')).id).toBe('cacu_riesgo_banda');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: composiciones (C2)', () => {
|
||||
const eu7 = () => medida('CACU-EU7');
|
||||
const conteos = (extra: Record<string, number> = {}) => ({ ...Object.fromEntries(declaradas(eu7()).map((c, i) => [c, [8, 3, 2, 1, 1, 0, 1][i]])), ...extra });
|
||||
|
||||
it('el reporte de EU7 conserva las unidades de cada periodo y la conciliación pasa', () => {
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos())], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 16 });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.figure.data.map(t => (t['y'] as number[])[0])).toEqual([8, 3, 2, 1, 1, 0, 1]);
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
});
|
||||
it('una categoría que el Measure no declara rompe la conciliación del Histórico y no cambia el Resumen', () => {
|
||||
// Pins down: a category the report counts but the Measure does not declare (the glandular results are still an open
|
||||
// decision) is no longer a shorter bar. The adapter itself reads the report as before.
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, conteos({ AGC: 2 }))], 'semestre');
|
||||
expect(datos.filas.map(f => f['categoria'])).not.toContain('AGC');
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).toThrow('Los conteos por categoría no suman las unidades del periodo');
|
||||
expect(() => historicoFigura(datos, 'claro')).not.toThrow();
|
||||
});
|
||||
it('un periodo sin pacientes es «sin dato» en CaCu y no barras en cero', () => {
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0), c2(eu7(), SEMESTRE_2, conteos())], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(figura.sinDato).toEqual(['2025 S1']);
|
||||
expect(figura.figure.data.every(t => (t['y'] as (number | null)[])[0] === null)).toBe(true);
|
||||
expect((figura.figure.data[0]['y'] as number[])[1]).toBe(8);
|
||||
});
|
||||
it('sin la opción de CaCu un periodo sin unidades se dibuja como antes (CaMa no cambia)', () => {
|
||||
// Regression: the rule is the domain's, not the figure module's.
|
||||
const vacio = Object.fromEntries(declaradas(eu7()).map(c => [c, 0]));
|
||||
const datos = datosDeReportes(eu7(), [c2(eu7(), SEMESTRE, vacio, 0)], 'semestre');
|
||||
const figura = historicoFigura(datos, 'claro');
|
||||
expect(figura.sinDato).toEqual([]);
|
||||
expect(figura.figure.data.every(t => (t['y'] as number[])[0] === 0)).toBe(true);
|
||||
});
|
||||
it('la confirmación por citología declara sus categorías y se concilia igual', () => {
|
||||
const m = medida('CACU-CONFIRMACION-CITOLOGIA');
|
||||
const datos = datosDeReportes(m, [c2(m, SEMESTRE, Object.fromEntries(declaradas(m).map((c, i) => [c, i])))], 'semestre');
|
||||
expect(datos['unidades_periodo']).toEqual({ '2025-S1': 21 });
|
||||
expect(() => historicoFigura(datos, 'claro', CACU)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico de CaCu: tiempos (C3r) y etiquetas de unidad', () => {
|
||||
const m = () => medida('CACU-EU-TIEMPO-REPORTE');
|
||||
it('la mediana y los cuartiles hablan de citologías en CaCu', () => {
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12), c3r(SEMESTRE_2, 0)], 'semestre');
|
||||
expect(datos.filas[0]).toMatchObject({ mediana: 12, q1: 10, q3: 15, n: 6, unidad: 'dias' });
|
||||
const figura = historicoFigura(datos, 'claro', CACU);
|
||||
expect(traza(datos, 1, CACU)['text'][0]).toBe('Mediana: 12 días<br>Q1 a Q3: 10 a 15 días<br>6 citologías');
|
||||
expect(figura.comoLeer).toContain('las citologías');
|
||||
expect(figura.comoLeer).not.toContain('mastograf');
|
||||
// A period without observations is missing, not zero.
|
||||
expect(traza(datos, 1, CACU)['y']).toEqual([12, null]);
|
||||
expect(figura.sinDato).toEqual(['2025 S2']);
|
||||
});
|
||||
it('sin la configuración de CaCu el texto de los exámenes sigue siendo el de CaMa', () => {
|
||||
// Regression: `examen` keeps reading «mastografías» wherever the domain does not name it otherwise.
|
||||
const datos = datosDeReportes(m(), [c3r(SEMESTRE, 6, 12)], 'semestre');
|
||||
expect(traza(datos, 1)['text'][0]).toContain('6 mastografías');
|
||||
expect(historicoFigura(datos, 'claro').comoLeer).toContain('las mastografías');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
// Covers CaCu's history tab: the six active panels and the three reserved ones, what is requested and when (nothing
|
||||
// until the tab is open, nothing for a reserved panel, only the latest periods at first), the states of a panel, and
|
||||
// the notice. Responses are synthetic, shaped like /cacu/indicadores/<id>/periodos and /datos.
|
||||
import { Component } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { IndicadoresHistorico } from './indicadores-historico';
|
||||
import { HISTORICO_CACU } from './indicadores-historico-config';
|
||||
import { Indicador } from './indicadores.models';
|
||||
|
||||
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
|
||||
class ChartStub { figure?: { data: { name?: string; y?: (number | null)[]; text?: string[] }[] }; label?: string; }
|
||||
|
||||
const MESES = Array.from({ length: 12 }, (_, i) => `2025-${String(i + 1).padStart(2, '0')}`);
|
||||
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 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);
|
||||
|
||||
function datos(id: string, tipo: string, periodos: string[], opciones: { contrato?: string; sinPoblacion?: string } = {}) {
|
||||
const contrato = opciones.contrato ?? CONTRATOS[id];
|
||||
const fila = (periodo: string, campos: Record<string, unknown>) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos });
|
||||
const vacio = (p: string) => p === opciones.sinPoblacion;
|
||||
const filas = contrato === 'C2'
|
||||
? periodos.flatMap(p => [fila(p, { categoria: 'NORMAL', n: vacio(p) ? 0 : 7, orden: 0 }), fila(p, { categoria: 'ASC-US', n: vacio(p) ? 0 : 5, orden: 1 })])
|
||||
: contrato === 'C1' ? periodos.map(p => fila(p, { valor: 0, numerador: 0, denominador: 10, ic_bajo: null, ic_alto: null }))
|
||||
: periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' }));
|
||||
return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' ? 'paciente' : 'examen', filas,
|
||||
categorias: { NORMAL: { etiqueta: 'Normal', color: '#9DBFE3' }, 'ASC-US': { etiqueta: 'ASC-US', color: '#2F6DB3' } },
|
||||
...(contrato === 'C2' ? { unidades_periodo: Object.fromEntries(periodos.map(p => [p, vacio(p) ? 0 : 12])) } : {}) };
|
||||
}
|
||||
|
||||
describe('Histórico de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
|
||||
const abrirDialogo = vi.fn();
|
||||
function montar(catalog: Indicador[] = CATALOGO, active = false) {
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [
|
||||
provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } },
|
||||
] });
|
||||
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
|
||||
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
|
||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); });
|
||||
// Answers in waves, because the shared request queue runs four at a time. `pedidos` keeps what each data request asked for.
|
||||
const pedidos: { id: string; periodos: string[] }[] = [];
|
||||
function responder(opciones: { fallo?: (r: TestRequest) => boolean; datos?: (id: string) => { contrato?: string; sinPoblacion?: string } } = {}) {
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
const url = r.request.url, id = url.split('/').at(-2)!;
|
||||
if (opciones.fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; }
|
||||
if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] });
|
||||
else {
|
||||
const periodos = r.request.params.get('periodos')!.split(',');
|
||||
pedidos.push({ id, periodos });
|
||||
r.flush(datos(id, periodos[0].includes('S') ? 'semestre' : 'mes', periodos, opciones.datos?.(id)));
|
||||
}
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
}
|
||||
beforeEach(() => { pedidos.length = 0; });
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[];
|
||||
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))!;
|
||||
|
||||
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.
|
||||
montar();
|
||||
http.expectNone(() => true);
|
||||
fixture.componentRef.setInput('active', true); fixture.detectChanges();
|
||||
const vistos = new Set<string>();
|
||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||
for (const r of ola) {
|
||||
vistos.add(r.request.url.split('/').at(-2)!);
|
||||
const id = r.request.url.split('/').at(-2)!;
|
||||
if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: MESES.map(periodo => ({ periodo, tipo: 'mes' })) });
|
||||
else r.flush(datos(id, 'mes', r.request.params.get('periodos')!.split(',')));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
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', () => {
|
||||
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(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']));
|
||||
});
|
||||
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'));
|
||||
fixture.destroy(); TestBed.resetTestingModule();
|
||||
}
|
||||
});
|
||||
it('no antepone ningún aviso a los paneles', () => {
|
||||
// Fails if a notice about clinical validation or suppression is shown again above the history's panels.
|
||||
montar();
|
||||
expect(root().querySelector('[data-aviso="historico"]')).toBeNull();
|
||||
expect(root().textContent).not.toContain('sujetos a validación clínica');
|
||||
});
|
||||
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);
|
||||
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)');
|
||||
});
|
||||
it('elegir «Todos» pide solo los periodos que faltan y los suma', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(0); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
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);
|
||||
// Going back to five is local: nothing is asked again.
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('.rango')?.textContent).toBe('ago 2025 a dic 2025 (5 meses)');
|
||||
});
|
||||
it.each([false, true])('acumula 5→10→Todos sin duplicados al recibir primero la segunda respuesta: %s', invertir => {
|
||||
// The two expansions are disjoint. Either arrival order must preserve all twelve periods.
|
||||
montar([item('ind1')], true); responder();
|
||||
fixture.componentInstance.elegirVentana(10);
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
const ampliaciones = http.match(r => r.url.endsWith('/datos'));
|
||||
const periodos = (r: TestRequest) => r.request.params.get('periodos')!.split(',');
|
||||
expect(ampliaciones.map(periodos)).toEqual([MESES.slice(2, 7), MESES.slice(0, 2)]);
|
||||
for (const r of invertir ? ampliaciones.reverse() : ampliaciones) {
|
||||
r.flush(datos('ind1', 'mes', periodos(r)));
|
||||
fixture.detectChanges();
|
||||
}
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('reintenta la ampliación fallida conservando los cinco periodos y sin repetir periodos cargados', () => {
|
||||
montar([item('ind1')], true); responder();
|
||||
fixture.componentInstance.elegirVentana(0);
|
||||
http.expectOne(r => r.url.endsWith('/datos')).flush('private', { status: 500, statusText: 'Error' });
|
||||
fixture.detectChanges();
|
||||
const panel = panelDe(tituloDe('ind1'));
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(5);
|
||||
expect(panel.querySelector('[role="alert"]')?.textContent).toContain('Error');
|
||||
(panel.querySelector('button') as HTMLButtonElement).click();
|
||||
const reintento = http.expectOne(r => r.url.endsWith('/datos'));
|
||||
expect(reintento.request.params.get('periodos')?.split(',')).toEqual(MESES.slice(0, 7));
|
||||
reintento.flush(datos('ind1', 'mes', MESES.slice(0, 7)));
|
||||
fixture.detectChanges();
|
||||
expect(graficaDe(tituloDe('ind1')).figure!.data[1].y).toHaveLength(12);
|
||||
expect(panel.querySelector('[role="alert"]')).toBeNull();
|
||||
});
|
||||
it('cambiar a Semestral pide los últimos cinco semestres una vez y volver a Mensual no repite', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toHaveLength(6);
|
||||
for (const p of pedidos) expect(p.periodos).toEqual(SEMESTRES.slice(-5));
|
||||
pedidos.length = 0;
|
||||
fixture.componentInstance.elegido.set('mes'); fixture.detectChanges(); responder();
|
||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); responder();
|
||||
expect(pedidos).toEqual([]);
|
||||
});
|
||||
it('una medida ausente muestra «Trabajo en desarrollo» y no se consulta', () => {
|
||||
montar(CATALOGO.filter(i => i.id !== 'cacu_eu13'), true); responder();
|
||||
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);
|
||||
});
|
||||
it('un error de red se muestra en su panel sin filtrar el cuerpo y el reintento vuelve a pedir', () => {
|
||||
montar(CATALOGO, true);
|
||||
responder({ fallo: r => r.request.url.includes('/cacu_eu13/') && r.request.url.endsWith('/datos') });
|
||||
const panel = panelDe(tituloDe('cacu_eu13'));
|
||||
expect(panel.querySelector('[role="alert"]')).not.toBeNull();
|
||||
expect(panel.textContent).not.toContain('private');
|
||||
expect(graficas()).toHaveLength(5);
|
||||
const reintentar = panel.querySelector('button') as HTMLButtonElement;
|
||||
reintentar.click(); fixture.detectChanges(); responder();
|
||||
expect(graficas()).toHaveLength(6);
|
||||
});
|
||||
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);
|
||||
});
|
||||
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' } : {} });
|
||||
expect(graficaDe(tituloDe('cacu_eu13')).figure!.data[1].y).toEqual([0, 0, 0, 0, 0]);
|
||||
expect(panelDe(tituloDe('cacu_eu13')).querySelector('[data-plegable="sin-dato"]')).toBeNull();
|
||||
const eu7 = panelDe(tituloDe('cacu_eu7'));
|
||||
expect(eu7.querySelector('[data-plegable="sin-dato"]')?.textContent).toContain('Periodos sin dato (1)');
|
||||
expect(eu7.textContent).toContain('oct 2025');
|
||||
expect(graficaDe(tituloDe('cacu_eu7')).figure!.data[0].y).toEqual([7, 7, null, 7, 7]);
|
||||
});
|
||||
it('los tiempos hablan de citologías', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
for (const id of ['cacu_eu_tiempo_reporte', 'cacu_dias_toma_diagnostico']) {
|
||||
expect(graficaDe(tituloDe(id)).figure!.data[1].text![0]).toContain('20 citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).toContain('las citologías');
|
||||
expect(panelDe(tituloDe(id)).textContent).not.toContain('mastograf');
|
||||
}
|
||||
});
|
||||
it('sin medidas disponibles conserva los nueve paneles y no hace consultas', () => {
|
||||
montar([item('cacu_riesgo_banda'), item('cacu_dias_toma_tratamiento')], true);
|
||||
expect(paneles()).toHaveLength(9);
|
||||
expect(paneles().every(p => p.querySelector('[role="status"]')?.textContent === 'Trabajo en desarrollo')).toBe(true);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
it('sin periodos con reportes un panel activo muestra «Sin datos»', () => {
|
||||
montar([item('ind1')], true);
|
||||
http.expectOne(r => r.url.endsWith('/periodos')).flush({ id: 'ind1', periodos: [] });
|
||||
fixture.detectChanges();
|
||||
expect(panelDe(tituloDe('ind1')).querySelector('[role="status"]')?.textContent).toBe('Sin datos');
|
||||
expect(graficas()).toHaveLength(0);
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
});
|
||||
@@ -83,10 +83,10 @@ describe('Histórico de CaMa', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
||||
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
|
||||
expect(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
|
||||
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 en la clasificación de BI-RADS 4, 5 o 6';
|
||||
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
|
||||
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()).toHaveLength(5);
|
||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
||||
@@ -96,7 +96,7 @@ describe('Histórico de CaMa', () => {
|
||||
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
|
||||
// list is open from the start, is cut short, or the figure changes.
|
||||
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
|
||||
const panel = paneles()[1];
|
||||
const panel = paneles()[4];
|
||||
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
|
||||
expect(plegable).not.toBeNull();
|
||||
expect(plegable.open).toBe(false);
|
||||
@@ -117,7 +117,7 @@ describe('Histórico de CaMa', () => {
|
||||
it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual');
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)');
|
||||
});
|
||||
it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
@@ -126,7 +126,7 @@ describe('Histórico de CaMa', () => {
|
||||
const semestrales = responder();
|
||||
expect(semestrales.length).toBeGreaterThan(0);
|
||||
expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true);
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)');
|
||||
toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
});
|
||||
@@ -135,7 +135,7 @@ describe('Histórico de CaMa', () => {
|
||||
const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } };
|
||||
expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']);
|
||||
fixture.componentInstance.elegirVentana(5); fixture.detectChanges();
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)');
|
||||
});
|
||||
it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => {
|
||||
montar(CATALOGO, true); responder();
|
||||
@@ -144,10 +144,10 @@ describe('Histórico de CaMa', () => {
|
||||
expect(abrirDialogo).toHaveBeenCalledTimes(1);
|
||||
const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] };
|
||||
expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES);
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) });
|
||||
fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges();
|
||||
expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
expect(paneles()[4].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)');
|
||||
});
|
||||
it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => {
|
||||
// Fails if one failing indicator blanks the others, leaks its body, or cannot be retried.
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
// What each domain's history tab draws, declared as data: the panels and their order, the contract each one is
|
||||
// expected to carry, the labels of its unit and what the tab may ask for. A domain without an entry here (TEA) draws
|
||||
// its whole catalog.
|
||||
|
||||
export type ContratoHistorico = 'C1' | 'C2' | 'C3r';
|
||||
// The mark each contract gets in `historicoFigura`: counts add up to a total, percentages and medians do not.
|
||||
export type GraficaHistorico = 'barras_apiladas' | 'linea_porcentaje' | 'linea_mediana';
|
||||
export interface PanelHistorico {
|
||||
// The page's id of the measure (what `indicadorId` gives).
|
||||
id: string;
|
||||
titulo: string;
|
||||
contrato?: ContratoHistorico;
|
||||
grafica?: GraficaHistorico;
|
||||
enDesarrollo?: boolean;
|
||||
// The FHIR ids the reserved panels will use even if the catalog already publishes them.
|
||||
fhir?: readonly string[];
|
||||
}
|
||||
export interface UnidadHistorico { plural: string; eje: string }
|
||||
export interface HistoricoDominio {
|
||||
paneles: readonly PanelHistorico[];
|
||||
// The unit a measure publishes (`examen`) named as the domain calls it; overrides the figure module's default.
|
||||
unidades?: Readonly<Record<string, UnidadHistorico>>;
|
||||
// How many of the latest periods are requested when the tab opens. Without it, every period is requested.
|
||||
periodosIniciales?: number;
|
||||
// A composition (C2) whose categories do not add up to the report's units is an error, not a shorter bar.
|
||||
conciliarC2?: boolean;
|
||||
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||
c2SinPoblacionSinDato?: boolean;
|
||||
}
|
||||
|
||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje de mastografías con resultado BI-RADS 4, 5 ó 6' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes con resultado BI-RADS 4, 5 ó 6' },
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ 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.
|
||||
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' },
|
||||
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica', contrato: 'C1', grafica: 'linea_porcentaje' },
|
||||
{ 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'] },
|
||||
];
|
||||
|
||||
const HISTORICOS: Readonly<Partial<Record<Dominio, HistoricoDominio>>> = {
|
||||
cama: { paneles: HISTORICO_CAMA },
|
||||
cacu: {
|
||||
paneles: HISTORICO_CACU,
|
||||
// `examen` is the citology here.
|
||||
unidades: { examen: { plural: 'citologías', eje: 'Citologías' } },
|
||||
periodosIniciales: 5,
|
||||
conciliarC2: true,
|
||||
c2SinPoblacionSinDato: true,
|
||||
},
|
||||
};
|
||||
|
||||
// The domain's declared history, if it has one and the tab is on.
|
||||
export const historicoDeDominio = (dominio: Dominio): HistoricoDominio | undefined => HISTORICOS[dominio];
|
||||
@@ -118,3 +118,41 @@ describe('Histórico: datos inválidos', () => {
|
||||
expect(() => historicoFigura(datos(), 'claro')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Histórico: pies de figura de CaMa y resultado experimental de EEG en TEA', () => {
|
||||
const med = (id: string) => figura({ ...base('C3r', MESES, [fila('2025-01', { mediana: 10, q1: 9, q3: 12, n: 9 })], { unidad: 'examen' }), id } as IndicadorDatos);
|
||||
const cats = [{ periodo: '2025-01', categoria: 'A', n: 2, orden: 0, suprimido: 0 }, { periodo: '2025-01', categoria: 'B', n: 3, orden: 1, suprimido: 0 }];
|
||||
it('las tres medianas de CaMa usan el pie de la solicitud y las de otros dominios conservan el suyo', () => {
|
||||
// Fails if a CaMa time figure keeps the general caption, or if the new one leaks into TEA's or CaCu's medians.
|
||||
for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
|
||||
expect(med(id).comoLeer).toBe('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.');
|
||||
}
|
||||
expect(med('cacu_eu_tiempo_reporte').comoLeer).toContain('la mitad central');
|
||||
});
|
||||
it('la tasa de confirmación de CaMa dice solo qué representa la línea; otros porcentajes conservan el pie con la banda', () => {
|
||||
// Fails if the confirmation rate keeps the confidence-band sentence, or if another percentage loses it.
|
||||
const pct = (id: string) => figura({ ...base('C1', MESES, [fila('2025-01', { valor: 50, numerador: 1, denominador: 2, ic_bajo: 9, ic_alto: 91 })]), id } as IndicadorDatos);
|
||||
expect(pct('cama_confirmacion_birads45').comoLeer).toBe('La línea representa el porcentaje de confirmación histopatológica.');
|
||||
expect(pct('ind1').comoLeer).toContain('su intervalo de confianza');
|
||||
});
|
||||
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.';
|
||||
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.
|
||||
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[0]['y']).toEqual([62.5, null, null, null]);
|
||||
expect(JSON.stringify(lineas[0]['text'])).toContain('5 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(m30.sinDato).toEqual(['feb 2025', 'mar 2025', 'abr 2025']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,12 +31,19 @@ export interface HistoricoOpciones {
|
||||
// Same vertical scale across small charts, so their heights compare.
|
||||
yMax?: number;
|
||||
pequena?: boolean;
|
||||
// The unit a measure publishes, named as the domain calls it; falls back to the defaults below (CaMa's).
|
||||
unidades?: Readonly<Record<string, { plural: string; eje: string }>>;
|
||||
// A composition whose categories do not add up to the report's units (`unidades_periodo`) is an error.
|
||||
conciliarC2?: boolean;
|
||||
// A composition period with no units is «sin dato», not a bar of zeros.
|
||||
c2SinPoblacionSinDato?: boolean;
|
||||
}
|
||||
// What the unit a measure publishes is called in the charts' texts.
|
||||
const UNIDADES: Readonly<Record<string, { plural: string; eje: string }>> = {
|
||||
paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' },
|
||||
};
|
||||
const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
|
||||
const unidadDe = (data: IndicadorDatos, propias?: HistoricoOpciones['unidades']) =>
|
||||
propias?.[String(data['unidad'])] ?? UNIDADES[String(data['unidad'])] ?? { plural: 'pacientes', eje: 'Pacientes' };
|
||||
function validar(data: IndicadorDatos) {
|
||||
for (const row of data.filas) {
|
||||
if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida');
|
||||
@@ -97,25 +104,41 @@ function colorDeLinea(id: string, tema: Tema) {
|
||||
return { linea, relleno: linea + '40' };
|
||||
}
|
||||
|
||||
export const M30_RESULTADO_EEG = 'M30_resultado_eeg';
|
||||
|
||||
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.',
|
||||
};
|
||||
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.']));
|
||||
|
||||
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';
|
||||
return {
|
||||
figure: { data: [
|
||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
|
||||
{ type: 'scatter', mode: 'lines+markers', name: nombre, x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
|
||||
text: validas.map(row => {
|
||||
if (!row) return '';
|
||||
const intervalo = numero(row['ic_bajo']) && numero(row['ic_alto']) ? `<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : '';
|
||||
return `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}${intervalo}`;
|
||||
}),
|
||||
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
|
||||
comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos pacientes.',
|
||||
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.',
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
||||
const periodos = validar(data), unidad = unidadDe(data);
|
||||
const periodos = validar(data), unidad = unidadDe(data, opciones.unidades);
|
||||
const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
||||
const trazo = colorDeLinea(data.id, tema);
|
||||
return {
|
||||
@@ -128,7 +151,7 @@ function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones):
|
||||
const layout = ejes(data, periodos, suprimidos, tema, 'Días', opciones.pequena);
|
||||
return opciones.yMax ? { ...layout, yaxis: { ...layout.yaxis, range: [0, opciones.yMax] } } : layout;
|
||||
})() },
|
||||
comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`,
|
||||
comoLeer: PIE_MEDIANA[data.id] ?? `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de ${unidad.plural === 'pacientes' ? 'los pacientes' : 'las ' + unidad.plural}.`,
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -137,8 +160,8 @@ const CONTEOS: Readonly<Record<string, { eje: string; comoLeer: string }>> = {
|
||||
M28_casos_por_estado: { eje: 'Casos', comoLeer: 'Cada barra cuenta todos los casos iniciados hasta el cierre del periodo, con su estado en esa fecha. Un caso en proceso puede estar completo en el siguiente periodo.' },
|
||||
M29_calidad_eeg: { eje: 'Estudios de EEG', comoLeer: 'Cada barra son los EEG del periodo, según su calificación general.' },
|
||||
};
|
||||
function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data);
|
||||
function conteo(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): Trazo {
|
||||
const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data, opciones.unidades);
|
||||
const celdas = new Map<string, Record<string, unknown>>(), categorias = new Map<string, number>();
|
||||
for (const row of data.filas) {
|
||||
const id = row['categoria'], key = JSON.stringify([id, row['periodo']]);
|
||||
@@ -151,7 +174,22 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))];
|
||||
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
|
||||
const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1));
|
||||
const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
|
||||
// The units each report says it has, when the adapter kept them: what the categories of a period must add up to.
|
||||
const unidades = record(data['unidades_periodo']) ? data['unidades_periodo'] : undefined;
|
||||
const suma = (p: string) => {
|
||||
const valores = estadoDe(p).map(row => row?.['n']);
|
||||
return valores.every(numero) ? (valores as number[]).reduce((s, v) => s + v, 0) : null;
|
||||
};
|
||||
if (opciones.conciliarC2 && unidades) {
|
||||
for (const p of periodos) {
|
||||
const total = unidades[p], contado = suma(p);
|
||||
if (numero(total) && contado !== null && contado !== total) throw new Error('Los conteos por categoría no suman las unidades del periodo');
|
||||
}
|
||||
}
|
||||
// A period with no units is not a period of zeros: it is drawn as a gap and listed.
|
||||
const sinPoblacion = new Set(opciones.c2SinPoblacionSinDato
|
||||
? 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 };
|
||||
return {
|
||||
figure: { data: orden.map((id, i) => {
|
||||
@@ -159,12 +197,12 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
||||
const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined;
|
||||
const tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
|
||||
const slot = tono === 'neutro' ? i : curso[tono]++;
|
||||
const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; });
|
||||
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>' };
|
||||
}), 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 ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
|
||||
: 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.`,
|
||||
suprimidos, sinDato,
|
||||
};
|
||||
}
|
||||
@@ -176,7 +214,7 @@ function etiquetaCategoria(meta: Record<string, unknown>, id: string) {
|
||||
// The plot follows from what the contract's numbers mean: counts add up to a total, percentages
|
||||
// and medians do not, so those two are never stacked.
|
||||
export function historicoFigura(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones = {}): HistoricoFigura {
|
||||
const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema)
|
||||
const figura = data.contrato === 'C2' ? conteo(data, tema, opciones) : data.contrato === 'C1' ? porcentaje(data, tema)
|
||||
: data.contrato === 'C3r' ? mediana(data, tema, opciones) : undefined;
|
||||
if (!figura) throw new Error('Representación no soportada');
|
||||
return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) };
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
|
||||
// Covers the history tab in the page: it exists for CaMa only, sits between Indicadores and Seguimiento, 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(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).not.toBeNull();
|
||||
fixture.componentInstance.changeSection('analisis');
|
||||
fixture.detectChanges();
|
||||
@@ -38,20 +38,21 @@ describe('Pestaña Histórico', () => {
|
||||
expect(root().querySelector('#panel-analisis')).toBeNull();
|
||||
http.expectNone(request => request.url.startsWith('/cama/analisis'));
|
||||
});
|
||||
it('cacu no tiene la pestaña Histórico', () => {
|
||||
// Fails if the history tab of TEA or CaMa leaks into CaCu.
|
||||
it('cacu tiene Histórico y no Análisis epidemiológico', () => {
|
||||
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
|
||||
abrir('cama', []);
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(root().querySelector('#panel-historico')).toBeNull();
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', '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', () => {
|
||||
abrir('cama', []);
|
||||
abrir('tea', [item('tea_x', 'C2')]);
|
||||
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(tabs()).toEqual(['Indicadores', 'Histórico', 'Análisis de riesgos', '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 Resumen se oculta', () => {
|
||||
it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Indicadores se oculta', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
const panel = () => root().querySelector('#panel-historico') as HTMLElement;
|
||||
expect(panel().hidden).toBe(true);
|
||||
@@ -62,7 +63,7 @@ describe('Pestaña Histórico', () => {
|
||||
fixture.componentInstance.changeSection('resumen'); fixture.detectChanges();
|
||||
expect(panel().hidden).toBe(true);
|
||||
});
|
||||
it('cambiar de dominio vuelve a Resumen', () => {
|
||||
it('cambiar de dominio vuelve a Indicadores', () => {
|
||||
abrir('cama', [item('cama_eu38a', 'C3r')]);
|
||||
fixture.componentInstance.changeSection('historico'); fixture.detectChanges();
|
||||
abrir('cacu', [item('cacu_x', 'C2')]);
|
||||
|
||||
@@ -192,11 +192,19 @@ describe('Pestaña Histórico', () => {
|
||||
}
|
||||
render();
|
||||
const paneles = fixture.componentInstance.paneles();
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['M28_casos_por_estado', 'en_proceso', 'tiempos']);
|
||||
const grupo = paneles[2] as Extract<(typeof paneles)[number], { estado: 'listo' }>;
|
||||
expect(paneles.map(p => p.item.id)).toEqual(['tiempos', 'M28_casos_por_estado', 'en_proceso']);
|
||||
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);
|
||||
});
|
||||
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.
|
||||
const ids = ['M30_resultado_eeg', 'M29_calidad_eeg', 'otro', 'M28_casos_por_estado', 'M22_diagnosticados_sin_eeg', 'M21_diagnosticados_con_eeg', 'M24_confirmacion_diagnostico', 'M23_pacientes_evaluados'];
|
||||
fixture.componentRef.setInput('catalog', ids.map(id => ({ id, titulo: id, contrato: 'C2', figuras: [], tipos_periodo: ['mes'] })));
|
||||
render();
|
||||
expect(fixture.componentInstance.paneles().map(p => p.item.id)).toEqual(['M23_pacientes_evaluados', 'M24_confirmacion_diagnostico', 'M21_diagnosticados_con_eeg',
|
||||
'M22_diagnosticados_sin_eeg', 'M28_casos_por_estado', 'M29_calidad_eeg', 'M30_resultado_eeg', 'otro']);
|
||||
});
|
||||
it('Personalizado abre el diálogo con los periodos del intervalo y muestra solo los elegidos', async () => {
|
||||
const c = fixture.componentInstance;
|
||||
const cerrar = new Subject<string[] | undefined>();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core';
|
||||
import { Component, computed, DestroyRef, effect, inject, input, output, signal, untracked, viewChild } from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||
@@ -6,35 +6,42 @@ import { MatDialog } from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatSelect, MatSelectModule } from '@angular/material/select';
|
||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs';
|
||||
import { defer, map, Subscription } from 'rxjs';
|
||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||
import { cronologico, enProcesoFigura, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures';
|
||||
import { cronologico, enProcesoFigura, 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 { IndicadoresService } from './indicadores.service';
|
||||
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
|
||||
import { HISTORICO_CAMA, historicoDeDominio, PanelHistorico } from './indicadores-historico-config';
|
||||
|
||||
export { HISTORICO_CAMA };
|
||||
|
||||
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
||||
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string } & (
|
||||
{ estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura; pasos?: { titulo: string; figura: HistoricoFigura }[] });
|
||||
interface Carga {
|
||||
disponibles?: string[];
|
||||
datos?: IndicadorDatos;
|
||||
errorPeriodos?: string;
|
||||
consultados: ReadonlySet<string>;
|
||||
enCurso: ReadonlySet<string>;
|
||||
fallos: ReadonlyMap<string, string>;
|
||||
}
|
||||
type Panel = { item: Pick<Indicador, 'id' | 'titulo'> & { contrato?: Indicador['contrato'] }; rango?: string; mensaje?: string } & (
|
||||
{ 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 PERSONALIZADO = -1;
|
||||
|
||||
// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not
|
||||
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
|
||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
|
||||
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
||||
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
|
||||
{ id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||
];
|
||||
function unir(a: IndicadorDatos, b: IndicadorDatos): IndicadorDatos {
|
||||
const nuevos = new Set(b.periodos.filter(p => !a.periodos.includes(p)));
|
||||
const reportes = [...(Array.isArray(a['reportes']) ? a['reportes'] : []),
|
||||
...(Array.isArray(b['reportes']) ? b['reportes'].filter(r => nuevos.has(r.periodo)) : [])];
|
||||
const unidades = { ...(a['unidades_periodo'] as object | undefined), ...(b['unidades_periodo'] as object | undefined) };
|
||||
return { ...a, periodos: [...a.periodos, ...nuevos], filas: [...a.filas, ...b.filas.filter(f => nuevos.has(f['periodo'] as string))],
|
||||
...(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[] {
|
||||
@@ -56,6 +63,14 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
});
|
||||
}
|
||||
|
||||
// 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];
|
||||
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);
|
||||
}
|
||||
|
||||
// Evolution of each indicator: the granularity and how many of the latest periods to show.
|
||||
// Nothing is requested until the tab is first opened, and each granularity is requested once.
|
||||
@Component({
|
||||
@@ -86,13 +101,16 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
||||
<article class="panel" [class.ancho]="panel.estado === 'listo' && panel.pasos" [attr.aria-busy]="panel.estado === 'cargando'">
|
||||
<h2>{{ panel.item.titulo }}</h2>
|
||||
@if (panel.rango) { <p class="rango">{{ panel.rango }}</p> }
|
||||
@if (panel.mensaje) {
|
||||
<div role="alert"><p>Error. {{ panel.mensaje }}</p>
|
||||
<button type="button" mat-stroked-button (click)="reintentar(panel.item.id)">Reintentar consulta</button></div>
|
||||
}
|
||||
@switch (panel.estado) {
|
||||
@case ('pendiente') { <p role="status">Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.</p> }
|
||||
@case ('desarrollo') { <p role="status">Trabajo en desarrollo</p> }
|
||||
@case ('cargando') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + panel.item.titulo" /> }
|
||||
@case ('vacio') { <p role="status">Sin reportes publicados para este intervalo de análisis.</p> }
|
||||
@case ('error') {
|
||||
<div role="alert"><p>{{ panel.mensaje }}</p>
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button></div>
|
||||
@case ('vacio') {
|
||||
<p role="status">{{ dominio() === 'cacu' ? 'Sin datos' : 'Sin reportes publicados para este intervalo de análisis.' }}</p>
|
||||
}
|
||||
@case ('listo') {
|
||||
@if (panel.pasos; as pasos) {
|
||||
@@ -171,9 +189,19 @@ export class IndicadoresHistorico {
|
||||
readonly catalog = input.required<readonly Indicador[]>();
|
||||
readonly tema = input.required<Tema>();
|
||||
readonly active = input(false);
|
||||
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
|
||||
private readonly publicados = computed(() => this.dominio() === 'cama'
|
||||
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
|
||||
readonly catalogLoading = input(false);
|
||||
readonly catalogError = input('');
|
||||
readonly retryCatalog = output<void>();
|
||||
// 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;
|
||||
// the whole catalog elsewhere. A reserved panel is never one of them, whatever the catalog publishes.
|
||||
private readonly publicados = computed(() => {
|
||||
const config = this.config();
|
||||
return config
|
||||
? config.paneles.filter(entrada => !entrada.enDesarrollo).flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))
|
||||
: this.catalog();
|
||||
});
|
||||
// Only the granularities some indicator publishes; monthly first when there is one.
|
||||
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
|
||||
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
|
||||
@@ -183,15 +211,23 @@ export class IndicadoresHistorico {
|
||||
});
|
||||
// How many of the latest periods to show, per granularity; 0 shows them all.
|
||||
private readonly ventanas = signal<Partial<Record<TipoPeriodo, number>>>({});
|
||||
readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0);
|
||||
// Until the user picks one, the domain's initial window (when it declares one and there are more periods) or all.
|
||||
readonly ventana = computed(() => {
|
||||
const elegida = this.ventanas()[this.tipo()];
|
||||
if (elegida !== undefined) return elegida;
|
||||
const inicial = this.config()?.periodosIniciales ?? 0, total = this.totalDisponibles();
|
||||
return inicial && (!total || total > inicial) ? inicial : 0;
|
||||
});
|
||||
readonly PERSONALIZADO = PERSONALIZADO;
|
||||
// The periods the user picked in the dialog, per granularity.
|
||||
private readonly personalizados = signal<Partial<Record<TipoPeriodo, readonly string[]>>>({});
|
||||
private readonly dialogo = inject(MatDialog);
|
||||
private readonly selector = viewChild<MatSelect>('selector');
|
||||
// Every period published for the granularity by any indicator.
|
||||
private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : [])));
|
||||
private readonly disponibles = computed(() => cronologico([...new Set(Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.flatMap(carga => this.config()?.periodosIniciales ? carga.disponibles ?? [] : carga.datos?.periodos ?? []))]));
|
||||
private readonly totalDisponibles = computed(() => Math.max(0, ...Object.values(this.cargas()[this.tipo()] ?? {})
|
||||
.map(carga => (this.config()?.periodosIniciales ? carga.disponibles : carga.datos?.periodos)?.length ?? 0)));
|
||||
// The periods on screen, out of those an indicator publishes.
|
||||
private recortar(periodos: readonly string[]) {
|
||||
const orden = cronologico(periodos), ventana = this.ventana();
|
||||
@@ -202,14 +238,13 @@ export class IndicadoresHistorico {
|
||||
private readonly service = inject(IndicadoresService);
|
||||
private readonly periodos = inject(IndicadoresPeriodos);
|
||||
private readonly cargas = signal<Partial<Record<TipoPeriodo, Record<string, Carga>>>>({});
|
||||
private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>();
|
||||
private solicitada?: string;
|
||||
private catalogoCargado?: readonly Indicador[];
|
||||
private peticiones = new Subscription();
|
||||
private ambito?: { dominio: Dominio; catalogo: readonly Indicador[] };
|
||||
|
||||
// Steps of five, up to what the indicator with the most periods has published.
|
||||
readonly opciones = computed(() => {
|
||||
const tipo = this.tipo();
|
||||
const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0));
|
||||
const total = this.totalDisponibles();
|
||||
const opciones = [];
|
||||
for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` });
|
||||
const elegidos = this.personalizados()[tipo]?.length;
|
||||
@@ -221,7 +256,7 @@ export class IndicadoresHistorico {
|
||||
// Top of the shared scale: the highest third quartile of the steps, in the periods on screen.
|
||||
const maxTiempos = () => Math.max(1, ...TIEMPOS.flatMap(id => {
|
||||
const carga = cargas?.[id];
|
||||
if (carga?.estado !== 'listo') return [];
|
||||
if (!carga?.datos) return [];
|
||||
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;
|
||||
@@ -229,56 +264,140 @@ export class IndicadoresHistorico {
|
||||
if (!item.tipos_periodo.includes(tipo)) return { item, estado: 'vacio' };
|
||||
const carga = cargas?.[item.id];
|
||||
if (!carga) return { item, estado: 'cargando' };
|
||||
if (carga.estado !== 'listo') return { item, ...carga };
|
||||
const periodos = this.recortar(carga.datos.periodos);
|
||||
if (!periodos.length) return { item, estado: 'vacio' };
|
||||
const necesarios = this.necesarios(carga.disponibles ?? [], tipo);
|
||||
const mensaje = carga.errorPeriodos ?? necesarios.map(p => carga.fallos.get(p)).find(Boolean);
|
||||
const periodos = this.config()?.periodosIniciales
|
||||
? necesarios.filter(p => carga.datos?.periodos.includes(p))
|
||||
: this.recortar(carga.datos?.periodos ?? []);
|
||||
if (!periodos.length || !carga.datos) {
|
||||
if (mensaje) return { item, estado: 'error', mensaje };
|
||||
return { item, estado: !carga.disponibles || necesarios.some(p => carga.enCurso.has(p)) ? 'cargando' : 'vacio' };
|
||||
}
|
||||
const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) };
|
||||
const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`;
|
||||
const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`;
|
||||
try {
|
||||
return { item, rango, estado: 'listo', figura: historicoFigura(datos, tema, TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}), datos };
|
||||
const propias = this.config();
|
||||
const opciones = { ...(TIEMPOS.includes(item.id) ? { yMax: maxTiempos(), pequena: true } : {}),
|
||||
...(propias ? { unidades: propias.unidades, conciliarC2: propias.conciliarC2, c2SinPoblacionSinDato: propias.c2SinPoblacionSinDato } : {}) };
|
||||
const figura = historicoFigura(datos, tema, opciones);
|
||||
if (this.dominio() === 'cacu' && figura.sinDato.length === periodos.length) {
|
||||
return { item, estado: mensaje ? 'error' : 'vacio', mensaje };
|
||||
}
|
||||
return { item, rango, estado: 'listo', figura, datos, mensaje };
|
||||
} catch (error) {
|
||||
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
|
||||
}
|
||||
};
|
||||
if (this.dominio() === 'cama') {
|
||||
if (!this.publicados().length) return [];
|
||||
return HISTORICO_CAMA.map((entrada): Panel => {
|
||||
const config = this.config();
|
||||
if (config) {
|
||||
const cacu = this.dominio() === 'cacu';
|
||||
if (!cacu && !this.publicados().length) return [];
|
||||
return config.paneles.map((entrada: PanelHistorico): Panel => {
|
||||
const visible = { id: entrada.id, titulo: entrada.titulo };
|
||||
if (entrada.enDesarrollo) return { item: visible, estado: 'desarrollo' };
|
||||
if (cacu && this.catalogError()) return { item: visible, estado: 'error', mensaje: this.catalogError() };
|
||||
if (cacu && this.catalogLoading()) return { item: visible, estado: 'cargando' };
|
||||
const item = this.catalog().find(i => i.id === entrada.id);
|
||||
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
|
||||
if (!item) return { item: visible, estado: cacu ? 'desarrollo' : 'pendiente' };
|
||||
return { ...panelDe(item), item: { ...visible, contrato: item.contrato } };
|
||||
});
|
||||
}
|
||||
return agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
const paneles = agrupar(this.catalog().filter(item => item.tipos_periodo.includes(tipo)).map(panelDe), tema);
|
||||
return this.dominio() === 'tea' ? ordenar(paneles, ORDEN_TEA) : paneles;
|
||||
});
|
||||
|
||||
constructor() {
|
||||
this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo))
|
||||
.map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))),
|
||||
takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => {
|
||||
this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) }));
|
||||
});
|
||||
this.destruccion.onDestroy(() => this.peticiones.unsubscribe());
|
||||
effect(() => {
|
||||
const tipo = this.tipo(), items = this.publicados();
|
||||
if (!this.active() || !items.length) return;
|
||||
const dominio = this.dominio(), catalogo = this.catalog(), tipo = this.tipo();
|
||||
const activo = this.active() && !this.catalogLoading() && !this.catalogError();
|
||||
untracked(() => {
|
||||
if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; }
|
||||
if (this.cargas()[tipo] || this.solicitada === tipo) return;
|
||||
this.solicitada = tipo;
|
||||
this.solicitudes.next({ tipo, items });
|
||||
if (this.ambito?.catalogo !== catalogo || this.ambito?.dominio !== dominio) {
|
||||
this.peticiones.unsubscribe();
|
||||
this.peticiones = new Subscription();
|
||||
this.cargas.set({});
|
||||
this.ambito = { dominio, catalogo };
|
||||
}
|
||||
if (activo) this.cargarVentana(tipo);
|
||||
});
|
||||
});
|
||||
}
|
||||
private cargar(item: Indicador, tipo: TipoPeriodo): Observable<Carga> {
|
||||
return this.periodos.periodos(this.dominio(), item.id).pipe(
|
||||
map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)),
|
||||
switchMap((periodos): Observable<Carga> => periodos.length
|
||||
? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos })))
|
||||
: of({ estado: 'vacio' })),
|
||||
catchError(error => of<Carga>({ estado: 'error', mensaje: httpMessage(error) })));
|
||||
|
||||
private necesarios(disponibles: readonly string[], tipo: TipoPeriodo): string[] {
|
||||
if (!this.config()?.periodosIniciales) return [...disponibles];
|
||||
const orden = cronologico(disponibles), ventana = this.ventanas()[tipo] ?? this.config()?.periodosIniciales;
|
||||
if (ventana === PERSONALIZADO) return orden.filter(p => (this.personalizados()[tipo] ?? []).includes(p));
|
||||
return ventana ? orden.slice(-ventana) : orden;
|
||||
}
|
||||
|
||||
private guardarCarga(tipo: TipoPeriodo, id: string, carga: Carga) {
|
||||
this.cargas.update(actual => ({ ...actual, [tipo]: { ...actual[tipo], [id]: carga } }));
|
||||
}
|
||||
|
||||
private cargarVentana(tipo: TipoPeriodo) {
|
||||
if (!this.active() || this.catalogLoading() || this.catalogError()) return;
|
||||
for (const { id, tipos_periodo } of this.publicados()) {
|
||||
if (!tipos_periodo.includes(tipo)) continue;
|
||||
const carga = this.cargas()[tipo]?.[id];
|
||||
if (carga) this.solicitarPeriodos(tipo, id, carga);
|
||||
else this.descubrirPeriodos(tipo, id);
|
||||
}
|
||||
}
|
||||
|
||||
private descubrirPeriodos(tipo: TipoPeriodo, id: string) {
|
||||
const carga: Carga = { consultados: new Set(), enCurso: new Set(), fallos: new Map() };
|
||||
this.guardarCarga(tipo, id, carga);
|
||||
this.peticiones.add(defer(() => this.periodos.periodos(this.dominio(), id)).subscribe({
|
||||
next: periodos => {
|
||||
const descubierta = { ...carga, disponibles: [...new Set(periodos.filter(p => p.tipo === tipo).map(p => p.periodo))] };
|
||||
this.guardarCarga(tipo, id, descubierta);
|
||||
if (this.active() && this.tipo() === tipo) this.solicitarPeriodos(tipo, id, descubierta);
|
||||
},
|
||||
error: error => this.guardarCarga(tipo, id, { ...carga, errorPeriodos: httpMessage(error) }),
|
||||
}));
|
||||
}
|
||||
|
||||
private solicitarPeriodos(tipo: TipoPeriodo, id: string, carga: Carga) {
|
||||
if (!carga.disponibles) return;
|
||||
const faltan = this.necesarios(carga.disponibles, tipo)
|
||||
.filter(p => !carga.consultados.has(p) && !carga.enCurso.has(p) && !carga.fallos.has(p));
|
||||
if (!faltan.length) return;
|
||||
this.guardarCarga(tipo, id, { ...carga, enCurso: new Set([...carga.enCurso, ...faltan]) });
|
||||
const solicitados = new Set(faltan);
|
||||
const vigente = () => {
|
||||
const actual = this.cargas()[tipo]![id];
|
||||
return { ...actual, enCurso: new Set([...actual.enCurso].filter(p => !solicitados.has(p))) };
|
||||
};
|
||||
const config = this.config();
|
||||
const esperado = config?.paneles.find(panel => panel.id === id)?.contrato;
|
||||
this.peticiones.add(defer(() => this.service.datos(this.dominio(), id, tipo, faltan)).pipe(map(datos => {
|
||||
if (esperado && datos.contrato !== esperado) {
|
||||
throw new ContratoHistoricoInvalido(`Contrato inesperado: se esperaba ${esperado} y llegó ${datos.contrato}`);
|
||||
}
|
||||
// Validate each batch before it is allowed to affect a series that already has valid periods.
|
||||
if (esperado && datos.periodos.length) historicoFigura(datos, this.tema(), config);
|
||||
return datos;
|
||||
})).subscribe({
|
||||
next: datos => {
|
||||
const actual = vigente();
|
||||
this.guardarCarga(tipo, id, { ...actual, consultados: new Set([...actual.consultados, ...faltan]),
|
||||
datos: actual.datos ? unir(actual.datos, datos) : datos });
|
||||
},
|
||||
error: error => {
|
||||
const actual = vigente(), fallos = new Map(actual.fallos);
|
||||
const mensaje = error instanceof ContratoHistoricoInvalido ? error.message : httpMessage(error);
|
||||
for (const periodo of faltan) fallos.set(periodo, mensaje);
|
||||
this.guardarCarga(tipo, id, { ...actual, fallos });
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
private readonly destruccion = inject(DestroyRef);
|
||||
elegirVentana(valor: number) {
|
||||
if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; }
|
||||
this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor }));
|
||||
this.cargarVentana(this.tipo());
|
||||
}
|
||||
abrirPersonalizado() {
|
||||
const tipo = this.tipo(), periodos = this.disponibles();
|
||||
@@ -286,19 +405,38 @@ export class IndicadoresHistorico {
|
||||
const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos;
|
||||
const data: PeriodosDialogoDatos = { tipo, periodos, elegidos };
|
||||
this.dialogo.open<IndicadoresHistoricoPeriodos, PeriodosDialogoDatos, string[]>(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' })
|
||||
.afterClosed().subscribe(resultado => {
|
||||
.afterClosed().pipe(takeUntilDestroyed(this.destruccion)).subscribe(resultado => {
|
||||
if (resultado?.length) {
|
||||
this.personalizados.update(actual => ({ ...actual, [tipo]: resultado }));
|
||||
this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO }));
|
||||
if (this.tipo() === tipo) this.cargarVentana(tipo);
|
||||
}
|
||||
// Cancelled, the selector goes back to what's on screen.
|
||||
this.selector()?.writeValue(this.ventana());
|
||||
});
|
||||
}
|
||||
reintentar() {
|
||||
reintentar(id: string) {
|
||||
if (this.catalogError()) {
|
||||
this.retryCatalog.emit();
|
||||
return;
|
||||
}
|
||||
const tipo = this.tipo();
|
||||
this.solicitada = tipo;
|
||||
this.cargas.update(({ [tipo]: _, ...resto }) => resto);
|
||||
this.solicitudes.next({ tipo, items: this.publicados() });
|
||||
const carga = this.cargas()[tipo]?.[id];
|
||||
if (!carga) return;
|
||||
if (carga.errorPeriodos) {
|
||||
this.descubrirPeriodos(tipo, id);
|
||||
return;
|
||||
}
|
||||
const seleccion = this.necesarios(carga.disponibles ?? [], tipo);
|
||||
if (!seleccion.some(periodo => carga.fallos.has(periodo))) {
|
||||
// A figure can fail after its reports were accepted. Reload just that panel.
|
||||
if (!carga.enCurso.size) this.descubrirPeriodos(tipo, id);
|
||||
return;
|
||||
}
|
||||
const fallos = new Map(carga.fallos);
|
||||
for (const periodo of seleccion) fallos.delete(periodo);
|
||||
const corregida = { ...carga, fallos };
|
||||
this.guardarCarga(tipo, id, corregida);
|
||||
this.solicitarPeriodos(tipo, id, corregida);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,11 +126,12 @@ describe('P0-C.1: cinco tarjetas de oportunidad', () => {
|
||||
http.expectOne(r => r.url.includes('/cacu_dias_toma_diagnostico/datos')).flush({ ...payload('2025-S1', { mediana: 52, q3: 90 }), id: 'cacu_dias_toma_diagnostico' });
|
||||
f.detectChanges();
|
||||
const cards = [...f.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Días de toma a resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('h3')!.textContent)).toEqual(['Pacientes evaluadas', 'Tiempo desde la toma de muestra al resultado', 'Tiempo de tamizaje a diagnóstico', 'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento']);
|
||||
expect(cards.map(c => c.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['20', '12', '52', undefined, undefined]);
|
||||
expect(cards.map(c => c.querySelector('.value span')?.textContent)).toEqual(['pacientes', 'días (mediana)', 'días (mediana)', undefined, undefined]);
|
||||
for (const card of cards.slice(3)) {
|
||||
expect(card.querySelectorAll('p')).toHaveLength(1); expect(card.querySelector('p')!.textContent).toBe('Indicador no disponible');
|
||||
expect(card.querySelector('.kpi-state')?.textContent?.trim()).toBe('Integración pendiente');
|
||||
expect(card.textContent).toContain('aún no está publicado');
|
||||
}
|
||||
http.expectNone(() => true);
|
||||
} finally { f.destroy(); vi.unstubAllGlobals(); http.verify(); }
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ActivatedRoute, provideRouter } from '@angular/router';
|
||||
import { datosDeReportes, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { CACU_TRATAMIENTO_KPIS, kpiResult } from './indicadores-kpi';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
|
||||
const PERIOD = '2025-S2';
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: [PERIOD] }, revision: 1 };
|
||||
const measure = (id: string): Measure => ({
|
||||
resourceType: 'Measure', id, title: id, extension: [
|
||||
{ url: 'contrato', valueCode: 'C3r' },
|
||||
{ url: 'tipos-periodo', valueCode: 'semestre' },
|
||||
{ url: 'figuras', valueString: 'fig_c3r_caja' },
|
||||
],
|
||||
});
|
||||
const report = (median: number, q1: number, q3: number, n: number): Report => ({
|
||||
resourceType: 'MeasureReport', period: { start: '2025-07-01', end: '2025-12-31' },
|
||||
group: [{
|
||||
code: { coding: [{ code: 'TOTAL' }] },
|
||||
population: [{ code: { coding: [{ code: 'measure-observation' }] }, count: n }],
|
||||
measureScore: { value: median, unit: 'd', extension: [
|
||||
{ url: 'q1', valueDecimal: q1 },
|
||||
{ url: 'q3', valueDecimal: q3 },
|
||||
] },
|
||||
}],
|
||||
});
|
||||
|
||||
describe('KPI de tratamiento de CaCu', () => {
|
||||
it.each([
|
||||
['CACU-DIAS-TOMA-TRATAMIENTO', 'cacu_dias_toma_tratamiento', 21.5, 8.25, 33.75, 12],
|
||||
['CACU-DIAS-DIAGNOSTICO-TRATAMIENTO', 'cacu_dias_diagnostico_tratamiento', 7.75, 2.5, 14, 9],
|
||||
] as const)('mapea %s y conserva los valores C3r publicados', (fhirId, id, median, q1, q3, n) => {
|
||||
const fhirMeasure = measure(fhirId);
|
||||
const definition = CACU_TRATAMIENTO_KPIS.find(kpi => kpi.id === id)!;
|
||||
expect(indicadorDeMeasure(fhirMeasure)).toMatchObject({ id, contrato: 'C3r' });
|
||||
const data = datosDeReportes(fhirMeasure, [report(median, q1, q3, n)], 'semestre');
|
||||
expect(kpiResult(data, definition, 'cacu', applied)).toEqual({
|
||||
state: 'Disponible', value: median,
|
||||
info: `${n} observaciones. Primer cuartil de ${q1} días y tercer cuartil de ${q3} días.`,
|
||||
});
|
||||
});
|
||||
|
||||
it('distingue una mediana publicada de cero días de la ausencia de observaciones o la supresión', () => {
|
||||
const fhirMeasure = measure('CACU-DIAS-TOMA-TRATAMIENTO');
|
||||
const definition = CACU_TRATAMIENTO_KPIS[0];
|
||||
const empty = datosDeReportes(fhirMeasure, [report(0, 0, 0, 0)], 'semestre');
|
||||
expect(kpiResult(empty, definition, 'cacu', applied)).toEqual({ state: 'Sin valor disponible' });
|
||||
const published = datosDeReportes(fhirMeasure, [report(0, 0, 0, 1)], 'semestre');
|
||||
expect(kpiResult(published, definition, 'cacu', applied).value).toBe(0);
|
||||
const suppressed = { ...published, filas: [{ ...published.filas[0], suprimido: 1 }] };
|
||||
expect(kpiResult(suppressed, definition, 'cacu', applied)).toEqual({ state: 'Dato oculto por tamaño' });
|
||||
});
|
||||
|
||||
it('presenta una sola tarjeta por medida con publicación parcial y conserva el periodo del dato', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([]),
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { data: { dominio: 'cacu' } } } }] });
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cacu');
|
||||
const fixture = TestBed.createComponent(IndicadoresPage), http = TestBed.inject(HttpTestingController);
|
||||
const fhirMeasure = measure('CACU-DIAS-DIAGNOSTICO-TRATAMIENTO');
|
||||
const { id } = indicadorDeMeasure(fhirMeasure);
|
||||
try {
|
||||
http.expectOne('/cacu/indicadores').flush([indicadorDeMeasure(fhirMeasure)]);
|
||||
http.expectOne(`/cacu/indicadores/${id}/periodos`).flush({ id, periodos: [{ periodo: PERIOD, tipo: 'semestre' }] });
|
||||
fixture.detectChanges();
|
||||
const request = http.expectOne(r => r.url === `/cacu/indicadores/${id}/datos`);
|
||||
expect(request.request.params.get('periodos')).toBe(PERIOD);
|
||||
request.flush(datosDeReportes(fhirMeasure, [report(7.75, 2.5, 14, 9)], 'semestre'));
|
||||
fixture.detectChanges();
|
||||
const root = fixture.nativeElement as HTMLElement;
|
||||
const cards = [...root.querySelectorAll('.kpi-grid app-indicador-kpi-card')];
|
||||
expect(cards.map(card => card.querySelector('h3')?.textContent)).toEqual([
|
||||
'Tiempo de tamizaje a tratamiento', 'Tiempo de diagnóstico a tratamiento',
|
||||
]);
|
||||
expect(cards[0].querySelector('.kpi-state')?.textContent).toBe('Integración pendiente');
|
||||
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');
|
||||
expect(root.querySelector('.graphic-section app-indicador-catalog-card')).toBeNull();
|
||||
http.expectNone(() => true);
|
||||
} finally {
|
||||
fixture.destroy();
|
||||
http.verify();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -73,7 +73,7 @@ it('TEA usa sus cinco indicadores destacados y su grupo C1 es TOTAL', () => {
|
||||
expect(kpiResult(eeg, KPI_BY_DOMAIN.tea[3], 'tea', applied).info).toBe('71 de 114 pacientes con diagnóstico confirmado tienen un EEG de buena calidad.');
|
||||
const d = data('tea', 1, [{ ...total, grupo: 'TOTAL', valor: 50, numerador: 3, denominador: 6 }]);
|
||||
expect(kpiResult(d, KPI_BY_DOMAIN.tea[1], 'tea', applied)).toEqual({ state: 'Disponible', value: '50.0',
|
||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.' });
|
||||
info: '3 de 6 pacientes con nota médica con diagnóstico CIE-10 F84.0.', numerador: 3, denominador: 6 });
|
||||
expect(kpiResult(data('tea', 1, [{ ...total, grupo: 'total', valor: 50, numerador: 3, denominador: 6 }]), KPI_BY_DOMAIN.tea[1], 'tea', applied).state)
|
||||
.toBe('Selección no consolidable');
|
||||
});
|
||||
|
||||
@@ -8,11 +8,27 @@ export interface KpiDefinition {
|
||||
c1Info?: (numerador: number, denominador: number) => string;
|
||||
// C3r only: a median over zero observations is no value, not zero days.
|
||||
requiresObservations?: boolean;
|
||||
c3rInfo?: (n: number, q1: number, q3: number) => string;
|
||||
note?: string;
|
||||
// C2 only: replaces the domain's explanatory line when the unit counted is not the domain's usual one.
|
||||
c2Info?: string;
|
||||
}
|
||||
// Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID.
|
||||
export const CACU_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
id: 'cacu_eu_tiempo_reporte', title: 'Tiempo desde la toma de muestra al resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
|
||||
};
|
||||
const CACU_TRATAMIENTO_C3R = {
|
||||
contrato: '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[] = [
|
||||
{ ...CACU_TRATAMIENTO_C3R, id: 'cacu_dias_toma_tratamiento', title: 'Tiempo de tamizaje a tratamiento' },
|
||||
{ ...CACU_TRATAMIENTO_C3R, id: 'cacu_dias_diagnostico_tratamiento', title: 'Tiempo de diagnóstico a tratamiento' },
|
||||
];
|
||||
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
};
|
||||
@@ -37,12 +53,42 @@ export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
// M28's stages at the period's end: a child finishes the screening with a good EEG; the other stages are in process.
|
||||
export const M28_COMPLETO = 'EEG';
|
||||
export const M28_EN_PROCESO = ['SOLO_MCHAT', 'PSICOLOGIA', 'NEUROPEDIATRIA'];
|
||||
// What only TEA's summary paragraph needs: the children by stage and the time of each screening step.
|
||||
// M29's category of the EEGs the analysis found valid.
|
||||
export const M29_BUENO = 'BUENO';
|
||||
// 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' },
|
||||
{ id: 'M26_dias_mchat_ados2', title: 'Tiempo de M-CHAT a ADOS-2', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M27_dias_ados2_diagnostico', title: 'Tiempo de ADOS-2 a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
{ id: 'M29_calidad_eeg', title: 'Estudios de EEG', contrato: 'C2', unit: 'estudios', c2Info: 'Estudios de EEG realizados en el periodo a niños de la cohorte.' },
|
||||
];
|
||||
// TEA's figures under «Indicadores de oportunidad» and under «Indicadores clínicos», each in display order. Any other
|
||||
// published TEA indicator follows the clinical ones.
|
||||
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.
|
||||
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
|
||||
// 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' },
|
||||
{ id: 'cama_dias_resultado_diagnostico', titulo: 'Tiempo de interpretación radiológica a diagnóstico' },
|
||||
{ titulo: 'Tiempo de interpretación radiológica a resultado de biopsia' },
|
||||
{ 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.
|
||||
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' },
|
||||
@@ -101,7 +147,8 @@ const C3R_INFO: Record<Dominio, (n: number, q1: number, q3: number) => string> =
|
||||
cacu: (n, q1, q3) => `${n} citologías; primer cuartil: ${q1} días; tercer cuartil: ${q3} días.`,
|
||||
cama: (n, q1, q3) => `${n} mastografías; Q1 a Q3: ${q1} a ${q3} días.`,
|
||||
};
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; }
|
||||
// C1 results also carry the counts the percentage comes from; C2 results, the count of each category.
|
||||
export interface KpiResult { state: string; value?: string | number; info?: string; loading?: boolean; notes?: string[]; categorias?: Record<string, number>; numerador?: number; denominador?: number; }
|
||||
const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
||||
const count = (v: unknown): v is number => finite(v) && Number.isSafeInteger(v) && v >= 0;
|
||||
const unscoped = { state: 'Selección no consolidable', info: 'Elige un único periodo. No hay una regla aprobada para consolidar periodos, grupos o estratos.' };
|
||||
@@ -137,8 +184,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
const value = rows.reduce((sum, row) => sum + (row['n'] as number), 0);
|
||||
if (!count(value)) return empty;
|
||||
return { state: 'Disponible', value, categorias: Object.fromEntries(rows.map(row => [row['categoria'] as string, row['n'] as number])),
|
||||
info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
||||
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.' };
|
||||
info: definition.c2Info ?? (domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.'
|
||||
: domain === 'cama' ? 'Pacientes con mastografía BI-RADS 4, 5 o 6 en el periodo.' : 'Conteo de pacientes únicos en el periodo.') };
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100) return empty;
|
||||
@@ -148,8 +195,9 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
return { state: 'Error de contrato', info: 'El numerador y el denominador deben ser conteos no negativos compatibles.' };
|
||||
}
|
||||
if (denominator === 0) return empty;
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator) };
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator),
|
||||
numerador: numerator, denominador: denominator };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty;
|
||||
return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) };
|
||||
return { state: 'Disponible', value: row['mediana'], info: (definition.c3rInfo ?? C3R_INFO[domain])(row['n'], row['q1'], row['q3']) };
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = kpiCards;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
@if ((kpis.length || (dominio === 'tea' && oportunidadSlots().length)) && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
@let resumen = teaResumenPeriodo;
|
||||
<div class="kpi-heading">
|
||||
@@ -52,24 +52,35 @@
|
||||
</div>
|
||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
||||
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
|
||||
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cama' ? 1 : 0)">
|
||||
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
||||
@if (card.pending) {
|
||||
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
} @else {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="card.definition" [indicador]="kpiIndicator(card.definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false"
|
||||
[showPeriod]="filters?.applied.selection.mode === 'todos' && esKpiTratamientoCacu(card.definition.id)" />
|
||||
}
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
|
||||
} @else if (dominio === 'cama') {
|
||||
@if (dominio === 'cama') {
|
||||
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
}
|
||||
</div>
|
||||
@if (oportunidadSlots().length) {
|
||||
@if (dominio === 'cacu' || dominio === 'cama') { <h3 class="subsection-title">Tiempo de tamizaje a diagnóstico</h3> }
|
||||
<div class="catalog-grid">
|
||||
@for (slot of oportunidadSlots(); track slot.item ? cardIdentity(slot.item) : slot.titulo) {
|
||||
@if (slot.item; as item) {
|
||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||
[pinned]="isPinned(item)" [individual]="true" (pinChanged)="togglePinned(item)" />
|
||||
} @else {
|
||||
<app-indicador-figura-pendiente [titulo]="slot.titulo" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@@ -117,19 +128,32 @@
|
||||
}
|
||||
@if (screeningRouteAvailable) { <app-indicador-screening-route [dominio]="dominio" [tema]="tema" /> }
|
||||
<div class="catalog-grid">
|
||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||
@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)" />
|
||||
}
|
||||
@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">
|
||||
@if (confirmacionCamaPendiente) {
|
||||
<app-indicador-kpi-card [title]="confirmacionCama.title" state="Integración pendiente"
|
||||
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
|
||||
} @else {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="confirmacionCama" [indicador]="kpiIndicator(confirmacionCama.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@if (conHistorico) {
|
||||
<section id="panel-historico" class="section-panel" [class.dark-theme]="tema === 'oscuro'" role="tabpanel" aria-labelledby="tab-historico" tabindex="0" [hidden]="activeSection() !== 'historico'">
|
||||
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'" />
|
||||
<app-indicadores-historico [dominio]="dominio" [catalog]="catalog()" [tema]="tema" [active]="activeSection() === 'historico'"
|
||||
[catalogLoading]="catalogLoading()" [catalogError]="catalogError()" (retryCatalog)="retryCatalog()" />
|
||||
</section>
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,9 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
.graphic-section { margin-top: var(--issste-space-6); }
|
||||
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
|
||||
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||
.kpi-section .catalog-grid { margin-top: var(--issste-space-6); }
|
||||
.subsection-title { margin: var(--issste-space-6) 0 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; }
|
||||
.subsection-title + .catalog-grid { margin-top: var(--issste-space-3); }
|
||||
.catalog-grid { align-items: stretch; }
|
||||
.reporte-acciones { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
|
||||
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
|
||||
@@ -17,12 +17,13 @@ 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, CAMA_FUERA_DEL_RESUMEN, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN, KPI_RESUMEN_TEA, KpiCardSlot, 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, CACU_FIGURA_CLINICA_PENDIENTE, 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 { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
import { identityElementId, indicatorIdentity } from './indicadores-identities';
|
||||
import { emptyAvailability, IndicadoresPeriodos } from './indicadores-periodos';
|
||||
@@ -33,12 +34,13 @@ import { IndicadoresTracking } from './indicadores-tracking';
|
||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||
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';
|
||||
|
||||
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
{ id: 'resumen', label: 'Resumen' },
|
||||
{ id: 'resumen', label: 'Indicadores' },
|
||||
{ id: 'seguimiento', label: 'Análisis de riesgos' },
|
||||
{ id: 'datos', label: 'Datos y definiciones' },
|
||||
];
|
||||
@@ -47,6 +49,12 @@ const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||
const SECTIONS_WITH_HISTORY: readonly { id: DashboardSection; label: string }[] = [SECTIONS[0], { id: 'historico', label: 'Histórico' }, 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.
|
||||
function ordenTea(catalog: Indicador[]): Indicador[] {
|
||||
const named = [...TEA_FIGURAS_OPORTUNIDAD, ...TEA_FIGURAS_CLINICAS];
|
||||
const first = named.flatMap(id => catalog.filter(item => item.id === id));
|
||||
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],
|
||||
...(CAMA_ANALYSIS_ENABLED ? [{ id: 'analisis' as const, label: 'Análisis' }] : []),
|
||||
@@ -54,13 +62,13 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
||||
|
||||
@Component({
|
||||
selector: 'app-indicadores-page',
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
|
||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorFiguraPendiente, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo, IndicadorScreeningRoute],
|
||||
templateUrl: './indicadores-page.html',
|
||||
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 conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
|
||||
get conHistorico() { return this.dominio === 'tea' || historicoDeDominio(this.dominio) !== undefined; }
|
||||
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
|
||||
readonly activeSection = signal<DashboardSection>('resumen');
|
||||
readonly fichaPacienteAbierta = signal(false);
|
||||
@@ -173,7 +181,7 @@ export class IndicadoresPage {
|
||||
}
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
this.sizeObserver ??= new ResizeObserver(this.viewportChanged);
|
||||
const targets = [this.document.querySelector('.institutional-header'), this.element.nativeElement.querySelector('.catalog-grid')]
|
||||
const targets = [this.document.querySelector('.institutional-header'), ...this.element.nativeElement.querySelectorAll('.catalog-grid')]
|
||||
.filter((target): target is Element => target !== null);
|
||||
for (const target of this.sizeTargets) {
|
||||
if (!targets.includes(target)) { this.sizeObserver.unobserve(target); this.sizeTargets.delete(target); }
|
||||
@@ -328,8 +336,8 @@ export class IndicadoresPage {
|
||||
private cardsDeCama(catalog: Indicador[]) {
|
||||
const ids = catalog.map(item => item.id);
|
||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
||||
// The histopathology card keeps its place, first, whether pending or published.
|
||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
||||
// The exams' and patients' counts come first, then the histopathology card (pending or published); the confirmation rate follows them.
|
||||
return [...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA)];
|
||||
}
|
||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
||||
get histopatologiaPendiente() {
|
||||
@@ -355,11 +363,15 @@ export class IndicadoresPage {
|
||||
return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI,
|
||||
...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)];
|
||||
}
|
||||
// What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish.
|
||||
// CaCu's treatment cards follow the existing KPIs without changing the initial-period anchor.
|
||||
get kpiCards(): KpiCardSlot[] {
|
||||
if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id));
|
||||
return this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
const cards = this.opportunityKpis.map(definition => ({ definition, pending: false }));
|
||||
if (this.dominio !== 'cacu') return cards;
|
||||
const tratamiento = CACU_TRATAMIENTO_KPIS.map(definition => ({ definition, pending: !this.kpiIndicator(definition.id) }));
|
||||
return cards.length || tratamiento.some(card => !card.pending) ? [...cards, ...tratamiento] : [];
|
||||
}
|
||||
esKpiTratamientoCacu(id: string) { return this.dominio === 'cacu' && CACU_TRATAMIENTO_KPIS.some(kpi => kpi.id === id); }
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
// Ids of the indicators to render; null shows the whole catalog.
|
||||
@@ -374,6 +386,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')))
|
||||
: catalog.filter(item => !item.vistas || item.vistas.includes('resumen'));
|
||||
});
|
||||
readonly selectedIndicators = computed(() => this.indicatorSelection() ?? this.catalog().map(item => item.id));
|
||||
@@ -387,6 +400,45 @@ 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 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;
|
||||
if (this.dominio === 'tea') return items.filter(item => TEA_FIGURAS_OPORTUNIDAD.includes(item.id)).map(item => ({ item, titulo: item.titulo }));
|
||||
if (this.dominio === 'cama') {
|
||||
// CaMa's time indicators have no card in the ordered list (the summary keeps them out), so look in the catalog
|
||||
// restricted to the selection. The slot names the figure as the request does, whatever title the catalog gives.
|
||||
if (!this.catalog().length) return [];
|
||||
const selected = new Set(this.selectedIndicators());
|
||||
return CAMA_FIGURAS_OPORTUNIDAD.map(figura => {
|
||||
const item = figura.id ? this.catalog().find(candidate => candidate.id === figura.id && selected.has(candidate.id)) : undefined;
|
||||
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 };
|
||||
});
|
||||
});
|
||||
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)
|
||||
&& !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); }
|
||||
readonly catalogLoading = signal(true);
|
||||
readonly catalogError = signal('');
|
||||
tema: Tema = 'claro';
|
||||
@@ -432,8 +484,8 @@ export class IndicadoresPage {
|
||||
private scrollToIndicator(key: string) {
|
||||
if (this.activeSection() !== 'resumen' || this.fichaPacienteAbierta()) return;
|
||||
const target = this.document.getElementById(identityElementId(key));
|
||||
const grid = this.element.nativeElement.querySelector('.catalog-grid');
|
||||
if (!target || !grid?.contains(target)) return;
|
||||
const grid = target?.closest('.catalog-grid');
|
||||
if (!target || !grid) return;
|
||||
const reducedMotion = this.document.defaultView?.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
target.scrollIntoView({ behavior: reducedMotion ? 'instant' : 'smooth', block: 'start' });
|
||||
target.querySelector('h2')?.focus({ preventScroll: true });
|
||||
@@ -503,7 +555,9 @@ export class IndicadoresPage {
|
||||
this.catalogLoading.set(false);
|
||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
||||
this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
|
||||
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
|
||||
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item)
|
||||
: this.dominio === 'cacu' ? items.map(item => ({ ...item, titulo: CACU_FIGURAS_OPORTUNIDAD.find(figura => figura.id === item.id)?.titulo ?? item.titulo }))
|
||||
: items);
|
||||
this.filtersEdited();
|
||||
this.catalogError.set(error);
|
||||
this.availabilityRequests.next();
|
||||
|
||||
@@ -163,7 +163,7 @@ 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(
|
||||
dominio === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
['Indicadores', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']);
|
||||
expect(e.root.querySelector('#panel-analisis')).toBeNull();
|
||||
}
|
||||
e.page.changeDominio('cama'); e.harness.detectChanges();
|
||||
|
||||
@@ -12,7 +12,8 @@ import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
import { ROUTE_IDS, ROUTE_ONLY_IDS } from './screening-route';
|
||||
|
||||
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] });
|
||||
// Each measure carries the figure of its contract, as the published ones do: the Indicadores tab draws no card for an indicator without figures.
|
||||
const item = (id: string, contrato = 'C3r') => ({ id, titulo: id, contrato, figuras: [contrato === 'C2' ? 'fig_c2_donas' : 'fig_c3r_caja'], tipos_periodo: ['semestre', 'mes'] });
|
||||
|
||||
describe('Ruta del tamizaje: página de CaCu', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
|
||||
@@ -33,15 +33,14 @@ describe('Secciones compartidas por dominio', () => {
|
||||
});
|
||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||
|
||||
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
|
||||
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas e Indicadores seleccionado', async domain => {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
|
||||
const root = harness.routeNativeElement!;
|
||||
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
|
||||
// TEA and CaMa also have Histórico; the follow-up tab is named Análisis de riesgos in every domain; CaCu keeps its three tabs.
|
||||
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones']
|
||||
: domain === 'tea' ? ['Resumen', 'Histórico', 'Análisis de riesgos', 'Datos y definiciones'] : ['Resumen', 'Análisis de riesgos', 'Datos y definiciones'];
|
||||
// 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'];
|
||||
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)!;
|
||||
@@ -76,7 +75,7 @@ describe('Secciones compartidas por dominio', () => {
|
||||
http.expectNone(() => true); // No patient, metadata, catalog or figure requests on section changes.
|
||||
});
|
||||
|
||||
it('cambiar de dominio reinicia Resumen tanto por router como por coordinación de página', async () => {
|
||||
it('cambiar de dominio reinicia Indicadores tanto por router como por coordinación de página', async () => {
|
||||
const harness = await RouterTestingHarness.create();
|
||||
for (const domain of DOMINIOS) {
|
||||
const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||
|
||||
@@ -195,13 +195,12 @@ describe('Seguimiento de CaMa (tabla)', () => {
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toBe('La respuesta del servicio no tiene el formato esperado.');
|
||||
expect(root().querySelector('table')).toBeNull(); expect(root().textContent).not.toContain('M-0081');
|
||||
});
|
||||
it('un tamaño de página inválido no sale del navegador', async () => {
|
||||
it('un tamaño de página mayor al máximo se acota y no sale del navegador sin acotar', async () => {
|
||||
await cargado();
|
||||
const tam = campo('Registros por página').querySelector('input') as HTMLInputElement;
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); fixture.detectChanges();
|
||||
tam.value = '500'; tam.dispatchEvent(new Event('input')); tam.dispatchEvent(new Event('change')); fixture.detectChanges();
|
||||
boton('Consultar').click(); fixture.detectChanges();
|
||||
http.expectNone(() => true);
|
||||
expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha');
|
||||
expect(parametros(solicitud())).toMatchObject({ page_size: '200' });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar';
|
||||
import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card';
|
||||
import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
|
||||
import {
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, acotarTamano, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery,
|
||||
SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor,
|
||||
} from './seguimiento-tabla.service';
|
||||
|
||||
@@ -76,7 +76,7 @@ const mismosFiltros = (a: Record<string, string | undefined>, b: Record<string,
|
||||
@for (o of filtro.opciones; 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" /></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]="estado() === 'loading'">Consultar</button>
|
||||
</form>
|
||||
@switch (estado()) {
|
||||
@@ -163,6 +163,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
private readonly consultas = new Subject<Consulta | null>();
|
||||
readonly etiquetaVentana = etiquetaVentana;
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
readonly estado = signal<Estado>('idle');
|
||||
readonly mensaje = signal('');
|
||||
readonly data = signal<SeguimientoTablaResponse | undefined>(undefined);
|
||||
@@ -315,7 +316,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges {
|
||||
this.appliedEtiqueta = etiqueta;
|
||||
// Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one.
|
||||
const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte;
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros,
|
||||
const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: acotarTamano(this.draft.page_size), filtros,
|
||||
contexto: otroCorte ? undefined : contexto };
|
||||
// A new query of the cohort starts from nothing on screen: what was there belongs to the previous one.
|
||||
if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); }
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// Covers how the Indicadores tab arranges TEA's figures: the time figures under «Indicadores de oportunidad», the
|
||||
// clinical ones under «Indicadores clínicos», each in its order, and the tab's name in the three domains.
|
||||
// Fixtures: a TEA catalog shaped like /tea/indicadores, published out of order on purpose.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadoresMemory } from './indicadores-memory';
|
||||
import { Dominio } from './indicadores.models';
|
||||
|
||||
const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||
const TEA = [
|
||||
item('M30_resultado_eeg', 'Porcentaje de EEG normal y anormal', 'C1', ['fig_c1_barras_alteracion']),
|
||||
item('M29_calidad_eeg', 'Calidad del EEG', 'C2', ['fig_c2_barras']),
|
||||
item('M28_casos_por_estado', 'Casos por estatus', 'C2', ['fig_c2_barras']),
|
||||
item('M27_dias_ados2_diagnostico', 'Días de ADOS-2 a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
||||
item('M26_dias_mchat_ados2', 'Días de M-CHAT a ADOS-2', 'C3r', ['fig_c3r_caja']),
|
||||
item('M25_dias_mchat_diagnostico', 'Días de M-CHAT a diagnóstico positivo', 'C3r', ['fig_c3r_caja']),
|
||||
item('M24_confirmacion_diagnostico', 'Porcentaje de confirmación diagnóstica', 'C1', ['fig_c1_barras_apiladas_edad']),
|
||||
item('M23_pacientes_evaluados', 'Pacientes evaluados por resultado diagnóstico', 'C2', ['fig_c2_barras']),
|
||||
item('M22_diagnosticados_sin_eeg', 'Porcentaje de pacientes con diagnóstico de TEA sin EEG', 'C1', ['fig_c1_barras_edad']),
|
||||
item('M21_diagnosticados_con_eeg', 'Porcentaje de pacientes con diagnóstico de TEA con EEG', 'C1', ['fig_c1_barras_edad']),
|
||||
];
|
||||
|
||||
describe('Indicadores de TEA: figuras de oportunidad y clínicas', () => {
|
||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] });
|
||||
for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain);
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
// The KPI and period requests are not what these tests are about.
|
||||
afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); });
|
||||
function open(domain: Dominio, catalog: unknown[]) {
|
||||
// The page starts in TEA, whose catalog is already answered: leave it first to load it again.
|
||||
if (domain === fixture.componentInstance.dominio) {
|
||||
fixture.componentInstance.changeDominio(domain === 'cacu' ? 'cama' : 'cacu'); fixture.detectChanges();
|
||||
http.match(() => true);
|
||||
}
|
||||
fixture.componentInstance.changeDominio(domain); fixture.detectChanges();
|
||||
http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges();
|
||||
http.match(() => true); fixture.detectChanges();
|
||||
}
|
||||
const root = () => fixture.nativeElement as HTMLElement;
|
||||
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.
|
||||
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']);
|
||||
expect(root().querySelector('#kpi-section-title')?.textContent).toBe('Indicadores de oportunidad');
|
||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||
});
|
||||
|
||||
it('un indicador no publicado deja el resto en su orden', () => {
|
||||
// Fails if the order depends on every figure being published.
|
||||
open('tea', TEA.filter(entry => entry.id !== 'M27_dias_ados2_diagnostico' && entry.id !== 'M23_pacientes_evaluados'));
|
||||
expect(titles('.kpi-section')).toEqual(['Días de M-CHAT a ADOS-2', 'Días de M-CHAT a diagnóstico positivo']);
|
||||
expect(titles('.graphic-section').slice(0, 2)).toEqual(['Porcentaje de confirmación diagnóstica', 'Porcentaje de pacientes con diagnóstico de TEA con EEG']);
|
||||
});
|
||||
|
||||
it('CaMa no recibe el resumen ni el orden de TEA en oportunidad', () => {
|
||||
// Fails if TEA's summary or its figure order leaks into CaMa's opportunity strip (CaMa has its own time section).
|
||||
open('cama', [item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja'])]);
|
||||
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.
|
||||
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.id).toBe('tab-resumen');
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
(registroAgregado)="pacienteDetalle.agregarRegistro($event)" (volver)="volverASeguimiento()" />
|
||||
}
|
||||
<div [hidden]="pacienteDetalle.estado().tipo !== 'cerrado'">
|
||||
@if (dominio !== 'cama') { <h2>Seguimiento de {{ domainLabel }}</h2> }
|
||||
@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()" />
|
||||
@@ -22,8 +22,8 @@
|
||||
<label>Ventana de meses <select name="meses" [(ngModel)]="draft.meses">
|
||||
@for (m of [1,3,6,12]; track m) { <option [ngValue]="m">{{ m }} {{ m === 1 ? 'mes' : 'meses' }}</option> }
|
||||
</select></label>
|
||||
<label>{{ dominio === 'tea' ? 'Alteraciones EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">{{ dominio === 'tea' ? 'Todas' : 'Todos' }}</option>
|
||||
<label>{{ dominio === 'tea' ? 'Estatus de EEG' : 'Estatus de seguimiento' }} <select name="estatus" [(ngModel)]="draft.estatus">
|
||||
<option [ngValue]="undefined">Todos</option>
|
||||
@for (s of statuses; track s.codigo) { <option [value]="s.codigo">{{ s.etiqueta }}</option> }
|
||||
</select></label>
|
||||
@if (dominio === 'tea') {
|
||||
@@ -48,7 +48,7 @@
|
||||
@for (t of tiposAlteracion; track t.codigo) { <option [value]="t.codigo">{{ t.etiqueta }}</option> }
|
||||
</select></label>
|
||||
}
|
||||
<label>Registros por página <input name="size" type="number" min="1" max="200" required [(ngModel)]="draft.page_size" /></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 (status === 'loading') { <p role="status">Cargando seguimiento…</p> }
|
||||
@@ -82,7 +82,7 @@
|
||||
<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">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Alteraciones EEG</th></tr></thead>
|
||||
<thead><tr><th scope="col">Identificador seudónimo</th><th scope="col">Grupo de edad</th><th scope="col">Estado del caso</th><th scope="col">Último EEG</th><th scope="col">Puntaje M-CHAT</th><th scope="col">CSS ADOS-2</th><th scope="col">Estatus de EEG</th></tr></thead>
|
||||
<tbody>
|
||||
@for (item of response.items; track item.id_seudonimo) {
|
||||
<tr class="tea-row" [class.abierta]="teaAbierto === item.id_seudonimo" (click)="alternarTea(item.id_seudonimo, $event)">
|
||||
|
||||
@@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { catchError, 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 { MatButtonModule } from '@angular/material/button';
|
||||
import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle';
|
||||
@@ -25,11 +26,18 @@ import { TeaPacienteResumen } from './tea-paciente-resumen';
|
||||
export class IndicadoresTracking implements OnChanges {
|
||||
@Input({ required: true }) domainLabel = '';
|
||||
@Input() dominio: Dominio = 'tea';
|
||||
// The section's heading: TEA's follows its EEG, CaCu's names the risk models it will hold; the other domains keep the follow-up one.
|
||||
get titulo() {
|
||||
return this.dominio === 'tea' ? 'Alteraciones de EEG relacionadas al TEA'
|
||||
: this.dominio === 'cacu' ? 'Modelos de riesgo asociados a cáncer cervicouterino' : 'Seguimiento de ' + this.domainLabel;
|
||||
}
|
||||
@Input() active = false;
|
||||
/** CaMa: the patients of a curve or a cell of the analysis, for its follow-up list. */
|
||||
@Input() seleccion?: SeleccionSeguimiento;
|
||||
/** CaMa: the way back to the analysis the selection came from. */
|
||||
readonly volverAlAnalisis = output<void>();
|
||||
readonly tamanoMaximo = PAGE_SIZE_MAX;
|
||||
readonly acotar = acotarTamano;
|
||||
private readonly service = inject(CacuSeguimientoService);
|
||||
private readonly indicators = inject(IndicadoresService);
|
||||
private readonly teaService = inject(TeaSeguimientoService);
|
||||
@@ -119,11 +127,11 @@ 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 200).'; 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.status = 'loading'; this.message = ''; this.data = undefined; this.teaData = undefined; this.applied = { ...q };
|
||||
(this.dominio === 'tea' ? this.teaRequests : this.requests).next(q);
|
||||
}
|
||||
apply() { this.load({ ...this.draft, 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;
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
<div><dt>Versión del modelo</dt><dd>{{ riesgo.modelo_version }}</dd></div>
|
||||
<div><dt>Fecha índice</dt><dd>{{ riesgo.fecha_indice }}</dd></div>
|
||||
<div><dt>Desenlace</dt><dd>{{ riesgo.desenlace_texto ?? riesgo.desenlace }}</dd></div>
|
||||
<div><dt>Evaluado en (UTC)</dt><dd>{{ riesgo.evaluado_en }}</dd></div>
|
||||
<div><dt>Evaluado en</dt><dd><time [attr.datetime]="riesgo.evaluado_en">{{ instante(riesgo.evaluado_en) }}</time></dd></div>
|
||||
<div><dt>Estado del lote</dt><dd>{{ riesgo.estado_lote === 'final' ? 'Final (final)' : 'Preliminar (preliminary)' }}</dd></div>
|
||||
</dl>
|
||||
@if (riesgo.horizontes.length) {
|
||||
|
||||
@@ -4,6 +4,12 @@ import { DominioRiesgo } from './paciente-riesgo.models';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
|
||||
/** A UTC instant as the day and the minute it happened, so it reads next to the index date (a calendar day, not an instant). */
|
||||
export const instanteUtc = (iso: string) => {
|
||||
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})/.exec(iso);
|
||||
return m ? `${m[1]} ${m[2]} UTC` : iso;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-paciente-riesgo-tabla',
|
||||
imports: [DecimalPipe],
|
||||
@@ -20,6 +26,7 @@ export class PacienteRiesgoTabla {
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
readonly instante = instanteUtc;
|
||||
constructor() {
|
||||
effect(() => { this.state.dominio.set(this.dominio()); this.state.pacId.set(this.pacId()); });
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { of, Subject, throwError } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { prediccion, riesgoCacuEjemplo } from './paciente-riesgo.testing';
|
||||
import { PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
import { instanteUtc, PacienteRiesgoTabla } from './paciente-riesgo-tabla';
|
||||
|
||||
describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
function setup(provider?: PacienteRiesgoProvider) {
|
||||
@@ -50,7 +50,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect([...root.querySelectorAll('.percentage')].map(c => c.textContent!.trim())).toEqual(['8 %', '21 %', '34 %']);
|
||||
expect(root.querySelector('.interval')!.textContent).toContain('5 % – 12 %');
|
||||
expect(root.textContent).toContain('Final (final)');
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01T00:00:00Z', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
for (const value of ['modelo-cacu', '2.1.0', '2026-10-01 00:00 UTC', '2026-06-01', 'CIN2+ por biopsia']) {
|
||||
expect(root.textContent).toContain(value);
|
||||
}
|
||||
// The record no longer shows the cohort's internals (its definition, version or model variables).
|
||||
@@ -135,3 +135,10 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
expect(f.nativeElement.textContent).toContain('Recomendaciones no disponibles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('instanteUtc', () => {
|
||||
it('shows the day and the minute of a UTC instant, and leaves anything else as it came', () => {
|
||||
expect(instanteUtc('2026-11-21T23:17:45.120Z')).toBe('2026-11-21 23:17 UTC');
|
||||
expect(instanteUtc('no es una fecha')).toBe('no es una fecha');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,6 +42,13 @@ describe('Ruta del tamizaje: modelo', () => {
|
||||
expect(routeModel(all(), 'semestre', '2025-S1').period).toBe('2025-S1');
|
||||
expect(routeModel(all(), 'semestre', '2024-S1').period).toBe('2025-S2');
|
||||
});
|
||||
it('sin periodo pedido, el más reciente vacío no se elige: se usa el más reciente con cajas publicadas', () => {
|
||||
// Fails if the chart opens on a semester that has just begun and shows nothing while an earlier one has data.
|
||||
const vacio = (id: string) => payload(id, [row('2025-S2', S2[id]), row('2026-S1', [0, null as never, null as never, null as never], { suprimido: 1 })], ['2025-S2', '2026-S1']);
|
||||
const data = Object.fromEntries(ROUTE_IDS.map(id => [id, vacio(id)]));
|
||||
expect(routeModel(data, 'semestre').period).toBe('2025-S2');
|
||||
expect(routeModel(data, 'semestre', '2026-S1').period).toBe('2026-S1');
|
||||
});
|
||||
it('un paso suprimido o sin datos no se dibuja y la cadena sigue desde el último publicado', () => {
|
||||
// Pins down: nothing is drawn as zero and the next step starts at the last published end. Fails if a suppressed box
|
||||
// becomes a bar or leaves a gap in the chain.
|
||||
|
||||
@@ -66,7 +66,9 @@ export function routeModel(data: Record<string, IndicadorDatos>, tipo: TipoPerio
|
||||
}
|
||||
}
|
||||
const periods = [...new Set(ROUTE_IDS.flatMap(id => data[id].periodos))].sort().reverse();
|
||||
const period = requested && periods.includes(requested) ? requested : periods[0];
|
||||
// Without a valid request the newest period that has a published box: a semester that has just begun is empty.
|
||||
const hasData = (p: string) => ROUTE_IDS.some(id => boxes[id][p]?.estado === 'Publicado');
|
||||
const period = requested && periods.includes(requested) ? requested : periods.find(hasData) ?? periods[0];
|
||||
let cursor = 0;
|
||||
const rows = ROUTE_STEPS.map((step): RouteRow => {
|
||||
const fromSample = period ? boxes[step.sinceSample][period] ?? NOT_AVAILABLE : NOT_AVAILABLE;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
||||
import fixtureData from './fixtures/cama_seguimiento.json';
|
||||
import finalResponse from './fixtures/cama_seguimiento-final.json';
|
||||
import outsideResponse from './fixtures/cama_seguimiento-out-of-range.json';
|
||||
import { PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
|
||||
import { acotarTamano, PAGE_SIZE_MAX, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse, validQuery } from './seguimiento-tabla.service';
|
||||
|
||||
const clonar = () => structuredClone(fixtureData) as unknown as Record<string, any>;
|
||||
const consulta: SeguimientoTablaQuery = { meses: 3, page: 1, page_size: 50 };
|
||||
@@ -132,3 +132,16 @@ describe('Seguimiento genérico: petición', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('acotarTamano', () => {
|
||||
it('brings a typed page size into 1 to the maximum, and falls back when it is not a number', () => {
|
||||
expect(acotarTamano(500)).toBe(PAGE_SIZE_MAX);
|
||||
expect(acotarTamano('999')).toBe(PAGE_SIZE_MAX);
|
||||
expect(acotarTamano(0)).toBe(1);
|
||||
expect(acotarTamano(-7)).toBe(1);
|
||||
expect(acotarTamano(25.9)).toBe(25);
|
||||
expect(acotarTamano('')).toBe(1);
|
||||
expect(acotarTamano('x')).toBe(50);
|
||||
expect(acotarTamano(undefined, 20)).toBe(20);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,6 +44,11 @@ export type MesesVentana = typeof MESES_VENTANA[number];
|
||||
/** What the window is called on screen and in the files: the whole cohort or a number of months. */
|
||||
export const etiquetaVentana = (meses: number) => meses === 0 ? 'Toda la cohorte' : `${meses} ${meses === 1 ? 'mes' : 'meses'}`;
|
||||
export const PAGE_SIZE_MAX = 200;
|
||||
/** A page size typed in a form, brought into 1..PAGE_SIZE_MAX: an input's `max` only flags the field, it does not stop a larger number. */
|
||||
export const acotarTamano = (valor: unknown, defecto = 50) => {
|
||||
const n = Math.trunc(Number(valor));
|
||||
return Number.isFinite(n) ? Math.min(PAGE_SIZE_MAX, Math.max(1, n)) : defecto;
|
||||
};
|
||||
const RESERVADAS = ['meses', 'page', 'page_size', 'corte', ...CLAVES_CONTEXTO];
|
||||
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
// Covers TEA's opportunity summary for one period: the sentences read their figures from the KPI panels and name
|
||||
// the population of each. Fixtures: fake panels holding the result each real panel would publish.
|
||||
import { signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { TeaResumenPeriodo } from './tea-resumen-periodo';
|
||||
|
||||
type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record<string, number> };
|
||||
type Result = { state: string; value?: string | number; loading?: boolean; period?: string; categorias?: Record<string, number>; numerador?: number; denominador?: number };
|
||||
function panel(id: string, result: Result) {
|
||||
return { definition: { id }, result: signal(result), retry: vi.fn() } as unknown as IndicadorKpiPanel & { result: ReturnType<typeof signal<Result>>; retry: ReturnType<typeof vi.fn> };
|
||||
}
|
||||
const listo = (value: string | number, period = '2025-S2'): Result => ({ state: 'Disponible', value, period });
|
||||
const c1 = (value: string, numerador: number, denominador: number): Result => ({ ...listo(value), numerador, denominador });
|
||||
|
||||
describe('Resumen TEA por periodo', () => {
|
||||
function render(paneles: IndicadorKpiPanel[]) {
|
||||
@@ -16,33 +19,77 @@ describe('Resumen TEA por periodo', () => {
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
const completos = () => [panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }), panel('M24_confirmacion_diagnostico', listo('86.5')),
|
||||
panel('M25_dias_mchat_diagnostico', listo(22)), panel('M21_diagnosticados_con_eeg', listo('71.9')), panel('M22_diagnosticados_sin_eeg', listo('28.1')),
|
||||
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14))];
|
||||
// 100 children in the screening, 60 of them at the EEG stage. 57 have a confirmed diagnosis, 41 with a good EEG.
|
||||
// 80 EEGs were done in the period: 20 good, 50 invalid, 10 not analysed yet.
|
||||
const completos = () => [
|
||||
panel('M28_casos_por_estado', { ...listo(100), categorias: { EEG: 60, SOLO_MCHAT: 15, PSICOLOGIA: 15, NEUROPEDIATRIA: 10 } }),
|
||||
panel('M24_confirmacion_diagnostico', c1('86.5', 57, 66)), panel('M25_dias_mchat_diagnostico', listo(22.5)),
|
||||
panel('M21_diagnosticados_con_eeg', c1('71.9', 41, 57)), panel('M22_diagnosticados_sin_eeg', c1('28.1', 16, 57)),
|
||||
panel('M26_dias_mchat_ados2', listo(8)), panel('M27_dias_ados2_diagnostico', listo(14)),
|
||||
panel('M29_calidad_eeg', { ...listo(80), categorias: { BUENO: 20, MALO: 50, SIN_ANALIZAR: 10 } })];
|
||||
const texto = (root: HTMLElement) => root.textContent!.replace(/\s+/g, ' ');
|
||||
|
||||
it('redacta el párrafo con cada población y resalta los valores', () => {
|
||||
it('redacta los dos párrafos con cada población y resalta los valores', () => {
|
||||
// Fails if a sentence reads another indicator's figure, if the stages stop adding up to the children evaluated
|
||||
// or if a median is cut (22.5 stays 22.5).
|
||||
const root: HTMLElement = render(completos()).nativeElement;
|
||||
const text = root.textContent!.replace(/\s+/g, ' ');
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, de los 100 niños en el tamizaje, 60 lo completaron con un EEG de buena calidad y 40 siguen en proceso: 15 solo con M-CHAT, 15 hasta la evaluación psicológica y 10 hasta la evaluación neuropediátrica.');
|
||||
expect(text).toContain('De los niños con diagnóstico confirmado o en proceso, 86.5 % tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('La mediana de M-CHAT a ADOS-2 fue de 8 días, de ADOS-2 a diagnóstico, de 14 días, y en total, de M-CHAT a diagnóstico, de 22 días.');
|
||||
expect(text).toContain('De los niños con diagnóstico confirmado, 71.9 % tienen un EEG de buena calidad y 28.1 % todavía no.');
|
||||
const text = texto(root);
|
||||
expect(text).toContain('Al cierre del periodo 2025-S2, se evaluaron 100 niños entre 16 y 36 meses; 15 únicamente tienen M-CHAT, 15 hasta la evaluación psicológica y 70 presentan evaluación neuropediátrica.');
|
||||
expect(text).toContain('En este periodo el 86.5% de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).');
|
||||
expect(text).toContain('Las ventanas de tiempo* de tamizaje son: 8 días de M-CHAT (psicología) a ADOS-2, 14 días de ADOS-2 a diagnóstico. El tiempo* de tamizaje completo de M-CHAT a diagnóstico fue de 22.5 días.');
|
||||
expect(text).toContain('De los 57 niños con diagnóstico confirmado al cierre del periodo, 41 tienen un EEG de buena calidad y 16 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
expect(text).toContain('*tomando la mediana de los tiempos');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim()))
|
||||
.toEqual(['2025-S2', '100', '60', '40', '15', '15', '10', '86.5 %', '8 días', '14 días', '22 días', '71.9 %', '28.1 %']);
|
||||
.toEqual(['2025-S2', '100', '15', '15', '70', '86.5%', '8 días', '14 días', '22.5 días', '57', '41', '16', '25.0%']);
|
||||
expect(root.querySelector('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('no copia cifras de ejemplo: otros conteos cambian toda la redacción', () => {
|
||||
// Fails if any figure of the sentences is a constant instead of the contract's value.
|
||||
const paneles = [
|
||||
panel('M28_casos_por_estado', { ...listo(3), categorias: { EEG: 0, SOLO_MCHAT: 1, PSICOLOGIA: 1, NEUROPEDIATRIA: 1 } }),
|
||||
panel('M24_confirmacion_diagnostico', c1('50.0', 1, 2)), panel('M25_dias_mchat_diagnostico', listo(31)),
|
||||
panel('M21_diagnosticados_con_eeg', c1('0.0', 0, 1)), panel('M22_diagnosticados_sin_eeg', c1('100.0', 1, 1)),
|
||||
panel('M26_dias_mchat_ados2', listo(5)), panel('M27_dias_ados2_diagnostico', listo(9)),
|
||||
panel('M29_calidad_eeg', { ...listo(4), categorias: { BUENO: 1, MALO: 1, SIN_ANALIZAR: 2 } })];
|
||||
const text = texto(render(paneles).nativeElement);
|
||||
expect(text).toContain('se evaluaron 3 niños entre 16 y 36 meses; 1 únicamente tienen M-CHAT, 1 hasta la evaluación psicológica y 1 presentan');
|
||||
expect(text).toContain('De los 1 niños con diagnóstico confirmado al cierre del periodo, 0 tienen un EEG de buena calidad y 1 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, 25.0% tienen buena calidad.');
|
||||
for (const ejemplo of ['47', '155.5', '18.6', '54 días', '97 días', '##']) expect(text).not.toContain(ejemplo);
|
||||
});
|
||||
|
||||
it('un cero publicado es un cero y la ausencia de estudios no inventa un porcentaje', () => {
|
||||
// Fails if a published 0 turns into «sin dato», or if 0 studies print a percentage of buena calidad.
|
||||
const paneles = completos();
|
||||
paneles[3].result.set(c1('0.0', 0, 57)); paneles[4].result.set(c1('100.0', 57, 57));
|
||||
paneles[7].result.set({ ...listo(0), categorias: { BUENO: 0, MALO: 0, SIN_ANALIZAR: 0 } });
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(texto(root)).toContain('0 tienen un EEG de buena calidad y 57 aún no cuentan con uno de esa calidad. Del total de estudios de EEG del periodo, sin dato (Sin estudios de EEG en el periodo) tienen buena calidad.');
|
||||
expect(Array.from(root.querySelectorAll('.dato.listo')).map(e => e.textContent!.trim())).toContain('0');
|
||||
});
|
||||
|
||||
it('muestra «sin dato» si falta, está oculto, es de otro periodo o no está publicado', () => {
|
||||
// Fails if a suppressed, foreign-period or unpublished figure is drawn as a number, or if its reason is lost.
|
||||
const paneles = completos();
|
||||
paneles[1].result.set({ state: 'Dato oculto por tamaño' });
|
||||
paneles[2].result.set(listo(30, '2025-S1'));
|
||||
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M22_diagnosticados_sin_eeg')).nativeElement;
|
||||
const root: HTMLElement = render(paneles.filter(p => p.definition.id !== 'M29_calidad_eeg')).nativeElement;
|
||||
const sinDato = Array.from(root.querySelectorAll('.dato.sin-dato'));
|
||||
expect(sinDato.map(e => e.getAttribute('title'))).toEqual(['Dato oculto por tamaño', 'Disponible', 'Indicador no publicado']);
|
||||
expect(root.textContent).not.toContain('30 días');
|
||||
});
|
||||
|
||||
it('no muestra los conteos de M21 y M22 si no hablan de los mismos niños', () => {
|
||||
// Fails if the confirmed children of M21 and of M22 disagree and the summary still prints them as one population.
|
||||
const paneles = completos();
|
||||
paneles[4].result.set(c1('28.1', 16, 58));
|
||||
const root: HTMLElement = render(paneles).nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('.dato.sin-dato')).map(e => e.getAttribute('title')))
|
||||
.toEqual(Array(3).fill('Las poblaciones de M21 y M22 no coinciden'));
|
||||
});
|
||||
|
||||
it('indica la carga y reintenta solo las consultas con error', () => {
|
||||
// Fails if the summary hides a pending query or retries panels that did not fail.
|
||||
const paneles = completos();
|
||||
paneles[0].result.set({ state: 'Cargando…', loading: true });
|
||||
paneles[3].result.set({ state: 'Error de consulta' });
|
||||
|
||||
@@ -2,32 +2,40 @@ import { NgTemplateOutlet } from '@angular/common';
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||
import { shareNumber } from './indicadores-format';
|
||||
import { M28_COMPLETO, M29_BUENO } from './indicadores-kpi';
|
||||
|
||||
interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; detalle?: string; }
|
||||
|
||||
const M21 = 'M21_diagnosticados_con_eeg', M22 = 'M22_diagnosticados_sin_eeg', M28 = 'M28_casos_por_estado', M29 = 'M29_calidad_eeg';
|
||||
|
||||
// TEA summary for one explicit period. It reads the results of the (hidden) KPI panels, so the
|
||||
// requests, contract checks and suppression rules stay those of the cards. Each sentence names
|
||||
// its own population: M28, M24, M25 and M21/M22 do not count the same patients.
|
||||
// its own population: M28, M24, M21/M22 and M29 do not count the same patients or exams.
|
||||
@Component({
|
||||
selector: 'app-tea-resumen-periodo',
|
||||
imports: [MatButtonModule, NgTemplateOutlet],
|
||||
template: `
|
||||
<article class="resumen" [attr.aria-busy]="cargando">
|
||||
<p>
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, de los <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños en el tamizaje,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(completo) }" /> lo completaron con un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(enProceso) }" /> siguen en proceso:
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> solo con M-CHAT,
|
||||
Al cierre del periodo <span class="dato listo">{{ periodo }}</span>, se evaluaron <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M28_casos_por_estado', '') }" /> niños entre 16 y 36 meses;
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['SOLO_MCHAT']) }" /> únicamente tienen M-CHAT,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['PSICOLOGIA']) }" /> hasta la evaluación psicológica y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(['NEUROPEDIATRIA']) }" /> hasta la evaluación neuropediátrica.
|
||||
De los niños con diagnóstico confirmado o en proceso, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', ' %') }" />
|
||||
tiene diagnóstico confirmado de TEA (CIE-10 F84.0). La mediana de M-CHAT a ADOS-2 fue de <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" />, de ADOS-2 a diagnóstico, de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" />, y en total, de M-CHAT a diagnóstico, de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: caso(conNeuropediatria) }" /> presentan evaluación neuropediátrica.
|
||||
En este periodo el <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M24_confirmacion_diagnostico', '%') }" />
|
||||
de los pacientes tiene diagnóstico confirmado de TEA (CIE-10 F84.0).
|
||||
Las ventanas de tiempo<sup>*</sup> de tamizaje son: <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M26_dias_mchat_ados2', ' días') }" /> de M-CHAT (psicología) a ADOS-2,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M27_dias_ados2_diagnostico', ' días') }" /> de ADOS-2 a diagnóstico.
|
||||
El tiempo<sup>*</sup> de tamizaje completo de M-CHAT a diagnóstico fue de
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M25_dias_mchat_diagnostico', ' días') }" />.
|
||||
De los niños con diagnóstico confirmado, <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M21_diagnosticados_con_eeg', ' %') }" />
|
||||
tienen un EEG de buena calidad y <ng-container *ngTemplateOutlet="dato; context: { $implicit: valor('M22_diagnosticados_sin_eeg', ' %') }" /> todavía no.
|
||||
<br>
|
||||
De los <ng-container *ngTemplateOutlet="dato; context: { $implicit: confirmados() }" /> niños con diagnóstico confirmado al cierre del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: conEeg() }" /> tienen un EEG de buena calidad y
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: sinEeg() }" /> aún no cuentan con uno de esa calidad.
|
||||
Del total de estudios de EEG del periodo,
|
||||
<ng-container *ngTemplateOutlet="dato; context: { $implicit: buenaCalidad() }" /> tienen buena calidad.
|
||||
</p>
|
||||
<p class="nota">*tomando la mediana de los tiempos</p>
|
||||
@if (conError.length) {
|
||||
<button type="button" mat-stroked-button (click)="reintentar()">Reintentar consulta</button>
|
||||
}
|
||||
@@ -41,6 +49,8 @@ interface Valor { texto: string; estado: 'listo' | 'cargando' | 'sin_dato'; deta
|
||||
.resumen { box-sizing: border-box; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||
p { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 2.1; overflow-wrap: anywhere; }
|
||||
p + p { margin-top: var(--issste-space-4); }
|
||||
p.nota { margin-top: var(--issste-space-2); font-size: .95rem; line-height: 1.5; color: var(--issste-text-secondary); }
|
||||
.dato { display: inline-block; padding: 0 .5em; border-radius: var(--issste-radius); line-height: 1.6; font-weight: 700; white-space: nowrap;
|
||||
background: var(--issste-background); border: 1px dashed var(--issste-border); color: var(--issste-text-secondary); }
|
||||
.dato.listo { background: color-mix(in srgb, var(--issste-accent) 22%, var(--issste-surface)); border: 1px solid var(--issste-accent); color: var(--issste-text); }
|
||||
@@ -54,26 +64,55 @@ export class TeaResumenPeriodo {
|
||||
@Input({ required: true }) paneles: readonly IndicadorKpiPanel[] = [];
|
||||
// Panels render after this paragraph, so on their first pass their inputs are not set yet.
|
||||
private panel(id: string) { return this.paneles.find(p => p.definition?.id === id); }
|
||||
valor(id: string, sufijo: string): Valor {
|
||||
// Why a panel has no figure for this period, or undefined when it has one.
|
||||
private fallo(id: string): Valor | undefined {
|
||||
const result = this.panel(id)?.result();
|
||||
if (!result) return { texto: 'sin dato', estado: 'sin_dato', detalle: 'Indicador no publicado' };
|
||||
if (result.loading) return { texto: '…', estado: 'cargando', detalle: 'Cargando' };
|
||||
// Never show a value from another period in a sentence about this one.
|
||||
if (result.state !== 'Disponible' || result.value === undefined || result.period !== this.periodo)
|
||||
return { texto: 'sin dato', estado: 'sin_dato', detalle: result.state };
|
||||
return { texto: result.value + sufijo, estado: 'listo' };
|
||||
return undefined;
|
||||
}
|
||||
private sinDato(detalle: string): Valor { return { texto: 'sin dato', estado: 'sin_dato', detalle }; }
|
||||
valor(id: string, sufijo: string): Valor {
|
||||
return this.fallo(id) ?? { texto: this.panel(id)!.result().value + sufijo, estado: 'listo' };
|
||||
}
|
||||
readonly completo = [M28_COMPLETO];
|
||||
readonly enProceso = M28_EN_PROCESO;
|
||||
// The children of M28 in some stages, under the same rules as valor().
|
||||
readonly conNeuropediatria = ['NEUROPEDIATRIA', M28_COMPLETO];
|
||||
caso(categorias: readonly string[]): Valor {
|
||||
const base = this.valor('M28_casos_por_estado', '');
|
||||
const base = this.valor(M28, '');
|
||||
if (base.estado !== 'listo') return base;
|
||||
const counts = this.panel('M28_casos_por_estado')?.result().categorias;
|
||||
const counts = this.panel(M28)?.result().categorias;
|
||||
const n = categorias.map(c => counts?.[c]);
|
||||
return n.some(v => v === undefined) ? { texto: 'sin dato', estado: 'sin_dato', detalle: 'Etapa no publicada' }
|
||||
return n.some(v => v === undefined) ? this.sinDato('Etapa no publicada')
|
||||
: { texto: String(n.reduce((s, v) => s! + v!, 0)), estado: 'listo' };
|
||||
}
|
||||
// M21 and M22 split the same confirmed children, so a count of either is only shown while their denominators agree.
|
||||
private poblacionComun(): boolean {
|
||||
const a = this.panel(M21)?.result(), b = this.panel(M22)?.result();
|
||||
return !(a?.denominador !== undefined && b?.denominador !== undefined && a.denominador !== b.denominador);
|
||||
}
|
||||
private conteo(id: string, parte: 'numerador' | 'denominador'): Valor {
|
||||
const fallo = this.fallo(id);
|
||||
if (fallo) return fallo;
|
||||
if (!this.poblacionComun()) return this.sinDato('Las poblaciones de M21 y M22 no coinciden');
|
||||
const n = this.panel(id)!.result()[parte];
|
||||
return n === undefined ? this.sinDato('Conteo no publicado') : { texto: String(n), estado: 'listo' };
|
||||
}
|
||||
// Children with a confirmed diagnosis at the period's end, the denominator of M21 and M22.
|
||||
confirmados() { return this.conteo(M21, 'denominador'); }
|
||||
// Of them, those with a good EEG (M21's numerator) and those without yet (M22's).
|
||||
conEeg() { return this.conteo(M21, 'numerador'); }
|
||||
sinEeg() { return this.conteo(M22, 'numerador'); }
|
||||
// The share of the period's EEGs (M29 counts exams, not patients) the analysis found valid.
|
||||
buenaCalidad(): Valor {
|
||||
const base = this.valor(M29, '');
|
||||
if (base.estado !== 'listo') return base;
|
||||
const result = this.panel(M29)!.result(), total = Number(result.value), buenos = result.categorias?.[M29_BUENO];
|
||||
if (total === 0) return this.sinDato('Sin estudios de EEG en el periodo');
|
||||
return buenos === undefined ? this.sinDato('Categoría no publicada') : { texto: shareNumber(buenos, total) + '%', estado: 'listo' };
|
||||
}
|
||||
get cargando() { return this.paneles.some(p => p.result().loading); }
|
||||
get conError() { return this.paneles.filter(p => p.result().state === 'Error de consulta'); }
|
||||
reintentar() { this.conError.forEach(p => p.retry()); }
|
||||
|
||||
@@ -62,7 +62,7 @@ describe('Seguimiento TEA', () => {
|
||||
request().flush(data); fixture.detectChanges();
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(Array.from(root.querySelectorAll('thead th')).map(th => th.textContent)).toEqual(
|
||||
['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Alteraciones EEG']);
|
||||
['Identificador seudónimo', 'Grupo de edad', 'Estado del caso', 'Último EEG', 'Puntaje M-CHAT', 'CSS ADOS-2', 'Estatus de EEG']);
|
||||
const rows = root.querySelectorAll('tbody tr');
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].textContent).toContain('Anormal');
|
||||
@@ -70,7 +70,7 @@ describe('Seguimiento TEA', () => {
|
||||
expect(root.textContent).toContain('Página 1 de 1, 2 registros');
|
||||
http.verify();
|
||||
});
|
||||
it('usa los filtros de CaCu con Alteraciones EEG en lugar del estatus', () => {
|
||||
it('usa los filtros de CaCu con Estatus de EEG en lugar del estatus, bajo el título de las alteraciones de EEG', () => {
|
||||
const fixture = open();
|
||||
const first = request();
|
||||
expect(first.request.params.get('meses')).toBe('3');
|
||||
@@ -79,8 +79,10 @@ describe('Seguimiento TEA', () => {
|
||||
const root: HTMLElement = fixture.nativeElement;
|
||||
expect(root.querySelector('input[type=date]')).not.toBeNull();
|
||||
const select = root.querySelector<HTMLSelectElement>('select[name=estatus]')!;
|
||||
expect(select.closest('label')?.textContent).toContain('Alteraciones EEG');
|
||||
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todas', 'Normal', 'Anormal', 'Sin EEG válido']);
|
||||
// Fails if the section goes back to the «Seguimiento de …» heading or the filter to «Alteraciones EEG».
|
||||
expect(root.querySelector('h2')?.textContent).toBe('Alteraciones de EEG relacionadas al TEA');
|
||||
expect(select.closest('label')?.textContent).toContain('Estatus de EEG');
|
||||
expect(Array.from(select.options).map(o => o.textContent?.trim())).toEqual(['Todos', 'Normal', 'Anormal', 'Sin EEG válido']);
|
||||
fixture.componentInstance.draft = { ...fixture.componentInstance.draft, estatus: 'anormal', corte: '2026-08-31', meses: 6, page_size: 20 };
|
||||
fixture.componentInstance.apply();
|
||||
const filtered = request();
|
||||
|
||||
Reference in New Issue
Block a user