feat(cama): adjust summary wording, double mastography counts and classify histologic types

Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
This commit is contained in:
Angel Capetillo Zavala
2026-11-20 00:32:27 -06:00
parent 2f5b1ce1f2
commit 6c063344a3
17 changed files with 232 additions and 21 deletions
@@ -0,0 +1,32 @@
// Covers the x2 shown for CaMa's mastographies in the demonstration build, on hand-made C2 rows.
import { ajustarMastografiasDemo } from './ajuste-mastografias-demo';
import { IndicadorDatos } from './indicadores.models';
const datos = (): IndicadorDatos => ({
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'],
filas: [
{ periodo: '2025-S1', categoria: 'BIRADS_4', n: 10, suprimido: 0 },
{ periodo: '2025-S2', categoria: 'BIRADS_4', n: 10, suprimido: 0 },
{ periodo: '2025-S2', categoria: 'BIRADS_5', n: null, suprimido: 1 },
],
});
describe('Mastografías en la demostración', () => {
it('duplica el conteo de todos los periodos y deja intactas las celdas suprimidas', () => {
// Fails if a period is left out (the factor must not depend on the filter), a suppressed cell becomes a number, or the factor changes.
const r = ajustarMastografiasDemo('cama', 'cama_birads_456_mastografia', datos());
expect(r.filas.map(f => f['n'])).toEqual([20, 20, null]);
});
it('no modifica los datos recibidos', () => {
// Fails if the cached API payload is mutated, which would double again on every read.
const original = datos();
ajustarMastografiasDemo('cama', 'cama_birads_456_mastografia', original);
expect(original.filas.map(f => f['n'])).toEqual([10, 10, null]);
});
it('no afecta a otros indicadores ni a otros dominios', () => {
// Fails if the factor leaks to the patients' count or to another domain with the same indicator id.
const d = datos();
expect(ajustarMastografiasDemo('cama', 'cama_birads_456_paciente', d)).toBe(d);
expect(ajustarMastografiasDemo('cacu', 'cama_birads_456_mastografia', d)).toBe(d);
});
});
@@ -0,0 +1,19 @@
import { IndicadorDatos } from './indicadores.models';
// The demonstration build shows twice the mastographies the API reports, in every period, for CaMa's BI-RADS 4, 5
// or 6 indicator. Resumen and Histórico read it through the same service call, so both show the same counts.
const INDICADOR = 'cama_birads_456_mastografia';
export const FACTOR_MASTOGRAFIAS = 2;
const doble = <T extends Record<string, unknown>>(fila: T): T =>
typeof fila['n'] === 'number' && Number.isFinite(fila['n']) ? { ...fila, n: fila['n'] * FACTOR_MASTOGRAFIAS } : fila;
/** The data with each published count `n`, and each stratum total, multiplied; suppressed or missing cells stay as they are. */
export function ajustarMastografiasDemo(dominio: string, indicador: string, datos: IndicadorDatos): IndicadorDatos {
if (dominio !== 'cama' || indicador !== INDICADOR) return datos;
return {
...datos,
filas: datos.filas.map(doble),
...(Array.isArray(datos['totales_estrato']) ? { totales_estrato: (datos['totales_estrato'] as Record<string, unknown>[]).map(doble) } : {}),
};
}
@@ -7,7 +7,7 @@
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' && model; as m) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo;
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
@if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
@@ -32,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con resultado maligno.' });
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
});
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -210,7 +210,7 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
expect(kpis()[4].querySelector('.value')).toBeNull();
@@ -308,3 +308,36 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () =>
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
describe('Ajuste x2 de mastografías en la ruta FHIR', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
function pedir(id: string, fhirId: string) {
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer;
}
it('las mastografías llegan a la tarjeta con el doble de cada conteo, exactamente una vez', async () => {
// Pins down: the page reads through FhirIndicadoresService, which does not call the base service, so the factor is
// applied there. Fails if the factor is missing (counts equal the published ones) or applied twice (four times).
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
expect(mostrado.filas.map(f => f['n'])).toEqual(publicado.filas.map(f => (f['n'] as number) * 2));
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(78);
expect(model.filas.map(f => f.examenes)).toEqual([32, 42, 4]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
});
it('los conteos de pacientes llegan sin el factor', async () => {
// Fails if the factor leaks to the patients' indicator, which shares the card and the history with the mastographies.
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas);
});
});
@@ -73,7 +73,7 @@ describe('Tasa de detección histopatológica (C1)', () => {
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.` });
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
});
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]);
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
});
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' });
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
});
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -214,7 +214,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
expect(cards().map(card => text(card, 'h3'))).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica',
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
@@ -234,7 +234,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
expect(text(cards()[4], '.value')).toBeUndefined();
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.');
expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
});
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
@@ -254,7 +254,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
expect(text(cards()[0], '.value')).toBe('5pacientes');
expect(fixture.nativeElement.textContent).not.toContain('private');
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía interpretación radiológica"]')).not.toBeNull();
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
});
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
@@ -213,7 +213,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
const h3 = [...root().querySelectorAll('app-indicador-conteos-pareados h3')].map(e => e.textContent?.trim());
expect(h3).toEqual([
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, 2025-S2',
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
]);
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
@@ -223,7 +223,8 @@ describe('Tarjeta pareada de CaMa en la página', () => {
expect(graficas.map(g => g.label)).toEqual(h3);
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]);
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
// The mastographies column shows twice the published counts (15 and 18) in the demonstration build.
expect(filas).toEqual([['BI-RADS 4', '13', '30'], ['BI-RADS 5', '18', '36'], ['BI-RADS 6', '0', '0']]);
expect(root().querySelector('.published-values caption')?.textContent).toContain('su categoría más alta');
expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente');
expect([...root().querySelectorAll('.help-icon')].map(b => b.getAttribute('aria-label'))).toEqual(['Cómo leer, mastografías por categoría', 'Cómo leer, pacientes por categoría']);
@@ -253,7 +254,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
it('sin pacientes verificados dibuja la estructura y deja pendiente solo la cifra de pacientes', () => {
abrir(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' }));
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '30'], ['BI-RADS 5', 'Pendiente', '36'], ['BI-RADS 6', 'Pendiente', '0']]);
expect(root().textContent).toContain('Pacientes pendientes');
expect(root().textContent).toContain('Dona de pacientes no disponible');
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
@@ -6,6 +6,7 @@ import { periodLabel } from './measure-report';
import {
DatosScope, Dominio, FigureSelection, Indicador, IndicadorDatos, IndicadorMetadatos, PlotlyFigure, requireDominio, TipoPeriodo,
} from './indicadores.models';
import { ajustarMastografiasDemo } from './ajuste-mastografias-demo';
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
@@ -367,7 +368,8 @@ export class FhirIndicadoresService extends IndicadoresService {
params = periodos ? params.set('periodo', [...new Set(periodos)].join(',')) : params.set('tipo-periodo', tipo);
return this.measures.one(dominio, indicador).pipe(
switchMap(measure => this.measures.reports(dominio, measure, params).pipe(
map(bundle => datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope)))));
map(bundle => ajustarMastografiasDemo(dominio, indicador,
datosValidos(datosDeReportes(measure, resources(bundle, 'MeasureReport') as Report[], tipo, scope), indicador, tipo, periodos, scope))))));
}
override figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
@@ -87,7 +87,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías');
});
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => {
it('Pacientes evaluadas con BI-RADS 4, 5 o 6 conserva la gráfica y omite la explicación de la barra', () => {
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
expect(pacientes.comoLeer).toBe('');
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
@@ -28,7 +28,7 @@ const PERSONALIZADO = -1;
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
} else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
};
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
};
// Institutional definitions retained for consumers outside the opportunity strip.
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
@@ -25,7 +25,7 @@ export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = {
};
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
c1Info: (n, d) => `${n} de ${d} biopsias con riesgo a carcinoma.`,
};
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
@@ -58,7 +58,7 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
],
cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
CAMA_TAMIZAJE_RESULTADO_KPI,
],
};
@@ -1,6 +1,7 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs';
import { ajustarMastografiasDemo } from './ajuste-mastografias-demo';
import { DatosScope, Dominio, IndicadorDatos, IndicadorMetadatos, FigureSelection, Indicador, parsePeriodos, PlotlyFigure, requireDominio, TipoPeriodo } from './indicadores.models';
function record(value: unknown): value is Record<string, unknown> {
@@ -20,7 +21,7 @@ export class IndicadoresService {
const domain = requireDominio(dominio);
const params = datosParams(tipo, periodos, scope);
return this.http.get<unknown>(`/${domain}/indicadores/${encodeURIComponent(indicador)}/datos`, { params })
.pipe(map(value => datosValidos(value, indicador, tipo, periodos, scope)));
.pipe(map(value => ajustarMastografiasDemo(domain, indicador, datosValidos(value, indicador, tipo, periodos, scope))));
}
figura(selection: FigureSelection) {
const dominio = requireDominio(selection.dominio ?? 'tea');
@@ -0,0 +1,76 @@
// Covers the histologic-type classification and its column in the follow-up table. It uses the CaMa follow-up
// fixture (fixtures/cama_seguimiento.json), to which each test adds a synthetic `tipo_histologico` per row.
import fixtureData from './fixtures/cama_seguimiento.json';
import { clasificacionHistologica, MAPEO_HISTOLOGICO, SIN_CLASIFICAR } from './mapeo-histologico';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
const respuesta = () => structuredClone(fixtureData) as unknown as { columnas: { clave: string; etiqueta: string }[]; items: Record<string, string | number | null>[] };
describe('Clasificación histológica', () => {
it.each([
['Ductal (NST)', 'Carcinoma invasor'], ['Lobulillar', 'Carcinoma invasor'], ['Ductal-lobulillar mixto', 'Carcinoma invasor'],
['Mucinoso', 'Carcinoma invasor'], ['Paget', 'Carcinoma in situ'], ['Papilar', 'Revisar (Benigno / In situ / Invasor)'],
['Tubular', 'Carcinoma invasor'], ['cribiforme', 'Revisar (In situ / Invasor)'], ['Micropapilar', 'Revisar (In situ / Invasor)'],
['Inflamatorio', 'Carcinoma invasor'], ['Medular', 'Carcinoma invasor'], ['Otros', 'Revisar (Benigno / In situ / Invasor)'],
['SIN MAPEAR', 'Sin clasificar'],
])('asigna a «%s» la clasificación «%s»', (tipo, clasificacion) => {
// Fails if a type is moved to another group or dropped from the mapping.
expect(clasificacionHistologica(tipo)).toBe(clasificacion);
});
it('la categoría combinada «Tubular / cribiforme» del gráfico es carcinoma invasor', () => {
// Fails if the chart's merged category stops being classified, which would leave its patients unclassified.
expect(clasificacionHistologica('Tubular / cribiforme')).toBe('Carcinoma invasor');
});
it('un tipo fuera del mapeo, incluido uno heredado del prototipo de objeto, es «Sin clasificar»', () => {
// Fails if the lookup returns inherited properties such as «constructor» instead of the fallback.
for (const tipo of ['Desconocido', '', 'constructor', 'toString']) expect(clasificacionHistologica(tipo)).toBe(SIN_CLASIFICAR);
});
it('el mapeo conserva sus trece tipos y sus cuatro clasificaciones directas', () => {
// Fails if a type is added or removed without reviewing its classification.
expect(Object.keys(MAPEO_HISTOLOGICO)).toHaveLength(14);
expect(new Set(Object.values(MAPEO_HISTOLOGICO))).toEqual(new Set([
'Carcinoma invasor', 'Carcinoma in situ', 'Revisar (Benigno / In situ / Invasor)', 'Revisar (In situ / Invasor)', 'Sin clasificar']));
});
});
describe('Seguimiento: columna de clasificación histológica', () => {
const tipos = ['Ductal (NST)', 'Paget', 'Otros', 'SIN MAPEAR', 'Zzz'];
it('cada paciente recibe la clasificación de su propio tipo, en una columna tras el tipo o tras el resultado de la biopsia', () => {
// Fails if the classification is computed from another row or placed away from the biopsy columns.
const datos = respuesta();
const conBiopsia = datos.items.filter(item => item['biopsia'] !== null);
conBiopsia.forEach((item, i) => { item['tipo_histologico'] = tipos[i % tipos.length]; });
const r = seguimientoTablaResponse(datos);
const claves = r.columnas.map(c => c.clave);
expect(claves[claves.indexOf('biopsia') + 1]).toBe('clasificacion_histologica');
expect(r.columnas.find(c => c.clave === 'clasificacion_histologica')!.etiqueta).toBe('Clasificación histológica');
for (const item of r.items.filter(item => typeof item['tipo_histologico'] === 'string')) {
expect(item['clasificacion_histologica']).toBe(clasificacionHistologica(item['tipo_histologico'] as string));
}
});
it('con una columna de tipo, la clasificación va justo después de ella', () => {
// Fails if the derived column ignores the type's own column and lands elsewhere.
const datos = respuesta();
datos.columnas.splice(datos.columnas.findIndex(c => c.clave === 'biopsia') + 1, 0, { clave: 'tipo_histologico', etiqueta: 'Tipo histológico' });
datos.items.forEach(item => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Lobulillar'; });
const claves = seguimientoTablaResponse(datos).columnas.map(c => c.clave);
expect(claves.slice(claves.indexOf('tipo_histologico'), claves.indexOf('tipo_histologico') + 2)).toEqual(['tipo_histologico', 'clasificacion_histologica']);
});
it('un paciente sin tipo no recibe clasificación y los demás campos quedan como llegaron', () => {
// Fails if a patient without biopsy is shown as «Sin clasificar», or if other row values are altered.
const datos = respuesta();
datos.items.forEach((item, i) => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Medular'; });
const original = structuredClone(datos.items);
const r = seguimientoTablaResponse(datos);
r.items.forEach((item, i) => {
if (original[i]['tipo_histologico'] === null) expect('clasificacion_histologica' in item).toBe(false);
expect({ ...item, clasificacion_histologica: undefined }).toEqual({ ...original[i], clasificacion_histologica: undefined });
});
});
it('una lista sin tipo histológico no cambia', () => {
// Fails if the column appears while the API does not send the field.
const r = seguimientoTablaResponse(respuesta());
expect(r.columnas.map(c => c.clave)).not.toContain('clasificacion_histologica');
expect(r.items.some(item => 'clasificacion_histologica' in item)).toBe(false);
});
});
@@ -0,0 +1,23 @@
// Groups the histologic type of a biopsy into the classification shown beside it.
export const SIN_CLASIFICAR = 'Sin clasificar';
export const MAPEO_HISTOLOGICO: Readonly<Record<string, string>> = {
'Ductal (NST)': 'Carcinoma invasor',
'Lobulillar': 'Carcinoma invasor',
'Ductal-lobulillar mixto': 'Carcinoma invasor',
'Mucinoso': 'Carcinoma invasor',
'Paget': 'Carcinoma in situ',
'Papilar': 'Revisar (Benigno / In situ / Invasor)',
'Tubular': 'Carcinoma invasor',
'Tubular / cribiforme': 'Carcinoma invasor',
'cribiforme': 'Revisar (In situ / Invasor)',
'Micropapilar': 'Revisar (In situ / Invasor)',
'Inflamatorio': 'Carcinoma invasor',
'Medular': 'Carcinoma invasor',
'Otros': 'Revisar (Benigno / In situ / Invasor)',
'SIN MAPEAR': SIN_CLASIFICAR,
};
/** The classification of a histologic type; a type outside the mapping is «Sin clasificar». */
export const clasificacionHistologica = (tipo: string) =>
Object.hasOwn(MAPEO_HISTOLOGICO, tipo) ? MAPEO_HISTOLOGICO[tipo] : SIN_CLASIFICAR;
@@ -4,6 +4,7 @@ import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { clasificacionHistologica } from './mapeo-histologico';
import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -96,10 +97,33 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
const respuesta = v as unknown as SeguimientoTablaResponse;
const respuesta = clasificarHistologia(v as unknown as SeguimientoTablaResponse);
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
}
const TIPO_HISTOLOGICO = 'tipo_histologico';
const CLASIFICACION_HISTOLOGICA = 'clasificacion_histologica';
/**
* A list that carries the histologic type of each patient (`tipo_histologico`) also shows its classification, computed
* from that same value in the same row, in a column placed after the type's (or after the biopsy result when the type
* has no column). Rows without a type, and lists without the field, are left as received.
*/
export function clasificarHistologia(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
if (!r.items.some(item => typeof item[TIPO_HISTOLOGICO] === 'string') || r.columnas.some(c => c.clave === CLASIFICACION_HISTOLOGICA)) return r;
const columnas = [...r.columnas];
const despuesDe = [TIPO_HISTOLOGICO, 'biopsia'].map(k => columnas.findIndex(c => c.clave === k)).find(i => i >= 0) ?? columnas.length - 1;
columnas.splice(despuesDe + 1, 0, { clave: CLASIFICACION_HISTOLOGICA, etiqueta: 'Clasificación histológica' });
return {
...r,
columnas,
items: r.items.map(item => {
const tipo = item[TIPO_HISTOLOGICO];
return typeof tipo === 'string' ? { ...item, [CLASIFICACION_HISTOLOGICA]: clasificacionHistologica(tipo) } : item;
}),
};
}
/**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays