diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index 66070ed..2249119 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -26,6 +26,12 @@ export const routes: Routes = [ loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage), 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' }, ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, diff --git a/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json new file mode 100644 index 0000000..d23a6f2 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu13_measure_report_bundle.json @@ -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 + } + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json new file mode 100644 index 0000000..36b91a3 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_eu7_measure_report_bundle.json @@ -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 + } + ] + } + ] + } + ] + } + ] + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json new file mode 100644 index 0000000..4615f5c --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_ind1_measure_report_bundle.json @@ -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" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/indicador-measure-report.ts b/src/app/features/indicadores/indicador-measure-report.ts new file mode 100644 index 0000000..c371f96 --- /dev/null +++ b/src/app/features/indicadores/indicador-measure-report.ts @@ -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') { } + @if (status() === 'error') {

No se pudo cargar el indicador.

} + @if (figure(); as figure) { } + `, +}) +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(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'); }, + }); + } +} diff --git a/src/app/features/indicadores/kpis-page.ts b/src/app/features/indicadores/kpis-page.ts new file mode 100644 index 0000000..8530413 --- /dev/null +++ b/src/app/features/indicadores/kpis-page.ts @@ -0,0 +1,39 @@ +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, proportionFigure } from './measure-report'; +import { 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: ` +

Indicadores

+ @if (status() === 'loading') { } + @if (status() === 'error') {

No se pudieron cargar los indicadores.

} + @for (item of figures(); track item.id) { +
+ } + `, +}) +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 => kpi.scoring === 'composition' + ? this.service.composition('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: compositionFigure(s, kpi.id) }))) + : this.service.series('cacu', kpi.id, PERIODOS).pipe(map(s => ({ id: kpi.id, figure: proportionFigure(s, kpi.id) })))))), + ).subscribe({ + next: figures => { this.figures.set(figures); this.status.set('ready'); }, + error: () => this.status.set('error'), + }); + } +} diff --git a/src/app/features/indicadores/measure-report.service.ts b/src/app/features/indicadores/measure-report.service.ts new file mode 100644 index 0000000..b290516 --- /dev/null +++ b/src/app/features/indicadores/measure-report.service.ts @@ -0,0 +1,34 @@ +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, MeasureReportBundle, Series, seriesFrom } from './measure-report'; + +export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' } + +/** 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(`/${requireDominio(dominio)}/kpis`); + } + + composition(dominio: Dominio, indicador: string, periodos: string[]) { + const params = new HttpParams().set('periodos', periodos.join(',')); + return this.http + .get(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .pipe(map((bundle): CompositionSeries => compositionFrom(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(`/${requireDominio(dominio)}/kpis/${encodeURIComponent(indicador)}`, { params }) + .pipe(map((bundle): Series => seriesFrom(bundle))); + } +} diff --git a/src/app/features/indicadores/measure-report.spec.ts b/src/app/features/indicadores/measure-report.spec.ts new file mode 100644 index 0000000..98d8783 --- /dev/null +++ b/src/app/features/indicadores/measure-report.spec.ts @@ -0,0 +1,145 @@ +// What this covers: reading the WebApi's FHIR `MeasureReport` bundles (`//kpis/`) 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): written by the WebApi's +// route tests over the synthetic fixture database, counts 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 { IndicadorMeasureReport } from './indicador-measure-report'; +import { compositionFigure, compositionFrom, 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(); label = input(); } + +const IND1 = ind1 as unknown as MeasureReportBundle; +const EU13 = eu13 as unknown as MeasureReportBundle; +const EU7 = eu7 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/kpis/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/kpis/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('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('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/kpis` and draws proportions and compositions + // 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/kpis').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' }, + ]); + http.expectOne(r => r.url === '/cacu/kpis/IND1').flush(IND1); + http.expectOne(r => r.url === '/cacu/kpis/CACU_EU13').flush(EU13); + http.expectOne(r => r.url === '/cacu/kpis/CACU_EU7').flush(EU7); + fixture.detectChanges(); + expect(fixture.componentInstance.status()).toBe('ready'); + expect(fixture.componentInstance.figures().map(f => f.id)).toEqual(['IND1', 'CACU_EU13', 'CACU_EU7']); + expect(fixture.componentInstance.figures()[2].figure.layout['barmode']).toBe('stack'); + }); +}); + diff --git a/src/app/features/indicadores/measure-report.ts b/src/app/features/indicadores/measure-report.ts new file mode 100644 index 0000000..953b8f6 --- /dev/null +++ b/src/app/features/indicadores/measure-report.ts @@ -0,0 +1,147 @@ +import { PlotlyFigure } from './indicadores.models'; + +/** The part of FHIR R4's `MeasureReport` the WebApi's `//kpis/` 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 ReportGroup { + id?: string; + population: ReportPopulation[]; + measureScore?: { value: number }; + 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>; +} + +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}
${p.numerator} de ${p.denominator}` + + (p.value === null ? '
sin denominador' : `
${(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 of its `resultado` stratifier. */ +export interface CompositionSeries { measure: string; periods: string[]; categories: Record } + +export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resultado'): 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 = {}; + reports.forEach((report, i) => { + const found = report.group[0]?.stratifier?.find(s => s.code[0]?.text === stratifier); + if (!found) throw new InvalidMeasureReport(`Falta el estratificador ${stratifier}`); + 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]}
${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' } }, + }; +}