Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 62cdb252ca | |||
| 8f2906fe6f | |||
| e8628508d8 |
@@ -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}`,
|
||||
|
||||
+85
@@ -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'); },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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' } },
|
||||
};
|
||||
}
|
||||
@@ -79,7 +79,7 @@
|
||||
</mat-card>
|
||||
<mat-card class="risks-card" appearance="outlined" aria-labelledby="riesgos-title">
|
||||
<mat-card-header><h3 id="riesgos-title">Riesgos y recomendaciones</h3></mat-card-header>
|
||||
<mat-card-content><app-paciente-riesgo-tabla [idSeudonimo]="estado.resumen.id_seudonimo" /></mat-card-content>
|
||||
<mat-card-content><app-paciente-riesgo-tabla /></mat-card-content>
|
||||
</mat-card>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -108,8 +108,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
let root: HTMLElement;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
fixture = TestBed.createComponent(IndicadoresTracking);
|
||||
root = fixture.nativeElement;
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
@@ -248,7 +247,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => {
|
||||
expect(tarjeta.textContent).toContain('Información simulada');
|
||||
expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3);
|
||||
expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith(pacientes[0].id_seudonimo);
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith();
|
||||
volver();
|
||||
const otra = abrir(1);
|
||||
expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
|
||||
@@ -7,13 +7,12 @@ import { MatSelectHarness } from '@angular/material/select/testing';
|
||||
import { MatInputHarness } from '@angular/material/input/testing';
|
||||
import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing';
|
||||
import { MatDialog } from '@angular/material/dialog';
|
||||
import { firstValueFrom, of } from 'rxjs';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import fixtureData from '../fixtures/cacu_seguimiento.json';
|
||||
import { seguimientoResponse } from '../cacu-seguimiento.service';
|
||||
import { IndicadoresTracking } from '../indicadores-tracking';
|
||||
import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures';
|
||||
import { PacienteDetalleState } from './paciente-detalle.state';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { PacienteRegistroDialog } from './paciente-registro-dialog';
|
||||
import { PacienteRegistrosSesion } from './paciente-registros-sesion';
|
||||
import { TipoRegistroTemporal } from './paciente-registro.models';
|
||||
@@ -32,8 +31,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => {
|
||||
let dialog: MatDialog;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
{ provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] });
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
|
||||
http = TestBed.inject(HttpTestingController);
|
||||
dialog = TestBed.inject(MatDialog);
|
||||
montarTracking();
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
@case ('cargando') { <p role="status">Cargando riesgo individual…</p> }
|
||||
@case ('no-disponible') {
|
||||
<p role="status">Riesgo individual no disponible para esta paciente.</p>
|
||||
<p class="availability">La consulta de riesgo individual aún no está habilitada.</p>
|
||||
}
|
||||
@case ('error') { <p role="alert">No se pudo validar o cargar el riesgo individual.</p> }
|
||||
@case ('disponible') {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Component, effect, inject, input } from '@angular/core';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { DecimalPipe } from '@angular/common';
|
||||
import { PacienteRiesgoState } from './paciente-riesgo.state';
|
||||
import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
@@ -11,12 +11,6 @@ import { tieneIntervalo } from './paciente-riesgo.validation';
|
||||
styleUrl: './paciente-riesgo-tabla.scss',
|
||||
})
|
||||
export class PacienteRiesgoTabla {
|
||||
readonly idSeudonimo = input.required<string>();
|
||||
private readonly state = inject(PacienteRiesgoState);
|
||||
readonly estado = this.state.estado;
|
||||
readonly estado = inject(PacienteRiesgoState).estado;
|
||||
readonly tieneIntervalo = tieneIntervalo;
|
||||
|
||||
constructor() {
|
||||
effect(() => this.state.idSeudonimo.set(this.idSeudonimo()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu {
|
||||
riesgo: LoteRiesgoCacu | null;
|
||||
}
|
||||
|
||||
/** `null` when the patient has no risk data. */
|
||||
/** Deliberately no patient argument until secure identity resolution is authorized. */
|
||||
export interface PacienteRiesgoProvider {
|
||||
obtener(idSeudonimo: string): Observable<unknown>;
|
||||
obtener(): Observable<unknown>;
|
||||
}
|
||||
|
||||
export type PacienteRiesgoEstado =
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { inject, InjectionToken } from '@angular/core';
|
||||
import { catchError, of, throwError } from 'rxjs';
|
||||
import { InjectionToken } from '@angular/core';
|
||||
import { of } from 'rxjs';
|
||||
import { PacienteRiesgoProvider } from './paciente-riesgo.models';
|
||||
|
||||
// The follow-up list identifies each patient by the `pac_id` of the risk batches; a 404 is a patient without risk data.
|
||||
// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization.
|
||||
export const PACIENTE_RIESGO_PROVIDER = new InjectionToken<PacienteRiesgoProvider>('PacienteRiesgoProvider', {
|
||||
providedIn: 'root', factory: () => {
|
||||
const http = inject(HttpClient);
|
||||
return {
|
||||
obtener: (idSeudonimo: string) => http.get<unknown>(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe(
|
||||
catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)),
|
||||
),
|
||||
};
|
||||
},
|
||||
providedIn: 'root', factory: () => ({ obtener: () => of(null) }),
|
||||
});
|
||||
|
||||
@@ -12,8 +12,6 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(),
|
||||
...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] });
|
||||
const fixture = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
fixture.componentRef.setInput('idSeudonimo', '42');
|
||||
fixture.detectChanges();
|
||||
fixture.detectChanges();
|
||||
return fixture;
|
||||
}
|
||||
@@ -22,15 +20,14 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
TestBed.inject(HttpTestingController).verify();
|
||||
});
|
||||
|
||||
it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => {
|
||||
it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => {
|
||||
const f = setup(), root: HTMLElement = f.nativeElement;
|
||||
TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo')
|
||||
.flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' });
|
||||
f.detectChanges();
|
||||
expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.');
|
||||
expect(root.textContent).toContain('aún no está habilitada');
|
||||
expect(root.textContent).toContain('Recomendaciones no disponibles');
|
||||
expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/);
|
||||
expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0);
|
||||
TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull());
|
||||
});
|
||||
|
||||
it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => {
|
||||
@@ -38,7 +35,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
data.riesgo!.horizontes[1].estado = 'preliminary';
|
||||
const baseline = structuredClone(data);
|
||||
const f = setup({ obtener }), root: HTMLElement = f.nativeElement;
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith('42');
|
||||
expect(obtener).toHaveBeenCalledExactlyOnceWith();
|
||||
expect(root.querySelectorAll('thead th')).toHaveLength(4);
|
||||
expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true);
|
||||
expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3);
|
||||
@@ -137,8 +134,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => {
|
||||
data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges();
|
||||
expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %');
|
||||
f.destroy();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla);
|
||||
otra.componentRef.setInput('idSeudonimo', 'P-OTRA'); otra.detectChanges();
|
||||
const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges();
|
||||
expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual');
|
||||
expect(otra.nativeElement.querySelector('table')).toBeNull();
|
||||
expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08);
|
||||
|
||||
@@ -1,22 +1,16 @@
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of, startWith, switchMap } from 'rxjs';
|
||||
import { inject, Injectable } from '@angular/core';
|
||||
import { toSignal } from '@angular/core/rxjs-interop';
|
||||
import { catchError, defer, map, of } from 'rxjs';
|
||||
import { PacienteRiesgoEstado } from './paciente-riesgo.models';
|
||||
import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider';
|
||||
import { riesgoPacienteResponse } from './paciente-riesgo.validation';
|
||||
|
||||
const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' };
|
||||
|
||||
@Injectable()
|
||||
export class PacienteRiesgoState {
|
||||
private readonly provider = inject(PACIENTE_RIESGO_PROVIDER);
|
||||
readonly idSeudonimo = signal<string | null>(null);
|
||||
readonly estado = toSignal(toObservable(this.idSeudonimo).pipe(
|
||||
switchMap(id => id === null ? of(CARGANDO) : defer(() => this.provider.obtener(id)).pipe(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
startWith(CARGANDO),
|
||||
)),
|
||||
), { initialValue: CARGANDO });
|
||||
readonly estado = toSignal(defer(() => this.provider.obtener()).pipe(
|
||||
map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' }
|
||||
: { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }),
|
||||
catchError(() => of<PacienteRiesgoEstado>({ tipo: 'error' })),
|
||||
), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user