47a0ab5f1b
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
243 lines
18 KiB
TypeScript
243 lines
18 KiB
TypeScript
// What this module covers: the three CaMa measures of L3 as the page reads them from FHIR: the detection rate (C1), the
|
|
// time from the mammogram's result to the diagnosis (C3r) and the histopathological result by BI-RADS (C2 stratified by
|
|
// BI-RADS): their ids, catalog entries, numerators and denominators, medians, the BI-RADS by result matrix, the periods
|
|
// with no data and the reports that don't add up.
|
|
// Fixtures: `fixtures/cama_fhir_measures.json` (the Measure bundle the WebApi serves from the current dbt definitions) and
|
|
// `fixtures/cama_fhir_l3_reportes.json` (real `GET /cama/fhir/MeasureReport` answers over a read-only copy of the data of
|
|
// the 18092 installation, with L3's views applied on the copy), cut to six semesters and three months. The semesters:
|
|
// 2021-S1 (no data), 2024-S2, 2025-S1, 2025-S2, 2026-S1 and 2026-S2 (the one the cut-off cuts).
|
|
import { Bundle, resources } from './fhir';
|
|
import { datosDeReportes, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
|
|
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
|
|
import { CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, kpiResult } from './indicadores-kpi';
|
|
import { GlobalApplied } from './indicadores-memory';
|
|
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
|
|
import { datosValidos } from './indicadores.service';
|
|
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
|
|
import { ESTRATOS_BIRADS, modeloHistopatologia, periodosHistopatologia, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
|
import measuresData from './fixtures/cama_fhir_measures.json';
|
|
import l3Data from './fixtures/cama_fhir_l3_reportes.json';
|
|
|
|
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
|
|
const answers = l3Data.reports as unknown as Record<string, { semestre: Bundle; mes: Bundle }>;
|
|
const TASA = 'CAMA-TASA-DETECCION-HISTOPATOLOGICA', DIAS = 'CAMA-DIAS-RESULTADO-DIAGNOSTICO', HISTO = 'CAMA-HISTOPATOLOGIA-BIRADS';
|
|
const measure = (fhirId: string) => measures.find(m => m.id === fhirId)!;
|
|
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start?: string) =>
|
|
(resources(answers[fhirId][tipo], 'MeasureReport') as Report[]).filter(r => !start || r.period?.start === start);
|
|
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
|
|
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
|
|
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', scope = {}): IndicadorDatos {
|
|
return datosDeReportes(measure(fhirId), reportsOf(fhirId, tipo, start), tipo, scope);
|
|
}
|
|
const SEMESTRES = [['2025-01-01', '2025-S1'], ['2025-07-01', '2025-S2'], ['2026-01-01', '2026-S1'], ['2026-07-01', '2026-S2']] as const;
|
|
const BIRADS_PACIENTES_2025_S2 = 36;
|
|
|
|
describe('Las tres medidas de L3 en el catálogo', () => {
|
|
it('cada una tiene su id de página, su contrato y su sentido', () => {
|
|
// Pins down: the explicit table names the three, none collides with another, and the catalog gives each its contract
|
|
// (a proportion, a duration with its box plot, a composition stratified by BI-RADS). Fails if a measure is published
|
|
// without a correspondence or its contract drifts.
|
|
expect(indicadorId(TASA)).toBe('cama_tasa_deteccion_histopatologica');
|
|
expect(indicadorId(DIAS)).toBe('cama_dias_resultado_diagnostico');
|
|
expect(indicadorId(HISTO)).toBe('cama_histopatologia_birads');
|
|
expect([TASA, DIAS, HISTO].every(id => Object.hasOwn(CAMA_MEASURE_IDS, id))).toBe(true);
|
|
const catalogo = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
|
|
expect(catalogo['cama_tasa_deteccion_histopatologica']).toMatchObject({ contrato: 'C1', figuras: [], unidad: 'examen', tipos_periodo: ['semestre', 'mes'] });
|
|
expect(catalogo['cama_dias_resultado_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
|
|
expect(catalogo['cama_histopatologia_birads']).toMatchObject({ contrato: 'C2', estratos: ['birads'], unidad: 'paciente' });
|
|
expect(new Set(measures.map(m => indicadorId(m.id!))).size).toBe(measures.length);
|
|
});
|
|
|
|
it('la ficha de cada una dice qué cuenta y qué no es', () => {
|
|
// Pins down: the description is the measure's definition: the detection rate is of biopsy reports and says it is not a
|
|
// rate over screened women nor the confirmation proportion; the time says its note isn't linked to the mammogram nor is
|
|
// the biopsy's date. Fails if the sheet is lost or reads like another indicator.
|
|
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/reporte de biopsia, no la\s+paciente/);
|
|
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/no es una tasa\s+sobre las mujeres tamizadas/);
|
|
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no está ligada a la mastografía/);
|
|
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no es la fecha de la biopsia/);
|
|
expect(metadatosDeMeasure(measure(HISTO)).descripcion).toMatch(/la misma regla de CAMA_BIRADS456_PACIENTE/);
|
|
const codigos = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
|
|
expect(new Set(codigos).size).toBe(measures.length);
|
|
expect(metadatosDeMeasure(measure(TASA)).ficha!.codigo).toBe('TASA-DETECCION-HISTOPATOLOGICA');
|
|
});
|
|
});
|
|
|
|
describe('Tasa de detección histopatológica (C1)', () => {
|
|
it.each([['2025-01-01', '2025-S1', 16, 24, 66.7], ['2025-07-01', '2025-S2', 14, 25, 56], ['2026-01-01', '2026-S1', 13, 18, 72.2], ['2026-07-01', '2026-S2', 10, 19, 52.6]] as const)(
|
|
'en %s el numerador y el denominador son los reportes de biopsia malignos y con resultado conocido', (inicio, periodo, numerador, denominador, valor) => {
|
|
// Pins down: each semester's rows carry the report counts (malignant over known result) and the percentage the card
|
|
// shows, in the page's group `total`, and the card reads «Disponible» with its sentence. Fails if a count is lost or
|
|
// the numerator leaves its denominator.
|
|
const d = datosValidos(datos(TASA, inicio, periodo), 'cama_tasa_deteccion_histopatologica', 'semestre', [periodo]);
|
|
expect(d['grupos']).toEqual({ total: 'Total' });
|
|
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
|
|
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
|
|
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
|
|
});
|
|
|
|
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
|
|
// Pins down: over the real periods, malignant ≤ known result, and the four semesters add up to 56 + ... = the reports
|
|
// (16+14+13+10 malignant of 24+25+18+19 with known result). Fails if a report is counted in two periods or one is dropped.
|
|
const filas = SEMESTRES.flatMap(([inicio, periodo]) => datos(TASA, inicio, periodo).filas);
|
|
expect(filas.every(f => (f['numerador'] as number) <= (f['denominador'] as number))).toBe(true);
|
|
expect(filas.reduce((s, f) => s + (f['numerador'] as number), 0)).toBe(53);
|
|
expect(filas.reduce((s, f) => s + (f['denominador'] as number), 0)).toBe(86);
|
|
});
|
|
|
|
it('un semestre sin reportes de biopsia no da una tasa: 0 de 0 es sin datos, no 0 %', () => {
|
|
// Pins down: 2021-S1 has no biopsy reports; the rows say 0 of 0 with no value and the card doesn't claim a rate.
|
|
// Fails if an empty period is shown as 0 % or as an error.
|
|
const d = datos(TASA, '2021-01-01', '2021-S1');
|
|
expect(d.filas).toEqual([expect.objectContaining({ numerador: 0, denominador: 0, valor: null })]);
|
|
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
|
|
});
|
|
});
|
|
|
|
describe('Tiempo de resultado a diagnóstico (C3r)', () => {
|
|
it.each([['2025-01-01', '2025-S1', 56, 41, 65], ['2025-07-01', '2025-S2', 59, 41, 49], ['2026-01-01', '2026-S1', 61, 21, 58], ['2026-07-01', '2026-S2', 18, 0, 40]] as const)(
|
|
'en %s mide las mastografías con nota diagnóstica y deja fuera, contadas, las que no la tienen', (inicio, periodo, n, sinEvento, mediana) => {
|
|
// Pins down: the observations (mammograms with a diagnosing note in the horizon), those without one and the median in
|
|
// days, as the report publishes them, with the card reading the median. Fails if an unmeasured mammogram is dropped
|
|
// without being counted or a median is read as zero.
|
|
const d = datosValidos(datos(DIAS, inicio, periodo), 'cama_dias_resultado_diagnostico', 'semestre', [periodo]);
|
|
expect(d.filas).toEqual([expect.objectContaining({ n, mediana, n_sin_evento: sinEvento, unidad: 'dias' })]);
|
|
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(periodo))).toMatchObject({ state: 'Disponible', value: mediana });
|
|
});
|
|
|
|
it('las mastografías del periodo son las observadas más las que no tienen nota', () => {
|
|
// Pins down: initial population = observations + exclusions in every real semester, so no mammogram is lost between
|
|
// the population and the box plot. Fails if the report's counts don't close.
|
|
for (const [inicio] of SEMESTRES) {
|
|
const grupo = reportsOf(DIAS, 'semestre', inicio)[0].group![0];
|
|
const n = (c: string) => grupo.population!.find(p => p.code?.coding?.[0].code === c)!.count!;
|
|
expect(n('measure-observation') + n('measure-population-exclusion'), inicio).toBe(n('initial-population'));
|
|
}
|
|
});
|
|
|
|
it('un semestre sin mastografías no da una mediana', () => {
|
|
// Pins down: with no observations the card has no value (a median over zero observations is no value, not zero days).
|
|
// Fails if an empty period reads as 0 days.
|
|
const d = datos(DIAS, '2021-01-01', '2021-S1');
|
|
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
|
|
});
|
|
});
|
|
|
|
describe('Resultado histopatológico por categoría BI-RADS (C2 por BI-RADS)', () => {
|
|
const matriz = (inicio: string, periodo: string, tipo: TipoPeriodo = 'semestre') =>
|
|
modeloHistopatologia(datosValidos(datos(HISTO, inicio, periodo, tipo, { estrato: 'birads' }), 'cama_histopatologia_birads', tipo, [periodo], { estrato: 'birads' }), periodo);
|
|
const celdas = (m: ReturnType<typeof matriz>) => Object.fromEntries(m.filas.map(f => [f.id,
|
|
{ ...Object.fromEntries(Object.entries(f.celdas).map(([k, c]) => [k, c.n])), ...Object.fromEntries(Object.entries(f.aparte).map(([k, c]) => [k, c.n])), total: f.total.n }]));
|
|
|
|
it('2025-S1: la matriz BI-RADS por resultado es la del reporte, con ceros publicados en las categorías sin pacientes', () => {
|
|
// Pins down: the cells of the real report (BI-RADS 4: 8 benign, 6 invasive, 6 without biopsy; BI-RADS 5: 6 invasive, 1 in
|
|
// situ, 3 without biopsy), every other stratum a published zero (never «No disponible»), each stratum's total the sum of
|
|
// its cells and the matrix the 30 patients of the period. Fails if a cell moves, a zero turns unavailable or a total drifts.
|
|
const m = matriz('2025-01-01', '2025-S1');
|
|
expect(m.filas.map(f => f.id)).toEqual([...ESTRATOS_BIRADS]);
|
|
expect(celdas(m)).toEqual({
|
|
BIRADS_4: { BENIGNO: 8, IN_SITU: 0, INVASOR: 6, SIN_BIOPSIA: 6, SIN_DATO: 0, total: 20 },
|
|
BIRADS_4A: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
|
BIRADS_4B: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
|
BIRADS_4C: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
|
BIRADS_5: { BENIGNO: 0, IN_SITU: 1, INVASOR: 6, SIN_BIOPSIA: 3, SIN_DATO: 0, total: 10 },
|
|
BIRADS_6: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
|
|
});
|
|
expect(m.filas.every(f => Object.values(f.celdas).every(c => c.estado === 'Publicado'))).toBe(true);
|
|
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(30);
|
|
expect(m.conResultado).toBe(21);
|
|
});
|
|
|
|
it('la lesión de riesgo (B3) no se inventa: no hay esa categoría en las fuentes y la matriz no la dibuja', () => {
|
|
// Pins down: the source grades are benign, in situ and invasive; the page's optional «Lesión de riesgo (B3)» isn't
|
|
// published, so the model lists three categories and two groups (non malignant, malignant). Fails if a category the
|
|
// source lacks appears, or the model needs it.
|
|
const m = matriz('2025-01-01', '2025-S1');
|
|
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'IN_SITU', 'INVASOR']);
|
|
expect(m.categorias.map(c => c.etiqueta)).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor']);
|
|
expect(m.grupos.map(g => [g.id, g.categorias])).toEqual([['NO_MALIGNO', ['BENIGNO']], ['MALIGNO', ['IN_SITU', 'INVASOR']]]);
|
|
expect(m.aparte.map(a => a.id)).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
|
|
});
|
|
|
|
it('las tasas por categoría usan solo a las pacientes con resultado de biopsia y llevan su intervalo', () => {
|
|
// Pins down: for the malignant group the rate of BI-RADS 4 is 6 of 14 and BI-RADS 5 is 7 of 7 (no biopsy and no data
|
|
// never enter the denominator), and a stratum with no patients has no rate. Fails if «sin biopsia» enters a denominator.
|
|
const m = matriz('2025-01-01', '2025-S1');
|
|
const t = Object.fromEntries(tasas(m, seleccionBase(m)).map(x => [x.fila.id, x]));
|
|
expect([t['BIRADS_4'].k, t['BIRADS_4'].fila.den]).toEqual([6, 14]);
|
|
expect([t['BIRADS_5'].k, t['BIRADS_5'].fila.den]).toEqual([7, 7]);
|
|
expect(t['BIRADS_5'].valor).toBe(100);
|
|
expect(t['BIRADS_4'].bajo).toBeLessThan(t['BIRADS_4'].valor!);
|
|
expect(t['BIRADS_4'].alto).toBeGreaterThan(t['BIRADS_4'].valor!);
|
|
expect(t['BIRADS_6'].valor).toBeNull();
|
|
});
|
|
|
|
it('el total de la matriz de cada semestre es el de pacientes BI-RADS 4, 5 y 6 del periodo', () => {
|
|
// Pins down: the matrix counts the same patients as CAMA_BIRADS456_PACIENTE (36 in 2025-S2, the report of the earlier
|
|
// fixture), and in every real semester the units of the report are the matrix's cells. Fails if the two measures count
|
|
// different patients.
|
|
const total = (inicio: string, periodo: string) => matriz(inicio, periodo).filas.reduce((s, f) => s + f.total.n!, 0);
|
|
expect(total('2025-07-01', '2025-S2')).toBe(BIRADS_PACIENTES_2025_S2);
|
|
for (const [inicio, periodo] of SEMESTRES) {
|
|
expect(total(inicio, periodo), periodo).toBe(reportsOf(HISTO, 'semestre', inicio)[0].group![0].population![0].count);
|
|
}
|
|
});
|
|
|
|
it('un semestre sin pacientes es una matriz de ceros publicados, no un error', () => {
|
|
// Pins down: 2021-S1 has no mammograms: the matrix is complete with zeros and the denominators are zero (no rate).
|
|
// Fails if an empty period breaks the view or turns into «No disponible».
|
|
const m = matriz('2021-01-01', '2021-S1');
|
|
expect(m.filas.every(f => f.total.n === 0 && f.den === 0)).toBe(true);
|
|
expect(m.conResultado).toBe(0);
|
|
});
|
|
|
|
it('un mes con pacientes se lee igual que un semestre', () => {
|
|
// Pins down: the monthly answer carries the month label and the same matrix shape. Fails if the month is read as a semester.
|
|
const m = matriz('2025-12-01', '2025-12', 'mes');
|
|
expect(m.periodo).toBe('2025-12');
|
|
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(8);
|
|
});
|
|
|
|
it('el catálogo de categorías sale de la Measure y los códigos desconocidos son un error, no ceros', () => {
|
|
// Pins down: an unknown BI-RADS or grade code in a report, or cells that don't add up to the units, throw instead of
|
|
// being read as zero. Fails if the adapter hides an inconsistent report.
|
|
const clon = (): Report[] => structuredClone(reportsOf(HISTO, 'semestre', '2025-01-01'));
|
|
const conCodigo = clon();
|
|
conCodigo[0].group![0].stratifier![1]['stratum']![0].component![0].value!.coding![0].code = 'B9';
|
|
expect(() => datosDeReportes(measure(HISTO), conCodigo, 'semestre', { estrato: 'birads' })).toThrow(/no reconocido/);
|
|
const desajustado = clon();
|
|
desajustado[0].group![0].stratifier![1]['stratum']![0].population![0].count! += 1;
|
|
expect(() => datosDeReportes(measure(HISTO), desajustado, 'semestre', { estrato: 'birads' })).toThrow(/no suman/);
|
|
const sinCruce = clon();
|
|
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
|
|
expect(() => datosDeReportes(measure(HISTO), sinCruce, 'semestre', { estrato: 'birads' })).toThrow(/no admitida/);
|
|
});
|
|
|
|
it('sin pedir el estrato, la medida se lee como una distribución por resultado y suma las mismas pacientes', () => {
|
|
// Pins down: asked without the stratum the measure is a plain C2 (categories of the biopsy result); its categories add
|
|
// to the report's units. Fails if the stratified reading changes the plain one.
|
|
const d = datos(HISTO, '2025-01-01', '2025-S1');
|
|
expect(d.filas.reduce((s, f) => s + (f['n'] as number), 0)).toBe(30);
|
|
expect(periodosHistopatologia(datos(HISTO, '2025-01-01', '2025-S1', 'semestre', { estrato: 'birads' }), 'semestre')).toEqual(['2025-S1']);
|
|
});
|
|
});
|
|
|
|
describe('Resumen e Histórico leen lo mismo', () => {
|
|
type Traza = { name?: string; x: (string | null)[]; y: (number | null)[] };
|
|
const serie = (d: IndicadorDatos, nombre: string): Traza =>
|
|
((historicoFigura(d, 'claro').figure as unknown as { data: Traza[] }).data).find(t => t.name === nombre)!;
|
|
it.each([[TASA, 'Porcentaje', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(p)).value)],
|
|
[DIAS, 'Mediana', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(p)).value)]] as const)(
|
|
'%s: el valor de la tarjeta de cada semestre es el punto del Histórico en ese semestre', (fhirId, nombre, tarjeta) => {
|
|
// Pins down: the card of one semester and the history of all of them are built from the same reports, so the number on the
|
|
// card is the point of the series for that period. Fails if the two screens compute the figure differently.
|
|
const historico = datosDeReportes(measure(fhirId), SEMESTRES.map(([inicio]) => reportsOf(fhirId, 'semestre', inicio)[0]), 'semestre');
|
|
const traza = serie(historico, nombre);
|
|
for (const [inicio, periodo] of SEMESTRES) {
|
|
const i = traza.x.indexOf(etiquetaPeriodo(periodo));
|
|
expect(i, periodo).toBeGreaterThanOrEqual(0);
|
|
expect(traza.y[i], periodo).toBe(tarjeta(datos(fhirId, inicio, periodo), periodo));
|
|
}
|
|
});
|
|
});
|