Compare commits

...

3 Commits

10 changed files with 1173 additions and 0 deletions
+6
View File
@@ -26,6 +26,12 @@ export const routes: Routes = [
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage), loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' }, data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
}, },
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
data: { workspace: true, breadcrumb: 'Indicadores' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' }, { path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({ ...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`, path: `indicadores/${dominio}`,
@@ -0,0 +1,85 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3",
"date": "2026-11-08T06:47:32.900609+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-evento",
"valueDate": "2026-11-08"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T06:47:32.766239+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 2
}
],
"measureScore": {
"value": 100.5,
"unit": "d",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q1",
"valueDecimal": 70.25
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/q3",
"valueDecimal": 130.75
}
]
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -0,0 +1,127 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 1,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU13|0.3.2",
"date": "2026-11-08T00:28:51.413089+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:51.351883+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
},
"stratifier": [
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 0
}
],
"measureScore": {
"value": 0.0
}
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,295 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.089006+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEBG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/CACU_EU7|0.3.3",
"date": "2026-11-08T00:28:56.099338+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:56.025101+00:00"
}
],
"group": [
{
"id": "TOTAL",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"count": 4
}
],
"stratifier": [
{
"code": [
{
"text": "resultado"
}
],
"stratum": [
{
"value": {
"text": "LIEAG"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "NEGATIVO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 1
}
]
},
{
"value": {
"text": "SIN_DATO"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 2
}
]
}
]
},
{
"code": [
{
"text": "grupo_edad"
}
],
"stratum": [
{
"value": {
"text": "45-54"
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
}
]
}
]
}
]
}
]
}
}
]
}
@@ -0,0 +1,155 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 2,
"entry": [
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.038223+00:00",
"period": {
"start": "2025-01-01",
"end": "2025-06-30"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 1
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
},
{
"resource": {
"resourceType": "MeasureReport",
"status": "complete",
"type": "summary",
"measure": "cacu/IND1|0.3.2",
"date": "2026-11-08T00:28:50.044435+00:00",
"period": {
"start": "2025-07-01",
"end": "2025-12-31"
},
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/reporte-id",
"valueInteger": 2
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/corte-conocimiento",
"valueDateTime": "2026-11-08T00:28:49.977023+00:00"
}
],
"group": [
{
"id": "principal",
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"count": 4
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"count": 1
}
],
"measureScore": {
"value": 0.25
}
}
],
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
}
}
]
}
@@ -0,0 +1,35 @@
import { Component, inject, Input, OnChanges, signal } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { Dominio, PlotlyFigure } from './indicadores.models';
import { proportionFigure } from './measure-report';
import { MeasureReportService } from './measure-report.service';
/** A proportion drawn from the WebApi's FHIR `MeasureReport`s: the data comes as the standard, the figure is ours. */
@Component({
selector: 'app-indicador-measure-report',
imports: [MatProgressBarModule, PlotlyChart],
template: `
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicador" /> }
@if (status() === 'error') { <p role="alert">No se pudo cargar el indicador.</p> }
@if (figure(); as figure) { <app-plotly-chart [figure]="figure" [label]="titulo" /> }
`,
})
export class IndicadorMeasureReport implements OnChanges {
@Input({ required: true }) dominio!: Dominio;
@Input({ required: true }) indicador!: string;
@Input({ required: true }) titulo!: string;
@Input({ required: true }) periodos!: string[];
@Input() estrato?: string;
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly figure = signal<PlotlyFigure | undefined>(undefined);
private readonly service = inject(MeasureReportService);
ngOnChanges() {
this.status.set('loading');
this.service.series(this.dominio, this.indicador, this.periodos).subscribe({
next: series => { this.figure.set(proportionFigure(series, this.titulo, this.estrato)); this.status.set('ready'); },
error: () => { this.figure.set(undefined); this.status.set('error'); },
});
}
}
+50
View File
@@ -0,0 +1,50 @@
import { Component, inject, OnInit, signal } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { forkJoin, map, of, switchMap } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { PlotlyFigure } from './indicadores.models';
import { compositionFigure, durationFigure, proportionFigure } from './measure-report';
import { KpiEntry, MeasureReportService } from './measure-report.service';
const PERIODOS = ['2025-S1', '2025-S2'];
/** Every measure the WebApi answers on request, drawn from its FHIR `MeasureReport`s: one contract for all. */
@Component({
selector: 'app-kpis-page',
imports: [MatProgressBarModule, PlotlyChart],
template: `
<h1>Indicadores</h1>
@if (status() === 'loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando indicadores" /> }
@if (status() === 'error') { <p role="alert">No se pudieron cargar los indicadores.</p> }
@for (item of figures(); track item.id) {
<section><app-plotly-chart [figure]="item.figure" [label]="item.id" /></section>
}
`,
})
export class KpisPage implements OnInit {
readonly status = signal<'loading' | 'ready' | 'error'>('loading');
readonly figures = signal<{ id: string; figure: PlotlyFigure }[]>([]);
private readonly service = inject(MeasureReportService);
ngOnInit() {
this.service.list('cacu').pipe(
switchMap(kpis => kpis.length === 0 ? of([]) : forkJoin(kpis.map(kpi => this.figureOf(kpi)))),
).subscribe({
next: figures => { this.figures.set(figures); this.status.set('ready'); },
error: () => this.status.set('error'),
});
}
/** Drawn by its scoring, from the one contract: nothing here is per measure. */
private figureOf(kpi: KpiEntry) {
const drawn = (figure: PlotlyFigure) => ({ id: kpi.id, figure });
switch (kpi.scoring) {
case 'composition':
return this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(compositionFigure(s, kpi.id))));
case 'continuous-variable':
return this.service.duration('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(durationFigure(s, kpi.id))));
default:
return this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => drawn(proportionFigure(s, kpi.id))));
}
}
}
@@ -0,0 +1,41 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { Dominio, requireDominio } from './indicadores.models';
import { CompositionSeries, compositionFrom, DurationSeries, durationFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report';
export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' | 'continuous-variable' }
/** A measure's periods answered on request by the WebApi, as FHIR `MeasureReport`s, read into a series. */
@Injectable({ providedIn: 'root' })
export class MeasureReportService {
private readonly http = inject(HttpClient);
/** The measures the WebApi answers on request for the domain. */
list(dominio: Dominio) {
return this.http.get<KpiEntry[]>(`/${requireDominio(dominio)}/indicadores`);
}
composition(dominio: Dominio, indicador: string, periodos: string[]) {
const params = new HttpParams().set('periodos', periodos.join(','));
return this.http
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
.pipe(map((bundle): CompositionSeries => compositionFrom(bundle)));
}
duration(dominio: Dominio, indicador: string, periodos: string[]) {
const params = new HttpParams().set('periodos', periodos.join(','));
return this.http
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
.pipe(map((bundle): DurationSeries => durationFrom(bundle)));
}
series(dominio: Dominio, indicador: string, periodos: string[], cortes: { evento?: string; conocimiento?: string } = {}) {
let params = new HttpParams().set('periodos', periodos.join(','));
if (cortes.evento) params = params.set('corte_evento', cortes.evento);
if (cortes.conocimiento) params = params.set('corte_conocimiento', cortes.conocimiento);
return this.http
.get<MeasureReportBundle>(`/${requireDominio(dominio)}/indicadores/${encodeURIComponent(indicador)}`, { params })
.pipe(map((bundle): Series => seriesFrom(bundle)));
}
}
@@ -0,0 +1,187 @@
// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`/<domain>/indicadores/<id>`) into a series, drawing
// it here, the service that asks for it and the component that shows it.
// Fixtures: `cacu_ind1_measure_report_bundle.json` (IND1, 2025-S1 and 2025-S2) and
// `cacu_eu13_measure_report_bundle.json` (EU13, 2025-S1, with the `grupo_edad` stratifier) and
// `cacu_eu7_measure_report_bundle.json` (EU7, a composition, 2025-S1 and 2025-S2) and
// `cacu_dias_toma_diagnostico_measure_report_bundle.json` (days to diagnosis, a duration, 2025-S2): written by the
// WebApi's route tests over the synthetic fixture database, counts and days only.
import { Component, input } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import ind1 from './fixtures/cacu_ind1_measure_report_bundle.json';
import eu13 from './fixtures/cacu_eu13_measure_report_bundle.json';
import eu7 from './fixtures/cacu_eu7_measure_report_bundle.json';
import dias from './fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json';
import { IndicadorMeasureReport } from './indicador-measure-report';
import { compositionFigure, compositionFrom, durationFigure, durationFrom, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './measure-report';
import { KpisPage } from './kpis-page';
import { MeasureReportService } from './measure-report.service';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); }
const IND1 = ind1 as unknown as MeasureReportBundle;
const EU13 = eu13 as unknown as MeasureReportBundle;
const EU7 = eu7 as unknown as MeasureReportBundle;
const DIAS = dias as unknown as MeasureReportBundle;
describe('measure reports', () => {
it('names a period from its FHIR dates', () => {
// Pins down: semesters and months read as the WebApp names them. Fails if FHIR's inclusive end is misread.
expect(periodLabel({ start: '2025-01-01', end: '2025-06-30' })).toBe('2025-S1');
expect(periodLabel({ start: '2025-07-01', end: '2025-12-31' })).toBe('2025-S2');
expect(periodLabel({ start: '2025-03-01', end: '2025-03-31' })).toBe('2025-03');
expect(periodLabel({ start: '2025-01-01', end: '2025-03-31' })).toBe('2025-01-01 a 2025-03-31');
});
it('reads one point per period from a bundle', () => {
// Pins down: the counts come from the populations, the order from the bundle. Fails if the reading of FHIR's
// population codes or of `improvementNotation` changes.
const series = seriesFrom(IND1);
expect(series.measure).toBe('cacu/IND1|0.3.2');
expect(series.lowerIsBetter).toBe(true);
expect(series.total).toEqual([
{ period: '2025-S1', numerator: 1, denominator: 4, value: 0.25 },
{ period: '2025-S2', numerator: 1, denominator: 4, value: 0.25 },
]);
});
it('reads the strata of a stratifier', () => {
// Pins down: each stratum's value is a series of its own. Fails if `stratifier` stops being read.
expect(seriesFrom(EU13).strata).toEqual({
grupo_edad: { '45-54': [{ period: '2025-S1', numerator: 0, denominator: 4, value: 0 }] },
});
});
it('rejects what is not a bundle of reports of one measure', () => {
// Pins down: a malformed answer fails loudly instead of drawing zeros. Fails if validation is dropped.
expect(() => seriesFrom({ resourceType: 'Bundle', entry: [] } as MeasureReportBundle)).toThrow(InvalidMeasureReport);
const mixed = { ...IND1, entry: [IND1.entry[0], { resource: { ...IND1.entry[1].resource, measure: 'otro' } }] };
expect(() => seriesFrom(mixed)).toThrow(InvalidMeasureReport);
});
it('draws the figure here: percentages per period, one line per stratum value', () => {
// Pins down: the WebApp decides the figure from the data. Fails if values stop being percentages, or a
// stratum stops giving one trace per value.
const total = proportionFigure(seriesFrom(IND1), 'Pacientes con citología anómala');
expect(total.data).toHaveLength(1);
expect(total.data[0]['x']).toEqual(['2025-S1', '2025-S2']);
expect(total.data[0]['y']).toEqual([25, 25]);
const byAge = proportionFigure(seriesFrom(EU13), 'Tasa de detección', 'grupo_edad');
expect(byAge.data.map(trace => trace['name'])).toEqual(['45-54']);
});
});
describe('MeasureReportService and IndicadorMeasureReport', () => {
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
it('asks the WebApi for the periods and cut-offs and reads the bundle', async () => {
// Pins down the request: the route, `periodos` comma-separated and the cut-offs only when given. Fails if
// the URL or a parameter's name drifts from the WebApi's.
const answer = firstValueFrom(TestBed.inject(MeasureReportService)
.series('cacu', 'IND1', ['2025-S1', '2025-S2'], { evento: '2025-12-31' }));
const request = TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1');
expect(request.request.params.get('periodos')).toBe('2025-S1,2025-S2');
expect(request.request.params.get('corte_evento')).toBe('2025-12-31');
expect(request.request.params.has('corte_conocimiento')).toBe(false);
request.flush(IND1);
expect((await answer).total.map(p => p.value)).toEqual([0.25, 0.25]);
});
it('shows the figure it drew from the answer', () => {
// Pins down: the component hands the chart the figure built from the bundle. Fails if it stops drawing.
TestBed.overrideComponent(IndicadorMeasureReport, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
const fixture = TestBed.createComponent(IndicadorMeasureReport);
Object.assign(fixture.componentInstance, { dominio: 'cacu', indicador: 'IND1', titulo: 'IND1', periodos: ['2025-S1', '2025-S2'] });
fixture.componentInstance.ngOnChanges();
TestBed.inject(HttpTestingController).expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1);
fixture.detectChanges();
expect(fixture.componentInstance.status()).toBe('ready');
expect(fixture.componentInstance.figure()?.data[0]['y']).toEqual([25, 25]);
});
});
describe('compositions', () => {
it('reads the categories of each period from the `resultado` stratifier', () => {
// Pins down: a composition is a count per category and period, zero where a period lacks one. Fails if the
// stratifier stops being read or a missing category stops being zero.
const series = compositionFrom(EU7);
expect(series.periods).toEqual(['2025-S1', '2025-S2']);
expect(series.categories).toEqual({ LIEBG: [1, 0], NEGATIVO: [2, 1], SIN_DATO: [1, 2], LIEAG: [0, 1] });
});
it('takes the categories from the first stratifier, whatever its column is called', () => {
// Pins down: a composition whose category isn't `resultado` (the confirmation by biopsia_grado) is read too, and
// a stratifier can still be asked for by name. Fails if the reader goes back to a fixed name.
const renamed = { ...EU7, entry: EU7.entry.map(e => ({ resource: { ...e.resource, group: [{ ...e.resource.group[0],
stratifier: e.resource.group[0].stratifier!.map((s, i) => (i === 0 ? { ...s, code: [{ text: 'biopsia_grado' }] } : s)) }] } })) };
expect(compositionFrom(renamed).categories).toEqual(compositionFrom(EU7).categories);
expect(() => compositionFrom(EU7, 'no_existe')).toThrow(InvalidMeasureReport);
});
it('draws stacked bars, one segment per category', () => {
// Pins down: the WebApp draws compositions from the same contract. Fails if a category stops being a trace.
const figure = compositionFigure(compositionFrom(EU7), 'EU7');
expect(figure.layout['barmode']).toBe('stack');
expect(figure.data.map(trace => trace['name']).sort()).toEqual(['LIEAG', 'LIEBG', 'NEGATIVO', 'SIN_DATO']);
});
});
describe('durations', () => {
it('reads the samples measurable and measured, the median and the quartiles of each period', () => {
// Pins down: a duration's populations and its score with the quartiles as extensions. Fails if the WebApi's
// duration contract or its reading drifts.
expect(durationFrom(DIAS).points).toEqual([
{ period: '2025-S2', initial: 4, n: 2, q1: 70.25, median: 100.5, q3: 130.75 },
]);
expect(durationFrom(DIAS).lowerIsBetter).toBe(true);
});
it('draws a box per period from the served quartiles, without whiskers', () => {
// Pins down: the WebApp draws durations from the same contract. Fails if the box stops using the quartiles or
// starts drawing extremes it wasn't given.
const [box] = durationFigure(durationFrom(DIAS), 'Días a diagnóstico').data;
expect(box['type']).toBe('box');
expect([box['q1'], box['median'], box['q3']]).toEqual([[70.25], [100.5], [130.75]]);
expect([box['lowerfence'], box['upperfence']]).toEqual([[70.25], [130.75]]);
});
it('rejects a duration measured without its median', () => {
// Pins down: a malformed answer fails loudly. Fails if the check on the score is dropped.
const [entry] = DIAS.entry;
const broken = { ...DIAS, entry: [{ resource: { ...entry.resource, group: [{ ...entry.resource.group[0], measureScore: undefined }] } }] };
expect(() => durationFrom(broken)).toThrow(InvalidMeasureReport);
});
});
describe('KpisPage', () => {
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
it('draws every measure the WebApi lists, each from its reports', () => {
// Pins down: the page needs nothing per measure: it lists `/cacu/indicadores` and draws proportions, compositions
// and durations from the one contract. Fails if a scoring stops being drawn or the page starts naming measures.
TestBed.overrideComponent(KpisPage, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
const fixture = TestBed.createComponent(KpisPage);
fixture.componentInstance.ngOnInit();
const http = TestBed.inject(HttpTestingController);
http.expectOne('/cacu/indicadores').flush([
{ id: 'IND1', url: 'cacu/IND1', version: '0.3.2', scoring: 'proportion' },
{ id: 'CACU_EU13', url: 'cacu/CACU_EU13', version: '0.3.2', scoring: 'proportion' },
{ id: 'CACU_EU7', url: 'cacu/CACU_EU7', version: '0.3.3', scoring: 'composition' },
{ id: 'CACU_DIAS_TOMA_DIAGNOSTICO', url: 'cacu/CACU_DIAS_TOMA_DIAGNOSTICO', version: '0.2.3', scoring: 'continuous-variable' },
]);
http.expectOne(r => r.url === '/cacu/indicadores/IND1').flush(IND1);
http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU13').flush(EU13);
http.expectOne(r => r.url === '/cacu/indicadores/CACU_EU7').flush(EU7);
http.expectOne(r => r.url === '/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO').flush(DIAS);
fixture.detectChanges();
expect(fixture.componentInstance.status()).toBe('ready');
expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7', 'CACU_DIAS_TOMA_DIAGNOSTICO']);
expect(fixture.componentInstance.figures()[2].figure.layout['barmode']).toBe('stack');
expect(fixture.componentInstance.figures()[3].figure.data[0]['type']).toBe('box');
});
});
@@ -0,0 +1,192 @@
import { PlotlyFigure } from './indicadores.models';
/** The part of FHIR R4's `MeasureReport` the WebApi's `/<domain>/indicadores/<id>` serves: one group, its populations,
* its score and its strata. */
export interface CodeableConcept { coding?: { system?: string; code: string }[]; text?: string }
export interface ReportPopulation { code: CodeableConcept; count: number }
export interface ReportStratum { value: CodeableConcept; population: ReportPopulation[]; measureScore?: { value: number } }
export interface ReportStratifier { code: CodeableConcept[]; stratum: ReportStratum[] }
export interface Score { value: number; unit?: string; extension?: { url: string; valueDecimal?: number }[] }
export interface ReportGroup {
id?: string;
population: ReportPopulation[];
measureScore?: Score;
stratifier?: ReportStratifier[];
}
export interface MeasureReport {
resourceType: 'MeasureReport';
status: string;
type: string;
measure: string;
period: { start: string; end: string };
group: ReportGroup[];
improvementNotation?: CodeableConcept;
extension?: { url: string; valueDate?: string; valueDateTime?: string; valueInteger?: number }[];
}
export interface MeasureReportBundle { resourceType: 'Bundle'; entry: { resource: MeasureReport }[] }
/** One period of a series: its label, the counts and the proportion (null without a denominator). */
export interface Point { period: string; numerator: number; denominator: number; value: number | null }
export interface Series {
measure: string;
lowerIsBetter: boolean;
total: Point[];
strata: Record<string, Record<string, Point[]>>;
}
export class InvalidMeasureReport extends Error {}
/** "2025-S1", "2025-03" or "2025-01-01 a 2025-03-31": the period's name from FHIR's dates (the end is inclusive). */
export function periodLabel(period: { start: string; end: string }): string {
const [y1, m1, d1] = period.start.split('-').map(Number);
const [y2, m2] = period.end.split('-').map(Number);
const months = (y2 - y1) * 12 + (m2 - m1) + 1;
if (d1 === 1 && months === 1) return `${y1}-${String(m1).padStart(2, '0')}`;
if (d1 === 1 && months === 6 && (m1 === 1 || m1 === 7)) return `${y1}-S${m1 === 1 ? 1 : 2}`;
return `${period.start} a ${period.end}`;
}
function count(populations: ReportPopulation[], code: string): number {
const found = populations.find(p => p.code.coding?.some(c => c.code === code));
if (!found || !Number.isInteger(found.count) || found.count < 0) throw new InvalidMeasureReport(`Falta la población ${code}`);
return found.count;
}
function point(period: string, populations: ReportPopulation[]): Point {
const numerator = count(populations, 'numerator');
const denominator = count(populations, 'denominator');
return { period, numerator, denominator, value: denominator ? numerator / denominator : null };
}
/** The series of a measure from the reports of its periods, in the order they came. */
export function seriesFrom(bundle: MeasureReportBundle): Series {
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
throw new InvalidMeasureReport('Respuesta de KPI inválida');
}
const reports = bundle.entry.map(e => e.resource);
if (!reports.every(r => r?.resourceType === 'MeasureReport' && r.group?.length === 1)) {
throw new InvalidMeasureReport('Respuesta de KPI inválida');
}
const measures = new Set(reports.map(r => r.measure));
if (measures.size !== 1) throw new InvalidMeasureReport('Los reportes son de indicadores distintos');
const strata: Series['strata'] = {};
const total = reports.map(report => {
const period = periodLabel(report.period);
const [group] = report.group;
for (const stratifier of group.stratifier ?? []) {
const name = stratifier.code[0]?.text ?? '';
for (const stratum of stratifier.stratum) {
const value = stratum.value.text ?? '';
((strata[name] ??= {})[value] ??= []).push(point(period, stratum.population));
}
}
return point(period, group.population);
});
const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false;
return { measure: reports[0].measure, lowerIsBetter, total, strata };
}
const hover = (p: Point) => `${p.period}<br>${p.numerator} de ${p.denominator}`
+ (p.value === null ? '<br>sin denominador' : `<br>${(100 * p.value).toFixed(1)} %`);
/** The figure, drawn here: one point per period, as a percentage; with a stratum, one line per value. */
export function proportionFigure(series: Series, title: string, stratum?: string): PlotlyFigure {
const traces = stratum
? Object.entries(series.strata[stratum] ?? {}).map(([value, points]) => ({ name: value, points }))
: [{ name: 'Total', points: series.total }];
const data = traces.map(({ name, points }) => ({
type: 'scatter', mode: 'lines+markers', name,
x: points.map(p => p.period),
y: points.map(p => (p.value === null ? null : 100 * p.value)),
text: points.map(hover), hoverinfo: 'text',
}));
const notes = series.lowerIsBetter ? [{ text: 'Menos es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : [];
return {
data,
layout: {
title: { text: title }, showlegend: traces.length > 1,
xaxis: { type: 'category', title: { text: 'Periodo' } },
yaxis: { title: { text: 'Porcentaje' }, ticksuffix: ' %', rangemode: 'tozero' },
annotations: notes,
},
};
}
/** A composition: per period, how many units fall in each category. The categories are the report's first
* stratifier (the WebApi puts them first, named after the category's column), or the one named `stratifier`. */
export interface CompositionSeries { measure: string; periods: string[]; categories: Record<string, number[]> }
export function compositionFrom(bundle: MeasureReportBundle, stratifier?: string): CompositionSeries {
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
throw new InvalidMeasureReport('Respuesta de KPI inválida');
}
const reports = bundle.entry.map(e => e.resource);
const periods = reports.map(r => periodLabel(r.period));
const categories: Record<string, number[]> = {};
reports.forEach((report, i) => {
const stratifiers = report.group[0]?.stratifier ?? [];
const found = stratifier === undefined ? stratifiers[0] : stratifiers.find(s => s.code[0]?.text === stratifier);
if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier ?? 'de categorías'}`);
for (const stratum of found.stratum) {
const name = stratum.value.text ?? '';
(categories[name] ??= periods.map(() => 0))[i] = count(stratum.population, 'initial-population');
}
});
return { measure: reports[0].measure, periods, categories };
}
/** Stacked bars, one per period, a segment per category, drawn here. */
export function compositionFigure(series: CompositionSeries, title: string): PlotlyFigure {
const data = Object.entries(series.categories).map(([name, counts]) => ({
type: 'bar', name, x: series.periods, y: counts,
text: counts.map((n, i) => `${series.periods[i]}<br>${name}: ${n}`), hoverinfo: 'text',
}));
return {
data,
layout: { title: { text: title }, barmode: 'stack', showlegend: true,
xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Pacientes' }, rangemode: 'tozero' } },
};
}
/** A duration: per period, the units measurable and measured and, if any was, the quartiles of their days. */
export interface DurationPoint { period: string; initial: number; n: number; q1: number | null; median: number | null; q3: number | null }
export interface DurationSeries { measure: string; lowerIsBetter: boolean; points: DurationPoint[] }
const quartile = (score: Score | undefined, name: string) =>
score?.extension?.find(e => e.url.endsWith(`/${name}`))?.valueDecimal ?? null;
export function durationFrom(bundle: MeasureReportBundle): DurationSeries {
if (bundle?.resourceType !== 'Bundle' || !Array.isArray(bundle.entry) || bundle.entry.length === 0) {
throw new InvalidMeasureReport('Respuesta de KPI inválida');
}
const reports = bundle.entry.map(e => e.resource);
const points = reports.map(report => {
const [group] = report.group;
const n = count(group.population, 'measure-observation');
const score = group.measureScore;
if (n > 0 && score === undefined) throw new InvalidMeasureReport('Falta la mediana');
return { period: periodLabel(report.period), initial: count(group.population, 'initial-population'), n,
q1: quartile(score, 'q1'), median: score?.value ?? null, q3: quartile(score, 'q3') };
});
const lowerIsBetter = reports[0].improvementNotation?.coding?.some(c => c.code === 'decrease') ?? false;
return { measure: reports[0].measure, lowerIsBetter, points };
}
/** One box per period, from the served quartiles: first to third quartile and the median, no whiskers. */
export function durationFigure(series: DurationSeries, title: string): PlotlyFigure {
const measured = series.points.filter(p => p.median !== null);
const data = [{
type: 'box', name: 'Días', x: measured.map(p => p.period),
q1: measured.map(p => p.q1), median: measured.map(p => p.median), q3: measured.map(p => p.q3),
lowerfence: measured.map(p => p.q1), upperfence: measured.map(p => p.q3),
text: measured.map(p => `${p.period}<br>n = ${p.n} de ${p.initial}<br>mediana ${p.median} días`), hoverinfo: 'text',
}];
const notes = series.lowerIsBetter ? [{ text: 'Menos días es mejor.', showarrow: false, xref: 'paper', yref: 'paper', x: 0, y: -0.2 }] : [];
return {
data,
layout: { title: { text: title }, showlegend: false, annotations: notes,
xaxis: { type: 'category', title: { text: 'Periodo' } }, yaxis: { title: { text: 'Días' }, rangemode: 'tozero' } },
};
}