feat(indicadores): CaMa's four opportunity cards, pending where the catalog lacks the indicator
Cards: patients with BI-RADS 4, 5 and 6, histopathological detection rate, screening to result and result to diagnosis times. The detection rate and the result-to-diagnosis time are not published by the catalog yet, so they are drawn as explicit pending cards and are queried once the catalog lists them. cama_eu38a is added to the CaMa KPIs.
This commit is contained in:
@@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';
|
||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||
}
|
||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
||||
<p class="kpi-state" role="status">{{ state }}</p>
|
||||
@if (!(quietWhenAvailable && state === 'Disponible')) { <p class="kpi-state" role="status">{{ state }}</p> }
|
||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
||||
</mat-card>
|
||||
`,
|
||||
@@ -28,6 +28,9 @@ import { MatCardModule } from '@angular/material/card';
|
||||
.kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
|
||||
.value { font: var(--mat-sys-headline-medium); }
|
||||
.value span { margin-inline-start: .3em; }
|
||||
// CaMa's cards are as tall as their grid row.
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiCard {
|
||||
@@ -38,6 +41,8 @@ export class IndicadorKpiCard {
|
||||
@Input() loading = false;
|
||||
@Input() notes: string[] = [];
|
||||
@Input() state = 'Pendiente de definición';
|
||||
// A card that shows its value needs no "Disponible" line.
|
||||
@Input() quietWhenAvailable = false;
|
||||
@Input() additionalInfo?: string;
|
||||
get informationLine(): string | undefined {
|
||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||
|
||||
@@ -172,13 +172,14 @@ describe('KPI integración con autoridad global', () => {
|
||||
for (const domain of ['cacu', 'cama'] as const) {
|
||||
load(domain);
|
||||
const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length);
|
||||
req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] }));
|
||||
// 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')];
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']);
|
||||
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', 'Disponible', 'Disponible']);
|
||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 6);
|
||||
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined, '40.0', '7']);
|
||||
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined, '%', 'días (mediana)']);
|
||||
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'] : [undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]);
|
||||
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining('2025-S1'),
|
||||
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,11 +19,15 @@ 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 === 'cacu' ? [] : result().notes ?? []" />
|
||||
[loading]="result().loading ?? false" [notes]="dominio === 'cacu' ? [] : result().notes ?? []" [quietWhenAvailable]="dominio === 'cama'" />
|
||||
@if (result().state === 'Error de consulta') {
|
||||
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
|
||||
}`,
|
||||
styles: ':host { display: block; min-width: 0; }',
|
||||
styles: `
|
||||
:host { display: block; min-width: 0; }
|
||||
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
|
||||
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
|
||||
`,
|
||||
})
|
||||
export class IndicadorKpiPanel implements OnChanges {
|
||||
@Input({ required: true }) dominio!: Dominio;
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
// Covers CaMa's four opportunity cards: their definitions, how each indicator's response becomes a card,
|
||||
// which cards are pending while the catalog lacks their indicator, and the page drawing them.
|
||||
// Fixtures are synthetic rows shaped like the /cama/indicadores/<id>/datos contract; no card reads a bundled value.
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { IndicadoresPage } from './indicadores-page';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import {
|
||||
CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI,
|
||||
KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult,
|
||||
} from './indicadores-kpi';
|
||||
import { GlobalApplied, IndicadoresMemory } from './indicadores-memory';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
|
||||
const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 };
|
||||
const row = { periodo: '2025-S1', estrato: null, suprimido: 0 };
|
||||
const datos = (definition: KpiDefinition, filas: Record<string, unknown>[]): IndicadorDatos => ({
|
||||
id: definition.id, contrato: definition.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas });
|
||||
const c1 = (fields: Record<string, unknown>) => datos(CAMA_TASA_DETECCION_KPI, [{ ...row, grupo: 'total', ...fields }]);
|
||||
const c3r = (definition: KpiDefinition, fields: Record<string, unknown>) => datos(definition, [{ ...row, grupo: 'TOTAL', unidad: 'dias', ...fields }]);
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
||||
it('son cuatro, en este orden, y la primera sigue siendo el ancla del periodo inicial', () => {
|
||||
// Fails if a card is dropped or reordered, or if the anchor (KPI_BY_DOMAIN.cama[0]) stops leading.
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => [d.id, d.contrato, d.unit])).toEqual([
|
||||
['cama_birads_456_paciente', 'C2', 'pacientes'],
|
||||
['cama_tasa_deteccion_histopatologica', 'C1', '%'],
|
||||
['cama_eu38a', 'C3r', 'días (mediana)'],
|
||||
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
||||
]);
|
||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado a diagnóstico']);
|
||||
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
||||
});
|
||||
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
||||
// Fails if an indicator the catalog does not publish is queried by default.
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual([
|
||||
'cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']);
|
||||
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI);
|
||||
expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI);
|
||||
});
|
||||
});
|
||||
|
||||
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 resultado maligno.' });
|
||||
});
|
||||
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);
|
||||
expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0');
|
||||
});
|
||||
it.each([
|
||||
['valor nulo', { valor: null, numerador: 0, denominador: 8 }],
|
||||
['denominador nulo', { valor: 0, numerador: 0, denominador: null }],
|
||||
['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }],
|
||||
])('la tasa con %s no se convierte en cero', (_name, fields) => {
|
||||
// Fails if a missing or incoherent rate is drawn as a value.
|
||||
const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied);
|
||||
expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible');
|
||||
});
|
||||
it('un dato suprimido por tamaño oculta la cifra en las cuatro tarjetas', () => {
|
||||
// Fails if a suppressed row leaks a number.
|
||||
const cases: [KpiDefinition, IndicadorDatos][] = [
|
||||
[CAMA_OPORTUNIDAD_KPIS[0], datos(CAMA_OPORTUNIDAD_KPIS[0], [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 3, suprimido: 1 }])],
|
||||
[CAMA_TASA_DETECCION_KPI, c1({ valor: 10, numerador: 1, denominador: 10, suprimido: 1 })],
|
||||
[CAMA_TAMIZAJE_RESULTADO_KPI, c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
||||
[CAMA_RESULTADO_DIAGNOSTICO_KPI, c3r(CAMA_RESULTADO_DIAGNOSTICO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })],
|
||||
];
|
||||
for (const [definition, data] of cases) {
|
||||
const result = kpiResult(data, definition, 'cama', applied);
|
||||
expect(result.state).toBe('Dato oculto por tamaño'); expect(result.value).toBeUndefined();
|
||||
}
|
||||
});
|
||||
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana y cuartiles tal como los publica el C3r', definition => {
|
||||
const result = kpiResult(c3r(definition, { mediana: 6.5, n: 40, q1: 3, q3: 11 }), definition, 'cama', applied);
|
||||
expect(result).toEqual({ state: 'Disponible', value: 6.5, info: '40 mastografías; Q1 a Q3: 3 a 11 días.' });
|
||||
});
|
||||
it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana de cero días con observaciones es un valor; sin observaciones no hay valor', definition => {
|
||||
// Fails if a median over zero observations is drawn as "0 días", or a true same-day median is dropped.
|
||||
expect(kpiResult(c3r(definition, { mediana: 0, n: 5, q1: 0, q3: 2 }), definition, 'cama', applied).value).toBe(0);
|
||||
const empty = kpiResult(c3r(definition, { mediana: 0, n: 0, q1: 0, q3: 0 }), definition, 'cama', applied);
|
||||
expect(empty.value).toBeUndefined(); expect(empty.state).toBe('Sin valor disponible');
|
||||
});
|
||||
it('los cuartiles inconsistentes o la unidad ajena no producen cifra', () => {
|
||||
const bad = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 9, n: 5, q1: 3, q3: 6 }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
||||
const unit = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 2, n: 5, q1: 1, q3: 3, unidad: 'horas' }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied);
|
||||
expect(bad.value).toBeUndefined(); expect(unit.value).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa: cuáles se dibujan', () => {
|
||||
const only = (...ids: string[]) => (id: string) => ids.includes(id);
|
||||
it('sin ningún indicador publicado no hay tarjetas, ni siquiera pendientes', () => {
|
||||
// Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed.
|
||||
expect(camaKpiCards(only())).toEqual([]);
|
||||
expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico')).filter(c => !c.pending).length).toBe(2);
|
||||
expect(camaKpiCards(only('cama_tasa_deteccion_histopatologica')).filter(c => !c.pending).length).toBe(1);
|
||||
});
|
||||
it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y las existentes de DEV siguen después', () => {
|
||||
const cards = camaKpiCards(only('cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a'));
|
||||
expect(cards.map(c => [c.definition.id, c.pending])).toEqual([
|
||||
['cama_birads_456_paciente', false], ['cama_tasa_deteccion_histopatologica', true],
|
||||
['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true],
|
||||
['cama_confirmacion_birads45', false], ['cama_dias_toma_diagnostico', false]]);
|
||||
});
|
||||
it('una tarjeta pendiente pasa a viva cuando el catálogo publica su indicador, sin tocar código', () => {
|
||||
const cards = camaKpiCards(only(...CAMA_OPORTUNIDAD_KPIS.map(d => d.id)));
|
||||
expect(cards.map(c => c.pending)).toEqual([false, false, false, false]);
|
||||
});
|
||||
it('un indicador de las tarjetas que el catálogo retira no deja una tarjeta consultable', () => {
|
||||
expect(camaKpiCards(only('cama_birads_456_paciente')).map(c => c.pending)).toEqual([false, true, true, true]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
||||
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()] });
|
||||
// The initial-period search has its own suites; these tests begin once it has finished.
|
||||
TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama');
|
||||
fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController);
|
||||
http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); });
|
||||
const catalog = (definitions: KpiDefinition[]) => definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }));
|
||||
const dataFor = (definition: KpiDefinition): IndicadorDatos => {
|
||||
if (definition.contrato === 'C2') return datos(definition, [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }]);
|
||||
if (definition.contrato === 'C1') return datos(definition, [{ ...row, grupo: 'total', valor: 40, numerador: 2, denominador: 5 }]);
|
||||
return c3r(definition, { mediana: 7, n: 5, q1: 3, q3: 9 });
|
||||
};
|
||||
// The period inventory runs four requests at a time: answer it in waves.
|
||||
function inventory() {
|
||||
for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) {
|
||||
wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] }));
|
||||
}
|
||||
fixture.detectChanges();
|
||||
}
|
||||
type Served = { listed?: ReturnType<typeof catalog>; answer?: (r: TestRequest, definition: KpiDefinition) => void };
|
||||
function load(definitions: KpiDefinition[], served: Served = {}) {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush(served.listed ?? catalog(definitions));
|
||||
inventory();
|
||||
// Data requests also go out in waves of four.
|
||||
const requested: string[] = [];
|
||||
for (let wave = http.match(r => r.url.endsWith('/datos')); wave.length; wave = http.match(r => r.url.endsWith('/datos'))) {
|
||||
wave.forEach(r => {
|
||||
requested.push(r.request.url);
|
||||
const definition = definitions.find(d => r.request.url.endsWith('/' + d.id + '/datos'))!;
|
||||
if (served.answer) served.answer(r, definition); else r.flush(dataFor(definition));
|
||||
});
|
||||
fixture.detectChanges();
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.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 ninguna consulta a indicadores sin publicar', () => {
|
||||
// Fails if a pending indicator is requested, or if a pending card is drawn with a number.
|
||||
const urls = load(KPI_BY_DOMAIN.cama);
|
||||
expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica') || url.includes('cama_dias_resultado_diagnostico'))).toBe(false);
|
||||
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
||||
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de tamizaje a resultado',
|
||||
'Tiempo de resultado a diagnóstico', 'Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico']);
|
||||
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, '40.0%', '7días (mediana)']);
|
||||
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]);
|
||||
expect(cards()[1].textContent).toContain('aún no está publicado');
|
||||
expect(cards()[1].textContent).not.toMatch(/\d/);
|
||||
});
|
||||
it('si el catálogo publica los cuatro indicadores no queda ninguna tarjeta pendiente', () => {
|
||||
// Fails if a published opportunity indicator is not queried and drawn.
|
||||
const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]);
|
||||
expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica'))).toBe(true);
|
||||
expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).toBe(true);
|
||||
expect(cards().map(card => text(card, 'h3')).slice(0, 4)).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title));
|
||||
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
|
||||
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.');
|
||||
});
|
||||
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
|
||||
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
|
||||
http.expectOne('/cama/indicadores').flush([]); fixture.detectChanges();
|
||||
expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull();
|
||||
expect(fixture.nativeElement.textContent).not.toContain('Integración pendiente'); http.expectNone(r => r.url.endsWith('/datos'));
|
||||
});
|
||||
it('un indicador publicado con otro contrato no se muestra como la tarjeta esperada', () => {
|
||||
// Fails if a contract mismatch (C1 served where C3r is expected) is drawn as a median.
|
||||
load(KPI_BY_DOMAIN.cama, { listed: catalog(KPI_BY_DOMAIN.cama).map(i => i.id === 'cama_eu38a' ? { ...i, contrato: 'C1' } : i) });
|
||||
const panel = fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel)
|
||||
.find(p => p.definition.id === 'cama_eu38a')!;
|
||||
expect(panel.result().state).toBe('Error de contrato'); expect(panel.result().value).toBeUndefined();
|
||||
});
|
||||
it('el error de una consulta se muestra en su tarjeta y las demás conservan sus datos', () => {
|
||||
load(KPI_BY_DOMAIN.cama, { answer: (r, definition) => definition.id === 'cama_eu38a' ? r.flush('private', { status: 500, statusText: 'Error' }) : r.flush(dataFor(definition)) });
|
||||
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
||||
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
||||
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de tamizaje a resultado"]')).not.toBeNull();
|
||||
});
|
||||
it('el estado Disponible solo se omite en CaMa: la tarjeta compartida lo sigue diciendo por defecto', () => {
|
||||
const card = TestBed.createComponent(IndicadorKpiCard);
|
||||
card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges();
|
||||
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Disponible');
|
||||
card.componentRef.setInput('quietWhenAvailable', true); card.detectChanges();
|
||||
expect(card.nativeElement.querySelector('.kpi-state')).toBeNull();
|
||||
card.componentRef.setInput('state', 'Sin datos del periodo'); card.detectChanges();
|
||||
expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Sin datos del periodo');
|
||||
card.destroy();
|
||||
});
|
||||
});
|
||||
@@ -33,9 +33,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); }
|
||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||
const inventory = http.match(r => r.url.endsWith('/periodos'));
|
||||
expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request.
|
||||
inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
|
||||
// The anchor shares the catalog inventory request. The inventory runs four requests at a time,
|
||||
// so a catalog of more than four indicators is answered in waves.
|
||||
let inventoried = 0;
|
||||
for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) {
|
||||
inventoried += wave.length;
|
||||
wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) }));
|
||||
}
|
||||
expect(inventoried).toBe(items.length);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
||||
|
||||
@@ -48,7 +48,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
|
||||
if (domain === 'cama') {
|
||||
expect(anchor.id).toBe('cama_birads_456_paciente');
|
||||
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico']);
|
||||
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']);
|
||||
} else expect(anchor.id).toBe('cacu_eu7');
|
||||
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
|
||||
expect(run.selected()?.periodo).toBe(periods[0]);
|
||||
|
||||
@@ -2,11 +2,27 @@ import { Dominio, IndicadorDatos } from './indicadores.models';
|
||||
import { GlobalApplied } from './indicadores-memory';
|
||||
import { percentNumber } from './indicadores-format';
|
||||
|
||||
export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; }
|
||||
export interface KpiDefinition {
|
||||
id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean;
|
||||
// C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one.
|
||||
c1Info?: (numerador: number, denominador: number) => string;
|
||||
// C3r only: a median over zero observations is no value, not zero days.
|
||||
requiresObservations?: boolean;
|
||||
}
|
||||
// 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,
|
||||
};
|
||||
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
|
||||
id: 'cama_eu38a', title: 'Tiempo de tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
};
|
||||
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
|
||||
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
|
||||
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
||||
};
|
||||
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
||||
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||
};
|
||||
// Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML
|
||||
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||
// (patients), not the distribution. If a TOML title changes, change it here too, until the
|
||||
@@ -25,8 +41,30 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
|
||||
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
|
||||
{ id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' },
|
||||
{ id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
|
||||
CAMA_TAMIZAJE_RESULTADO_KPI,
|
||||
],
|
||||
};
|
||||
|
||||
// CaMa's four opportunity cards, in display order. Two of them have no indicator in the catalog yet
|
||||
// (indicadores_kit defines neither `cama_tasa_deteccion_histopatologica` nor `cama_dias_resultado_diagnostico`),
|
||||
// so they stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them.
|
||||
export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [
|
||||
KPI_BY_DOMAIN.cama[0],
|
||||
CAMA_TASA_DETECCION_KPI,
|
||||
CAMA_TAMIZAJE_RESULTADO_KPI,
|
||||
CAMA_RESULTADO_DIAGNOSTICO_KPI,
|
||||
];
|
||||
export interface KpiCardSlot { definition: KpiDefinition; pending: boolean; }
|
||||
// The four opportunity cards first, each pending while its indicator is not in the catalog, then the
|
||||
// other published CaMa cards. Nothing at all (not even pending cards) until the catalog publishes one of them.
|
||||
export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[] {
|
||||
const cards = [
|
||||
...CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) })),
|
||||
...KPI_BY_DOMAIN.cama.filter(definition => !CAMA_OPORTUNIDAD_KPIS.includes(definition) && published(definition.id))
|
||||
.map(definition => ({ definition, pending: false })),
|
||||
];
|
||||
return cards.some(card => !card.pending) ? cards : [];
|
||||
}
|
||||
// C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`.
|
||||
const C1_GROUP: Record<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };
|
||||
const C1_INFO: Record<Dominio, (numerador: number, denominador: number) => string> = {
|
||||
@@ -78,8 +116,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai
|
||||
}
|
||||
if (definition.contrato === 'C1') {
|
||||
if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty;
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) };
|
||||
return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) };
|
||||
}
|
||||
if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && 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;
|
||||
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']) };
|
||||
}
|
||||
|
||||
@@ -73,14 +73,19 @@
|
||||
} @else if (initialPeriodState() === 'manual') {
|
||||
<p role="status">La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.</p>
|
||||
}
|
||||
@let kpis = opportunityKpis;
|
||||
@let kpis = kpiCards;
|
||||
@if (kpis.length && !initialPeriodBlocked) {
|
||||
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
|
||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}</h2>
|
||||
<div class="kpi-grid" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
|
||||
@for (definition of kpis; track dominio + ':' + definition.id) {
|
||||
<app-indicador-kpi-panel [dominio]="dominio" [definition]="definition" [indicador]="kpiIndicator(definition.id)"
|
||||
[applied]="filters?.applied" [availability]="availability()" [initialPresentation]="false" />
|
||||
@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" />
|
||||
}
|
||||
}
|
||||
@if (dominio === 'cacu') {
|
||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
||||
|
||||
@@ -65,6 +65,10 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
||||
|
||||
// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids.
|
||||
// CaMa's opportunity cards: one size, four in a row on wide screens and two by two below.
|
||||
.kpi-section[data-domain='cama'] .kpi-grid { grid-auto-rows: 1fr; }
|
||||
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
|
||||
.kpi-section[data-domain='cacu'] .kpi-grid {
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||
align-items: stretch;
|
||||
|
||||
@@ -17,7 +17,7 @@ import { IndicadoresService } from './indicadores.service';
|
||||
import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory';
|
||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi';
|
||||
import { IndicadorKpiPanel } from './indicador-kpi-panel';
|
||||
import { IndicadorKpiCard } from './indicador-kpi-card';
|
||||
import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection';
|
||||
@@ -298,6 +298,11 @@ 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.
|
||||
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 }));
|
||||
}
|
||||
private readonly catalogRequests = new Subject<void>();
|
||||
readonly catalog = signal<Indicador[]>([]);
|
||||
readonly searchQuery = signal('');
|
||||
|
||||
@@ -63,13 +63,13 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
}
|
||||
}
|
||||
it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => {
|
||||
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]);
|
||||
load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1'], ['2026-S1', '2025-S1']]);
|
||||
const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos'));
|
||||
const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges();
|
||||
const requests = flushDatos(domain);
|
||||
expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1'));
|
||||
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]);
|
||||
expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, undefined, '0.0', 0]); // Display order; the second card is the new median over n = 0, which is no value
|
||||
expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] });
|
||||
expect(fixture.componentInstance.filters!.applied.revision).toBe(1);
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true);
|
||||
@@ -85,11 +85,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
|
||||
expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true);
|
||||
});
|
||||
it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => {
|
||||
load('cama', [[], ['2025-S2'], ['2025-S1']]);
|
||||
load('cama', [[], ['2025-S2'], ['2025-S1'], ['2025-S2']]);
|
||||
expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0);
|
||||
http.expectNone(r => r.url.endsWith('/datos'));
|
||||
fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama');
|
||||
expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
|
||||
expect(requests).toHaveLength(3); expect(panels()[0].result().state).toBe('Sin reportes disponibles');
|
||||
expect(panels()[0].result().value).toBeUndefined();
|
||||
});
|
||||
it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => {
|
||||
|
||||
Reference in New Issue
Block a user