feat(indicadores): read CaCu category groups and stratified compositions from FHIR
This commit is contained in:
@@ -48,6 +48,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#9DBFE3"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "NO_ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -65,6 +69,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#E8C28E"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "NO_ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -82,6 +90,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#D98E4A"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -99,6 +111,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#B55A1F"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -116,6 +132,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#7A2E0E"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -150,9 +170,52 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#C9CDD2"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "SIN_DATO"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "NO_ANORMAL"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "Menor que LIEAG"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "ANORMAL"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "LIEAG o más"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "SIN_DATO"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "Biopsia sin grado"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-CONFIRMACION-CITOLOGIA",
|
||||
@@ -636,6 +699,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#9DBFE3"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "NO_ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -653,6 +720,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#2F6DB3"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -670,6 +741,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#E8C28E"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -687,6 +762,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#D98E4A"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -704,6 +783,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#B55A1F"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -721,6 +804,10 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#7A2E0E"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "ANORMAL"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
@@ -738,9 +825,52 @@
|
||||
{
|
||||
"url": "color",
|
||||
"valueString": "#C9CDD2"
|
||||
},
|
||||
{
|
||||
"url": "grupo",
|
||||
"valueCode": "SIN_DATO"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "NO_ANORMAL"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "Sin anomalía"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "ANORMAL"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "Anormal"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
},
|
||||
{
|
||||
"extension": [
|
||||
{
|
||||
"url": "codigo",
|
||||
"valueCode": "SIN_DATO"
|
||||
},
|
||||
{
|
||||
"url": "etiqueta",
|
||||
"valueString": "Sin dato"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/StructureDefinition/categoria-grupo"
|
||||
}
|
||||
],
|
||||
"url": "https://isssteleon.org/fhir/Measure/CACU-EU7",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -80,44 +80,7 @@
|
||||
"filas": []
|
||||
},
|
||||
"citologia_alto_grado": {
|
||||
"id": "cacu_confirmacion_citologia",
|
||||
"titulo": "Tasa de confirmación histopatológica",
|
||||
"version": "0.1.2",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "citologia_alto_grado",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 35,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:24.181623+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 44,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:24.682752+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -733,84 +696,10 @@
|
||||
"filas": []
|
||||
},
|
||||
"grupo_edad": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "grupo_edad",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 83,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 92,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
},
|
||||
"estatus_seguimiento": {
|
||||
"id": "cacu_eu7",
|
||||
"titulo": "Distribución de resultados citológicos",
|
||||
"version": "0.3.3",
|
||||
"contrato": "C2",
|
||||
"unidad": "paciente",
|
||||
"tipo_periodo": "semestre",
|
||||
"periodos": [
|
||||
"2021-S1",
|
||||
"2025-S2"
|
||||
],
|
||||
"estrato": "estatus_seguimiento",
|
||||
"valores_estrato": [],
|
||||
"etiquetas_estrato": {},
|
||||
"grupos": {
|
||||
"TOTAL": "Total"
|
||||
},
|
||||
"categorias": {},
|
||||
"grupos_de_categoria": {},
|
||||
"notas": [],
|
||||
"reportes": [
|
||||
{
|
||||
"periodo": "2021-S1",
|
||||
"report_id": 83,
|
||||
"periodo_inicio": "2021-01-01",
|
||||
"periodo_fin": "2021-07-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:29.557925+00:00"
|
||||
},
|
||||
{
|
||||
"periodo": "2025-S2",
|
||||
"report_id": 92,
|
||||
"periodo_inicio": "2025-07-01",
|
||||
"periodo_fin": "2026-01-01",
|
||||
"fecha_corte": "2026-11-16",
|
||||
"generado_en": "2026-11-16T23:08:31.081202+00:00"
|
||||
}
|
||||
],
|
||||
"filas": []
|
||||
"error": "Categoría no declarada en el estrato"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
|
||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||
import { httpMessage } from './indicadores-http';
|
||||
import { percentText } from './indicadores-format';
|
||||
import { stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
|
||||
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
|
||||
|
||||
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
|
||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|
||||
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|
||||
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|
||||
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|
||||
|| !compatibility.compatible) {
|
||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
|
||||
this.status.set('incompatible'); return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
|
||||
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
|
||||
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
|
||||
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
|
||||
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
|
||||
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
|
||||
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
|
||||
import { Bundle, resources } from './fhir';
|
||||
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
|
||||
import { barras, dona, modelo } from './indicadores-eu7-escenario';
|
||||
import { modeloConfirmacion } from './indicadores-confirmacion-citologia';
|
||||
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
|
||||
import { IndicadorDatos } from './indicadores.models';
|
||||
import measuresData from './fixtures/cacu_fhir_measures.json';
|
||||
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
|
||||
import camaData from './fixtures/cama_fhir_measures.json';
|
||||
|
||||
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
||||
const measure = (id: string) => measures.find(m => m.id === id)!;
|
||||
const answers = reportsData as unknown as Record<string, Bundle>;
|
||||
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
|
||||
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
|
||||
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
|
||||
type Fila = Record<string, unknown>;
|
||||
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
|
||||
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
|
||||
|
||||
describe('Grupos de categoría publicados por la Measure', () => {
|
||||
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
|
||||
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
|
||||
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
|
||||
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
|
||||
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
|
||||
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
|
||||
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
|
||||
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
|
||||
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
|
||||
});
|
||||
|
||||
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
|
||||
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
|
||||
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const m of cama) {
|
||||
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
|
||||
expect(gruposDeCategoria(m), m.id).toEqual({});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Composiciones por estrato desde el estratificador cruzado', () => {
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
|
||||
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
|
||||
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
|
||||
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
|
||||
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
|
||||
const valores = porEstatus['valores_estrato'] as string[];
|
||||
expect(valores.length).toBeGreaterThan(0);
|
||||
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
|
||||
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
|
||||
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
|
||||
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
|
||||
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
|
||||
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
|
||||
});
|
||||
|
||||
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
|
||||
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
|
||||
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
|
||||
const totales = porEstatus['totales_estrato'] as { n: number }[];
|
||||
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
for (const categoria of Object.keys(general['categorias'] as object)) {
|
||||
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
|
||||
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
|
||||
}
|
||||
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
|
||||
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
|
||||
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
|
||||
});
|
||||
|
||||
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
|
||||
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
|
||||
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
|
||||
// of them is silently turned into a zero.
|
||||
const sinCelda = clone(reports('eu7_2025S2'));
|
||||
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
|
||||
cruzado.stratum.shift();
|
||||
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
|
||||
const ajena = clone(reports('eu7_2025S2'));
|
||||
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
|
||||
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
|
||||
celda.component[1].value.coding[0].code = 'GLANDULAR';
|
||||
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Categoría no declarada en el estrato');
|
||||
const sinCruce = clone(reports('eu7_2025S2'));
|
||||
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
||||
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
|
||||
.toThrowError('Dimensión no admitida');
|
||||
});
|
||||
|
||||
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
|
||||
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
|
||||
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
|
||||
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
|
||||
expect(vacio.periodos).toEqual(['2021-S1']);
|
||||
expect(vacio.filas).toEqual([]);
|
||||
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
|
||||
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Vistas propias de CaCu con los datos de FHIR', () => {
|
||||
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
|
||||
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
|
||||
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
|
||||
// falls back to «incompatible» with the data FHIR publishes.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
|
||||
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
|
||||
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
|
||||
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
|
||||
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
|
||||
// «incompatible», or if a real mismatch is hidden as empty.
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
const m = modelo(general, escenarios, '2021-S1');
|
||||
expect(m.vacio).toBe(true);
|
||||
expect(m.escenarios).toEqual([]);
|
||||
const conPacientes = clone(general);
|
||||
conPacientes.filas[0]['n'] = 3;
|
||||
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
|
||||
});
|
||||
|
||||
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
|
||||
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
|
||||
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
|
||||
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
|
||||
// report, or accepts two anonymous answers generated apart.
|
||||
const segunda = clone(reports('eu7_2025S2'));
|
||||
segunda[0].date = '2099-01-01T00:00:00Z';
|
||||
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
|
||||
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
|
||||
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
|
||||
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
|
||||
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
|
||||
});
|
||||
|
||||
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
|
||||
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
|
||||
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
|
||||
// apart. Fails if the view can't read FHIR's groups or strata.
|
||||
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
||||
const m = modeloConfirmacion(datos, '2025-S2');
|
||||
expect(m.vacio).toBe(false);
|
||||
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
|
||||
expect(m.base).toBe('ANORMAL');
|
||||
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
||||
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
|
||||
});
|
||||
|
||||
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
|
||||
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
|
||||
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
|
||||
// or if filters appear for compositions that never had them.
|
||||
const eu7 = indicadorDeMeasure(measure(EU7));
|
||||
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
|
||||
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
|
||||
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
|
||||
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -119,8 +119,12 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return active[0];
|
||||
};
|
||||
const rg = reporte(general), re = reporte(porEscenario);
|
||||
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
|
||||
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
// With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
|
||||
// `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
|
||||
// Without ids, the generation time is still part of the provenance.
|
||||
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
|
||||
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
|
||||
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
|
||||
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
|
||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
||||
// list of missing categories; a partial distribution is never drawn as a donut.
|
||||
@@ -145,17 +149,20 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
||||
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
|
||||
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
|
||||
});
|
||||
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
|
||||
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
|
||||
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
|
||||
// Compare only fully published sums. Never derive a hidden value by subtraction.
|
||||
if (escenarios.length) {
|
||||
for (const c of cats) {
|
||||
const total = suma(escenarios.map(s => s.celdas[c.id]));
|
||||
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
|
||||
}
|
||||
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
} else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
|
||||
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
|
||||
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
|
||||
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
|
||||
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
|
||||
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
|
||||
}
|
||||
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
|
||||
|
||||
@@ -57,10 +57,21 @@ function decimal(score: Score | undefined, name: string): number | null {
|
||||
}
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10;
|
||||
|
||||
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
|
||||
// keeps every category ungrouped.
|
||||
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 }]] : [];
|
||||
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
|
||||
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
|
||||
}));
|
||||
}
|
||||
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
|
||||
// when the Measure declares none.
|
||||
export function gruposDeCategoria(measure: Measure): Record<string, string> {
|
||||
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
|
||||
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
|
||||
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
|
||||
}));
|
||||
}
|
||||
function contrato(measure: Measure): string {
|
||||
@@ -194,6 +205,34 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
|
||||
return celdas;
|
||||
}
|
||||
|
||||
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
|
||||
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
|
||||
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
|
||||
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
|
||||
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
|
||||
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
|
||||
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
|
||||
const unidades = count(group.population, 'initial-population');
|
||||
const valores = new Map<string, string>(), celdas = new Map<string, number>();
|
||||
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
|
||||
if (!stratifier && unidades === 0) return { valores, celdas };
|
||||
if (!stratifier) throw new Error('Dimensión no admitida');
|
||||
let suma = 0;
|
||||
for (const stratum of stratifier.stratum ?? []) {
|
||||
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
|
||||
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
|
||||
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
|
||||
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
|
||||
const e = estratoValor(valor), clave = `${e}|${categoria}`;
|
||||
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
|
||||
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
|
||||
celdas.set(clave, n);
|
||||
suma += n;
|
||||
}
|
||||
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
|
||||
return { valores, celdas };
|
||||
}
|
||||
|
||||
// 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), estrato = scope.estrato, cama = esMedidaCama(measure.id);
|
||||
@@ -201,6 +240,8 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
|
||||
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
|
||||
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
|
||||
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
|
||||
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
|
||||
const cats: Record<string, Categoria> = cruzado
|
||||
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
|
||||
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
|
||||
@@ -242,6 +283,21 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (porEstrato) {
|
||||
const declaradasEnOrden = Object.keys(cats);
|
||||
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
|
||||
for (const [e, etiqueta] of delPeriodo) {
|
||||
let total = 0;
|
||||
declaradasEnOrden.forEach((categoria, orden) => {
|
||||
const n = celdas.get(`${e}|${categoria}`) ?? 0;
|
||||
total += n;
|
||||
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
|
||||
});
|
||||
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
|
||||
if (!valores.has(e)) valores.set(e, etiqueta);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (kind === 'C2') {
|
||||
const strata = group.stratifier?.[0]?.stratum ?? [];
|
||||
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
|
||||
@@ -281,10 +337,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
|
||||
periodos,
|
||||
estrato: estrato ?? null,
|
||||
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
|
||||
...(cruzado ? { totales_estrato: totales } : {}),
|
||||
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
|
||||
grupos,
|
||||
categorias: cats,
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
|
||||
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
|
||||
notas: [],
|
||||
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
|
||||
filas,
|
||||
|
||||
@@ -10,6 +10,13 @@ export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
|
||||
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
|
||||
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
|
||||
}
|
||||
// Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata
|
||||
// (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status);
|
||||
// it doesn't turn on stratified figures or filters for other C2 measures.
|
||||
export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean {
|
||||
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
|
||||
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
|
||||
}
|
||||
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
|
||||
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
|
||||
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
|
||||
|
||||
Reference in New Issue
Block a user