224 lines
17 KiB
TypeScript
224 lines
17 KiB
TypeScript
// 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 { donaConfirmacion, 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: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
|
|
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
|
|
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
|
|
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
|
|
// template goes back to indexing `customdata` or a sector loses its text.
|
|
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');
|
|
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
|
expect(anillos.length).toBe(2);
|
|
for (const anillo of anillos) {
|
|
expect(anillo['hovertemplate']).not.toContain('customdata');
|
|
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
|
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
|
}
|
|
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
|
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
|
expect(m.total).toBe(95);
|
|
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
|
|
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
|
|
});
|
|
|
|
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('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
|
|
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
|
|
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
|
|
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
|
|
// template goes back to indexing `customdata` or a sector loses its text.
|
|
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
|
|
const m = modeloConfirmacion(datos, '2025-S2');
|
|
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
|
|
expect(anillos.length).toBe(2);
|
|
for (const anillo of anillos) {
|
|
expect(anillo['hovertemplate']).not.toContain('customdata');
|
|
expect(anillo['hovertemplate']).toContain('%{hovertext}');
|
|
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
|
|
}
|
|
const exterior = anillos.find(t => t['name'] === 'categorias')!;
|
|
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
|
|
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
|
|
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
|
|
});
|
|
|
|
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([]);
|
|
});
|
|
});
|