From b68af3a48aeef5eda49e418284a9839b0c424806 Mon Sep 17 00:00:00 2001 From: edgar Date: Sun, 8 Nov 2026 01:16:04 -0600 Subject: [PATCH] KPIs page draws durations as boxes and reads a composition's categories from its first stratifier --- ...oma_diagnostico_measure_report_bundle.json | 85 +++++++++++++++++++ src/app/features/indicadores/kpis-page.ts | 21 +++-- .../indicadores/measure-report.service.ts | 11 ++- .../indicadores/measure-report.spec.ts | 54 ++++++++++-- .../features/indicadores/measure-report.ts | 55 ++++++++++-- 5 files changed, 208 insertions(+), 18 deletions(-) create mode 100644 src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json diff --git a/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json new file mode 100644 index 0000000..d337f2a --- /dev/null +++ b/src/app/features/indicadores/fixtures/cacu_dias_toma_diagnostico_measure_report_bundle.json @@ -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" + } + ] + } + } + } + ] +} \ No newline at end of file diff --git a/src/app/features/indicadores/kpis-page.ts b/src/app/features/indicadores/kpis-page.ts index 8530413..d665db8 100644 --- a/src/app/features/indicadores/kpis-page.ts +++ b/src/app/features/indicadores/kpis-page.ts @@ -3,8 +3,8 @@ 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'; +import { compositionFigure, durationFigure, proportionFigure } from './measure-report'; +import { KpiEntry, MeasureReportService } from './measure-report.service'; const PERIODOS = ['2025-S1', '2025-S2']; @@ -28,12 +28,23 @@ export class KpisPage implements OnInit { 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) })))))), + 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)))); + } + } } diff --git a/src/app/features/indicadores/measure-report.service.ts b/src/app/features/indicadores/measure-report.service.ts index b290516..a26dd5d 100644 --- a/src/app/features/indicadores/measure-report.service.ts +++ b/src/app/features/indicadores/measure-report.service.ts @@ -2,9 +2,9 @@ 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'; +import { CompositionSeries, compositionFrom, DurationSeries, durationFrom, MeasureReportBundle, Series, seriesFrom } from './measure-report'; -export interface KpiEntry { id: string; url: string; version: string; scoring: 'proportion' | 'composition' } +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' }) @@ -23,6 +23,13 @@ export class MeasureReportService { .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(`/${requireDominio(dominio)}/kpis/${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); diff --git a/src/app/features/indicadores/measure-report.spec.ts b/src/app/features/indicadores/measure-report.spec.ts index 98d8783..efa9ae1 100644 --- a/src/app/features/indicadores/measure-report.spec.ts +++ b/src/app/features/indicadores/measure-report.spec.ts @@ -2,8 +2,9 @@ // 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. +// `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'; @@ -13,8 +14,9 @@ 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, InvalidMeasureReport, MeasureReportBundle, periodLabel, proportionFigure, seriesFrom } from './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'; @@ -24,6 +26,7 @@ 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; +const DIAS = dias as unknown as MeasureReportBundle; describe('measure reports', () => { it('names a period from its FHIR dates', () => { @@ -110,6 +113,15 @@ describe('compositions', () => { 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'); @@ -118,12 +130,39 @@ describe('compositions', () => { }); }); +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/kpis` and draws proportions and compositions - // from the one contract. Fails if a scoring stops being drawn or the page starts naming measures. + // Pins down: the page needs nothing per measure: it lists `/cacu/kpis` 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(); @@ -132,14 +171,17 @@ describe('KpisPage', () => { { 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/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); + http.expectOne(r => r.url === '/cacu/kpis/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']); + 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'); }); }); diff --git a/src/app/features/indicadores/measure-report.ts b/src/app/features/indicadores/measure-report.ts index 953b8f6..c14c88e 100644 --- a/src/app/features/indicadores/measure-report.ts +++ b/src/app/features/indicadores/measure-report.ts @@ -6,10 +6,11 @@ export interface CodeableConcept { coding?: { system?: string; code: 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?: { value: number }; + measureScore?: Score; stratifier?: ReportStratifier[]; } export interface MeasureReport { @@ -112,10 +113,11 @@ export function proportionFigure(series: Series, title: string, stratum?: string } -/** A composition: per period, how many units fall in each category of its `resultado` stratifier. */ +/** 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 } -export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resultado'): CompositionSeries { +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'); } @@ -123,8 +125,9 @@ export function compositionFrom(bundle: MeasureReportBundle, stratifier = 'resul 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}`); + 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'); @@ -145,3 +148,45 @@ export function compositionFigure(series: CompositionSeries, title: string): Plo 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}
n = ${p.n} de ${p.initial}
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' } }, + }; +}