KPIs page drawing CaCu's measures from the WebApi's FHIR MeasureReport bundles
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
import { PlotlyFigure } from './indicadores.models';
|
||||
|
||||
/** The part of FHIR R4's `MeasureReport` the WebApi's `/<domain>/kpis/<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 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<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 of its `resultado` stratifier. */
|
||||
export interface CompositionSeries { measure: string; periods: string[]; categories: Record<string, number[]> }
|
||||
|
||||
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<string, number[]> = {};
|
||||
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]}<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' } },
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user