342 lines
17 KiB
TypeScript
342 lines
17 KiB
TypeScript
import { inject, Injectable } from '@angular/core';
|
|
import { HttpClient, HttpParams } from '@angular/common/http';
|
|
import { map, Observable, shareReplay, switchMap } from 'rxjs';
|
|
import { Bundle, code, Concept, display, extension, extensions, Extension, Resource, resources } from './fhir';
|
|
import { periodLabel } from './measure-report';
|
|
import {
|
|
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
|
|
} from './indicadores.models';
|
|
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
|
|
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
|
|
import { IndicadoresRequests } from './indicadores-requests';
|
|
|
|
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
|
|
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
|
|
// by the same rules as before.
|
|
|
|
interface Population { code?: Concept; count?: number; description?: string; criteria?: { expression?: string } }
|
|
interface Score { value?: number; unit?: string; extension?: Extension[] }
|
|
interface Stratum { value?: Concept; population?: Population[]; measureScore?: Score; component?: { code?: Concept; value?: Concept }[] }
|
|
interface Stratifier { code?: Concept[] | Concept }
|
|
interface ReportStratifier { code?: Concept[]; stratum?: Stratum[] }
|
|
interface Group { code?: Concept; population?: Population[]; measureScore?: Score; stratifier?: (Stratifier & ReportStratifier)[] }
|
|
export interface Measure extends Resource {
|
|
url?: string; version?: string; name?: string; title?: string; description?: string;
|
|
scoring?: Concept; subjectCodeableConcept?: Concept; improvementNotation?: Concept; group?: Group[];
|
|
relatedArtifact?: { type?: string; display?: string; citation?: string }[];
|
|
}
|
|
export interface Report extends Resource {
|
|
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
|
|
}
|
|
interface Categoria { etiqueta: string; color: string | null; grupo: null }
|
|
|
|
const MAX_COUNT = 200;
|
|
const POPULATION_GROUP: Record<string, string> = {
|
|
'initial-population': 'poblacion', denominator: 'denominador', numerator: 'numerador',
|
|
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
|
|
};
|
|
|
|
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
|
|
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
|
|
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
|
|
// Age groups travel as `16_23`; the page names them `16-23`.
|
|
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
|
|
|
|
function count(populations: Population[] | undefined, name: string): number | null {
|
|
const found = populations?.find(p => code(p.code) === name);
|
|
return found && Number.isSafeInteger(found.count) ? found.count! : null;
|
|
}
|
|
function decimal(score: Score | undefined, name: string): number | null {
|
|
const value = extension(score, name)?.valueDecimal;
|
|
return typeof value === 'number' ? value : null;
|
|
}
|
|
const round1 = (value: number) => Math.round(value * 10) / 10;
|
|
|
|
export function categorias(measure: Measure): Record<string, Categoria> {
|
|
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
|
|
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
|
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
|
|
}));
|
|
}
|
|
function contrato(measure: Measure): string {
|
|
return extension(measure, 'contrato')?.valueCode ?? '';
|
|
}
|
|
// The strata a measure can be broken down by. A C2's first stratifier holds its categories, not a stratum.
|
|
function estratos(measure: Measure): string[] {
|
|
const all = (measure.group?.[0]?.stratifier ?? []).map(stratifierCode).filter((c): c is string => !!c);
|
|
return contrato(measure) === 'C2' ? all.slice(1) : all;
|
|
}
|
|
|
|
export function indicadorDeMeasure(measure: Measure): Indicador & Record<string, unknown> {
|
|
const notation = code(measure.improvementNotation);
|
|
const vistas = extensions(measure, 'vistas').map(e => e.valueCode).filter((v): v is string => !!v);
|
|
return {
|
|
id: indicadorId(measure.id ?? ''),
|
|
version: measure.version,
|
|
titulo: measure.title ?? measure.name ?? measure.id ?? '',
|
|
contrato: contrato(measure),
|
|
figuras: extensions(measure, 'figuras').map(e => e.valueString).filter((f): f is string => !!f),
|
|
tipos_periodo: extensions(measure, 'tipos-periodo').map(e => e.valueCode).filter((t): t is TipoPeriodo => t === 'semestre' || t === 'mes'),
|
|
unidad: code(measure.subjectCodeableConcept) ?? null,
|
|
sentido: notation === 'increase' ? 'mayor_mejor' : notation === 'decrease' ? 'menor_mejor' : null,
|
|
estratos: estratos(measure),
|
|
filtros: [],
|
|
...(vistas.length ? { vistas } : {}),
|
|
};
|
|
}
|
|
|
|
const FICHA_FIELDS = ['codigo', 'para', 'unidad', 'pregunta', 'definicion', 'nota'] as const;
|
|
|
|
// The technical sheet: the measure's `ficha` extension when it has one, and without it its code, unit and description.
|
|
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
|
|
const unidad = code(measure.subjectCodeableConcept) ?? null;
|
|
const sheet = extensions(measure, 'ficha')[0];
|
|
const written = Object.fromEntries(FICHA_FIELDS.flatMap(f => {
|
|
const value = extension(sheet, f)?.valueString;
|
|
return value ? [[f, value]] : [];
|
|
}));
|
|
return {
|
|
id: indicadorId(measure.id ?? ''),
|
|
version: measure.version,
|
|
descripcion: measure.description ?? null,
|
|
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null, ...written },
|
|
unidad,
|
|
referencias: (measure.relatedArtifact ?? []).filter(a => !!a.display)
|
|
.map(a => ({ tipo: a.type ?? 'citation', etiqueta: a.display!, ref: a.citation ?? null })),
|
|
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
|
|
grupo: POPULATION_GROUP[code(p.code) ?? ''] ?? code(p.code) ?? '',
|
|
codigo: p.criteria?.expression ?? code(p.code) ?? '',
|
|
descripcion: p.description ?? '',
|
|
})),
|
|
figuras_detalle: extensions(measure, 'figura-detalle').flatMap(e => {
|
|
const figura = extension(e, 'figura')?.valueString;
|
|
return figura ? [{
|
|
figura, descripcion: extension(e, 'descripcion')?.valueString ?? null,
|
|
como_leer: extensions(e, 'como-leer').map(l => l.valueString).filter((l): l is string => !!l),
|
|
}] : [];
|
|
}),
|
|
categorias: categorias(measure),
|
|
};
|
|
}
|
|
|
|
// FHIR's period end is inclusive; the page's `periodo_fin`, like `dim_periodo`, is the next day.
|
|
function nextDay(day: string): string {
|
|
const date = new Date(day + 'T00:00:00Z');
|
|
date.setUTCDate(date.getUTCDate() + 1);
|
|
return date.toISOString().slice(0, 10);
|
|
}
|
|
function reporte(report: Report, periodo: string) {
|
|
const knowledge = extension(report, 'corte-conocimiento')?.valueDateTime;
|
|
return {
|
|
periodo,
|
|
report_id: extension(report, 'reporte-id')?.valueInteger ?? null,
|
|
periodo_inicio: report.period?.start ?? null,
|
|
periodo_fin: report.period ? nextDay(report.period.end) : null,
|
|
fecha_corte: extension(report, 'corte-evento')?.valueDate ?? knowledge?.slice(0, 10) ?? null,
|
|
generado_en: report.date ?? null,
|
|
};
|
|
}
|
|
|
|
function proporcion(populations: Population[] | undefined, score: Score | undefined) {
|
|
const numerador = count(populations, 'numerator'), denominador = count(populations, 'denominator');
|
|
return {
|
|
suprimido: 0, numerador, denominador,
|
|
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
|
|
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
|
|
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
|
|
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
|
|
};
|
|
}
|
|
function duracion(populations: Population[] | undefined, score: Score | undefined) {
|
|
return {
|
|
suprimido: 0,
|
|
n: count(populations, 'measure-observation') ?? 0,
|
|
mediana: typeof score?.value === 'number' ? score.value : null,
|
|
q1: decimal(score, 'q1'), q3: decimal(score, 'q3'),
|
|
// The units without a value at the cut-off: FHIR's population exclusion.
|
|
n_sin_evento: count(populations, 'measure-population-exclusion') ?? 0,
|
|
n_excluido: 0,
|
|
unidad: 'dias',
|
|
};
|
|
}
|
|
function stratumValue(stratum: Stratum): string | undefined {
|
|
const value = code(stratum.value);
|
|
return value === undefined ? undefined : estratoValor(value);
|
|
}
|
|
|
|
// The `/datos` answer for `measure`, from one report per period.
|
|
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
|
|
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
|
|
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
|
|
const id = code(g.code) ?? 'TOTAL';
|
|
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
|
|
}));
|
|
const valores = new Map<string, string>();
|
|
const filas: Record<string, unknown>[] = [];
|
|
const periodos: string[] = [];
|
|
for (const report of reports) {
|
|
if (!report.period) continue;
|
|
const periodo = periodLabel(report.period);
|
|
periodos.push(periodo);
|
|
for (const group of report.group ?? []) {
|
|
const grupo = code(group.code) ?? 'TOTAL';
|
|
if (kind === 'C2') {
|
|
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
|
Object.keys(cats).forEach((categoria, orden) =>
|
|
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
|
|
continue;
|
|
}
|
|
const row = (populations: Population[] | undefined, score: Score | undefined) =>
|
|
kind === 'C3r' ? duracion(populations, score) : proporcion(populations, score);
|
|
if (!estrato) {
|
|
filas.push({ periodo, grupo, estrato: null, ...row(group.population, group.measureScore) });
|
|
continue;
|
|
}
|
|
const stratifier = group.stratifier?.find(s => code(s.code?.[0]) === estrato);
|
|
if (!stratifier) throw new Error('Dimensión no admitida');
|
|
for (const stratum of stratifier.stratum ?? []) {
|
|
const valor = stratumValue(stratum);
|
|
// A stratum nobody falls in, like an empty «Sin dato», isn't a bar of its own.
|
|
if (!valor || !(stratum.population ?? []).some(p => (p.count ?? 0) > 0) && valor === 'sin_dato') continue;
|
|
valores.set(valor, display(stratum.value) ?? valor);
|
|
filas.push({ periodo, grupo, estrato: valor, ...row(stratum.population, stratum.measureScore) });
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
id: indicadorId(measure.id ?? ''),
|
|
titulo: measure.title ?? measure.name ?? '',
|
|
version: measure.version,
|
|
contrato: kind,
|
|
unidad: code(measure.subjectCodeableConcept) ?? '',
|
|
tipo_periodo: tipo,
|
|
periodos,
|
|
estrato: estrato ?? null,
|
|
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
|
|
grupos,
|
|
categorias: cats,
|
|
grupos_de_categoria: {},
|
|
notas: [],
|
|
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
|
filas,
|
|
};
|
|
}
|
|
|
|
// One box per period, from each period's median and quartiles.
|
|
export function cajaDeDatos(datos: IndicadorDatos): PlotlyFigure {
|
|
const filas = datos.filas.filter(f => f['grupo'] === 'TOTAL' && f['estrato'] == null && typeof f['mediana'] === 'number');
|
|
const values = (field: string) => filas.map(f => f[field]);
|
|
return {
|
|
data: filas.length ? [{ type: 'box', name: 'Total', x: values('periodo'), q1: values('q1'), median: values('mediana'), q3: values('q3'),
|
|
lowerfence: values('q1'), upperfence: values('q3') }] : [],
|
|
layout: { title: { text: String(datos['titulo'] ?? '') }, autosize: true, margin: { l: 60, r: 24, t: 60, b: 60 },
|
|
yaxis: { title: { text: 'días' }, rangemode: 'tozero' } },
|
|
};
|
|
}
|
|
|
|
function tipoDe(periodo: string): TipoPeriodo {
|
|
return periodo.includes('-S') ? 'semestre' : 'mes';
|
|
}
|
|
// The `count` periods of `tipo` from the one starting on `start`, in order.
|
|
export function periodosDesde(start: string, tipo: TipoPeriodo, total: number): string[] {
|
|
const [year, month] = start.split('-').map(Number);
|
|
return Array.from({ length: total }, (_, i) => {
|
|
if (tipo === 'semestre') {
|
|
const n = (year * 2 + (month >= 7 ? 1 : 0)) + i;
|
|
return `${Math.floor(n / 2)}-S${n % 2 + 1}`;
|
|
}
|
|
const n = year * 12 + month - 1 + i;
|
|
return `${Math.floor(n / 12)}-${String(n % 12 + 1).padStart(2, '0')}`;
|
|
});
|
|
}
|
|
// A period that hasn't started by `today` has no data to show.
|
|
export function periodoIniciado(periodo: string, today: Date): boolean {
|
|
const current = periodOrder(tipoDe(periodo) === 'semestre'
|
|
? `${today.getFullYear()}-S${today.getMonth() < 6 ? 1 : 2}`
|
|
: `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}`);
|
|
return periodOrder(periodo) <= current;
|
|
}
|
|
|
|
@Injectable({ providedIn: 'root' })
|
|
export class FhirMeasures {
|
|
private readonly http = inject(HttpClient);
|
|
private readonly cache = new Map<Dominio, Observable<Measure[]>>();
|
|
all(dominio: Dominio): Observable<Measure[]> {
|
|
const domain = requireDominio(dominio);
|
|
let request = this.cache.get(domain);
|
|
if (!request) {
|
|
request = this.http.get<Bundle>(`/${domain}/fhir/Measure`).pipe(
|
|
map(bundle => resources(bundle, 'Measure') as Measure[]), shareReplay({ bufferSize: 1, refCount: false }));
|
|
this.cache.set(domain, request);
|
|
}
|
|
return request;
|
|
}
|
|
one(dominio: Dominio, indicador: string): Observable<Measure> {
|
|
return this.all(dominio).pipe(map(measures => {
|
|
const found = measures.find(m => indicadorId(m.id ?? '') === indicador);
|
|
if (!found) throw new Error('Indicador no publicado');
|
|
return found;
|
|
}));
|
|
}
|
|
reports(dominio: Dominio, measure: Measure, params: HttpParams): Observable<Bundle> {
|
|
return this.http.get<Bundle>(`/${requireDominio(dominio)}/fhir/MeasureReport`, { params: params.set('measure', measure.url ?? measure.id ?? '') });
|
|
}
|
|
}
|
|
|
|
@Injectable()
|
|
export class FhirIndicadoresService extends IndicadoresService {
|
|
private readonly measures = inject(FhirMeasures);
|
|
override catalogo(dominio: Dominio = 'tea') {
|
|
return this.measures.all(dominio).pipe(map(all => catalogoValido(all.map(indicadorDeMeasure))));
|
|
}
|
|
override metadatos(dominio: Dominio, indicador: string) {
|
|
return this.measures.one(dominio, indicador).pipe(map(m => metadatosValidos(metadatosDeMeasure(m))));
|
|
}
|
|
override datos(dominio: Dominio, indicador: string, tipo: TipoPeriodo, periodos?: string[], scope: DatosScope = {}) {
|
|
datosParams(tipo, periodos, scope);
|
|
if (scope.filtros?.length) throw new Error('Filtro no admitido');
|
|
let params = new HttpParams().set('_count', MAX_COUNT);
|
|
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
|
|
return this.measures.one(dominio, indicador).pipe(
|
|
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
|
|
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
|
|
}
|
|
override figura(selection: FigureSelection) {
|
|
const dominio = requireDominio(selection.dominio ?? 'tea');
|
|
const periodos = figuraPeriodos(selection);
|
|
if (selection.figura !== 'fig_c3r_caja') throw new Error('Figura no disponible');
|
|
const tipo = selection.tipoPeriodo ?? (periodos ? tipoDe(periodos[0]) : 'semestre');
|
|
return this.datos(dominio, selection.indicador, tipo, periodos).pipe(map(datos => figuraValida(cajaDeDatos(datos))));
|
|
}
|
|
}
|
|
|
|
// Every measure of a domain shares its periods (`dim_periodo`, whole years); one report of each type gives the first
|
|
// period and the search's total how many follow.
|
|
@Injectable()
|
|
export class FhirIndicadoresPeriodos extends IndicadoresPeriodos {
|
|
private readonly measures = inject(FhirMeasures);
|
|
private readonly queue = inject(IndicadoresRequests);
|
|
private readonly byDomain = new Map<Dominio, Observable<AvailablePeriod[]>>();
|
|
today = () => new Date();
|
|
override periodos(domain: Dominio, id: string): Observable<AvailablePeriod[]> {
|
|
const dominio = requireDominio(domain);
|
|
let request = this.byDomain.get(dominio);
|
|
if (!request) {
|
|
request = this.measures.one(dominio, id).pipe(
|
|
switchMap(measure => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'semestre').set('_count', 1))).pipe(
|
|
switchMap(semestres => this.queue.run(() => this.measures.reports(dominio, measure, new HttpParams().set('tipo-periodo', 'mes').set('_count', 1))).pipe(
|
|
map(meses => [...this.listed(semestres, 'semestre'), ...this.listed(meses, 'mes')]
|
|
.sort((a, b) => periodOrder(b.periodo) - periodOrder(a.periodo))))))),
|
|
shareReplay({ bufferSize: 1, refCount: false }));
|
|
this.byDomain.set(dominio, request);
|
|
}
|
|
return request;
|
|
}
|
|
private listed(bundle: Bundle, tipo: TipoPeriodo): AvailablePeriod[] {
|
|
const first = (resources(bundle, 'MeasureReport')[0] as Report | undefined)?.period;
|
|
if (!first || !bundle.total) return [];
|
|
const today = this.today();
|
|
return periodosDesde(first.start, tipo, bundle.total).filter(p => periodoIniciado(p, today)).map(periodo => ({ periodo, tipo }));
|
|
}
|
|
}
|