From bc75c058e1645133773970ef29378581f95ab1a7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 11 Nov 2026 21:57:45 -0600 Subject: [PATCH 01/38] feat(indicadores): CaMa's four opportunity cards, pending where the catalog lacks the indicator Cards: patients with BI-RADS 4, 5 and 6, histopathological detection rate, screening to result and result to diagnosis times. The detection rate and the result-to-diagnosis time are not published by the catalog yet, so they are drawn as explicit pending cards and are queried once the catalog lists them. cama_eu38a is added to the CaMa KPIs. --- .../indicadores/indicador-kpi-card.ts | 7 +- .../indicadores/indicador-kpi-panel.spec.ts | 11 +- .../indicadores/indicador-kpi-panel.ts | 8 +- .../indicadores-cama-oportunidad.spec.ts | 216 ++++++++++++++++++ .../indicadores-initial-integration.spec.ts | 11 +- .../indicadores-initial-period.spec.ts | 2 +- .../features/indicadores/indicadores-kpi.ts | 44 +++- .../indicadores/indicadores-page.html | 13 +- .../indicadores/indicadores-page.scss | 4 + .../features/indicadores/indicadores-page.ts | 7 +- .../indicadores-periodos-integration.spec.ts | 8 +- 11 files changed, 307 insertions(+), 24 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts diff --git a/src/app/features/indicadores/indicador-kpi-card.ts b/src/app/features/indicadores/indicador-kpi-card.ts index 363d5b1..a76d6db 100644 --- a/src/app/features/indicadores/indicador-kpi-card.ts +++ b/src/app/features/indicadores/indicador-kpi-card.ts @@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';

{{ value }}@if (unit) { {{ unit }} }

} @if (temporalReference) {

{{ temporalReference }}

} -

{{ state }}

+ @if (!(quietWhenAvailable && state === 'Disponible')) {

{{ state }}

} @if (informationLine) {

{{ informationLine }}

} `, @@ -28,6 +28,9 @@ import { MatCardModule } from '@angular/material/card'; .kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } .value { font: var(--mat-sys-headline-medium); } .value span { margin-inline-start: .3em; } + // CaMa's cards are as tall as their grid row. + :host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; } + :host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; } `, }) export class IndicadorKpiCard { @@ -38,6 +41,8 @@ export class IndicadorKpiCard { @Input() loading = false; @Input() notes: string[] = []; @Input() state = 'Pendiente de definición'; + // A card that shows its value needs no "Disponible" line. + @Input() quietWhenAvailable = false; @Input() additionalInfo?: string; get informationLine(): string | undefined { const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value); diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 4c274ce..1dab35f 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -172,13 +172,14 @@ describe('KPI integración con autoridad global', () => { for (const domain of ['cacu', 'cama'] as const) { load(domain); const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length); - req.forEach((r, i) => r.flush({ ...response(i, domain), notas: ['Nota del pie de la figura.'] })); + // CaMa draws its cards in a different order than KPI_BY_DOMAIN: answer each request by its indicator. + req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] })); fixture.detectChanges(); const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; - expect(cards).toHaveLength(domain === 'cacu' ? 5 : 3); - expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', '40.0', '7']); - expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', '%', 'días (mediana)']); - expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Disponible', 'Disponible']); + expect(cards).toHaveLength(domain === 'cacu' ? 5 : 6); + expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined, '40.0', '7']); + expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined, '%', 'días (mediana)']); + expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : [undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]); expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect.stringContaining('2025-S1'), expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), diff --git a/src/app/features/indicadores/indicador-kpi-panel.ts b/src/app/features/indicadores/indicador-kpi-panel.ts index 8cc7bcc..224161a 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.ts @@ -19,11 +19,15 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver imports: [IndicadorKpiCard, MatButtonModule], template: ` + [loading]="result().loading ?? false" [notes]="dominio === 'cacu' ? [] : result().notes ?? []" [quietWhenAvailable]="dominio === 'cama'" /> @if (result().state === 'Error de consulta') { }`, - styles: ':host { display: block; min-width: 0; }', + styles: ` + :host { display: block; min-width: 0; } + :host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; } + :host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; } + `, }) export class IndicadorKpiPanel implements OnChanges { @Input({ required: true }) dominio!: Dominio; diff --git a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts new file mode 100644 index 0000000..10143f5 --- /dev/null +++ b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts @@ -0,0 +1,216 @@ +// Covers CaMa's four opportunity cards: their definitions, how each indicator's response becomes a card, +// which cards are pending while the catalog lacks their indicator, and the page drawing them. +// Fixtures are synthetic rows shaped like the /cama/indicadores//datos contract; no card reads a bundled value. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorKpiPanel } from './indicador-kpi-panel'; +import { IndicadorKpiCard } from './indicador-kpi-card'; +import { + CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, + KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult, +} from './indicadores-kpi'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { IndicadorDatos } from './indicadores.models'; + +const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 }; +const row = { periodo: '2025-S1', estrato: null, suprimido: 0 }; +const datos = (definition: KpiDefinition, filas: Record[]): IndicadorDatos => ({ + id: definition.id, contrato: definition.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas }); +const c1 = (fields: Record) => datos(CAMA_TASA_DETECCION_KPI, [{ ...row, grupo: 'total', ...fields }]); +const c3r = (definition: KpiDefinition, fields: Record) => datos(definition, [{ ...row, grupo: 'TOTAL', unidad: 'dias', ...fields }]); + +describe('Tarjetas de oportunidad de CaMa: definiciones', () => { + it('son cuatro, en este orden, y la primera sigue siendo el ancla del periodo inicial', () => { + // Fails if a card is dropped or reordered, or if the anchor (KPI_BY_DOMAIN.cama[0]) stops leading. + expect(CAMA_OPORTUNIDAD_KPIS.map(d => [d.id, d.contrato, d.unit])).toEqual([ + ['cama_birads_456_paciente', 'C2', 'pacientes'], + ['cama_tasa_deteccion_histopatologica', 'C1', '%'], + ['cama_eu38a', 'C3r', 'días (mediana)'], + ['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 detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado 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', () => { + // Fails if an indicator the catalog does not publish is queried by default. + expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual([ + 'cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']); + expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI); + expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI); + }); +}); + +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.' }); + }); + 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); + expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0'); + }); + it.each([ + ['valor nulo', { valor: null, numerador: 0, denominador: 8 }], + ['denominador nulo', { valor: 0, numerador: 0, denominador: null }], + ['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }], + ])('la tasa con %s no se convierte en cero', (_name, fields) => { + // Fails if a missing or incoherent rate is drawn as a value. + const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied); + expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible'); + }); + it('un dato suprimido por tamaño oculta la cifra en las cuatro tarjetas', () => { + // Fails if a suppressed row leaks a number. + const cases: [KpiDefinition, IndicadorDatos][] = [ + [CAMA_OPORTUNIDAD_KPIS[0], datos(CAMA_OPORTUNIDAD_KPIS[0], [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 3, suprimido: 1 }])], + [CAMA_TASA_DETECCION_KPI, c1({ valor: 10, numerador: 1, denominador: 10, suprimido: 1 })], + [CAMA_TAMIZAJE_RESULTADO_KPI, c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })], + [CAMA_RESULTADO_DIAGNOSTICO_KPI, c3r(CAMA_RESULTADO_DIAGNOSTICO_KPI, { mediana: 4, n: 9, q1: 2, q3: 6, suprimido: 1 })], + ]; + for (const [definition, data] of cases) { + const result = kpiResult(data, definition, 'cama', applied); + expect(result.state).toBe('Dato oculto por tamaño'); expect(result.value).toBeUndefined(); + } + }); + it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana y cuartiles tal como los publica el C3r', definition => { + const result = kpiResult(c3r(definition, { mediana: 6.5, n: 40, q1: 3, q3: 11 }), definition, 'cama', applied); + expect(result).toEqual({ state: 'Disponible', value: 6.5, info: '40 mastografías; Q1 a Q3: 3 a 11 días.' }); + }); + it.each([CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI])('$title: mediana de cero días con observaciones es un valor; sin observaciones no hay valor', definition => { + // Fails if a median over zero observations is drawn as "0 días", or a true same-day median is dropped. + expect(kpiResult(c3r(definition, { mediana: 0, n: 5, q1: 0, q3: 2 }), definition, 'cama', applied).value).toBe(0); + const empty = kpiResult(c3r(definition, { mediana: 0, n: 0, q1: 0, q3: 0 }), definition, 'cama', applied); + expect(empty.value).toBeUndefined(); expect(empty.state).toBe('Sin valor disponible'); + }); + it('los cuartiles inconsistentes o la unidad ajena no producen cifra', () => { + const bad = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 9, n: 5, q1: 3, q3: 6 }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied); + const unit = kpiResult(c3r(CAMA_TAMIZAJE_RESULTADO_KPI, { mediana: 2, n: 5, q1: 1, q3: 3, unidad: 'horas' }), CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', applied); + expect(bad.value).toBeUndefined(); expect(unit.value).toBeUndefined(); + }); +}); + +describe('Tarjetas de oportunidad de CaMa: cuáles se dibujan', () => { + const only = (...ids: string[]) => (id: string) => ids.includes(id); + it('sin ningún indicador publicado no hay tarjetas, ni siquiera pendientes', () => { + // Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed. + expect(camaKpiCards(only())).toEqual([]); + expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico')).filter(c => !c.pending).length).toBe(2); + expect(camaKpiCards(only('cama_tasa_deteccion_histopatologica')).filter(c => !c.pending).length).toBe(1); + }); + it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y las existentes de DEV siguen después', () => { + const cards = camaKpiCards(only('cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a')); + expect(cards.map(c => [c.definition.id, c.pending])).toEqual([ + ['cama_birads_456_paciente', false], ['cama_tasa_deteccion_histopatologica', true], + ['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true], + ['cama_confirmacion_birads45', false], ['cama_dias_toma_diagnostico', false]]); + }); + it('una tarjeta pendiente pasa a viva cuando el catálogo publica su indicador, sin tocar código', () => { + const cards = camaKpiCards(only(...CAMA_OPORTUNIDAD_KPIS.map(d => d.id))); + expect(cards.map(c => c.pending)).toEqual([false, false, false, false]); + }); + it('un indicador de las tarjetas que el catálogo retira no deja una tarjeta consultable', () => { + expect(camaKpiCards(only('cama_birads_456_paciente')).map(c => c.pending)).toEqual([false, true, true, true]); + }); +}); + +describe('Tarjetas de oportunidad de CaMa en la página', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + // The initial-period search has its own suites; these tests begin once it has finished. + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama'); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + const catalog = (definitions: KpiDefinition[]) => definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })); + const dataFor = (definition: KpiDefinition): IndicadorDatos => { + if (definition.contrato === 'C2') return datos(definition, [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }]); + if (definition.contrato === 'C1') return datos(definition, [{ ...row, grupo: 'total', valor: 40, numerador: 2, denominador: 5 }]); + return c3r(definition, { mediana: 7, n: 5, q1: 3, q3: 9 }); + }; + // The period inventory runs four requests at a time: answer it in waves. + function inventory() { + for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) { + wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] })); + } + fixture.detectChanges(); + } + type Served = { listed?: ReturnType; answer?: (r: TestRequest, definition: KpiDefinition) => void }; + function load(definitions: KpiDefinition[], served: Served = {}) { + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush(served.listed ?? catalog(definitions)); + inventory(); + // Data requests also go out in waves of four. + const requested: string[] = []; + for (let wave = http.match(r => r.url.endsWith('/datos')); wave.length; wave = http.match(r => r.url.endsWith('/datos'))) { + wave.forEach(r => { + requested.push(r.request.url); + const definition = definitions.find(d => r.request.url.endsWith('/' + d.id + '/datos'))!; + if (served.answer) served.answer(r, definition); else r.flush(dataFor(definition)); + }); + fixture.detectChanges(); + } + return requested; + } + const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[]; + const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim(); + + it('con el catálogo actual: dos tarjetas con datos, dos pendientes y ninguna consulta a indicadores sin publicar', () => { + // Fails if a pending indicator is requested, or if a pending card is drawn with a number. + const urls = load(KPI_BY_DOMAIN.cama); + expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica') || url.includes('cama_dias_resultado_diagnostico'))).toBe(false); + expect(cards().map(card => text(card, 'h3'))).toEqual([ + 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de tamizaje a resultado', + 'Tiempo de resultado a diagnóstico', 'Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico']); + expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, '40.0%', '7días (mediana)']); + expect(cards().map(card => text(card, '.kpi-state'))).toEqual([undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]); + expect(cards()[1].textContent).toContain('aún no está publicado'); + expect(cards()[1].textContent).not.toMatch(/\d/); + }); + it('si el catálogo publica los cuatro indicadores no queda ninguna tarjeta pendiente', () => { + // Fails if a published opportunity indicator is not queried and drawn. + const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]); + expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica'))).toBe(true); + expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).toBe(true); + expect(cards().map(card => text(card, 'h3')).slice(0, 4)).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)); + expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false); + expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.'); + }); + it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => { + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush([]); fixture.detectChanges(); + expect(fixture.nativeElement.querySelector('#kpi-section-title')).toBeNull(); + expect(fixture.nativeElement.textContent).not.toContain('Integración pendiente'); http.expectNone(r => r.url.endsWith('/datos')); + }); + it('un indicador publicado con otro contrato no se muestra como la tarjeta esperada', () => { + // Fails if a contract mismatch (C1 served where C3r is expected) is drawn as a median. + load(KPI_BY_DOMAIN.cama, { listed: catalog(KPI_BY_DOMAIN.cama).map(i => i.id === 'cama_eu38a' ? { ...i, contrato: 'C1' } : i) }); + const panel = fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(p => p.componentInstance as IndicadorKpiPanel) + .find(p => p.definition.id === 'cama_eu38a')!; + expect(panel.result().state).toBe('Error de contrato'); expect(panel.result().value).toBeUndefined(); + }); + it('el error de una consulta se muestra en su tarjeta y las demás conservan sus datos', () => { + load(KPI_BY_DOMAIN.cama, { answer: (r, definition) => definition.id === 'cama_eu38a' ? r.flush('private', { status: 500, statusText: 'Error' }) : r.flush(dataFor(definition)) }); + 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 tamizaje a resultado"]')).not.toBeNull(); + }); + it('el estado Disponible solo se omite en CaMa: la tarjeta compartida lo sigue diciendo por defecto', () => { + const card = TestBed.createComponent(IndicadorKpiCard); + card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges(); + expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Disponible'); + card.componentRef.setInput('quietWhenAvailable', true); card.detectChanges(); + expect(card.nativeElement.querySelector('.kpi-state')).toBeNull(); + card.componentRef.setInput('state', 'Sin datos del periodo'); card.detectChanges(); + expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Sin datos del periodo'); + card.destroy(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 8671c65..9fa4416 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -33,9 +33,14 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid http = TestBed.inject(HttpTestingController); if (domain !== 'tea') { http.expectOne('/tea/indicadores').flush([]); page.changeDominio(domain); } http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); - const inventory = http.match(r => r.url.endsWith('/periodos')); - expect(inventory).toHaveLength(items.length); // The anchor shares the catalog inventory request. - inventory.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) })); + // The anchor shares the catalog inventory request. The inventory runs four requests at a time, + // so a catalog of more than four indicators is answered in waves. + let inventoried = 0; + for (let wave = http.match(r => r.url.endsWith('/periodos')); wave.length; wave = http.match(r => r.url.endsWith('/periodos'))) { + inventoried += wave.length; + wave.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [...periods].reverse().map(periodo => ({ periodo, tipo: 'semestre' })) })); + } + expect(inventoried).toBe(items.length); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); diff --git a/src/app/features/indicadores/indicadores-initial-period.spec.ts b/src/app/features/indicadores/indicadores-initial-period.spec.ts index 3284c83..7367408 100644 --- a/src/app/features/indicadores/indicadores-initial-period.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-period.spec.ts @@ -48,7 +48,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma 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(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico']); + expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']); } else expect(anchor.id).toBe('cacu_eu7'); const run = start(); inventory(); request(periods[0]).flush(data(periods[0])); expect(run.selected()?.periodo).toBe(periods[0]); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 9985a79..96b542a 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -2,11 +2,27 @@ import { Dominio, IndicadorDatos } from './indicadores.models'; import { GlobalApplied } from './indicadores-memory'; import { percentNumber } from './indicadores-format'; -export interface KpiDefinition { id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; } +export interface KpiDefinition { + id: string; title: string; contrato: 'C1' | 'C2' | 'C3r'; unit: string; singleAppliedPeriod?: boolean; + // C1 only: replaces the domain's explanatory line when the numerator is not the domain's usual one. + c1Info?: (numerador: number, denominador: number) => string; + // C3r only: a median over zero observations is no value, not zero days. + requiresObservations?: boolean; +} // Same laboratory-result source used by PARES_TIEMPOS; diagnosis has its own ID. 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 tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, +}; +export const CAMA_TASA_DETECCION_KPI: KpiDefinition = { + id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%', + c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`, +}; +export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = { + id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, +}; // Provisional (oct 2026): titles are copied by hand from the `title` of each indicator's TOML // in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories // (patients), not the distribution. If a TOML title changes, change it here too, until the @@ -25,8 +41,30 @@ export const KPI_BY_DOMAIN: Record = { { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + CAMA_TAMIZAJE_RESULTADO_KPI, ], }; + +// CaMa's four opportunity cards, in display order. Two of them have no indicator in the catalog yet +// (indicadores_kit defines neither `cama_tasa_deteccion_histopatologica` nor `cama_dias_resultado_diagnostico`), +// so they stay outside KPI_BY_DOMAIN: they are queried only once the catalog publishes them. +export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [ + KPI_BY_DOMAIN.cama[0], + CAMA_TASA_DETECCION_KPI, + CAMA_TAMIZAJE_RESULTADO_KPI, + CAMA_RESULTADO_DIAGNOSTICO_KPI, +]; +export interface KpiCardSlot { definition: KpiDefinition; pending: boolean; } +// The four opportunity cards first, each pending while its indicator is not in the catalog, then the +// other published CaMa cards. Nothing at all (not even pending cards) until the catalog publishes one of them. +export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[] { + const cards = [ + ...CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) })), + ...KPI_BY_DOMAIN.cama.filter(definition => !CAMA_OPORTUNIDAD_KPIS.includes(definition) && published(definition.id)) + .map(definition => ({ definition, pending: false })), + ]; + return cards.some(card => !card.pending) ? cards : []; +} // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; const C1_INFO: Record string> = { @@ -78,8 +116,8 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai } if (definition.contrato === 'C1') { if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: percentNumber(row['valor']), info: C1_INFO[domain](row['numerador'], row['denominador']) }; + return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) }; } - if (!finite(row['mediana']) || !count(row['n']) || (definition.id === CACU_RESULTADO_KPI.id && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; + if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; } diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index ece0cad..a882e76 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -73,14 +73,19 @@ } @else if (initialPeriodState() === 'manual') {

La búsqueda inicial se detuvo para conservar tu selección. Pulsa Aplicar para consultar.

} - @let kpis = opportunityKpis; + @let kpis = kpiCards; @if (kpis.length && !initialPeriodBlocked) {

{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

- @for (definition of kpis; track dominio + ':' + definition.id) { - + @for (card of kpis; track dominio + ':' + card.definition.id) { + @if (card.pending) { + + } @else { + + } } @if (dominio === 'cacu') { diff --git a/src/app/features/indicadores/indicadores-page.scss b/src/app/features/indicadores/indicadores-page.scss index c3f0285..6fdacce 100644 --- a/src/app/features/indicadores/indicadores-page.scss +++ b/src/app/features/indicadores/indicadores-page.scss @@ -65,6 +65,10 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; } @container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } } // Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids. +// CaMa's opportunity cards: one size, four in a row on wide screens and two by two below. +.kpi-section[data-domain='cama'] .kpi-grid { grid-auto-rows: 1fr; } +@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } } .kpi-section[data-domain='cacu'] .kpi-grid { grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr)); align-items: stretch; diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index b42015b..1dac968 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,7 +17,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; @@ -298,6 +298,11 @@ export class IndicadoresPage { return [...definitions.slice(0, diagnosis < 0 ? definitions.length : diagnosis), CACU_RESULTADO_KPI, ...definitions.slice(diagnosis < 0 ? definitions.length : diagnosis)]; } + // What the KPI grid draws. CaMa adds explicit pending cards for opportunity indicators the catalog does not publish. + get kpiCards(): KpiCardSlot[] { + if (this.dominio === 'cama') return camaKpiCards(id => this.catalog().some(item => item.id === id)); + return this.opportunityKpis.map(definition => ({ definition, pending: false })); + } private readonly catalogRequests = new Subject(); readonly catalog = signal([]); readonly searchQuery = signal(''); diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index 651d938..696ae81 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -63,13 +63,13 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { } } it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => { - load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); + load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1'], ['2026-S1', '2025-S1']]); const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos')); const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges(); const requests = flushDatos(domain); expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1')); expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1')); - expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, '0.0', 0]); + expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, undefined, '0.0', 0]); // Display order; the second card is the new median over n = 0, which is no value expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] }); expect(fixture.componentInstance.filters!.applied.revision).toBe(1); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); @@ -85,11 +85,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); }); it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { - load('cama', [[], ['2025-S2'], ['2025-S1']]); + load('cama', [[], ['2025-S2'], ['2025-S1'], ['2025-S2']]); expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama'); - expect(requests).toHaveLength(2); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); + expect(requests).toHaveLength(3); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); expect(panels()[0].result().value).toBeUndefined(); }); it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { From 8a3f68df6bc2cb040e011e7e5b904d6a88e00cf3 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 11 Nov 2026 23:56:14 -0600 Subject: [PATCH 02/38] fix(indicadores): guard invalid C1 denominators and preserve status --- .../indicadores/indicador-kpi-card.ts | 4 +- .../indicadores/indicador-kpi-panel.spec.ts | 2 +- .../indicadores-cama-oportunidad.spec.ts | 52 +++++++++++++++++-- .../features/indicadores/indicadores-kpi.ts | 10 +++- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/indicador-kpi-card.ts b/src/app/features/indicadores/indicador-kpi-card.ts index a76d6db..09d0a69 100644 --- a/src/app/features/indicadores/indicador-kpi-card.ts +++ b/src/app/features/indicadores/indicador-kpi-card.ts @@ -13,7 +13,7 @@ import { MatCardModule } from '@angular/material/card';

{{ value }}@if (unit) { {{ unit }} }

} @if (temporalReference) {

{{ temporalReference }}

} - @if (!(quietWhenAvailable && state === 'Disponible')) {

{{ state }}

} +

{{ state }}

@if (informationLine) {

{{ informationLine }}

} `, @@ -26,6 +26,8 @@ import { MatCardModule } from '@angular/material/card'; h3, p { overflow-wrap: anywhere; } p { margin: var(--issste-space-3) 0 0; } .kpi-state, .additional-info { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } + .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; + clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } .value { font: var(--mat-sys-headline-medium); } .value span { margin-inline-start: .3em; } // CaMa's cards are as tall as their grid row. diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 1dab35f..50ee29c 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -179,7 +179,7 @@ describe('KPI integración con autoridad global', () => { expect(cards).toHaveLength(domain === 'cacu' ? 5 : 6); expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined, '40.0', '7']); expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined, '%', 'días (mediana)']); - expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : [undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]); + expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Disponible', 'Disponible']); expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect.stringContaining('2025-S1'), expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), diff --git a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts index 10143f5..2372853 100644 --- a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts @@ -55,15 +55,51 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => { const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0'); }); + it('un denominador de cero no se presenta como una tasa válida', () => { + // Fails if the 0/0 response that activated the CaMa card is drawn as a valid 0.0%. + const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 0 }), CAMA_TASA_DETECCION_KPI, 'cama', applied); + expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined(); + }); it.each([ ['valor nulo', { valor: null, numerador: 0, denominador: 8 }], ['denominador nulo', { valor: 0, numerador: 0, denominador: null }], - ['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }], + ['denominador ausente', { valor: 0, numerador: 0 }], ])('la tasa con %s no se convierte en cero', (_name, fields) => { // Fails if a missing or incoherent rate is drawn as a value. const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied); expect(result.value).toBeUndefined(); expect(result.state).toBe('Sin valor disponible'); }); + it.each([ + ['numerador mayor que denominador', { valor: 100, numerador: 9, denominador: 8 }], + ['numerador positivo con denominador cero', { valor: 0, numerador: 1, denominador: 0 }], + ['denominador negativo', { valor: 0, numerador: 0, denominador: -1 }], + ])('los conteos incompatibles (%s) son error de contrato', (_name, fields) => { + // Fails if structurally impossible counts are collapsed into a legitimate no-value response. + const result = kpiResult(c1(fields), CAMA_TASA_DETECCION_KPI, 'cama', applied); + expect(result.state).toBe('Error de contrato'); expect(result.value).toBeUndefined(); + }); + it.each(['tea', 'cacu', 'cama'] as const)('el 0/0 se trata como tasa sin valor para %s', domain => { + // Fails if the shared C1 result path regresses another domain's zero-denominator semantics. + const definition = domain === 'cacu' + ? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' } + : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; + const group = domain === 'tea' ? 'TOTAL' : 'total'; + const data = { ...c1({ valor: 0, numerador: 0, denominador: 0 }), id: definition.id, + filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 0 }] }; + const result = kpiResult(data, definition, domain, applied); + expect(result.state).toBe('Sin valor disponible'); expect(result.value).toBeUndefined(); + }); + it.each(['tea', 'cacu', 'cama'] as const)('el cero con denominador positivo permanece disponible para %s', domain => { + // Fails if the denominator guard accidentally rejects a real zero rate in any C1 domain. + const definition = domain === 'cacu' + ? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' } + : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; + const group = domain === 'tea' ? 'TOTAL' : 'total'; + const data = { ...c1({ valor: 0, numerador: 0, denominador: 8 }), id: definition.id, + filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 8 }] }; + const result = kpiResult(data, definition, domain, applied); + expect(result.state).toBe('Disponible'); expect(result.value).toBe('0.0'); + }); it('un dato suprimido por tamaño oculta la cifra en las cuatro tarjetas', () => { // Fails if a suppressed row leaks a number. const cases: [KpiDefinition, IndicadorDatos][] = [ @@ -170,7 +206,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado a diagnóstico', 'Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico']); expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, '40.0%', '7días (mediana)']); - expect(cards().map(card => text(card, '.kpi-state'))).toEqual([undefined, 'Integración pendiente', undefined, 'Integración pendiente', undefined, undefined]); + expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Disponible', 'Disponible']); expect(cards()[1].textContent).toContain('aún no está publicado'); expect(cards()[1].textContent).not.toMatch(/\d/); }); @@ -203,14 +239,22 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de tamizaje a resultado"]')).not.toBeNull(); }); - it('el estado Disponible solo se omite en CaMa: la tarjeta compartida lo sigue diciendo por defecto', () => { + it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => { const card = TestBed.createComponent(IndicadorKpiCard); card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges(); expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Disponible'); card.componentRef.setInput('quietWhenAvailable', true); card.detectChanges(); - expect(card.nativeElement.querySelector('.kpi-state')).toBeNull(); + const status = card.nativeElement.querySelectorAll('[role="status"]'); + expect(status).toHaveLength(1); + expect(status[0].textContent).toBe('Disponible'); + expect(status[0].classList.contains('visually-hidden')).toBe(true); card.componentRef.setInput('state', 'Sin datos del periodo'); card.detectChanges(); + expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1); expect(card.nativeElement.querySelector('.kpi-state').textContent).toBe('Sin datos del periodo'); + expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false); + card.componentRef.setInput('quietWhenAvailable', false); card.componentRef.setInput('state', 'Disponible'); card.detectChanges(); + expect(card.nativeElement.querySelectorAll('[role="status"]')).toHaveLength(1); + expect(card.nativeElement.querySelector('.kpi-state').classList.contains('visually-hidden')).toBe(false); card.destroy(); }); }); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 96b542a..f4b7607 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -115,8 +115,14 @@ export function kpiResult(data: IndicadorDatos, definition: KpiDefinition, domai return { state: 'Disponible', value, info: domain === 'cacu' ? 'Pacientes con citología tomada en el periodo.' : 'Conteo de pacientes únicos en el periodo.' }; } if (definition.contrato === 'C1') { - if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100 || !count(row['numerador']) || !count(row['denominador']) || row['numerador'] > row['denominador']) return empty; - return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(row['numerador'], row['denominador']) }; + if (!finite(row['valor']) || row['valor'] < 0 || row['valor'] > 100) return empty; + const numerator = row['numerador'], denominator = row['denominador']; + if (numerator == null || denominator == null) return empty; + if (!count(numerator) || !count(denominator) || numerator > denominator) { + return { state: 'Error de contrato', info: 'El numerador y el denominador deben ser conteos no negativos compatibles.' }; + } + if (denominator === 0) return empty; + return { state: 'Disponible', value: percentNumber(row['valor']), info: (definition.c1Info ?? C1_INFO[domain])(numerator, denominator) }; } if (!finite(row['mediana']) || !count(row['n']) || ((definition.id === CACU_RESULTADO_KPI.id || definition.requiresObservations) && row['n'] === 0) || !finite(row['q1']) || !finite(row['q3']) || row['q1'] < 0 || row['q1'] > row['mediana'] || row['mediana'] > row['q3'] || row['unidad'] !== 'dias') return empty; return { state: 'Disponible', value: row['mediana'], info: C3R_INFO[domain](row['n'], row['q1'], row['q3']) }; From 7b8fd9e01daef79d9c4524167776e0a6b60ee302 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Wed, 11 Nov 2026 23:48:03 -0600 Subject: [PATCH 03/38] feat(indicadores): CaMa labels, single-period filters and the four-card strip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CaMa reads «cáncer de mama» everywhere on the indicators page and uses the compact filter: interval, one period and Aplicar on one row, without the mode selector, the multiple selection or the editing summaries. The opportunity strip is the four cards only, and the biopsy distribution card is no longer drawn in the summary (it stays in Datos y definiciones). Other domains keep their filter and strip. (cherry picked from commit 7c9dcf634e5870fec35ab96347b0863b2e3bb86e) --- .../indicadores/indicador-kpi-panel.spec.ts | 10 +- .../indicadores/indicador-period-filters.html | 52 ++++++++ .../indicadores/indicador-period-filters.scss | 3 + .../indicadores/indicador-period-filters.ts | 2 + .../indicadores-cama-oportunidad.spec.ts | 113 +++++++++++++++--- .../indicadores/indicadores-definitions.ts | 2 +- .../indicadores-initial-period.spec.ts | 2 +- .../indicadores-kpi-cama-real.spec.ts | 8 +- .../indicadores/indicadores-kpi.spec.ts | 6 +- .../features/indicadores/indicadores-kpi.ts | 14 +-- .../indicadores/indicadores-page.html | 6 +- .../features/indicadores/indicadores-page.ts | 8 +- .../indicadores-periodos-integration.spec.ts | 8 +- 13 files changed, 188 insertions(+), 46 deletions(-) diff --git a/src/app/features/indicadores/indicador-kpi-panel.spec.ts b/src/app/features/indicadores/indicador-kpi-panel.spec.ts index 50ee29c..35e4d87 100644 --- a/src/app/features/indicadores/indicador-kpi-panel.spec.ts +++ b/src/app/features/indicadores/indicador-kpi-panel.spec.ts @@ -168,7 +168,7 @@ describe('KPI integración con autoridad global', () => { expect(panels()).toHaveLength(2); expect(panels().every(p => p.result().state === 'Sin reportes disponibles')).toBe(true); http.expectNone(r => r.url.endsWith('/datos')); }); - it('las seis tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => { + it('las tarjetas conservan valores, unidades, periodo e información sin etiqueta estadística frontend', () => { for (const domain of ['cacu', 'cama'] as const) { load(domain); const req = requests(); expect(req).toHaveLength(KPI_BY_DOMAIN[domain].length); @@ -176,10 +176,10 @@ describe('KPI integración con autoridad global', () => { req.forEach(r => r.flush({ ...response(KPI_BY_DOMAIN[domain].findIndex(d => r.request.url.endsWith('/' + d.id + '/datos')), domain), notas: ['Nota del pie de la figura.'] })); fixture.detectChanges(); const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')]; - expect(cards).toHaveLength(domain === 'cacu' ? 5 : 6); - expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined, '40.0', '7']); - expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined, '%', 'días (mediana)']); - expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Disponible', 'Disponible']); + expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4); + expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(domain === 'cacu' ? ['5', undefined, '7', undefined, undefined] : ['5', undefined, '7', undefined]); + expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(domain === 'cacu' ? ['pacientes', undefined, 'días (mediana)', undefined, undefined] : ['pacientes', undefined, 'días (mediana)', undefined]); + expect(cards.map(card => card.querySelector('.kpi-state')?.textContent.trim())).toEqual(domain === 'cacu' ? ['Disponible', 'Selección no consolidable', 'Disponible', 'Indicador no disponible', 'Indicador no disponible'] : ['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']); expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([ expect.stringContaining('2025-S1'), expect.stringContaining(domain === 'cacu' ? '5 citologías; primer cuartil: 3 días; tercer cuartil: 9 días.' : '5 mastografías; Q1 a Q3: 3 a 9 días.'), diff --git a/src/app/features/indicadores/indicador-period-filters.html b/src/app/features/indicadores/indicador-period-filters.html index 653235b..51264f2 100644 --- a/src/app/features/indicadores/indicador-period-filters.html +++ b/src/app/features/indicadores/indicador-period-filters.html @@ -1,3 +1,54 @@ +@if (compact) { +
+@if (!types.includes(state.tipo)) {

El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.

} +
+ Intervalo de análisis + + @for (tipo of types; track tipo) { {{ tipo === 'mes' ? 'Mensual' : 'Semestral' }} } + + + Periodo seleccionado + + {{ selectedPeriods[0] }} + @for (period of options; track period) { {{ period }} } + @if (availability) { + @for (period of unavailableSelection; track period) { {{ period }}, disponibilidad no confirmada } + } + + + + @if (hasPending) { Hay cambios sin aplicar. } +
+

Filtro general aplicado: {{ appliedSummary }}. {{ availability ? 'Existe reporte en al menos un indicador del dominio.' : 'Disponibilidad desconocida hasta consultar.' }}

+@if (availability) { + @if (availability.status === 'loading') {

Consultando periodos disponibles…

} + @else if (availability.status === 'error') { +

No se pudo completar la consulta de periodos disponibles.

+ + } @else if (!options.length) {

Sin reportes disponibles para este intervalo de análisis.

} + @if (entry.draft.mode === 'explicit' && unavailableSelection.length) {

La selección conservada contiene periodos cuya disponibilidad no está confirmada. Elige periodos disponibles antes de aplicar.

} +} +@if (!availability) { +

Periodos agregados por ti. Su disponibilidad se desconoce hasta consultar; esta lista no es un inventario de reportes.

+
+ Año + {{ state.tipo === 'mes' ? 'Mes' : 'Semestre' }} + + @for (value of state.tipo === 'mes' ? months : ['S1', 'S2']; track value) { {{ value }} } + + + +
+
+ @for (period of entry.added; track period) { + + } +
+} +@if (error) { } +@if (!canApply) {

Selecciona un periodo válido para aplicar.

} +
+} @else {
@if (state.tipo === 'mes') {

Para consultar meses debes elegir periodos explícitos. Todos con reporte utiliza semestres.

} @if (!types.includes(state.tipo)) {

El intervalo de tiempo del borrador ya no está publicado para este proyecto. Elige un intervalo de tiempo disponible.

} @@ -64,3 +115,4 @@

Filtro general aplicado: {{ appliedSummary }}

+} diff --git a/src/app/features/indicadores/indicador-period-filters.scss b/src/app/features/indicadores/indicador-period-filters.scss index ed8f559..831bfdc 100644 --- a/src/app/features/indicadores/indicador-period-filters.scss +++ b/src/app/features/indicadores/indicador-period-filters.scss @@ -13,6 +13,9 @@ p { overflow-wrap: anywhere; line-height: 1.5; margin: var(--issste-space-3) 0; .remove { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); } .remove button { min-height: 44px; } .apply-button { min-height: 44px; margin-top: var(--issste-space-2); } +.fields.compact { align-items: center; } +.fields.compact mat-form-field { flex: 0 1 14rem; } +.fields.compact .apply-button { margin-top: 0; } @media (max-width: 550px) { mat-form-field, .period-builder mat-form-field { flex: 1 1 100%; max-width: none; } .period-builder button { margin-top: 0; } diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts index 170abce..adbd545 100644 --- a/src/app/features/indicadores/indicador-period-filters.ts +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -19,6 +19,8 @@ export class IndicadorPeriodFilters implements OnChanges { @Input({ required: true }) types!: TipoPeriodo[]; @Input() availability?: PeriodAvailability; @Input() initialPresentation = false; + // One period at a time, with the interval and Aplicar on one row. + @Input() compact = false; @Output() retryAvailability = new EventEmitter(); @Output() edited = new EventEmitter(); @Output() apply = new EventEmitter(); diff --git a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts index 2372853..6b65584 100644 --- a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts @@ -9,6 +9,8 @@ import { By } from '@angular/platform-browser'; import { IndicadoresPage } from './indicadores-page'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; +import { IndicadorPeriodFilters } from './indicador-period-filters'; +import { emptyAvailability } from './indicadores-periodos'; import { CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult, @@ -37,9 +39,8 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => { 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', () => { - // Fails if an indicator the catalog does not publish is queried by default. - expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual([ - 'cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']); + // Fails if an indicator the catalog does not publish is queried by default, or if a card the summary retired comes back. + expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']); expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI); expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI); }); @@ -132,18 +133,18 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => { describe('Tarjetas de oportunidad de CaMa: cuáles se dibujan', () => { const only = (...ids: string[]) => (id: string) => ids.includes(id); - it('sin ningún indicador publicado no hay tarjetas, ni siquiera pendientes', () => { - // Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed. + it('sin ningún indicador de oportunidad publicado no hay tarjetas, ni siquiera pendientes', () => { + // Fails if "Integración pendiente" is shown while the catalog is empty, loading or failed, or because of other CaMa indicators. expect(camaKpiCards(only())).toEqual([]); - expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico')).filter(c => !c.pending).length).toBe(2); + expect(camaKpiCards(only('cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_biopsias'))).toEqual([]); expect(camaKpiCards(only('cama_tasa_deteccion_histopatologica')).filter(c => !c.pending).length).toBe(1); }); - it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y las existentes de DEV siguen después', () => { + it('con el catálogo actual del laboratorio hay dos tarjetas vivas y dos pendientes, y nada más', () => { + // Fails if the confirmation and screening-to-diagnosis cards, retired from the strip, are drawn again. const cards = camaKpiCards(only('cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a')); expect(cards.map(c => [c.definition.id, c.pending])).toEqual([ ['cama_birads_456_paciente', false], ['cama_tasa_deteccion_histopatologica', true], - ['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true], - ['cama_confirmacion_birads45', false], ['cama_dias_toma_diagnostico', false]]); + ['cama_eu38a', false], ['cama_dias_resultado_diagnostico', true]]); }); it('una tarjeta pendiente pasa a viva cuando el catálogo publica su indicador, sin tocar código', () => { const cards = camaKpiCards(only(...CAMA_OPORTUNIDAD_KPIS.map(d => d.id))); @@ -166,6 +167,12 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { }); afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); const catalog = (definitions: KpiDefinition[]) => definitions.map(d => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] })); + // What 18080 publishes besides the opportunity indicators: none of them has a card in the strip. + const otros = (): KpiDefinition[] => [ + { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, + { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, + { id: 'cama_biopsias', title: 'Distribución de resultados de biopsia', contrato: 'C2', unit: 'biopsias' }, + { id: 'cama_birads_456_mastografia', title: 'Porcentaje individual de mastografías', contrato: 'C2', unit: 'mastografías' }]; const dataFor = (definition: KpiDefinition): IndicadorDatos => { if (definition.contrato === 'C2') return datos(definition, [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }]); if (definition.contrato === 'C1') return datos(definition, [{ ...row, grupo: 'total', valor: 40, numerador: 2, denominador: 5 }]); @@ -200,22 +207,24 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { it('con el catálogo actual: dos tarjetas con datos, dos pendientes y ninguna consulta a indicadores sin publicar', () => { // Fails if a pending indicator is requested, or if a pending card is drawn with a number. - const urls = load(KPI_BY_DOMAIN.cama); + const urls = load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) }); expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica') || url.includes('cama_dias_resultado_diagnostico'))).toBe(false); + expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false); + 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 detección histopatológica', 'Tiempo de tamizaje a resultado', - 'Tiempo de resultado a diagnóstico', 'Tasa de confirmación histopatológica', 'Tiempo de tamizaje a diagnóstico']); - expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, '40.0%', '7días (mediana)']); - expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Disponible', 'Disponible']); + 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado a diagnóstico']); + expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]); + expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']); expect(cards()[1].textContent).toContain('aún no está publicado'); expect(cards()[1].textContent).not.toMatch(/\d/); }); it('si el catálogo publica los cuatro indicadores no queda ninguna tarjeta pendiente', () => { // Fails if a published opportunity indicator is not queried and drawn. const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]); + expect(cards()).toHaveLength(4); expect(urls.some(url => url.includes('cama_tasa_deteccion_histopatologica'))).toBe(true); expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).toBe(true); - expect(cards().map(card => text(card, 'h3')).slice(0, 4)).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)); + expect(cards().map(card => text(card, 'h3'))).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)); expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false); expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.'); }); @@ -239,6 +248,22 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { expect(fixture.nativeElement.textContent).not.toContain('private'); expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de tamizaje a resultado"]')).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. + load(KPI_BY_DOMAIN.cama, { listed: catalog([...KPI_BY_DOMAIN.cama, ...otros()]) }); + const ids = fixture.componentInstance.searchResults().items.map(item => item.id); + expect(ids).not.toContain('cama_biopsias'); + expect(ids).toContain('cama_birads_456_mastografia'); + expect(fixture.nativeElement.querySelector('.catalog-grid').textContent).not.toContain('Distribución de resultados de biopsia'); + }); + it('los rótulos de CaMa dicen «cáncer de mama»', () => { + load(KPI_BY_DOMAIN.cama); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Cáncer de mama, investigación'); + expect(text).toContain('Explora los indicadores de cáncer de mama.'); + expect(text).toContain('Filtros generales de cáncer de mama'); + expect(text).toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.'); + }); it('Disponible queda visualmente oculto y sigue en un único estado accesible en CaMa', () => { const card = TestBed.createComponent(IndicadorKpiCard); card.componentRef.setInput('title', 'Indicador'); card.componentRef.setInput('state', 'Disponible'); card.detectChanges(); @@ -258,3 +283,61 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { card.destroy(); }); }); + +describe('Filtros generales de CaMa: periodo único', () => { + let fixture: ReturnType>; + const availability = () => ({ ...emptyAvailability('ready'), options: { semestre: ['2025-S2', '2025-S1'], mes: ['2025-12', '2025-11'] } }); + function mount(compact: boolean, draft: unknown = { mode: 'explicit', periodos: ['2025-S2'] }, applied: unknown = { mode: 'explicit', periodos: ['2025-S2'] }) { + TestBed.configureTestingModule({ imports: [IndicadorPeriodFilters] }); + fixture = TestBed.createComponent(IndicadorPeriodFilters); + fixture.componentRef.setInput('types', ['semestre', 'mes']); + fixture.componentRef.setInput('compact', compact); + fixture.componentRef.setInput('availability', availability()); + fixture.componentRef.setInput('state', { tipo: 'semestre', editors: { semestre: { added: [], draft }, mes: { added: [], draft: { mode: 'empty' } } }, + applied: { tipo: 'semestre', selection: applied } }); + fixture.detectChanges(); + return fixture.componentInstance; + } + afterEach(() => fixture.destroy()); + const labels = () => [...fixture.nativeElement.querySelectorAll('mat-label')].map(e => (e as HTMLElement).textContent?.trim()); + + it('muestra Intervalo de análisis, Periodo seleccionado y Aplicar en una fila, sin modalidad ni resúmenes de edición', () => { + // Fails if the multi-period controls or the editing summaries come back to CaMa. + mount(true); + expect(labels()).toEqual(['Intervalo de análisis', 'Periodo seleccionado']); + expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull(); + const text = fixture.nativeElement.textContent as string; + expect(text).not.toContain('Modalidad'); + expect(text).not.toContain('Selección en edición'); + expect(text).not.toContain('Sin cambios pendientes'); + expect(text).toContain('Filtro general aplicado: 2025-S2. Existe reporte en al menos un indicador del dominio.'); + }); + it('elegir otro periodo deja un solo periodo en el borrador y avisa que hay cambios sin aplicar', () => { + // Fails if the control keeps more than one period, or if the pending notice is lost. + const control = mount(true); + expect(fixture.nativeElement.textContent).not.toContain('Hay cambios sin aplicar.'); + control.select(['2025-S1']); fixture.componentRef.setInput('state', { ...control.state }); fixture.detectChanges(); + expect(control.state.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: ['2025-S1'] }); + expect(fixture.nativeElement.textContent).toContain('Hay cambios sin aplicar.'); + let applied = 0; control.apply.subscribe(() => applied++); + (fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).click(); + expect(applied).toBe(1); + }); + it('Aplicar no se puede pulsar sin cambios pendientes', () => { + mount(true); + expect((fixture.nativeElement.querySelector('.apply-button') as HTMLButtonElement).disabled).toBe(true); + }); + it('sin periodo elegido no hay nada que aplicar', () => { + const control = mount(true, { mode: 'empty' }); + expect(control.canApply).toBe(false); + expect(fixture.nativeElement.textContent).toContain('Selecciona un periodo válido para aplicar.'); + }); + it('los demás dominios conservan Modalidad, la selección múltiple y sus resúmenes', () => { + // Fails if the single-period layout leaks to CaCu or TEA. + mount(false, { mode: 'todos' }, { mode: 'todos' }); + expect(labels()).toEqual(['Intervalo de tiempo', 'Modalidad']); + const text = fixture.nativeElement.textContent as string; + expect(text).toContain('Selección en edición: Todos con reporte'); + expect(text).toContain('Sin cambios pendientes.'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-definitions.ts b/src/app/features/indicadores/indicadores-definitions.ts index 78f09de..4561cb6 100644 --- a/src/app/features/indicadores/indicadores-definitions.ts +++ b/src/app/features/indicadores/indicadores-definitions.ts @@ -19,7 +19,7 @@ export class IndicadoresDefinitions { @Input() loading = false; @Input() error = ''; readonly retry = output(); - readonly domainNames: Record = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' }; + readonly domainNames: Record = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' }; readonly periodNames: Record = { semestre: 'Semestral', mes: 'Mensual' }; readonly figureDisplayName = figureDisplayName; readonly periodInterpretation = PERIOD_INTERPRETATION; diff --git a/src/app/features/indicadores/indicadores-initial-period.spec.ts b/src/app/features/indicadores/indicadores-initial-period.spec.ts index 7367408..9d6d180 100644 --- a/src/app/features/indicadores/indicadores-initial-period.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-period.spec.ts @@ -48,7 +48,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma 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(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']); + 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])); expect(run.selected()?.periodo).toBe(periods[0]); diff --git a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts index 93285fd..246052a 100644 --- a/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi-cama-real.spec.ts @@ -1,4 +1,4 @@ -import { KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi'; +import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi'; import { IndicadorDatos } from './indicadores.models'; // /cama/indicadores//datos?periodos=2025-S2 as WebApi served it (oct 2026) over a CaMa base @@ -129,7 +129,11 @@ const DATOS_2025_S2: Record = { describe('KPI de CaMa con respuestas reales de WebApi', () => { const applied = { tipo: 'semestre' as const, selection: { mode: 'explicit' as const, periodos: ['2025-S2'] as [string] }, revision: 0 }; - const result = (index: number) => kpiResult(DATOS_2025_S2[KPI_BY_DOMAIN.cama[index].id], KPI_BY_DOMAIN.cama[index], 'cama', applied); + // The two cards CaMa's summary no longer draws; their real responses still have to read correctly (the history charts use them). + const confirmacion: KpiDefinition = { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }; + const tomaDiagnostico: KpiDefinition = { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }; + const definitions = [KPI_BY_DOMAIN.cama[0], confirmacion, tomaDiagnostico]; + const result = (index: number) => kpiResult(DATOS_2025_S2[definitions[index].id], definitions[index], 'cama', applied); it('pacientes evaluadas con BI-RADS 4, 5 y 6: la suma de sus categorías', () => { expect(result(0)).toEqual(expect.objectContaining({ state: 'Disponible', value: 31 })); diff --git a/src/app/features/indicadores/indicadores-kpi.spec.ts b/src/app/features/indicadores/indicadores-kpi.spec.ts index 9b612f7..e5054da 100644 --- a/src/app/features/indicadores/indicadores-kpi.spec.ts +++ b/src/app/features/indicadores/indicadores-kpi.spec.ts @@ -1,11 +1,13 @@ -import { KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi'; +import { CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi'; import { GlobalApplied } from './indicadores-memory'; import { Dominio, IndicadorDatos } from './indicadores.models'; const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 }; const total = { periodo: '2025-S1', grupo: 'TOTAL', estrato: null, suprimido: 0 }; // Keep C1 numerical-contract coverage even though CaCu no longer presents a C1 KPI. +// CaMa's C1 and C3r cards are the opportunity ones the catalog may not publish yet; the contract rules are the same. const definitions = { ...KPI_BY_DOMAIN, cacu: [KPI_BY_DOMAIN.cacu[0], - { id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]] }; + { id: 'cacu_eu13', title: 'Confirmación', contrato: 'C1', unit: '%' } as KpiDefinition, KPI_BY_DOMAIN.cacu[1]], + cama: [KPI_BY_DOMAIN.cama[0], CAMA_TASA_DETECCION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI] }; function data(domain: Dominio, index: number, filas: Record[]): IndicadorDatos { const d = definitions[domain][index]; return { id: d.id, contrato: d.contrato, tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: Object.fromEntries(filas.filter(row => typeof row['categoria'] === 'string').map(row => [row['categoria'], {}])), filas }; } diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index f4b7607..48a7788 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -39,8 +39,6 @@ export const KPI_BY_DOMAIN: Record = { ], cama: [ { id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' }, - { id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%' }, - { id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' }, CAMA_TAMIZAJE_RESULTADO_KPI, ], }; @@ -55,16 +53,14 @@ export const CAMA_OPORTUNIDAD_KPIS: KpiDefinition[] = [ CAMA_RESULTADO_DIAGNOSTICO_KPI, ]; export interface KpiCardSlot { definition: KpiDefinition; pending: boolean; } -// The four opportunity cards first, each pending while its indicator is not in the catalog, then the -// other published CaMa cards. Nothing at all (not even pending cards) until the catalog publishes one of them. +// The four opportunity cards, each pending while its indicator is not in the catalog. Nothing at all +// (not even pending cards) until the catalog publishes one of them. export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[] { - const cards = [ - ...CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) })), - ...KPI_BY_DOMAIN.cama.filter(definition => !CAMA_OPORTUNIDAD_KPIS.includes(definition) && published(definition.id)) - .map(definition => ({ definition, pending: false })), - ]; + const cards = CAMA_OPORTUNIDAD_KPIS.map(definition => ({ definition, pending: !published(definition.id) })); return cards.some(card => !card.pending) ? cards : []; } +// Published CaMa indicators whose card the summary does not draw. +export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias']; // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; const C1_INFO: Record string> = { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a882e76..d871e29 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -52,8 +52,8 @@ @if (!catalogLoading() && filters; as state) {

Filtros generales de {{ domainLabels[dominio] }}

-

{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}

- {{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : dominio === 'cama' ? 'Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}

+
@@ -76,7 +76,7 @@ @let kpis = kpiCards; @if (kpis.length && !initialPeriodBlocked) {
-

{{ dominio === 'cacu' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

+

{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : 'Indicadores destacados' }}

@for (card of kpis; track dominio + ':' + card.definition.id) { @if (card.pending) { diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 1dac968..c8f4b40 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,7 +17,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; -import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; import { figureApplied, independentFigurePeriods } from './indicadores-figure-selection'; @@ -268,9 +268,9 @@ export class IndicadoresPage { private readonly route = inject(ActivatedRoute, { optional: true }); readonly dominios = DOMINIOS; dominio: Dominio = 'tea'; - readonly domainLabels: Record = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'CaMa' }; + readonly domainLabels: Record = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' }; // At the start of the header line. - readonly domainTitles: Record = { ...this.domainLabels, cacu: 'Cáncer cervicouterino' }; + readonly domainTitles: Record = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' }; // Short form for the domain-switcher buttons (our shell's own nav, see the // template comment above it) -- `domainLabels`/`domainTitles` are prose-length. readonly domainNavLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'CaMa' }; @@ -312,7 +312,7 @@ export class IndicadoresPage { // Stable presentation priority; search matches and pins still take precedence. const items = this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] - : catalog; + : this.dominio === 'cama' ? catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id)) : catalog; const query = this.normalizeSearch(this.searchQuery()); const prioritize = (group: Indicador[]) => [ ...group.filter(item => this.isPinned(item)), diff --git a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts index 696ae81..792e459 100644 --- a/src/app/features/indicadores/indicadores-periodos-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-periodos-integration.spec.ts @@ -63,13 +63,13 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { } } it.each(['cacu', 'cama'] as const)('%s comparte el periodo del ancla aunque otros inventarios difieran y conserva sus ceros', domain => { - load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1'], ['2026-S1', '2025-S1']]); + load(domain, [['2026-S1', '2024-S2', '2025-S2'], ['2025-S1', '2026-S2', '2025-12'], ['2025-S2', '2024-S1']]); const anchor = http.expectOne(r => r.url.endsWith('/' + KPI_BY_DOMAIN[domain][0].id + '/datos')); const positive = data(0, domain, '2026-S1'); positive.filas[0]['n'] = 4; anchor.flush(positive); fixture.detectChanges(); const requests = flushDatos(domain); expect(requests.map(r => r.request.params.get('periodos'))).toEqual(KPI_BY_DOMAIN[domain].slice(1).map(() => '2026-S1')); expect(panels().map(p => p.temporalReference)).toEqual(KPI_BY_DOMAIN[domain].map(() => '2026-S1')); - expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, undefined, '0.0', 0]); // Display order; the second card is the new median over n = 0, which is no value + expect(panels().map(p => p.result().value)).toEqual(domain === 'cacu' ? [4, 0] : [4, undefined]); // CaMa's second card is a median over n = 0, which is no value expect(fixture.componentInstance.filters!.applied.selection).toEqual({ mode: 'explicit', periodos: ['2026-S1'] }); expect(fixture.componentInstance.filters!.applied.revision).toBe(1); fixture.componentInstance.applyFilters(); fixture.detectChanges(); http.expectNone(() => true); @@ -85,11 +85,11 @@ describe('P0.1 selección publicada y último periodo por KPI', () => { expect(panels().every(p => p.temporalReference === '2026-S2')).toBe(true); http.expectNone(() => true); }); it('sin reportes en una tarjeta no consulta datos y no impide las otras', () => { - load('cama', [[], ['2025-S2'], ['2025-S1'], ['2025-S2']]); + load('cama', [[], ['2025-S2']]); expect(fixture.componentInstance.initialPeriodState()).toBe('empty'); expect(panels()).toHaveLength(0); http.expectNone(r => r.url.endsWith('/datos')); fixture.componentInstance.applyFilters(); fixture.detectChanges(); const requests = flushDatos('cama'); - expect(requests).toHaveLength(3); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); + expect(requests).toHaveLength(1); expect(panels()[0].result().state).toBe('Sin reportes disponibles'); expect(panels()[0].result().value).toBeUndefined(); }); it('multiselección mensual edita sin HTTP; un periodo consulta y varios no consolidan', async () => { From d159067efd4cfd270269eecdf72206911e639559 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 00:01:17 -0600 Subject: [PATCH 04/38] feat(indicadores): CaMa clinical section heading and counter, without search, pins, navigation or representation selector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CaMa's graphic section reads «Indicadores clínicos» and counts the indicators it draws. The search box, pins, floating navigation, representation selector and figure count are not drawn for CaMa; CaCu and TEA keep them. (cherry picked from commit e54ee5a55aa3722f6895300fa7e8cefb28f12ebb) --- .../indicadores/indicador-catalog-card.ts | 18 ++-- .../indicadores-cama-resumen-clinico.spec.ts | 91 +++++++++++++++++++ .../indicadores-navegacion-lateral.spec.ts | 11 ++- .../indicadores/indicadores-page.html | 4 +- .../features/indicadores/indicadores-page.ts | 8 +- .../indicadores/indicadores-pinning.spec.ts | 3 +- 6 files changed, 118 insertions(+), 17 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 25e56cd..39c133b 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -33,13 +33,15 @@ import { parTiempos } from './indicadores-tiempos-pareados';

{{ indicador.titulo }}

- + @if (!sobrio) { + + }
- + @if (!sobrio) { } @if (isEu7) {
@@ -53,7 +55,7 @@ import { parTiempos } from './indicadores-tiempos-pareados';
} @else if (selectedFigure) { - @if (!pair.length || otherFigures.length) { + @if (!sobrio && (!pair.length || otherFigures.length)) { Representación gráfica this.updateNumeric()); }); } + // CaMa's cards carry no pin, representation selector or figure count, as in the mockup. + get sobrio() { return this.dominio === 'cama'; } get pair() { return dualFigures(this.indicador); } get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; } get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } diff --git a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts new file mode 100644 index 0000000..76deebd --- /dev/null +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -0,0 +1,91 @@ +// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not +// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep. +// Fixtures are catalogs shaped like //indicadores; no figure is requested (the cards stay out of view). +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Dominio } from './indicadores.models'; + +const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); +// The catalog 18080 publishes for CaMa. +const CAMA = [ + item('cama_biopsias', 'Distribución de resultados de biopsia', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']), + item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']), + item('cama_eu38a', 'Días de la toma de la mastografía a su resultado', 'C3r', ['fig_c3r_caja']), +]; +const OTRO = (prefijo: string) => ['a', 'b', 'c', 'd', 'e', 'f'].map(letra => item(`${prefijo}_${letra}`, `Indicador ${letra}`, 'C2', ['f', 'g'])); + +describe('Resumen clínico de CaMa y los demás dominios', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + // The KPI and period requests are not what these tests are about. + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + function open(domain: Dominio, catalog: unknown[]) { + // The page starts in TEA, whose catalog is already answered: leave it first to load it again. + if (domain === fixture.componentInstance.dominio) { + fixture.componentInstance.changeDominio(domain === 'cacu' ? 'cama' : 'cacu'); fixture.detectChanges(); + http.match(() => true); + } + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); + http.match(() => true); fixture.detectChanges(); + } + const root = () => fixture.nativeElement as HTMLElement; + const section = () => root().querySelector('.graphic-section') as HTMLElement; + const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); + + it('CaMa: «Indicadores clínicos» y un contador que cuenta lo que la sección muestra', () => { + // Fails if the heading or the counter go back to the whole catalog (6) while a card is not drawn. + open('cama', CAMA); + expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); + expect(titles()).not.toContain('Distribución de resultados de biopsia'); + expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe(titles().length + ' indicadores publicados'); + }); + it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => { + // Fails if any of the controls the mockup does not have comes back to CaMa's summary. + open('cama', CAMA); + expect(root().querySelector('.catalog-search')).toBeNull(); + expect(section().textContent).not.toContain('Buscar indicadores'); + expect(root().querySelector('.pin-toggle')).toBeNull(); + expect(section().textContent).not.toContain('Fijar indicador'); + expect(root().querySelector('.graphic-navigation-trigger')).toBeNull(); + expect(section().querySelector('mat-form-field')).toBeNull(); + expect(section().textContent).not.toContain('Representación gráfica'); + expect(section().textContent).not.toContain('figuras publicadas'); + }); + it('CaMa: las figuras guardadas como fijadas no reordenan las tarjetas', () => { + // Fails if a pin saved earlier (the control is gone) still changes the order of CaMa's cards. + open('cama', CAMA); + const before = titles(); + fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges(); + expect(titles()).toEqual(before); + }); + it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados, navegación flotante, selector y conteo de figuras', domain => { + // Fails if CaMa's simplified section leaks into the other domains. + open(domain, OTRO(domain)); + expect(root().querySelector('.catalog-search')).not.toBeNull(); + expect(root().querySelectorAll('.pin-toggle').length).toBe(6); + expect(root().querySelector('.graphic-navigation-trigger')).not.toBeNull(); + expect(section().querySelector('app-indicador-catalog-card mat-form-field')).not.toBeNull(); + expect(section().textContent).toContain('2 figuras publicadas'); + expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados'); + }); + it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => { + open('cacu', OTRO('cacu')); + expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); + open('tea', OTRO('tea')); + expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts b/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts index f531f6c..639ee05 100644 --- a/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts +++ b/src/app/features/indicadores/indicadores-navegacion-lateral.spec.ts @@ -65,7 +65,8 @@ describe('UX-10 navegación lateral del catálogo gráfico', () => { } function expectNoFigureRequests() { http.expectNone(request => request.url.includes('/figuras/') || request.url.endsWith('/datos')); } - it.each(['tea', 'cacu', 'cama'] as const)('aparece solo en Resumen para el dominio %s', async domain => { + // CaMa follows the mockup and has no floating navigation (indicadores-cama-resumen-clinico.spec.ts). + it.each(['tea', 'cacu'] as const)('aparece solo en Resumen para el dominio %s', async domain => { await load([item('chart', 'Indicador gráfico')], domain); expect(trigger()).not.toBeNull(); page.changeSection('seguimiento'); fixture.detectChanges(); @@ -160,7 +161,7 @@ describe('UX-10 navegación lateral del catálogo gráfico', () => { it('mantiene keys únicas para títulos duplicados y navega a la tarjeta elegida', async () => { const items = [item('duplicate-a', 'Resultado clínico'), item('duplicate-b', 'Resultado clínico')]; - await load(items, 'cama'); + await load(items, 'cacu'); const scroll = vi.fn(); const focus = vi.spyOn(HTMLElement.prototype, 'focus'); for (const card of fixture.nativeElement.querySelectorAll('app-indicador-catalog-card')) { @@ -173,7 +174,7 @@ describe('UX-10 navegación lateral del catálogo gráfico', () => { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); - const targetId = identityElementId(indicatorIdentity('cama', 'duplicate-b')); + const targetId = identityElementId(indicatorIdentity('cacu', 'duplicate-b')); expect(scroll).toHaveBeenCalledOnce(); expect(scroll.mock.instances[0]).toBe(fixture.nativeElement.querySelector('#' + targetId)); expect(focus).toHaveBeenCalled(); @@ -394,8 +395,8 @@ describe('UX-10 navegación lateral del catálogo gráfico', () => { vi.advanceTimersByTime(500); expect(page.navigationOpen()).toBe(true); pointer(trigger()!, 'pointerleave'); - page.changeDominio('cama'); - http.expectOne('/cama/indicadores').flush([item('b', 'CaMa')]); fixture.detectChanges(); + page.changeDominio('cacu'); + http.expectOne('/cacu/indicadores').flush([item('b', 'CaCu')]); fixture.detectChanges(); expect(page.navigationAttached()).toBe(false); pointer(trigger()!, 'pointerenter'); vi.advanceTimersByTime(500); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index d871e29..5893415 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -97,9 +97,9 @@
-

{{ dominio === 'cacu' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}

+

{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}

@if (!catalogLoading() && !catalogError() && catalog().length) { -

{{ catalog().length }} indicadores publicados

+

{{ shownIndicators }} indicadores publicados

}
@if (catalogLoading()) { diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index c8f4b40..d209a54 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -289,6 +289,8 @@ export class IndicadoresPage { } return undefined; } + // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. + get shownIndicators() { return this.dominio === 'cama' ? this.searchResults().items.length : this.catalog().length; } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } get opportunityKpis() { const definitions = this.availableKpis; @@ -306,13 +308,15 @@ export class IndicadoresPage { private readonly catalogRequests = new Subject(); readonly catalog = signal([]); readonly searchQuery = signal(''); - readonly searchVisible = computed(() => this.catalog().length >= 5); + // CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws. + readonly searchVisible = computed(() => this.dominio !== 'cama' && this.catalog().length >= 5); readonly searchResults = computed(() => { const catalog = this.catalog(); // Stable presentation priority; search matches and pins still take precedence. const items = this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] : this.dominio === 'cama' ? catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id)) : catalog; + if (this.dominio === 'cama') return { items, active: false, count: 0 }; const query = this.normalizeSearch(this.searchQuery()); const prioritize = (group: Indicador[]) => [ ...group.filter(item => this.isPinned(item)), @@ -360,7 +364,7 @@ export class IndicadoresPage { cardIdentity(item: Indicador) { return indicatorIdentity(this.dominio, item.id); } cardElementId(item: Indicador) { return identityElementId(this.cardIdentity(item)); } get showGraphicNavigation() { - return this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading() + return this.dominio !== 'cama' && this.activeSection() === 'resumen' && !this.fichaPacienteAbierta() && !this.catalogLoading() && !this.catalogError() && !this.initialPeriodBlocked && this.navigationItems().length > 0; } toggleGraphicNavigation(event?: MouseEvent) { diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 8906a5e..cec6032 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -85,8 +85,9 @@ describe('UX-06E.D.3.B fijación temporal', () => { }); it('memoria independiente por dominio y persistente al recrear la página', async () => { await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id)); + // CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins. await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id)); - await pin('i4'); page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); + page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1'); page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3'); fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true); }); From ce3ed34fbfd3a73cf438ca1c016a0ae7e318f473 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 00:14:36 -0600 Subject: [PATCH 05/38] feat(indicadores): CaMa paired card of mammograms and patients by BI-RADS One card draws the exams by category as a donut and, per BI-RADS family, the patients next to the exams. Patients come from cama_birads_456_paciente (each patient once per period, in the category of the most severe exam), so its exclusive categories are added within that indicator only, for the verified version 0.2.0; other versions, suppressed or missing cells leave the figure unknown. No exams-per-patient ratio is computed and patients are never derived from exams. The patients' indicator has no card of its own while the exams' one is published. (cherry picked from commit b7bafd178896cb2715049d5c8293185f31391c92) --- .../indicadores/indicador-catalog-card.ts | 12 +- .../indicador-conteos-pareados.html | 57 +++++ .../indicador-conteos-pareados.scss | 22 ++ .../indicadores/indicador-conteos-pareados.ts | 115 +++++++++ .../indicadores-cama-resumen-clinico.spec.ts | 3 + .../indicadores-conteos-pareados.spec.ts | 220 ++++++++++++++++++ .../indicadores-conteos-pareados.ts | 136 +++++++++++ .../features/indicadores/indicadores-page.ts | 8 +- 8 files changed, 570 insertions(+), 3 deletions(-) create mode 100644 src/app/features/indicadores/indicador-conteos-pareados.html create mode 100644 src/app/features/indicadores/indicador-conteos-pareados.scss create mode 100644 src/app/features/indicadores/indicador-conteos-pareados.ts create mode 100644 src/app/features/indicadores/indicadores-conteos-pareados.spec.ts create mode 100644 src/app/features/indicadores/indicadores-conteos-pareados.ts diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 39c133b..bb25c5b 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -21,11 +21,13 @@ import { IndicadorTiemposPareados } from './indicador-tiempos-pareados'; import { IndicadorConfirmacionCitologia } from './indicador-confirmacion-citologia'; import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia'; import { parTiempos } from './indicadores-tiempos-pareados'; +import { IndicadorConteosPareados } from './indicador-conteos-pareados'; +import { parConteos } from './indicadores-conteos-pareados'; @Component({ selector: 'app-indicador-catalog-card', - host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos' }, - imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia], + host: { '[class.dual-card]': 'isDual || isEu7 || isConfirmacion || !!tiempos || !!conteos' }, + imports: [MatButtonModule, MatCardModule, MatIconModule, MatFormFieldModule, MatSelectModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorConteosPareados], template: `
@@ -54,6 +56,10 @@ import { parTiempos } from './indicadores-tiempos-pareados';
+ } @else if (conteos; as par) { +
+ +
} @else if (selectedFigure) { @if (!sobrio && (!pair.length || otherFigures.length)) { @@ -140,6 +146,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; } // Connected time pairs replace the diagnosis card with one coordinated box plot. get tiempos() { return parTiempos(this.dominio, this.indicador.id); } + // Exams and patients of the same finding, drawn together on the exams' card. + get conteos() { return parConteos(this.dominio, this.indicador.id); } get otherFigures() { return this.indicador.figuras.filter(id => !this.pair.includes(id)); } get isDual() { return this.pair.includes(this.selectedFigure ?? ''); } get displayFigures() { return this.isDual ? this.pair : this.selectedFigure ? [this.selectedFigure] : []; } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.html b/src/app/features/indicadores/indicador-conteos-pareados.html new file mode 100644 index 0000000..22e0deb --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.html @@ -0,0 +1,57 @@ +
+ + @if (helpOpen) { +
+
+

Dona por categoría

+ @if (donutGuide; as guide) { + @if (guide.descripcion) {

{{ guide.descripcion }}

} + @if (guide.como_leer.length) {
    @for (line of guide.como_leer; track $index) {
  • {{ line }}
  • }
} + } @else if (!metadata) {

Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.

} + @else {

El servicio no publica instrucciones de lectura para esta figura.

} +
+
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}

+

Cada paciente cuenta una vez en el periodo, en la categoría más grave de sus mastografías. Cada mastografía cuenta en su propia categoría. Las barras comparan ambos conteos por familia de BI-RADS; no se calcula cuántas mastografías tiene cada paciente, porque no son las mismas poblaciones.

+
+
+ } + @switch (status()) { + @case ('deferred') {

La vista se cargará al acercarse a esta región.

} + @case ('loading') {

Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…

} + @case ('empty') {

No hay periodos publicados por los dos conteos.

} + @case ('error') {

{{ message }}

} + @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + } + @if (status() === 'ready' && model; as m) { + @if (pages.length > 1) { + + } +
+

{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}

+ @if (total) { + + } @else {

{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}

} + @if (m.sinDato) {

Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.

} +
+

{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}

+ + @if (!m.pacientesVerificados) {

Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.

} +
+
+

Cada paciente cuenta una vez, en la categoría más grave de sus mastografías del periodo; cada mastografía cuenta en su categoría. Por eso no se calcula la razón de mastografías por paciente.

+ @for (note of m.notas; track $index) {

{{ note }}

} +
Valores publicados +
+ + + @for (f of m.filas; track f.id) { } +
{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}
Familia de BI-RADS{{ par.unidades.pacientes | titlecase }}{{ par.unidades.examenes | titlecase }}
{{ f.etiqueta }}{{ textoPacientes(f.pacientes) }}{{ texto(f.examenes) }}
+
+
+ } +
diff --git a/src/app/features/indicadores/indicador-conteos-pareados.scss b/src/app/features/indicadores/indicador-conteos-pareados.scss new file mode 100644 index 0000000..632a2a3 --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.scss @@ -0,0 +1,22 @@ +:host { display: block; min-width: 0; } +.conteos { min-width: 0; padding-top: var(--issste-space-3); } +p, h3, summary { overflow-wrap: anywhere; } +.applied-summary, .note { color: var(--issste-text-secondary); } +.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } +.reading-guide h3 { margin: 0 0 .25rem; } +.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; } +h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; } +.periods { display: flex; align-items: center; gap: var(--issste-space-3); } +.periods button { min-width: 44px; min-height: 44px; font-size: 1.25rem; color: var(--issste-text); background: var(--issste-surface); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; } +.periods button:disabled { opacity: .5; cursor: default; } +// The two figures share the card in equal halves; one above the other on a narrow card. +.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } +@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +app-plotly-chart { --plot-height: 400px; } +summary { cursor: pointer; padding-block: .75rem; } +summary:focus-visible, .table-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } +.table-scroll { overflow: auto; } +table { border-collapse: collapse; width: 100%; margin-block: 1rem; } +th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); } +caption { text-align: start; font-weight: 600; } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.ts b/src/app/features/indicadores/indicador-conteos-pareados.ts new file mode 100644 index 0000000..3ae0ebf --- /dev/null +++ b/src/app/features/indicadores/indicador-conteos-pareados.ts @@ -0,0 +1,115 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { TitleCasePipe } from '@angular/common'; +import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados'; + +@Component({ + selector: 'app-indicador-conteos-pareados', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart, TitleCasePipe], + templateUrl: './indicador-conteos-pareados.html', + styleUrl: './indicador-conteos-pareados.scss', +}) +export class IndicadorConteosPareados implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) par!: ParConteos; + // The card's indicator (the exams); its partner (the patients) has no card and is requested by id. + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + periodIndex = 0; + pages: ModeloConteos[] = []; + donutFigure?: PlotlyFigure; + barsFigure?: PlotlyFigure; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + + get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; } + get total() { return this.model ? totalExamenes(this.model) : null; } + texto(n: number | null) { return n === null ? 'Sin dato' : n.toLocaleString('es-MX'); } + textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); } + helpOpen = false; + // "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's + // description of its own bars does not apply to them and is not used. + get donutGuide() { + const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas'); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? { descripcion, como_leer } : undefined; + } + toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.clear(); + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + } + retry() { if (this.visible) this.load(); } + private clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.barsFigure = undefined; } + private load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.clear(); + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.indicador.id !== this.par.examenes || this.indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica el conteo necesario para esta vista.'; + this.status.set('incompatible'); return; + } + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = combineLatest([ + this.snapshots.datos(this.dominio, this.par.examenes, this.applied.tipo, periods, this.indicador.version), + this.snapshots.datos(this.dominio, this.par.pacientes, this.applied.tipo, periods), + ]).pipe(timeout({ first: 40000 })).subscribe({ + next: ([examenes, pacientes]) => { + if (key !== this.key) return; + try { + this.pages = modelosConteos(this.par, examenes, pacientes, this.applied.tipo); + // The most recent period first; navigation goes back. + this.periodIndex = Math.max(0, this.pages.length - 1); + this.draw(); this.status.set(this.model ? 'ready' : 'empty'); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof ConteosIncompatibles ? error.message : httpMessage(error); + this.status.set(error instanceof ConteosIncompatibles || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.draw(); + } + private draw() { + const m = this.model; + if (!m) return; + this.donutFigure = donaConteos(m, this.par, this.tema); + this.barsFigure = barrasConteos(m, this.par, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts index 76deebd..d14f322 100644 --- a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -51,6 +51,9 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { open('cama', CAMA); expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos'); expect(titles()).not.toContain('Distribución de resultados de biopsia'); + // The patients' counts go on the exams' card, so the partner indicator has no card of its own. + expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6'); + expect(titles()).toHaveLength(4); expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe(titles().length + ' indicadores publicados'); }); it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => { diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts new file mode 100644 index 0000000..410ca73 --- /dev/null +++ b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts @@ -0,0 +1,220 @@ +// Covers CaMa's paired card (mammograms by BI-RADS category and patients by their most severe one): what the model +// is allowed to add up, what it refuses to compute, and the card drawing it. Fixtures are shaped like the +// /cama/indicadores//datos responses of cama_birads_456_mastografia and cama_birads_456_paciente (version 0.2.0) +// served by WebApi for 2025-S2; the counts are synthetic. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorConteosPareados } from './indicador-conteos-pareados'; +import { IndicadoresMemory } from './indicadores-memory'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadorDatos } from './indicadores.models'; +import { barrasConteos, ConteosIncompatibles, donaConteos, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes } from './indicadores-conteos-pareados'; + +const PAR = parConteos('cama', 'cama_birads_456_mastografia')!; +const CATEGORIAS = { + B4A: { etiqueta: 'BI-RADS 4A', color: '#E0A060', grupo: null, gravedad: 6 }, B4B: { etiqueta: 'BI-RADS 4B', color: '#CF7D3C', grupo: null, gravedad: 7 }, + B4C: { etiqueta: 'BI-RADS 4C', color: '#C26A2B', grupo: null, gravedad: 8 }, B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null, gravedad: 9 }, + B6: { etiqueta: 'BI-RADS 6', color: '#7A2E0E', grupo: null, gravedad: 10 }, SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2', grupo: null, gravedad: null }, + B4: { etiqueta: 'B4', color: null, grupo: null, gravedad: 5 }, +}; +type Conteos = Partial>; +function respuesta(id: string, unidad: string, conteos: Conteos, extra: Partial & Record = {}, suprimidas: string[] = []): IndicadorDatos { + return { + id, titulo: id, version: '0.2.0', contrato: 'C2', unidad, tipo_periodo: 'semestre', periodos: ['2025-S2'], estrato: null, grupos: { TOTAL: 'Total' }, + categorias: CATEGORIAS, notas: [unidad === 'paciente' ? 'Pacientes cuyo BI-RADS más grave entre sus mastografías del semestre es 4, 5 o 6.' : 'Mastografías tomadas en el semestre con BI-RADS 4, 5 o 6, cada una con su categoría.'], + filas: Object.keys(CATEGORIAS).map((categoria, orden) => ({ + periodo: '2025-S2', grupo: 'TOTAL', estrato: null, categoria, n: conteos[categoria as keyof Conteos] ?? 0, orden, suprimido: suprimidas.includes(categoria) ? 1 : 0 })), + ...extra } as unknown as IndicadorDatos; +} +const examenes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_mastografia', 'examen', c, extra, suprimidas); +const pacientes = (c: Conteos, extra = {}, suprimidas: string[] = []) => respuesta('cama_birads_456_paciente', 'paciente', c, extra, suprimidas); +// The 2025-S2 counts of the laboratory instance. +const LAB_E: Conteos = { B5: 18, B4: 15 }, LAB_P: Conteos = { B5: 18, B4: 13 }; +const modelo = (e: IndicadorDatos, p: IndicadorDatos) => modelosConteos(PAR, e, p, 'semestre')[0]; + +describe('Conteos pareados de CaMa: lo que se puede sumar', () => { + it('con los datos del laboratorio: BI-RADS 4 suma sus subcategorías en ambas unidades', () => { + // Fails if the family rows stop adding the categories of each indicator (B4 without subcategory included). + const m = modelo(examenes(LAB_E), pacientes(LAB_P)); + expect(m.filas.map(f => [f.etiqueta, f.pacientes, f.examenes])).toEqual([['BI-RADS 4', 13, 15], ['BI-RADS 5', 18, 18], ['BI-RADS 6', 0, 0]]); + expect(totalExamenes(m)).toBe(33); + expect(m.pacientesVerificados).toBe(true); + }); + it('las subcategorías se suman dentro de cada indicador y los pacientes no se derivan de las mastografías', () => { + // Fails if patients are taken from the exams' counts: here 10 exams belong to 7 patients. + const m = modelo(examenes({ B4: 1, B4A: 2, B4B: 3, B4C: 4, B5: 5 }), pacientes({ B4: 1, B4A: 1, B4B: 2, B4C: 3, B5: 5 })); + expect(m.filas[0]).toMatchObject({ pacientes: 7, examenes: 10 }); + expect(m.filas[1]).toMatchObject({ pacientes: 5, examenes: 5 }); + }); + it('una celda suprimida o sin fila deja desconocida la familia que la contiene, no en cero', () => { + // Fails if an unknown cell is added as zero. + const suprimida = modelo(examenes(LAB_E), pacientes({ B4: 13, B4B: 2, B5: 18 }, {}, ['B4B'])); + expect(suprimida.filas.map(f => f.pacientes)).toEqual([null, 18, 0]); + const sinFila = pacientes(LAB_P); sinFila.filas = sinFila.filas.filter(f => f['categoria'] !== 'B4C'); + expect(modelo(examenes(LAB_E), sinFila).filas.map(f => f.pacientes)).toEqual([null, 18, 0]); + const examenSuprimido = modelo(examenes(LAB_E, {}, ['B6']), pacientes(LAB_P)); + expect(examenSuprimido.filas.map(f => f.examenes)).toEqual([15, 18, null]); + expect(totalExamenes(examenSuprimido)).toBeNull(); + expect(donaConteos(examenSuprimido, PAR, 'claro').data).toEqual([]); + }); + it('una versión del indicador de pacientes que no se verificó no se suma', () => { + // Fails if another version of the patients' indicator is added up without its definition being checked again. + const m = modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })); + expect(m.pacientesVerificados).toBe(false); + expect(m.filas.map(f => f.pacientes)).toEqual([null, null, null]); + expect(m.filas.map(f => f.examenes)).toEqual([15, 18, 0]); + const texto = JSON.stringify(barrasConteos(m, PAR, 'claro').data[0]); + expect(texto).toContain('Pendiente'); expect(texto).not.toContain('Sin dato'); + }); + it('la mastografía sin categoría solo cuenta si el indicador la publica', () => { + expect(modelo(examenes({ ...LAB_E, SIN_DATO: 3 }), pacientes(LAB_P)).sinDato).toBe(3); + const sin = examenes(LAB_E); delete (sin as unknown as Record>)['categorias']['SIN_DATO']; + expect(modelo(sin, pacientes(LAB_P)).sinDato).toBe(0); + }); + it('solo hay modelo para los periodos que publican los dos conteos, en orden cronológico', () => { + const e = examenes(LAB_E), p = pacientes(LAB_P); + e.periodos = ['2025-S2', '2025-S1', '2024-S2']; p.periodos = ['2025-S1', '2025-S2']; + expect(modelosConteos(PAR, e, p, 'semestre').map(m => m.periodo)).toEqual(['2025-S1', '2025-S2']); + }); + it('la dona muestra las categorías de las mastografías con la etiqueta publicada y un nombre claro para el 4 sin subcategoría', () => { + const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P)); + const dona = donaConteos(m, PAR, 'claro') as unknown as { data: { labels: string[]; values: number[] }[]; layout: { annotations: { text: string }[] } }; + expect(dona.data[0].labels).toEqual(['BI-RADS 4 (sin subcategoría)', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); + expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]); + expect(dona.layout.annotations[0].text).toBe('35
mastografías'); + }); +}); + +describe('Conteos pareados de CaMa: lo que no se calcula', () => { + it('no hay razón de mastografías por paciente en la figura ni en el modelo', () => { + // Fails if a "≈ x por paciente" annotation comes back: exams of a category include those of patients whose + // most severe category is another one, so the quotient mixes populations. + const m = modelo(examenes(LAB_E), pacientes(LAB_P)); + const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record }; + expect(barras.layout['annotations']).toBeUndefined(); + expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i); + expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']); + }); + it.each([ + ['unidades cambiadas', () => [examenes(LAB_E, { unidad: 'paciente' }), pacientes(LAB_P)]], + ['indicador que no es el esperado', () => [examenes(LAB_E, { id: 'otro' }), pacientes(LAB_P)]], + ['contrato que no es C2', () => [examenes(LAB_E, { contrato: 'C1' }), pacientes(LAB_P)]], + ['categorías de pacientes de otro catálogo (BIRADS_4, 5 y 6)', () => [examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } })]], + ])('respuesta incompatible: %s', (_nombre, datos) => { + // Fails if a response that is not the pair of indicators is drawn as if it were. + const [e, p] = datos(); + expect(() => modelosConteos(PAR, e, p, 'semestre')).toThrow(ConteosIncompatibles); + }); + it('el par solo existe en CaMa y su socio no tiene tarjeta propia mientras la tarjeta de mastografías esté publicada', () => { + expect(PARES_CONTEOS.map(p => p.dominio)).toEqual(['cama']); + expect(parConteos('cacu', 'cama_birads_456_mastografia')).toBeUndefined(); + expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_mastografia', 'cama_birads_456_paciente'])).toBe(true); + // Without the exams' indicator in the catalog, the patients' one keeps its own card. + expect(esSocioConteos('cama', 'cama_birads_456_paciente', ['cama_birads_456_paciente'])).toBe(false); + expect(esSocioConteos('cacu', 'cama_birads_456_paciente', ['cama_birads_456_mastografia'])).toBe(false); + }); +}); + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: { data: unknown[] }; label?: string; } + +describe('Tarjeta pareada de CaMa en la página', () => { + let fixture: ReturnType>, http: HttpTestingController; + const item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] }); + const CATALOGO = [ + item('cama_birads_456_mastografia', 'Porcentaje individual de mastografías', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_birads_456_paciente', 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6', 'C2', ['fig_c2_donas', 'fig_c2_barras']), + item('cama_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']), + ]; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorConteosPareados, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama'); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush(CATALOGO); fixture.detectChanges(); + // Only the card's own requests matter here. The period inventory is answered and the KPI requests are + // closed, because unanswered requests would hold the shared request queue. + const responder = () => { + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + if (r.request.url.endsWith('/periodos')) r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ periodo: '2025-S2', tipo: 'semestre' }] }); + else r.flush(null, { status: 404, statusText: 'Missing' }); + } + fixture.detectChanges(); + } + }; + responder(); + fixture.componentInstance.filters!.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S2'] }; + fixture.componentInstance.applyFilters(); fixture.detectChanges(); + responder(); + }); + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + const root = () => fixture.nativeElement as HTMLElement; + const tarjeta = () => fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(d => d.componentInstance as IndicadorCatalogCard) + .find(c => c.indicador.id === 'cama_birads_456_mastografia')!; + const pedidos = () => http.match(r => /cama_birads_456_(mastografia|paciente)\/datos$/.test(r.url)); + function abrir(e: IndicadorDatos = examenes(LAB_E), p: IndicadorDatos = pacientes(LAB_P)) { + tarjeta().setVisible(true); fixture.detectChanges(); + const r = pedidos(); + expect(r.map(q => q.request.url).sort()).toEqual(['/cama/indicadores/cama_birads_456_mastografia/datos', '/cama/indicadores/cama_birads_456_paciente/datos']); + expect(r.every(q => q.request.params.get('periodos') === '2025-S2')).toBe(true); + for (const q of r) q.flush(q.request.url.includes('mastografia') ? e : p); + fixture.detectChanges(); + } + + it('el resumen dibuja una sola tarjeta para mastografías y pacientes, y no dibuja el socio ni biopsias', () => { + // Fails if the patients' indicator keeps a card of its own beside the pair. + const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); + expect(titulos).toEqual(['Porcentaje individual de mastografías', 'Tasa de confirmación histopatológica']); + expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('2 indicadores publicados'); + }); + it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => { + abrir(); + 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(['Mastografías por categoría, 2025-S2', 'Pacientes y mastografías, 2025-S2']); + const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); + expect(graficas).toHaveLength(2); + expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 2]); + 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']]); + expect(texto('app-indicador-conteos-pareados')).toContain('no se calcula la razón de mastografías por paciente'); + expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato'); + }); + 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(root().textContent).toContain('Pacientes pendientes'); + expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2); + }); + it('una respuesta incompatible no dibuja cifras y lo dice', () => { + // Fails if a pair of responses that are not the two indicators is drawn as if it were. + abrir(examenes(LAB_E), pacientes(LAB_P, { categorias: { BIRADS_4: {}, BIRADS_5: {}, BIRADS_6: {} } })); + expect(root().querySelector('app-indicador-conteos-pareados [role=alert]')?.textContent).toContain('Respuesta incompatible'); + expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + expect(root().querySelector('.published-values')).toBeNull(); + }); + it('un error de red no filtra su cuerpo, no dibuja cifras y el reintento vuelve a pedir los dos conteos', () => { + tarjeta().setVisible(true); fixture.detectChanges(); + for (const q of pedidos()) { + if (q.request.url.includes('paciente')) q.flush('private', { status: 500, statusText: 'Error' }); + else q.flush(examenes(LAB_E)); + } + fixture.detectChanges(); + const alerta = root().querySelector('app-indicador-conteos-pareados [role=alert]'); + expect(alerta).not.toBeNull(); expect(alerta!.textContent).not.toContain('private'); + expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + (alerta!.querySelector('button') as HTMLButtonElement).click(); fixture.detectChanges(); + expect(pedidos().length).toBeGreaterThan(0); + }); +}); diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.ts b/src/app/features/indicadores/indicadores-conteos-pareados.ts new file mode 100644 index 0000000..c531203 --- /dev/null +++ b/src/app/features/indicadores/indicadores-conteos-pareados.ts @@ -0,0 +1,136 @@ +import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Theme } from './indicadores-c2-palette'; +import { percentNumber } from './indicadores-format'; + +// Two C2 indicators of the same finding: the exams by BI-RADS category and the patients by their most severe one. +// +// What the kit publishes (indicadores_kit, cama/familias/birads, version 0.2.0 of both): +// - exams: each exam counts once, in its own category; +// - patients: each patient counts once per period, in the category of the most severe exam of that period, +// so the patient categories are mutually exclusive and their sum is a number of different patients. +// Adding categories inside one indicator is therefore a count of the same unit. What is not allowed is mixing +// the two: the exams of a category include those of patients whose most severe exam is another category, so +// no ratio of exams to patients is computed, and patients are never derived from exams. +export interface GrupoConteo { id: string; etiqueta: string; categorias: readonly string[]; } +export interface ParConteos { + dominio: Dominio; + examenes: string; + pacientes: string; + // Exam categories in severity order, as the donut draws them. + categoriasExamen: readonly string[]; + // Rows of the bars: a BI-RADS family and the categories of both indicators that add up to it. + grupos: readonly GrupoConteo[]; + // Versions of the patient indicator whose definition was checked as above; another version is not added up. + versionesPacientes: readonly string[]; + unidades: { examenes: string; pacientes: string }; +} +export const PARES_CONTEOS: readonly ParConteos[] = [ + { dominio: 'cama', examenes: 'cama_birads_456_mastografia', pacientes: 'cama_birads_456_paciente', + categoriasExamen: ['B4', 'B4A', 'B4B', 'B4C', 'B5', 'B6'], + grupos: [ + { id: 'BIRADS_4', etiqueta: 'BI-RADS 4', categorias: ['B4', 'B4A', 'B4B', 'B4C'] }, + { id: 'BIRADS_5', etiqueta: 'BI-RADS 5', categorias: ['B5'] }, + { id: 'BIRADS_6', etiqueta: 'BI-RADS 6', categorias: ['B6'] }, + ], + versionesPacientes: ['0.2.0'], + unidades: { examenes: 'mastografías', pacientes: 'pacientes' } }, +]; +// The card of the exams draws the pair; the patients' indicator is its partner and has no card of its own. +export const parConteos = (dominio: Dominio, id: string) => PARES_CONTEOS.find(p => p.dominio === dominio && p.examenes === id); +export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly string[]) => + PARES_CONTEOS.some(p => p.dominio === dominio && p.pacientes === id && ids.includes(p.examenes)); + +// The kit publishes a 4 without subcategory as «B4», with no colour. +const ETIQUETA_RESPALDO: Readonly> = { B4: 'BI-RADS 4 (sin subcategoría)' }; +const COLOR_RESPALDO: Readonly> = { B4: '#E9C08C' }; +const COLOR_NEUTRO = '#8A9199'; + +export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; } +export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; } +export interface ModeloConteos { + periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[]; + // False when the patients' version is not one whose definition was checked: their cells stay unknown. + pacientesVerificados: boolean; notas: string[]; +} +export class ConteosIncompatibles extends Error {} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const fail = (message: string): never => { throw new ConteosIncompatibles(message); }; +const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const miles = (v: number) => v.toLocaleString('es-MX'); +// A suppressed, unpublished or invalid cell is unknown, never zero. +function cuenta(filas: Record[], periodo: string, categoria: string): number | null { + const fila = filas.find(f => f['periodo'] === periodo && f['categoria'] === categoria && f['grupo'] === 'TOTAL' && (f['estrato'] ?? null) === null); + return fila && fila['suprimido'] === 0 && typeof fila['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 ? fila['n'] : null; +} +const sumar = (valores: (number | null)[]) => valores.some(v => v === null) ? null : valores.reduce((s, v) => s + v!, 0); + +/** One model per period both responses publish, in chronological order. */ +export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacientes: IndicadorDatos, tipo: string): ModeloConteos[] { + for (const [d, id] of [[examenes, par.examenes], [pacientes, par.pacientes]] as const) { + if (d.id !== id || d.contrato !== 'C2' || d.tipo_periodo !== tipo || !Array.isArray(d.periodos) || !Array.isArray(d.filas) || !registro(d['categorias'])) { + fail('Los datos no corresponden a los conteos por mastografía y por paciente.'); + } + } + if (examenes['unidad'] !== 'examen' || pacientes['unidad'] !== 'paciente') fail('Las unidades publicadas no son mastografías y pacientes.'); + const catExamenes = examenes['categorias'] as Record, catPacientes = pacientes['categorias'] as Record; + const etiqueta = (cat: Record, id: string) => { + const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : ''; + return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id; + }; + const color = (id: string) => registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO; + const todas = par.grupos.flatMap(g => g.categorias); + if (par.categoriasExamen.some(id => !Object.hasOwn(catExamenes, id)) || todas.some(id => !Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id))) { + fail('Las categorías de mastografías y pacientes no coinciden.'); + } + const verificados = par.versionesPacientes.includes(String(pacientes['version'] ?? '')); + const periodos = [...examenes.periodos].filter(p => pacientes.periodos.includes(p)).sort(); + const filasE = examenes.filas as Record[], filasP = pacientes.filas as Record[]; + return periodos.map(periodo => ({ + periodo, + examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })), + // Only the exams the response reports apart; an indicator that lists no such category has none. + sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0, + filas: par.grupos.map(g => ({ + id: g.id, etiqueta: g.etiqueta, + pacientes: verificados ? sumar(g.categorias.map(id => cuenta(filasP, periodo, id))) : null, + examenes: sumar(g.categorias.map(id => cuenta(filasE, periodo, id))), + })), + pacientesVerificados: verificados, + notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])], + })); +} +export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n)); + +/** Exams by category around their total; nothing is drawn when a cell is unknown. */ +export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure { + const total = totalExamenes(m); + if (!total) return { data: [], layout: {} }; + const p = c2Theme(tema), n = m.examenes.map(c => c.n!); + return { data: [{ type: 'pie', hole: .6, sort: false, direction: 'clockwise', values: n, labels: m.examenes.map(c => escapar(c.etiqueta)), + marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'text', textposition: 'inside', + text: n.map((v, i) => v / total < .05 ? '' : escapar(m.examenes[i].etiqueta) + '
' + percentNumber(100 * v / total) + ' %'), + customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]), + hovertemplate: `%{label}
%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %` }], + layout: { autosize: true, height: 400, showlegend: false, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text }, + annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text }, + text: `${miles(total)}
${par.unidades.examenes}` }] }, config: { displayModeBar: false } }; +} + +/** Per BI-RADS family: patients (in their most severe category) next to exams. No ratio between them is drawn. */ +export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure { + const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta)); + const nombres = { pacientes: `${par.unidades.pacientes} (su categoría más grave)`, examenes: par.unidades.examenes }; + const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') => + v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato'; + const traza = (clave: 'pacientes' | 'examenes', color: string) => ({ + type: 'bar', orientation: 'h', name: nombres[clave], y, x: m.filas.map(f => f[clave]), marker: { color }, + text: m.filas.map(f => textoDe(f[clave], clave)), textposition: 'outside', cliponaxis: false, + hovertemplate: `%{y}: %{x} ${nombres[clave]}` }); + const maximo = Math.max(1, ...m.filas.map(f => f.examenes ?? 0), ...m.filas.map(f => f.pacientes ?? 0)); + return { data: [traza('pacientes', '#7A8794'), traza('examenes', '#C26A2B')], + layout: { autosize: true, height: 400, barmode: 'group', bargap: .3, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { t: 16, l: 96, r: 70, b: 56 }, legend: { orientation: 'h', y: -0.14, itemclick: false, itemdoubleclick: false }, + yaxis: { type: 'category', autorange: 'reversed', automargin: true, fixedrange: true }, + xaxis: { range: [0, maximo * 1.18], gridcolor: p.grid, zeroline: false, fixedrange: true } }, config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index d209a54..42b462a 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -17,6 +17,7 @@ import { IndicadoresService } from './indicadores.service'; import { applyGlobal, domainTypes, GlobalFilterState, IndicadoresMemory, pending, validDraft } from './indicadores-memory'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { esSocioConteos } from './indicadores-conteos-pareados'; import { CACU_RESULTADO_KPI, CAMA_FUERA_DEL_RESUMEN, KPI_BY_DOMAIN, KpiCardSlot, camaKpiCards } from './indicadores-kpi'; import { IndicadorKpiPanel } from './indicador-kpi-panel'; import { IndicadorKpiCard } from './indicador-kpi-card'; @@ -289,6 +290,11 @@ export class IndicadoresPage { } return undefined; } + // CaMa's summary: without the indicators it does not draw, and with the patients' counts on the exams' card. + private cardsDeCama(catalog: Indicador[]) { + const ids = catalog.map(item => item.id); + return catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids)); + } // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. get shownIndicators() { return this.dominio === 'cama' ? this.searchResults().items.length : this.catalog().length; } get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } @@ -315,7 +321,7 @@ export class IndicadoresPage { // Stable presentation priority; search matches and pins still take precedence. const items = this.dominio === 'cacu' ? [...catalog.filter(item => item.id === 'cacu_eu7'), ...catalog.filter(item => item.id !== 'cacu_eu7')] - : this.dominio === 'cama' ? catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id)) : catalog; + : this.dominio === 'cama' ? this.cardsDeCama(catalog) : catalog; if (this.dominio === 'cama') return { items, active: false, count: 0 }; const query = this.normalizeSearch(this.searchQuery()); const prioritize = (group: Indicador[]) => [ From 5e16f5454bf9fa2196e5a1716becc463ebec2dc7 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 00:39:57 -0600 Subject: [PATCH 06/38] fix(indicadores): reconcile CaMa period selection and contracts --- .../indicadores/indicador-period-filters.spec.ts | 7 +++++++ .../indicadores/indicador-period-filters.ts | 2 +- .../indicadores-cama-oportunidad.spec.ts | 15 +++++++++------ src/app/features/indicadores/indicadores-kpi.ts | 9 ++++++++- .../indicadores/indicadores-memory.spec.ts | 15 +++++++++++++++ .../features/indicadores/indicadores-memory.ts | 10 ++++++++++ 6 files changed, 50 insertions(+), 8 deletions(-) diff --git a/src/app/features/indicadores/indicador-period-filters.spec.ts b/src/app/features/indicadores/indicador-period-filters.spec.ts index 31bd18c..702c47a 100644 --- a/src/app/features/indicadores/indicador-period-filters.spec.ts +++ b/src/app/features/indicadores/indicador-period-filters.spec.ts @@ -18,6 +18,13 @@ describe('UX-04 control asistido', () => { control = fixture.componentInstance; }); afterEach(() => fixture.destroy()); + it('en modo compacto agregar otro periodo sustituye la selección anterior', () => { + fixture.componentRef.setInput('compact', true); fixture.detectChanges(); + control.year = '2025'; control.unit = 'S1'; control.add(); + control.unit = 'S2'; control.add(); + expect(control.selectedPeriods).toEqual(['2025-S2']); + expect(control.entry.added).toEqual(['2025-S1', '2025-S2']); + }); it('UX-06C: valores largos del trigger preservan Todos, selección explícita y borrador vacío', async () => { await fixture.whenStable(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.select-value')?.textContent).toContain('Todos con reporte'); diff --git a/src/app/features/indicadores/indicador-period-filters.ts b/src/app/features/indicadores/indicador-period-filters.ts index adbd545..a96104e 100644 --- a/src/app/features/indicadores/indicador-period-filters.ts +++ b/src/app/features/indicadores/indicador-period-filters.ts @@ -58,7 +58,7 @@ export class IndicadorPeriodFilters implements OnChanges { this.edited.emit(); } select(values: string[]) { - const unique = [...new Set(values)]; + const unique = [...new Set(this.compact ? values.slice(-1) : values)]; if (unique.some(p => !this.options.includes(p) || parsePeriodos(p, this.state.tipo)?.[0] !== p)) return; this.entry.draft = unique.length ? { mode: 'explicit', periodos: unique as [string, ...string[]] } : { mode: 'empty' }; this.edited.emit(); diff --git a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts index 6b65584..f52f470 100644 --- a/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-oportunidad.spec.ts @@ -12,7 +12,7 @@ import { IndicadorKpiCard } from './indicador-kpi-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { emptyAvailability } from './indicadores-periodos'; import { - CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, + CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, CAMA_OPORTUNIDAD_KPIS, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, camaKpiCards, kpiResult, } from './indicadores-kpi'; import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; @@ -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 detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado a diagnóstico']); + 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado 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', () => { @@ -43,6 +43,9 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => { expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']); expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_TASA_DETECCION_KPI); expect(KPI_BY_DOMAIN.cama).not.toContain(CAMA_RESULTADO_DIAGNOSTICO_KPI); + expect([CAMA_CONFIRMACION_KPI, CAMA_TOMA_DIAGNOSTICO_KPI].map(d => [d.id, d.contrato])).toEqual([ + ['cama_confirmacion_birads45', 'C1'], ['cama_dias_toma_diagnostico', 'C3r'], + ]); }); }); @@ -83,7 +86,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => { // Fails if the shared C1 result path regresses another domain's zero-denominator semantics. const definition = domain === 'cacu' ? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' } - : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; + : domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; const group = domain === 'tea' ? 'TOTAL' : 'total'; const data = { ...c1({ valor: 0, numerador: 0, denominador: 0 }), id: definition.id, filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 0 }] }; @@ -94,7 +97,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => { // Fails if the denominator guard accidentally rejects a real zero rate in any C1 domain. const definition = domain === 'cacu' ? { id: 'cacu_c1_regression', title: 'Prueba C1 de CaCu', contrato: 'C1' as const, unit: '%' } - : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; + : domain === 'cama' ? CAMA_TASA_DETECCION_KPI : KPI_BY_DOMAIN[domain].find(d => d.contrato === 'C1')!; const group = domain === 'tea' ? 'TOTAL' : 'total'; const data = { ...c1({ valor: 0, numerador: 0, denominador: 8 }), id: definition.id, filas: [{ ...row, grupo: group, valor: 0, numerador: 0, denominador: 8 }] }; @@ -212,7 +215,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => { expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false); 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 detección histopatológica', 'Tiempo de tamizaje a resultado', 'Tiempo de resultado a diagnóstico']); + 'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de detección histopatológica', 'Tiempo de mastografía a resultado', 'Tiempo de resultado a diagnóstico']); expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]); expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']); expect(cards()[1].textContent).toContain('aún no está publicado'); @@ -246,7 +249,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 tamizaje a resultado"]')).not.toBeNull(); + expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de mastografía a resultado"]')).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. diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 48a7788..ee52230 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -14,7 +14,14 @@ 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 tamizaje a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, + id: 'cama_eu38a', title: 'Tiempo de mastografía a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true, +}; +// Institutional definitions retained for consumers outside the opportunity strip. +export const CAMA_CONFIRMACION_KPI: KpiDefinition = { + id: 'cama_confirmacion_birads45', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%', +}; +export const CAMA_TOMA_DIAGNOSTICO_KPI: KpiDefinition = { + id: 'cama_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', }; export const CAMA_TASA_DETECCION_KPI: KpiDefinition = { id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%', diff --git a/src/app/features/indicadores/indicadores-memory.spec.ts b/src/app/features/indicadores/indicadores-memory.spec.ts index 12de7c8..38c2360 100644 --- a/src/app/features/indicadores/indicadores-memory.spec.ts +++ b/src/app/features/indicadores/indicadores-memory.spec.ts @@ -19,6 +19,21 @@ describe('D.2 memoria global por dominio', () => { restored.editors.mes!.added.length = 0; expect(memory.restoreGlobal('tea', ['semestre', 'mes']).editors.mes?.added).toEqual(['2025-01']); }); + it('restaura CaMa con un periodo visible y aplicado sin recortar otros dominios', () => { + for (const domain of ['cama', 'cacu', 'tea'] as const) { + const state = memory.restoreGlobal(domain, ['semestre', 'mes']); + state.editors.semestre!.draft = { mode: 'explicit', periodos: ['2025-S1', '2025-S2'] }; + applyGlobal(state, ['semestre', 'mes']); + state.editors.mes!.draft = { mode: 'explicit', periodos: ['2025-01', '2025-02'] }; + memory.saveGlobal(domain, state); + const restored = memory.restoreGlobal(domain, ['semestre', 'mes']); + const expected = domain === 'cama' ? ['2025-S1'] : ['2025-S1', '2025-S2']; + expect(restored.applied.selection).toEqual({ mode: 'explicit', periodos: expected }); + expect(restored.editors.semestre!.draft).toEqual({ mode: 'explicit', periodos: expected }); + expect(restored.editors.mes!.draft).toEqual({ mode: 'explicit', periodos: domain === 'cama' ? ['2025-01'] : ['2025-01', '2025-02'] }); + expect(restored.applied.revision).toBe(domain === 'cama' ? 2 : 1); + } + }); it('aísla los tres dominios sin tomar selecciones de figuras', () => { const state = memory.restoreGlobal('tea', ['semestre']); state.editors.semestre = { added: ['2025-S1'], draft: { mode: 'explicit', periodos: ['2025-S1'] } }; diff --git a/src/app/features/indicadores/indicadores-memory.ts b/src/app/features/indicadores/indicadores-memory.ts index 1a1ac43..2ba8ad6 100644 --- a/src/app/features/indicadores/indicadores-memory.ts +++ b/src/app/features/indicadores/indicadores-memory.ts @@ -96,6 +96,16 @@ export class IndicadoresMemory { applied: { tipo: 'semestre', selection: { mode: 'todos' }, revision: 0 }, }; for (const tipo of types) state.editors[tipo] ??= newEditor(tipo, 'semestre'); + // Legacy CaMa selections can contain several periods although its editor now shows one. + if (domain === 'cama' && stored) { + for (const editor of Object.values(state.editors)) { + if (editor?.draft.mode === 'explicit' && editor.draft.periodos.length > 1) + editor.draft = { mode: 'explicit', periodos: [editor.draft.periodos[0]] }; + } + const selection = state.applied.selection; + if (selection.mode === 'explicit' && selection.periodos.length > 1) + state.applied = { ...state.applied, selection: { mode: 'explicit', periodos: [selection.periodos[0]] }, revision: state.applied.revision + 1 }; + } // Preserve an application whose capabilities changed: consumers explain incompatibility, // rather than silently replacing or trimming the user's temporal selection. return state; From 2982d482bfda6ed00e37f069c747934ec521ae7c Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 01:06:56 -0600 Subject: [PATCH 07/38] feat(indicadores): CaMa history tab with the charts the published contracts support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Histórico tab between Resumen and Seguimiento, for CaMa only: monthly or semestral interval, how many periods to show, and a custom period dialog. Counts are stacked, rates draw their confidence band and medians their quartile band; suppressed periods are shaded and listed, and a rate over no denominator or a median over no observations is no value. Five charts use published indicators; the three whose indicator the catalog does not publish are drawn as pending panels. (cherry picked from commit 268d7443e0a89da8d6bc67ecb2b5db2715236f93) --- .../indicadores/indicadores-c2-palette.ts | 5 +- .../indicadores-historico-figures.spec.ts | 113 +++++++++ .../indicadores-historico-figures.ts | 150 ++++++++++++ .../indicadores-historico-periodos.ts | 58 +++++ .../indicadores-historico-pestana.spec.ts | 60 +++++ .../indicadores/indicadores-historico.spec.ts | 142 +++++++++++ .../indicadores/indicadores-historico.ts | 220 ++++++++++++++++++ .../indicadores/indicadores-page.html | 6 + .../features/indicadores/indicadores-page.ts | 20 +- .../indicadores/indicadores-sections.spec.ts | 14 +- 10 files changed, 774 insertions(+), 14 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-historico-figures.spec.ts create mode 100644 src/app/features/indicadores/indicadores-historico-figures.ts create mode 100644 src/app/features/indicadores/indicadores-historico-periodos.ts create mode 100644 src/app/features/indicadores/indicadores-historico-pestana.spec.ts create mode 100644 src/app/features/indicadores/indicadores-historico.spec.ts create mode 100644 src/app/features/indicadores/indicadores-historico.ts diff --git a/src/app/features/indicadores/indicadores-c2-palette.ts b/src/app/features/indicadores/indicadores-c2-palette.ts index 5042997..22cc67b 100644 --- a/src/app/features/indicadores/indicadores-c2-palette.ts +++ b/src/app/features/indicadores/indicadores-c2-palette.ts @@ -5,8 +5,9 @@ import { Tema } from './indicadores.models'; export const C2_PALETTE = Object.freeze({ series: Object.freeze(['#7184A2', '#A4B88A', '#D0B778', '#B78B8E']), states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }), - claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1' }), - oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F' }), + // line: the green for thin marks; the brand green itself is too light to read as a line on white. + claro: Object.freeze({ background: '#FFFFFF', text: '#081839', grid: '#E4E7E9', outline: '#BCC6D1', line: '#6A8000' }), + oscuro: Object.freeze({ background: '#081839', text: '#FFFFFF', grid: '#53647F', outline: '#53647F', line: '#A8C243' }), }); export function c2Theme(tema: Tema) { return C2_PALETTE[tema]; } export function c2Color(published: string | undefined, index: number): string { diff --git a/src/app/features/indicadores/indicadores-historico-figures.spec.ts b/src/app/features/indicadores/indicadores-historico-figures.spec.ts new file mode 100644 index 0000000..10e52a2 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-figures.spec.ts @@ -0,0 +1,113 @@ +// Covers how the history charts read each contract: what is drawn, what is shaded as suppressed, and what is +// never turned into a number. Fixtures are synthetic rows shaped like /cama/indicadores//datos. +import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures'; +import { IndicadorDatos } from './indicadores.models'; + +type Fig = { data: Record[]; layout: Record }; +const figura = (d: IndicadorDatos) => historicoFigura(d, 'claro'); +const fig = (d: IndicadorDatos) => figura(d).figure as unknown as Fig; +const base = (contrato: string, periodos: string[], filas: Record[], extra: Record = {}) => + ({ id: 'x', contrato, tipo_periodo: 'mes', periodos, filas, ...extra }) as unknown as IndicadorDatos; +const fila = (periodo: string, campos: Record): Record => ({ periodo, grupo: 'TOTAL', estrato: null, suprimido: 0, ...campos }); +const MESES = ['2025-01', '2025-02', '2025-03', '2025-04']; + +describe('Histórico: etiquetas y orden de periodos', () => { + it('los meses se leen «mar 2024» y los semestres «2024 S1»', () => { + expect(etiquetaPeriodo('2024-03')).toBe('mar 2024'); expect(etiquetaPeriodo('2024-S1')).toBe('2024 S1'); + }); + it('el tiempo corre de izquierda a derecha aunque el servidor ordene al revés', () => { + expect(cronologico(['2025-03', '2024-12', '2025-01'])).toEqual(['2024-12', '2025-01', '2025-03']); + }); +}); + +describe('Histórico: C3r (mediana y cuartiles)', () => { + const d = (filas: Record[], extra = {}) => base('C3r', MESES, filas, { unidad: 'examen', ...extra }); + const ok = (p: string, mediana: number, n = 9) => fila(p, { mediana, q1: mediana - 1, q3: mediana + 2, n, unidad: 'dias' }); + it('dibuja la banda de cuartiles y la línea de medianas con la unidad que publica el indicador', () => { + const f = fig(d([ok('2025-01', 10), ok('2025-02', 12), ok('2025-03', 8), ok('2025-04', 9)])); + expect(f.data.map(t => t['name'])).toEqual(['Primer a tercer cuartil', 'Mediana']); + expect(f.data[1]['y']).toEqual([10, 12, 8, 9]); + expect(JSON.stringify(f.data[1]['text'])).toContain('9 mastografías'); + expect(figura(d([ok('2025-01', 10)], { unidad: 'paciente' })).comoLeer).toContain('pacientes'); + expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Días'); + }); + it('un periodo suprimido se sombrea y se lista, sin valor; la banda no cruza el hueco', () => { + // Fails if a suppressed period is drawn as a number, or if the band bridges the gap. + const r = figura(d([ok('2025-01', 10), fila('2025-02', { suprimido: 1, mediana: null, q1: null, q3: null, n: null }), ok('2025-03', 8), ok('2025-04', 9)])); + const f = r.figure as unknown as Fig; + expect(f.data[1]['y']).toEqual([10, null, 8, 9]); + expect(r.suprimidos).toEqual(['feb 2025']); expect(r.sinDato).toEqual([]); + expect((f.layout['shapes'] as unknown[]).length).toBe(1); + expect((f.data[0]['x'] as (string | null)[]).includes(null)).toBe(true); + }); + it('una mediana sin observaciones o una fila ausente es «sin dato», no cero', () => { + const r = figura(d([ok('2025-01', 10), fila('2025-02', { mediana: 0, q1: 0, q3: 0, n: 0, unidad: 'dias' }), ok('2025-03', 0), ok('2025-04', 9)].filter(f => f['periodo'] !== '2025-04'))); + expect((r.figure as unknown as Fig).data[1]['y']).toEqual([10, null, 0, null]); + expect(r.sinDato).toEqual(['feb 2025', 'abr 2025']); + }); +}); + +describe('Histórico: C1 (porcentaje con intervalo)', () => { + const d = (filas: Record[]) => base('C1', MESES, filas); + const tasa = (p: string, valor: number, num: number, den: number) => fila(p, { grupo: 'total', valor, numerador: num, denominador: den, ic_bajo: Math.max(0, valor - 10), ic_alto: Math.min(100, valor + 10) }); + it('línea y banda de confianza en una escala de 0 a 100 %', () => { + const f = fig(d([tasa('2025-01', 40, 4, 10), tasa('2025-02', 50, 5, 10), tasa('2025-03', 60, 6, 10), tasa('2025-04', 55, 11, 20)])); + expect(f.data.map(t => t['name'])).toEqual(['Intervalo de confianza', 'Porcentaje']); + expect(f.data[1]['y']).toEqual([40, 50, 60, 55]); + expect((f.layout['yaxis'] as { range: number[]; ticksuffix: string })).toMatchObject({ range: [0, 100], ticksuffix: ' %' }); + }); + it('un cero con denominador positivo es un valor; 0 de 0 y un valor nulo no se dibujan como cero', () => { + // Fails if a rate over nobody is drawn as 0 %, or a real 0 % is dropped. + const r = figura(d([tasa('2025-01', 0, 0, 8), tasa('2025-02', 0, 0, 0), fila('2025-03', { grupo: 'total', valor: null, numerador: null, denominador: null }), tasa('2025-04', 50, 5, 10)])); + expect((r.figure as unknown as Fig).data[1]['y']).toEqual([0, null, null, 50]); + expect(r.sinDato).toEqual(['feb 2025', 'mar 2025']); + }); + it('un periodo suprimido se lista como suprimido y no como sin dato', () => { + const r = figura(d([tasa('2025-01', 40, 4, 10), fila('2025-02', { grupo: 'total', suprimido: 1, valor: null }), tasa('2025-03', 60, 6, 10), tasa('2025-04', 55, 11, 20)])); + expect(r.suprimidos).toEqual(['feb 2025']); expect(r.sinDato).toEqual([]); + }); +}); + +describe('Histórico: C2 (conteos por categoría)', () => { + const categorias = { B4: { etiqueta: 'B4', color: null }, B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, SIN_DATO: { etiqueta: 'Sin dato', color: '#C9CDD2' } }; + const celda = (p: string, categoria: string, n: number | null, orden: number, suprimido = 0) => fila(p, { categoria, n, orden, suprimido }); + const d = (filas: Record[], extra = {}) => base('C2', MESES, filas, { categorias, unidad: 'paciente', ...extra }); + const completo = MESES.flatMap(p => [celda(p, 'B5', 4, 0), celda(p, 'B4', 6, 1), celda(p, 'SIN_DATO', 0, 2)]); + it('apila las categorías en el orden que publica el indicador, con sus colores y etiquetas', () => { + const f = fig(d(completo)); + expect(f.data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']); + expect((f.data[0]['marker'] as { color: string }).color).toBe('#B55A1F'); + expect(f.data[0]['y']).toEqual([4, 4, 4, 4]); + expect(f.layout['barmode']).toBe('stack'); + expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes'); + }); + it('el eje y el texto hablan de mastografías cuando la unidad es el examen', () => { + const r = figura(d(completo, { unidad: 'examen' })); + expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } }); + expect(r.comoLeer).toContain('mastografías'); + }); + it('un periodo con una celda suprimida se sombrea completo y sus barras no se dibujan como cero', () => { + // Fails if the known cells of a partly suppressed period pass for its total. + const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f); + const r = figura(d(filas)); + expect(r.suprimidos).toEqual(['feb 2025']); + expect((r.figure as unknown as Fig).data[1]['y']).toEqual([6, null, 6, 6]); + }); + it('una celda sin valor y sin suprimir es «sin dato»', () => { + const filas = completo.map(f => f['periodo'] === '2025-03' && f['categoria'] === 'B5' ? { ...f, n: null } : f); + const r = figura(d(filas)); + expect(r.sinDato).toEqual(['mar 2025']); expect(r.suprimidos).toEqual([]); + }); +}); + +describe('Histórico: datos inválidos', () => { + it.each([ + ['supresión que no es 0 ni 1', () => base('C3r', MESES, [fila('2025-01', { suprimido: 2, mediana: 1 })])], + ['dos filas del mismo periodo', () => base('C3r', MESES, [fila('2025-01', { mediana: 1, q1: 0, q3: 2, n: 3 }), fila('2025-01', { mediana: 2, q1: 0, q3: 2, n: 3 })])], + ['categoría repetida', () => base('C2', MESES, [fila('2025-01', { categoria: 'A', n: 1, orden: 0 }), fila('2025-01', { categoria: 'A', n: 1, orden: 0 })])], + ['categoría sin orden', () => base('C2', MESES, [fila('2025-01', { categoria: 'A', n: 1 })])], + ['contrato no soportado', () => base('C9', MESES, [])], + ])('lanza error con %s', (_nombre, datos) => { + expect(() => historicoFigura(datos(), 'claro')).toThrow(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts new file mode 100644 index 0000000..84d9705 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -0,0 +1,150 @@ +import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette'; +import { sortedPeriods } from './indicadores-periodos'; + +export interface HistoricoFigura { + contrato: string; + figure: PlotlyFigure; + comoLeer: string; + suprimidos: string[]; + sinDato: string[]; +} +const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const escape = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); +// sortedPeriods lists the newest first, for selectors; time here runs left to right. +export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse(); + +const MESES = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sep', 'oct', 'nov', 'dic']; +// «mar 2024» and «2024 S1»: a bare 2024-03 was read as a mix of months and years. +export function etiquetaPeriodo(periodo: string): string { + const [anio, resto] = periodo.split('-'); + return resto.startsWith('S') ? `${anio} ${resto}` : `${MESES[Number(resto) - 1]} ${anio}`; +} +// What the unit the kit publishes is called in the charts' texts. +const UNIDADES: Readonly> = { + paciente: { plural: 'pacientes', eje: 'Pacientes' }, examen: { plural: 'mastografías', eje: 'Mastografías' }, +}; +const unidadDe = (data: IndicadorDatos) => UNIDADES[String(data['unidad'])] ?? { plural: 'casos', eje: 'Casos' }; + +function validar(data: IndicadorDatos) { + for (const row of data.filas) { + if (![0, 1].includes(row['suprimido'] as number)) throw new Error('Fila de histórico inválida'); + } + return cronologico(data.periodos); +} +function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], tema: Tema, titulo: string) { + const theme = c2Theme(tema), mensual = data.tipo_periodo === 'mes', etiquetas = periodos.map(etiquetaPeriodo); + // A label for every month does not fit: one per quarter is still readable, with the full period on hover. + return { + autosize: true, height: 400, paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text }, + margin: { l: 64, r: 16, t: 16, b: mensual ? 110 : 84 }, showlegend: true, legend: { orientation: 'h', y: mensual ? -0.42 : -0.26, itemclick: false, itemdoubleclick: false }, + xaxis: { type: 'category', categoryorder: 'array', categoryarray: etiquetas, showgrid: false, automargin: true, tickangle: mensual ? -45 : 0, + title: { text: mensual ? 'Mes y año' : 'Semestre' }, tickmode: 'array', tickvals: etiquetas.filter((_, i) => periodos.length <= 12 || i % 3 === 0) }, + yaxis: { rangemode: 'tozero', title: { text: titulo }, gridcolor: theme.grid, zeroline: false }, + // Shaded, because an empty space alone reads as zero. Text below the figure says the same. + shapes: suprimidos.map(periodo => ({ type: 'rect', layer: 'below', xref: 'x', yref: 'paper', y0: 0, y1: 1, line: { width: 0 }, + x0: periodos.indexOf(periodo) - .5, x1: periodos.indexOf(periodo) + .5, fillcolor: C2_PALETTE.states.suppressed, opacity: .18 })), + }; +} +// One polygon per run of consecutive values: a band must not bridge a gap in the line. +function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string) { + const x: (string | null)[] = [], y: (number | null)[] = []; + let run: number[] = []; + const cerrar = () => { + if (run.length) { + if (x.length) { x.push(null); y.push(null); } + x.push(...run.map(i => periodos[i]), ...[...run].reverse().map(i => periodos[i])); + y.push(...run.map(i => alto[i]), ...[...run].reverse().map(i => bajo[i])); + } + run = []; + }; + periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); }); + cerrar(); + return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor: color + '40', line: { width: 0 }, hoverinfo: 'skip' }; +} +// Separate rows from what is missing or suppressed; a period is judged by its only row. +function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record) => boolean) { + const filas = new Map(data.filas.map(row => [row['periodo'] as string, row])); + if (filas.size !== data.filas.length) throw new Error('Filas ambiguas'); + const suprimidos: string[] = [], sinDato: string[] = []; + const validas = periodos.map(periodo => { + const row = filas.get(periodo); + if (row?.['suprimido'] === 1) { suprimidos.push(periodo); return null; } + if (!row || !valor(row)) { sinDato.push(periodo); return null; } + return row; + }); + return { validas, suprimidos, sinDato }; +} +const campo = (filas: (Record | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null); + +type Trazo = Omit; +function porcentaje(data: IndicadorDatos, tema: Tema): Trazo { + const periodos = validar(data); + // A rate over no denominator is no value; the contract's own rule for it is not reinterpreted here. + const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['valor']) && numero(row['denominador']) && row['denominador'] > 0); + const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), linea = c2Theme(tema).line; + return { + figure: { data: [ + banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', linea), + { type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: linea, width: 2 }, + text: validas.map(row => row ? `${row['valor']} %
${row['numerador']} de ${row['denominador']}
IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''), + hovertemplate: '%{x}
%{text}' }, + ], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } }, + comoLeer: 'La línea es el porcentaje de cada periodo y la banda, su intervalo de confianza: es más ancha cuando hay menos casos.', + suprimidos, sinDato, + }; +} +function mediana(data: IndicadorDatos, tema: Tema): Trazo { + const periodos = validar(data), unidad = unidadDe(data); + const { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0); + const linea = c2Theme(tema).line; + return { + figure: { data: [ + banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea), + { type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, + text: validas.map(row => row ? `Mediana: ${row['mediana']} días
Q1 a Q3: ${row['q1']} a ${row['q3']} días
${row['n']} ${unidad.plural}` : ''), + hovertemplate: '%{x}
%{text}' }, + ], layout: ejes(data, periodos, suprimidos, tema, 'Días') }, + comoLeer: `La línea es la mediana de días de cada periodo. La banda va del primer al tercer cuartil: la mitad central de las ${unidad.plural}.`, + suprimidos, sinDato, + }; +} +function conteo(data: IndicadorDatos, tema: Tema): Trazo { + const periodos = validar(data), catalogo = record(data['categorias']) ? data['categorias'] : {}, unidad = unidadDe(data); + const celdas = new Map>(), categorias = new Map(); + for (const row of data.filas) { + const id = row['categoria'], key = JSON.stringify([id, row['periodo']]); + if (typeof id !== 'string' || !id || !numero(row['orden']) || celdas.has(key)) throw new Error('Fila de histórico inválida'); + celdas.set(key, row); + categorias.set(id, row['orden']); + } + const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id); + const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo]))); + const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1)); + const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))); + return { + figure: { data: orden.map((id, i) => { + const meta = record(catalogo[id]) ? catalogo[id] : {}; + const color = typeof meta['color'] === 'string' && /^#[0-9a-f]{6}$/i.test(meta['color']) ? meta['color'] : undefined; + const valores = periodos.map(p => { const n = celdas.get(JSON.stringify([id, p]))?.['n']; return numero(n) ? n : null; }); + return { type: 'bar', name: escape(etiquetaCategoria(meta, id)), x: periodos.map(etiquetaPeriodo), y: valores, + marker: { color: c2Color(color, i) }, hovertemplate: '%{y}%{fullData.name}' }; + }), layout: { ...ejes(data, periodos, suprimidos, tema, unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } }, + comoLeer: `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`, + suprimidos, sinDato, + }; +} +// The kit publishes a 4 without subcategory as «B4», with no colour. +function etiquetaCategoria(meta: Record, id: string) { + const publicada = typeof meta['etiqueta'] === 'string' ? meta['etiqueta'] : ''; + return publicada && publicada !== id ? publicada : id === 'B4' ? 'BI-RADS 4 (sin subcategoría)' : id; +} +// The plot follows from what the contract's numbers mean: counts add up to a total, percentages +// and medians do not, so those two are never stacked. +export function historicoFigura(data: IndicadorDatos, tema: Tema): HistoricoFigura { + const figura = data.contrato === 'C2' ? conteo(data, tema) : data.contrato === 'C1' ? porcentaje(data, tema) + : data.contrato === 'C3r' ? mediana(data, tema) : undefined; + if (!figura) throw new Error('Representación no soportada'); + return { ...figura, contrato: data.contrato, suprimidos: figura.suprimidos.map(etiquetaPeriodo), sinDato: figura.sinDato.map(etiquetaPeriodo) }; +} diff --git a/src/app/features/indicadores/indicadores-historico-periodos.ts b/src/app/features/indicadores/indicadores-historico-periodos.ts new file mode 100644 index 0000000..5eeab0e --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-periodos.ts @@ -0,0 +1,58 @@ +import { Component, computed, inject, signal } from '@angular/core'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCheckboxModule } from '@angular/material/checkbox'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { etiquetaPeriodo } from './indicadores-historico-figures'; +import { TipoPeriodo } from './indicadores.models'; + +export interface PeriodosDialogoDatos { tipo: TipoPeriodo; periodos: readonly string[]; elegidos: readonly string[]; } + +// The periods of the chosen analysis interval, by year. Closes with the chosen ones, oldest first, or with nothing if cancelled. +@Component({ + selector: 'app-indicadores-historico-periodos', + imports: [MatButtonModule, MatCheckboxModule, MatDialogModule], + template: ` +

Elegir {{ datos.tipo === 'mes' ? 'meses' : 'semestres' }}

+ +
+ + +
+ @for (grupo of anios; track grupo.anio) { +
+ {{ grupo.anio }} + @for (periodo of grupo.periodos; track periodo) { + {{ etiqueta(periodo) }} + } +
+ } +
+ + {{ cuenta() }} + + + + `, + styles: ` + .acciones { display: flex; gap: .5rem; margin-bottom: .5rem; } + fieldset { display: grid; grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr)); gap: 0 .5rem; margin: 0 0 .75rem; padding: .25rem .5rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + legend { padding-inline: .25rem; font-weight: 600; } + .cuenta { margin-inline-end: auto; padding-inline-start: .75rem; font: var(--mat-sys-body-medium); } + `, +}) +export class IndicadoresHistoricoPeriodos { + readonly datos = inject(MAT_DIALOG_DATA); + private readonly dialogo = inject>(MatDialogRef); + readonly etiqueta = etiquetaPeriodo; + readonly todos = [...this.datos.periodos]; + readonly elegidos = signal(this.datos.elegidos); + readonly anios = [...new Set(this.todos.map(p => p.slice(0, 4)))].map(anio => ({ anio, periodos: this.todos.filter(p => p.startsWith(anio)) })); + readonly cuenta = computed(() => { + const n = this.elegidos().length, mes = this.datos.tipo === 'mes'; + return n === 1 ? (mes ? '1 mes elegido' : '1 semestre elegido') : `${n} ${mes ? 'meses elegidos' : 'semestres elegidos'}`; + }); + alternar(periodo: string) { + this.elegidos.update(actual => actual.includes(periodo) ? actual.filter(p => p !== periodo) : [...actual, periodo]); + } + aplicar() { this.dialogo.close(this.todos.filter(p => this.elegidos().includes(p))); } +} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts new file mode 100644 index 0000000..afdfb84 --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -0,0 +1,60 @@ +// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its +// panel loads nothing until it is opened. Catalogs are synthetic, shaped like //indicadores. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; +import { Dominio } from './indicadores.models'; + +const item = (id: string, contrato: string) => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }); + +describe('Pestaña Histórico', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + for (const domain of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(domain); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + const root = () => fixture.nativeElement as HTMLElement; + const tabs = () => [...root().querySelectorAll('[role=tab]')].map(e => e.textContent?.trim()); + function abrir(domain: Dominio, catalog: unknown[]) { + fixture.componentInstance.changeDominio(domain); fixture.detectChanges(); + http.expectOne('/' + domain + '/indicadores').flush(catalog); fixture.detectChanges(); + http.match(() => true); + } + + it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => { + abrir('cama', [item('cama_eu38a', 'C3r')]); + expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']); + expect(root().querySelector('#panel-historico')).not.toBeNull(); + }); + it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => { + // Fails if CaMa's tab leaks into the other domains. + abrir(domain === 'tea' ? 'cacu' : 'cama', []); + abrir(domain, [item(domain + '_x', 'C2')]); + expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); + expect(root().querySelector('#panel-historico')).toBeNull(); + }); + it('al cambiar a Histórico se piden los datos del histórico y el panel se muestra; al volver a Resumen se oculta', () => { + abrir('cama', [item('cama_eu38a', 'C3r')]); + const panel = () => root().querySelector('#panel-historico') as HTMLElement; + expect(panel().hidden).toBe(true); + fixture.componentInstance.changeSection('historico'); fixture.detectChanges(); + expect(panel().hidden).toBe(false); + // The period inventory is shared with the page, so the panel is seen waiting for it, not as a new request. + expect(panel().querySelector('article.panel[aria-busy="true"]')).not.toBeNull(); + fixture.componentInstance.changeSection('resumen'); fixture.detectChanges(); + expect(panel().hidden).toBe(true); + }); + it('cambiar de dominio vuelve a Resumen', () => { + abrir('cama', [item('cama_eu38a', 'C3r')]); + fixture.componentInstance.changeSection('historico'); fixture.detectChanges(); + abrir('cacu', [item('cacu_x', 'C2')]); + expect(fixture.componentInstance.activeSection()).toBe('resumen'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico.spec.ts b/src/app/features/indicadores/indicadores-historico.spec.ts new file mode 100644 index 0000000..2827dda --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico.spec.ts @@ -0,0 +1,142 @@ +// Covers CaMa's history tab: what it requests and when, the controls (interval, periods to show, custom +// periods), the pending panels for indicators the catalog does not publish, and error handling. Responses are +// synthetic, shaped like /cama/indicadores//periodos and /datos. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import { MatDialog } from '@angular/material/dialog'; +import { of } from 'rxjs'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { HISTORICO_CAMA, IndicadoresHistorico } from './indicadores-historico'; +import { Indicador } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: { data: { name?: string }[] }; label?: string; } + +const MESES = ['2025-01', '2025-02', '2025-03', '2025-04', '2025-05', '2025-06', '2025-07']; +const SEMESTRES = ['2024-S2', '2025-S1']; +const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador; +// What 18080 publishes for CaMa, including biopsias, which the history does not draw. +const CATALOGO = [item('cama_biopsias', 'C2'), item('cama_birads_456_mastografia', 'C2'), item('cama_birads_456_paciente', 'C2'), + item('cama_confirmacion_birads45', 'C1'), item('cama_dias_toma_diagnostico', 'C3r'), item('cama_eu38a', 'C3r')]; +const PUBLICADOS = CATALOGO.filter(i => i.id !== 'cama_biopsias'); + +function datos(id: string, contrato: string, tipo: string, periodos: string[]) { + const fila = (periodo: string, campos: Record) => ({ periodo, grupo: contrato === 'C1' ? 'total' : 'TOTAL', estrato: null, suprimido: 0, ...campos }); + const filas = contrato === 'C2' + ? periodos.flatMap(p => [fila(p, { categoria: 'B5', n: 7, orden: 0 }), fila(p, { categoria: 'B4', n: 5, orden: 1 })]) + : contrato === 'C1' ? periodos.map(p => fila(p, { valor: 50, numerador: 5, denominador: 10, ic_bajo: 30, ic_alto: 70 })) + : periodos.map(p => fila(p, { mediana: 9, q1: 5, q3: 12, n: 20, unidad: 'dias' })); + return { id, contrato, tipo_periodo: tipo, periodos, unidad: contrato === 'C2' && id.includes('paciente') ? 'paciente' : 'examen', filas, + categorias: { B5: { etiqueta: 'BI-RADS 5', color: '#B55A1F' }, B4: { etiqueta: 'B4', color: null } } }; +} + +describe('Histórico de CaMa', () => { + let fixture: ReturnType>, http: HttpTestingController; + const abrirDialogo = vi.fn(); + function montar(catalog: Indicador[] = CATALOGO, active = false) { + TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: abrirDialogo } }] }); + TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', catalog); + fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', active); + fixture.detectChanges(); + } + afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); abrirDialogo.mockReset(); }); + // Answers in waves, because the shared request queue runs four at a time. + function responder(fallo?: (r: TestRequest) => boolean) { + const vistos: string[] = []; + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + const url = r.request.url; vistos.push(url + (r.request.params.get('periodos') ? '?' + r.request.params.get('periodos') : '')); + const id = url.split('/').at(-2)!, entrada = CATALOGO.find(i => i.id === id)!; + if (fallo?.(r)) { r.flush('private', { status: 500, statusText: 'Error' }); continue; } + if (url.endsWith('/periodos')) r.flush({ id, periodos: [...MESES.map(periodo => ({ periodo, tipo: 'mes' })), ...SEMESTRES.map(periodo => ({ periodo, tipo: 'semestre' }))] }); + else { + const periodos = r.request.params.get('periodos')!.split(','); + r.flush(datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos)); + } + } + fixture.detectChanges(); + } + return vistos; + } + const root = () => fixture.nativeElement as HTMLElement; + const paneles = () => [...root().querySelectorAll('article.panel')] as HTMLElement[]; + const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); + + it('no pide nada hasta que la pestaña está activa, y entonces solo los indicadores de la lista que el catálogo publica', () => { + // Fails if the tab loads data while hidden, or if biopsias (not in the history) is requested. + montar(); + http.expectNone(() => true); + fixture.componentRef.setInput('active', true); fixture.detectChanges(); + const vistos = responder(); + const ids = new Set(vistos.map(u => u.split('/').at(-2))); + expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort()); + expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false); + }); + it('dibuja los ocho paneles en el orden del mockup: cinco con gráfica y tres pendientes por falta de indicador', () => { + montar(CATALOGO, true); responder(); + expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo)); + const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent); + expect(pendientes).toEqual(['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica']); + expect(graficas()).toHaveLength(5); + expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0); + }); + it('mensual por omisión, con el rango y la cuenta de periodos de cada panel', () => { + montar(CATALOGO, true); responder(); + expect((root().querySelector('mat-button-toggle.mat-button-toggle-checked') ?? root().querySelector('mat-button-toggle[checked="true"]'))?.textContent?.trim()).toBe('Mensual'); + expect(paneles()[1].querySelector('.rango')?.textContent).toBe('ene 2025 a jul 2025 (7 meses)'); + }); + it('cambiar a Semestral pide solo ese tipo, una vez, y volver a Mensual no repite la consulta', () => { + montar(CATALOGO, true); responder(); + const toggle = fixture.debugElement.query(By.css('mat-button-toggle-group')); + toggle.triggerEventHandler('change', { value: 'semestre' }); fixture.detectChanges(); + const semestrales = responder(); + expect(semestrales.length).toBeGreaterThan(0); + expect(semestrales.filter(u => u.includes('datos')).every(u => u.includes('2024-S2,2025-S1') || u.includes('2025-S1,2024-S2'))).toBe(true); + expect(paneles()[1].querySelector('.rango')?.textContent).toBe('2024 S2 a 2025 S1 (2 semestres)'); + toggle.triggerEventHandler('change', { value: 'mes' }); fixture.detectChanges(); + http.expectNone(() => true); + }); + it('«Periodos a mostrar» ofrece pasos de cinco y «Todos»; elegir los últimos cinco recorta cada gráfica', () => { + montar(CATALOGO, true); responder(); + const selector = fixture.debugElement.query(By.css('mat-select')).componentInstance as { options: { toArray(): { viewValue: string }[] } }; + expect(selector.options.toArray().map(o => o.viewValue)).toEqual(['Últimos 5 meses', 'Todos (7 meses)', 'Personalizado…']); + fixture.componentInstance.elegirVentana(5); fixture.detectChanges(); + expect(paneles()[1].querySelector('.rango')?.textContent).toBe('mar 2025 a jul 2025 (5 meses)'); + }); + it('«Personalizado» abre el diálogo y dibuja solo los periodos elegidos; cancelar no cambia nada', () => { + montar(CATALOGO, true); responder(); + abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(['2025-02', '2025-05']) }); + fixture.componentInstance.elegirVentana(-1); fixture.detectChanges(); + expect(abrirDialogo).toHaveBeenCalledTimes(1); + const datosDialogo = abrirDialogo.mock.calls[0][1].data as { tipo: string; periodos: string[]; elegidos: string[] }; + expect(datosDialogo.tipo).toBe('mes'); expect(datosDialogo.periodos).toEqual(MESES); + expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); + abrirDialogo.mockReturnValueOnce({ afterClosed: () => of(undefined) }); + fixture.componentInstance.abrirPersonalizado(); fixture.detectChanges(); + expect(paneles()[1].querySelector('.rango')?.textContent).toBe('feb 2025 a may 2025 (2 meses, elegidos)'); + }); + it('un error de red en un indicador se muestra en su panel sin filtrar el cuerpo, y el reintento vuelve a pedir', () => { + // Fails if one failing indicator blanks the others, leaks its body, or cannot be retried. + montar(CATALOGO, true); + responder(r => r.request.url.includes('cama_eu38a/periodos')); + const panel = paneles().find(p => p.querySelector('h2')!.textContent === 'Días de la toma de la mastografía a su resultado')!; + expect(panel.querySelector('[role=alert]')).not.toBeNull(); + expect(panel.textContent).not.toContain('private'); + expect(graficas()).toHaveLength(4); + (panel.querySelector('[role=alert] button') as HTMLButtonElement).click(); fixture.detectChanges(); + const nuevos = responder(); + expect(nuevos.length).toBeGreaterThan(0); + expect(paneles().some(p => p.querySelector('[role=alert]'))).toBe(false); + expect(graficas()).toHaveLength(5); + }); + it('sin ningún indicador de la lista en el catálogo no hay paneles ni consultas', () => { + montar([item('cama_biopsias', 'C2')], true); + http.expectNone(() => true); + expect(paneles()).toHaveLength(0); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico.ts b/src/app/features/indicadores/indicadores-historico.ts new file mode 100644 index 0000000..1e2ca3f --- /dev/null +++ b/src/app/features/indicadores/indicadores-historico.ts @@ -0,0 +1,220 @@ +import { Component, computed, DestroyRef, effect, inject, input, signal, untracked, viewChild } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatButtonToggleModule } from '@angular/material/button-toggle'; +import { MatDialog } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelect, MatSelectModule } from '@angular/material/select'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { catchError, forkJoin, map, Observable, of, Subject, switchMap } from 'rxjs'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { cronologico, etiquetaPeriodo, historicoFigura, HistoricoFigura } from './indicadores-historico-figures'; +import { httpMessage } from './indicadores-http'; +import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadores-historico-periodos'; +import { IndicadoresPeriodos } from './indicadores-periodos'; +import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models'; +import { IndicadoresService } from './indicadores.service'; + +const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres'); +type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string }; +type Panel = { id: string; titulo: string; rango?: string } & ( + { estado: 'cargando' | 'vacio' | 'pendiente' } | { estado: 'error'; mensaje: string } | { estado: 'listo'; figura: HistoricoFigura }); +const PERSONALIZADO = -1; + +// CaMa's history, in the order of the mockup. The titles are the mockup's; an indicator the catalog does not +// 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 por categoría BI-RADS' }, + { id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' }, + { id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' }, + { id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' }, + { id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' }, + { id: 'cama_eu38a', titulo: 'Días de la toma de la mastografía a su resultado' }, + { id: 'cama_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' }, + { id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' }, +]; + +// Evolution of each indicator: the granularity and how many of the latest periods to show. +// Nothing is requested until the tab is first opened, and each granularity is requested once. +@Component({ + selector: 'app-indicadores-historico', + imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart], + template: ` +
+ Intervalo de análisis + + @if (tipos().includes('mes')) { Mensual } + @if (tipos().includes('semestre')) { Semestral } + + + Periodos a mostrar + + @for (opcion of opciones(); track opcion.valor) { {{ opcion.etiqueta }} } + + + @if (ventana() === PERSONALIZADO) { } +
+
+ @for (panel of paneles(); track panel.id) { +
+

{{ panel.titulo }}

+ @if (panel.rango) {

{{ panel.rango }}

} + @switch (panel.estado) { + @case ('pendiente') {

Integración pendiente. Este indicador aún no está publicado por el catálogo institucional.

} + @case ('cargando') { } + @case ('vacio') {

Sin reportes publicados para este intervalo de análisis.

} + @case ('error') { +

{{ panel.mensaje }}

+
+ } + @case ('listo') { + +

{{ panel.figura.comoLeer }}

+ @if (panel.figura.suprimidos.length) { +

Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.figura.contrato === 'C2') {El total de esos periodos está incompleto.}

+ } + @if (panel.figura.sinDato.length) {

Sin dato: {{ panel.figura.sinDato.join(', ') }}.

} + } + } +
+ } +
+ `, + styles: ` + :host { display: block; min-width: 0; } + .controles { display: flex; flex-wrap: wrap; align-items: center; gap: var(--issste-space-3); margin-bottom: var(--issste-space-6); padding: var(--issste-space-3) var(--issste-space-6); + background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + .paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); } + .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } + p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } + .rango, .nota { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } + app-plotly-chart { margin-top: var(--issste-space-3); } + mat-form-field { min-width: 18rem; } + `, +}) +export class IndicadoresHistorico { + readonly dominio = input.required(); + readonly catalog = input.required(); + readonly tema = input.required(); + readonly active = input(false); + // The indicators of the list the catalog publishes. + private readonly publicados = computed(() => HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id))); + // Only the granularities some indicator publishes; monthly first when there is one. + readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo)))); + readonly elegido = signal(undefined); + readonly tipo = computed(() => { + const elegido = this.elegido(), tipos = this.tipos(); + return elegido && tipos.includes(elegido) ? elegido : tipos[0] ?? 'mes'; + }); + // How many of the latest periods to show, per granularity; 0 shows them all. + private readonly ventanas = signal>>({}); + readonly ventana = computed(() => this.ventanas()[this.tipo()] ?? 0); + readonly PERSONALIZADO = PERSONALIZADO; + // The periods the user picked in the dialog, per granularity. + private readonly personalizados = signal>>({}); + private readonly dialogo = inject(MatDialog); + private readonly selector = viewChild('selector'); + // Every period published for the granularity by any indicator. + private readonly disponibles = computed(() => cronologico(Object.values(this.cargas()[this.tipo()] ?? {}) + .flatMap(carga => carga.estado === 'listo' ? carga.datos.periodos : []))); + // The periods on screen, out of those an indicator publishes. + private recortar(periodos: readonly string[]) { + const orden = cronologico(periodos), ventana = this.ventana(); + if (ventana !== PERSONALIZADO) return ventana ? orden.slice(-ventana) : orden; + const elegidos = this.personalizados()[this.tipo()] ?? []; + return orden.filter(p => elegidos.includes(p)); + } + private readonly service = inject(IndicadoresService); + private readonly periodos = inject(IndicadoresPeriodos); + private readonly cargas = signal>>>({}); + private readonly solicitudes = new Subject<{ tipo: TipoPeriodo; items: readonly Indicador[] }>(); + private solicitada?: string; + private catalogoCargado?: readonly Indicador[]; + + // Steps of five, up to what the indicator with the most periods has published. + readonly opciones = computed(() => { + const tipo = this.tipo(); + const total = Math.max(0, ...Object.values(this.cargas()[tipo] ?? {}).map(carga => carga.estado === 'listo' ? carga.datos.periodos.length : 0)); + const opciones = []; + for (let n = 5; n < total; n += 5) opciones.push({ valor: n, etiqueta: `Últimos ${n} ${unidad(tipo, n)}` }); + const elegidos = this.personalizados()[tipo]?.length; + return [...opciones, { valor: 0, etiqueta: total ? `Todos (${total} ${unidad(tipo, total)})` : 'Todos' }, + ...(total ? [{ valor: PERSONALIZADO, etiqueta: elegidos && this.ventana() === PERSONALIZADO ? `Personalizado (${elegidos} ${unidad(tipo, elegidos)})` : 'Personalizado…' }] : [])]; + }); + readonly paneles = computed(() => { + const tipo = this.tipo(), cargas = this.cargas()[tipo], tema = this.tema(); + if (!this.publicados().length) return []; + return HISTORICO_CAMA.map((entrada): Panel => { + const item = this.catalog().find(i => i.id === entrada.id); + if (!item) return { ...entrada, estado: 'pendiente' }; + if (!item.tipos_periodo.includes(tipo)) return { ...entrada, estado: 'vacio' }; + const carga = cargas?.[item.id]; + if (!carga) return { ...entrada, estado: 'cargando' }; + if (carga.estado !== 'listo') return { ...entrada, ...carga }; + const periodos = this.recortar(carga.datos.periodos); + if (!periodos.length) return { ...entrada, estado: 'vacio' }; + const datos = { ...carga.datos, periodos, filas: carga.datos.filas.filter(fila => periodos.includes(fila['periodo'] as string)) }; + const extremos = periodos.length === 1 ? etiquetaPeriodo(periodos[0]) : `${etiquetaPeriodo(periodos[0])} a ${etiquetaPeriodo(periodos[periodos.length - 1])}`; + const rango = `${extremos} (${periodos.length} ${unidad(tipo, periodos.length)}${this.ventana() === PERSONALIZADO ? ', elegidos' : ''})`; + try { + return { ...entrada, rango, estado: 'listo', figura: historicoFigura(datos, tema) }; + } catch (error) { + return { ...entrada, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' }; + } + }); + }); + + constructor() { + this.solicitudes.pipe(switchMap(({ tipo, items }) => forkJoin(items.filter(item => item.tipos_periodo.includes(tipo)) + .map(item => this.cargar(item, tipo).pipe(map(carga => [item.id, carga] as const)))).pipe(map(cargas => ({ tipo, cargas })))), + takeUntilDestroyed(inject(DestroyRef))).subscribe(({ tipo, cargas }) => { + this.cargas.update(actual => ({ ...actual, [tipo]: Object.fromEntries(cargas) })); + }); + effect(() => { + const tipo = this.tipo(), items = this.publicados(); + if (!this.active() || !items.length) return; + untracked(() => { + if (this.catalogoCargado !== this.catalog()) { this.catalogoCargado = this.catalog(); this.cargas.set({}); this.solicitada = undefined; } + if (this.cargas()[tipo] || this.solicitada === tipo) return; + this.solicitada = tipo; + this.solicitudes.next({ tipo, items }); + }); + }); + } + private cargar(item: Indicador, tipo: TipoPeriodo): Observable { + return this.periodos.periodos(this.dominio(), item.id).pipe( + map(periodos => periodos.filter(p => p.tipo === tipo).map(p => p.periodo)), + switchMap((periodos): Observable => periodos.length + ? this.service.datos(this.dominio(), item.id, tipo, periodos).pipe(map(datos => ({ estado: 'listo', datos }))) + : of({ estado: 'vacio' })), + catchError(error => of({ estado: 'error', mensaje: httpMessage(error) }))); + } + elegirVentana(valor: number) { + if (valor === PERSONALIZADO) { this.abrirPersonalizado(); return; } + this.ventanas.update(actual => ({ ...actual, [this.tipo()]: valor })); + } + abrirPersonalizado() { + const tipo = this.tipo(), periodos = this.disponibles(); + // Starts from what's on screen, so the user only adjusts it. + const elegidos = this.ventana() === PERSONALIZADO ? this.personalizados()[tipo] ?? [] : this.ventana() ? periodos.slice(-this.ventana()) : periodos; + const data: PeriodosDialogoDatos = { tipo, periodos, elegidos }; + this.dialogo.open(IndicadoresHistoricoPeriodos, { data, width: 'min(40rem, 92vw)', maxHeight: '85vh' }) + .afterClosed().subscribe(resultado => { + if (resultado?.length) { + this.personalizados.update(actual => ({ ...actual, [tipo]: resultado })); + this.ventanas.update(actual => ({ ...actual, [tipo]: PERSONALIZADO })); + } + // Cancelled, the selector goes back to what's on screen. + this.selector()?.writeValue(this.ventana()); + }); + } + reintentar() { + const tipo = this.tipo(); + this.solicitada = tipo; + this.cargas.update(({ [tipo]: _, ...resto }) => resto); + this.solicitudes.next({ tipo, items: this.publicados() }); + } +} diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 5893415..654018d 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -143,6 +143,12 @@
+ @if (conHistorico) { +
+ +
+ } +
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 42b462a..11ffcc6 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -28,22 +28,28 @@ import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; +import { IndicadoresHistorico } from './indicadores-historico'; import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel'; -type DashboardSection = 'resumen' | 'seguimiento' | 'datos'; +type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos'; + +const SECCIONES: readonly { id: DashboardSection; label: string }[] = [ + { id: 'resumen', label: 'Resumen' }, + { id: 'seguimiento', label: 'Seguimiento' }, + { id: 'datos', label: 'Datos y definiciones' }, +]; +const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]]; @Component({ selector: 'app-indicadores-page', - imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel], + imports: [RouterLink, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - readonly sections: readonly { id: DashboardSection; label: string }[] = [ - { id: 'resumen', label: 'Resumen' }, - { id: 'seguimiento', label: 'Seguimiento' }, - { id: 'datos', label: 'Datos y definiciones' }, - ]; + // The history tab is CaMa's; the other domains keep their three sections. + get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; } + get conHistorico() { return this.dominio === 'cama'; } readonly activeSection = signal('resumen'); readonly fichaPacienteAbierta = signal(false); setFichaPacienteAbierta(open: boolean) { diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 7ce6cb3..7ec66c0 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -31,14 +31,16 @@ describe('Secciones compartidas por dominio', () => { }); afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); - it.each(DOMINIOS)('entrada directa en %s presenta tres pestañas y Resumen seleccionado', async domain => { + it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => { const harness = await RouterTestingHarness.create(); const page = await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - expect(tabs.map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); - expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(['true', 'false', 'false']); + // CaMa also has Histórico, between Resumen and Seguimiento. + const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']; + expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); + expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); // Upstream moved domain selection to its own App shell; ours keeps it on // the page itself (see indicadores-page.html), since our shell is shared @@ -50,7 +52,9 @@ describe('Secciones compartidas por dominio', () => { expect(panel.hidden).toBe(tab.id !== 'tab-resumen'); } const cards = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance); - tabs[1].click(); harness.detectChanges(); + // By id, since CaMa has one more tab. + const pestana = (id: string) => tabs.find(t => t.id === 'tab-' + id)!; + pestana('seguimiento').click(); harness.detectChanges(); if (domain === 'cacu') { http.expectOne(r => r.url === '/cacu/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); @@ -67,7 +71,7 @@ describe('Secciones compartidas por dominio', () => { expect(tracking.querySelector('tbody td')?.getAttribute('colspan')).toBe('6'); expect(tracking.querySelectorAll('input,button,select')).toHaveLength(0); } - tabs[2].click(); harness.detectChanges(); + pestana('datos').click(); harness.detectChanges(); expect(root.querySelector('#panel-datos')!.hidden).toBe(false); tabs[0].click(); harness.detectChanges(); expect(harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance)).toEqual(cards); From d761a6fb1abebd8faa7f5a9f4d037ea0bd9bc0f3 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 01:18:47 -0600 Subject: [PATCH 08/38] feat(shell): indicators header with the platform title and a domain selector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On /indicadores/ the header shows «Plataforma de Indicadores» and a menu button with the current domain (TEA, CaCu, Cáncer de mama) that links to the other two through the router. Institutional routes keep their breadcrumb header. (cherry picked from commit 79a18fd7a8ed1a3a58201e7cc24c9692b53dbc47) --- src/app/app-encabezado.spec.ts | 90 ++++++++++++++++++++++++++++++++++ src/app/app.html | 27 +++++++--- src/app/app.scss | 25 ++++++++++ src/app/app.ts | 14 +++++- 4 files changed, 148 insertions(+), 8 deletions(-) create mode 100644 src/app/app-encabezado.spec.ts diff --git a/src/app/app-encabezado.spec.ts b/src/app/app-encabezado.spec.ts new file mode 100644 index 0000000..24ab7a6 --- /dev/null +++ b/src/app/app-encabezado.spec.ts @@ -0,0 +1,90 @@ +// Covers the shell's header: on an indicators page it carries the platform title and the domain selector; on +// the institutional routes it keeps the breadcrumb. The pages are stubs: only the header and the router matter. +import { Component } from '@angular/core'; +import { Location } from '@angular/common'; +import { TestBed } from '@angular/core/testing'; +import { provideRouter, Router } from '@angular/router'; +import { provideHttpClient } from '@angular/common/http'; +import { provideHttpClientTesting } from '@angular/common/http/testing'; +import { App } from './app'; +import { routes } from './app.routes'; +import { DOMINIOS } from './features/indicadores/indicadores.models'; + +@Component({ template: 'página', selector: 'app-stub' }) +class Stub {} + +describe('Encabezado del marco', () => { + const rutas = [ + { path: '', component: Stub }, + { path: 'conectar', component: Stub, data: { workspace: true, breadcrumb: 'Conectar datos' } }, + { path: 'gobernanza', component: Stub, data: { workspace: true, breadcrumb: 'Gobernanza de modelos' } }, + ...DOMINIOS.map(dominio => ({ path: `indicadores/${dominio}`, component: Stub, data: { workspace: true, breadcrumb: 'Indicadores', dominio } })), + ]; + let fixture: ReturnType>, router: Router; + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [App], providers: [provideRouter(rutas), provideHttpClient(), provideHttpClientTesting()] }).compileComponents(); + fixture = TestBed.createComponent(App); router = TestBed.inject(Router); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); document.querySelectorAll('.cdk-overlay-container').forEach(e => e.replaceChildren()); }); + const root = () => fixture.nativeElement as HTMLElement; + async function ir(url: string) { await router.navigateByUrl(url); await fixture.whenStable(); fixture.detectChanges(); } + const selector = () => root().querySelector('.domain-selector') as HTMLButtonElement | null; + async function abrirMenu() { + selector()!.click(); fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); + return [...document.querySelectorAll('.mat-mdc-menu-panel a[mat-menu-item]')] as HTMLAnchorElement[]; + } + + it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => { + // Fails if the selector would point at a route the application does not have. + const paths = routes.map(r => r.path); + for (const dominio of DOMINIOS) expect(paths).toContain(`indicadores/${dominio}`); + }); + it.each([['tea', 'TEA'], ['cacu', 'CaCu'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => { + await ir('/indicadores/' + dominio); + expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores'); + expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾'); + expect(root().querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON'); + // The breadcrumb is replaced, not duplicated beside the selector. + expect(root().querySelector('.site-header__nav')).toBeNull(); + expect(root().querySelector('.app-shell--indicadores')).not.toBeNull(); + }); + it('el selector tiene nombre accesible con el dominio actual y anuncia un menú', async () => { + await ir('/indicadores/cama'); + expect(selector()!.getAttribute('aria-label')).toBe('Dominio actual: Cáncer de mama. Cambiar dominio'); + expect(selector()!.getAttribute('aria-haspopup')).toBe('menu'); + expect(selector()!.tagName).toBe('BUTTON'); + expect(selector()!.tabIndex).toBeGreaterThanOrEqual(0); + }); + it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => { + await ir('/indicadores/cama'); + const items = await abrirMenu(); + expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']); + expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']); + expect(selector()!.getAttribute('aria-expanded')).toBe('true'); + }); + it('elegir otro dominio navega por el enrutador, actualiza el selector y deja una entrada en el historial', async () => { + await ir('/indicadores/cama'); + const items = await abrirMenu(); + items[1].click(); await fixture.whenStable(); fixture.detectChanges(); + expect(router.url).toBe('/indicadores/cacu'); + expect(selector()!.textContent).toContain('CaCu'); + // The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain. + const ubicacion = TestBed.inject(Location); + ubicacion.back(); await new Promise(r => setTimeout(r, 100)); + expect(ubicacion.path()).toBe('/indicadores/cama'); + }); + it.each(['/', '/conectar', '/gobernanza'])('en %s conserva el encabezado institucional sin selector', async url => { + // Fails if the indicators header leaks into the institutional routes. + await ir(url); + expect(selector()).toBeNull(); + expect(root().querySelector('.platform-title')).toBeNull(); + expect(root().querySelector('.site-header__section')?.textContent).toBe('Análisis de información'); + expect(root().querySelector('.app-shell--indicadores')).toBeNull(); + if (url !== '/') expect(root().querySelector('.site-header__crumb')?.textContent).toContain(url === '/conectar' ? 'Conectar datos' : 'Gobernanza de modelos'); + }); + it('una ruta parecida que no es de indicadores no activa el selector', async () => { + await router.navigateByUrl('/'); fixture.detectChanges(); + expect(selector()).toBeNull(); + }); +}); diff --git a/src/app/app.html b/src/app/app.html index b41af08..0cbc82f 100644 --- a/src/app/app.html +++ b/src/app/app.html @@ -1,15 +1,28 @@ -
+
diff --git a/src/app/app.scss b/src/app/app.scss index 234d0f1..8400cfb 100644 --- a/src/app/app.scss +++ b/src/app/app.scss @@ -103,3 +103,28 @@ width: 155px; } } + +.platform-title { + color: var(--color-text); + font-family: var(--issste-font-heading); + font-size: 1.25rem; + font-weight: 500; + line-height: 1.15; + margin-inline-start: var(--issste-space-4); + margin-inline-end: auto; + overflow-wrap: anywhere; +} + +.domain-selector { + flex: 0 0 auto; + background-color: var(--issste-accent); + color: var(--issste-text); + font-weight: 700; + white-space: nowrap; +} +.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); } +.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + +@media (max-width: 599px) { + .platform-title { font-size: 1.125rem; min-width: 0; } +} diff --git a/src/app/app.ts b/src/app/app.ts index b18cd4e..f426daf 100644 --- a/src/app/app.ts +++ b/src/app/app.ts @@ -1,10 +1,13 @@ import { Component, computed, inject } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router'; +import { MatButtonModule } from '@angular/material/button'; +import { MatMenuModule } from '@angular/material/menu'; import { filter, map } from 'rxjs'; +import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models'; @Component({ - imports: [RouterLink, RouterOutlet], + imports: [RouterLink, RouterOutlet, MatButtonModule, MatMenuModule], selector: 'app-root', styleUrl: './app.scss', templateUrl: './app.html', @@ -28,4 +31,13 @@ export class App { /** Full-height workspace routes (`data.workspace`) drop the marketing footer. */ readonly workspace = computed(() => !!this.leafRouteData()['workspace']); readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined); + + protected readonly title = 'Plataforma de Indicadores'; + protected readonly domainLabels: Record = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' }; + private readonly url = toSignal(this.router.events.pipe( + filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url }); + /** On an indicators page the header names its domain and switches to the others. */ + protected readonly activeDomain = computed(() => + DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url()))); + protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain())); } From ff03a88ea0a9013b1e5b839c844c53010774681d Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 01:21:53 -0600 Subject: [PATCH 09/38] feat(indicadores): domain navigation moves to the header; searchVisible reads the catalog before the domain The in-page domain buttons are removed, since the header selector replaces them. Also fixes a computed that, after a visit to CaMa, never became true again, so CaCu and TEA lost their search box when switched to from CaMa. (cherry picked from commit 3678c3653b33fcb98ba2334ca8f03f838dc86440) --- .../indicadores-cambio-dominio.spec.ts | 60 +++++++++++++++++++ .../indicadores-navigation.spec.ts | 4 +- .../indicadores/indicadores-page.html | 8 --- .../indicadores/indicadores-page.scss | 28 --------- .../indicadores/indicadores-page.spec.ts | 11 ++-- .../features/indicadores/indicadores-page.ts | 14 ++--- .../indicadores/indicadores-sections.spec.ts | 6 +- 7 files changed, 74 insertions(+), 57 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-cambio-dominio.spec.ts diff --git a/src/app/features/indicadores/indicadores-cambio-dominio.spec.ts b/src/app/features/indicadores/indicadores-cambio-dominio.spec.ts new file mode 100644 index 0000000..328e3e3 --- /dev/null +++ b/src/app/features/indicadores/indicadores-cambio-dominio.spec.ts @@ -0,0 +1,60 @@ +// Covers switching domains with requests still pending: nothing of the domain that was left may show up in +// the one that was chosen, and the controls particular to each domain stay as they were. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresMemory } from './indicadores-memory'; + +const item = (id: string, titulo: string, contrato: string) => ({ id, titulo, contrato, figuras: ['f', 'g'], tipos_periodo: ['semestre', 'mes'] }); + +describe('Cambio de dominio con consultas pendientes', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + for (const d of ['tea', 'cacu', 'cama'] as const) TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation(d); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.match(() => true); http.verify(); vi.unstubAllGlobals(); }); + const text = () => (fixture.nativeElement as HTMLElement).textContent!; + + it('el catálogo pendiente del dominio que se dejó se cancela y su respuesta tardía no se dibuja', () => { + // Fails if a late answer of CaMa shows its indicators in CaCu. + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + const cama = http.expectOne('/cama/indicadores'); + fixture.componentInstance.changeDominio('cacu'); fixture.detectChanges(); + expect(cama.cancelled).toBe(true); + http.expectOne('/cacu/indicadores').flush([item('cacu_x', 'Indicador de CaCu', 'C2')]); fixture.detectChanges(); + expect(text()).toContain('Indicador de CaCu'); + expect(() => cama.flush([item('cama_x', 'Indicador de CaMa', 'C2')])).toThrow(); + fixture.detectChanges(); + expect(text()).not.toContain('Indicador de CaMa'); + }); + it('los controles propios de cada dominio se conservan al ir y volver', () => { + // CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other. + const abrir = (d: 'cacu' | 'cama', n: number) => { + fixture.componentInstance.changeDominio(d); fixture.detectChanges(); + http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges(); + http.match(() => true); + }; + const el = () => fixture.nativeElement as HTMLElement; + abrir('cacu', 6); + expect(el().querySelector('.catalog-search')).not.toBeNull(); + expect(el().querySelectorAll('.pin-toggle').length).toBe(6); + expect(el().textContent).toContain('Modalidad'); + abrir('cama', 6); + expect(el().querySelector('.catalog-search')).toBeNull(); + expect(el().querySelector('.pin-toggle')).toBeNull(); + expect(el().textContent).not.toContain('Modalidad'); + expect(el().textContent).not.toContain('cacu_'); + abrir('cacu', 6); + // On the way back the page state (not only the DOM) says CaCu has its search again. + expect(fixture.componentInstance.dominio).toBe('cacu'); + expect(fixture.componentInstance.searchVisible()).toBe(true); + expect(el().textContent).toContain('Modalidad'); + expect(el().textContent).not.toContain('cama_'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index f14b57f..ffef693 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -44,8 +44,8 @@ describe('UX-04 navegación Angular', () => { const harness = await setup(); await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage); load(domain, harness); harness.detectChanges(); - // Our shell keeps the domain nav on the page itself, see indicadores-page.html. - expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav a')).toHaveLength(3); + // The domain links are in the shell's header selector (app-encabezado.spec.ts); the page has none of its own. + expect(harness.routeNativeElement!.querySelectorAll('nav.domain-nav')).toHaveLength(0); http.expectNone(() => true); }); it('mantiene la ruta, restaura borradores y reconsulta la aplicación entre TEA/CaCu/CaMa', async () => { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 654018d..fdd3c73 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -10,14 +10,6 @@ } @if (!fichaPacienteAbierta()) { - -
@for (section of sections; track section.id) { - - @for (option of otherDomains(); track option) { - {{ domainLabels[option] }} - } - + @defer (on immediate) { + + } @placeholder { + + + } } @else {
diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.ts b/src/app/features/indicadores/indicador-histopatologia-cama.ts new file mode 100644 index 0000000..c78083d --- /dev/null +++ b/src/app/features/indicadores/indicador-histopatologia-cama.ts @@ -0,0 +1,145 @@ +import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; +import { HttpErrorResponse } from '@angular/common/http'; +import { Subscription, timeout, TimeoutError } from 'rxjs'; +import { MatButtonModule } from '@angular/material/button'; +import { MatProgressBarModule } from '@angular/material/progress-bar'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; +import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; +import { httpMessage } from './indicadores-http'; +import { Celda } from './indicadores-confirmacion-citologia'; +import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA, + lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama'; + +// Figures of the kit whose "Cómo leer" describes this coordinated view. +const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const; + +/** + * CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the + * result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service + * for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`. + */ +@Component({ + selector: 'app-indicador-histopatologia-cama', + imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + templateUrl: './indicador-histopatologia-cama.html', + styleUrl: './indicador-confirmacion-citologia.scss', +}) +export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { + @Input({ required: true }) dominio!: Dominio; + @Input({ required: true }) indicador!: Indicador; + @Input({ required: true }) tema!: Tema; + @Input({ required: true }) applied!: GlobalApplied; + @Input() visible = true; + @Input() metadata?: IndicadorMetadatos; + readonly metadataRequested = output(); + readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); + message = ''; + selection?: SeleccionHistopatologia; + periods: string[] = []; + periodIndex = 0; + model?: ModeloHistopatologia; + donutFigure?: PlotlyFigure; + ratesFigure?: PlotlyFigure; + helpOpen = false; + private readonly snapshots = inject(IndicadoresSnapshots); + private readonly changeDetector = inject(ChangeDetectorRef); + private subscription?: Subscription; + private key = ''; + private loaded = false; + private pages: ModeloHistopatologia[] = []; + + get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } + get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } + get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; } + get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; } + get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; } + readonly estadoTasa = estadoTasa; + cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } + denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); } + get readingGuide() { + const details = this.metadata?.figuras_detalle ?? []; + return FIGURAS.flatMap(([figura, nombre]) => { + const detail = details.find(item => item.figura === figura); + const descripcion = detail?.descripcion?.trim() ?? ''; + const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); + return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; + }); + } + toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } + + ngOnChanges(changes: SimpleChanges) { + const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS }) + + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]); + if (key !== this.key) { + this.subscription?.unsubscribe(); this.key = key; this.loaded = false; + this.clear(); + if (!this.visible) { this.status.set('deferred'); return; } + this.load(); + } else if (this.visible && !this.loaded) this.load(); + else if (this.model && changes['tema']) this.draw(); + } + retry() { if (this.visible) this.load(); } + private clear() { + this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined; + this.donutFigure = undefined; this.ratesFigure = undefined; + } + private load() { + this.subscription?.unsubscribe(); + this.loaded = true; this.clear(); + const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); + if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) { + this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.'; + this.status.set('incompatible'); return; + } + const key = this.key; + const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; + this.status.set('loading'); + this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, + { estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({ + next: datos => { + if (key !== this.key) return; + try { + this.periods = periodosHistopatologia(datos, this.applied.tipo, periods); + this.pages = this.periods.map(p => modeloHistopatologia(datos, p)); + // The most recent period first; navigation goes back. + this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod(); + } catch (error) { this.failure(error); } + }, + error: error => { if (key === this.key) this.failure(error); }, + }); + } + private failure(error: unknown) { + this.clear(); + this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' + : error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error); + this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) + ? 'incompatible' : 'error'); + this.changeDetector.markForCheck(); + } + private activatePeriod() { + this.model = this.pages[this.periodIndex]; + this.selection = this.model ? seleccionBase(this.model) : undefined; + this.draw(); this.status.set(this.model && !this.model.vacio ? 'ready' : 'empty'); + } + changePeriod(step: number) { + if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; + this.periodIndex += step; this.activatePeriod(); + } + select(trace: string, index = 0) { + if (!this.model || !this.selection || this.status() !== 'ready') return; + this.selection = clicHistopatologia(this.model, this.selection, trace, index); this.draw(); + } + plotClicked(event: unknown) { + const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; + if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); + } + private draw() { + if (!this.model || !this.selection) return; + this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema); + this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); + this.changeDetector.markForCheck(); + } + ngOnDestroy() { this.subscription?.unsubscribe(); } +} diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts new file mode 100644 index 0000000..48a7535 --- /dev/null +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -0,0 +1,338 @@ +// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows, +// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic +// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per +// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator). +import { Component, input, output } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { By } from '@angular/platform-browser'; +import estratoFixture from './fixtures/cama_histopatologia_birads_estrato.json'; +import generalFixture from './fixtures/cama_histopatologia_birads_general.json'; +import catalogoFixture from './fixtures/cama_catalogo_f4c.json'; +import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama'; +import { IndicadorCatalogCard } from './indicador-catalog-card'; +import { IndicadorFigurePanel } from './indicador-figure-panel'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { GlobalApplied } from './indicadores-memory'; +import { Indicador, IndicadorDatos } from './indicadores.models'; +import { wilson } from './indicadores-confirmacion-citologia'; +import { clicHistopatologia, donaHistopatologia, estadoTasa, figuraTasas, HistopatologiaIncompatible, lectura, modeloHistopatologia, + periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama'; + +@Component({ selector: 'app-plotly-chart', template: '' }) +class ChartStub { figure = input(); label = input(); showNotes = input(); plotClick = output(); } + +const estrato = () => structuredClone(estratoFixture) as unknown as IndicadorDatos & { filas: Record[]; totales_estrato: Record[]; valores_estrato: string[]; categorias: Record }; +const fila = (d: { filas: Record[] }, e: string, c: string) => d.filas.find(f => f['estrato'] === e && f['categoria'] === c)!; +const PERIODO = '2025-S1'; +const base = (d = estrato()) => modeloHistopatologia(d, PERIODO); + +describe('Histopatología por BI-RADS: modelo', () => { + it('lee la matriz completa: seis estratos, cuatro categorías con resultado y dos aparte', () => { + const m = base(); + expect(m.filas.map(f => f.id)).toEqual(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']); + expect(m.filas.map(f => f.etiqueta)).toEqual(['BI-RADS 4 sin subtipo', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); + expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']); + expect(m.categorias.map(c => c.color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E']); + expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([ + ['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]); + expect(m.base).toBe('MALIGNO'); + expect(m.aparte).toEqual([{ id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' }, { id: 'SIN_DATO', etiqueta: 'Sin dato' }]); + expect(m.filas.map(f => [f.aparte['SIN_BIOPSIA'].n, f.aparte['SIN_DATO'].n, f.total.n])).toEqual([[1, 1, 6], [1, 1, 7], [1, 1, 6], [1, 1, 6], [1, 1, 6], [1, 1, 6]]); + expect(m.notas[0]).toContain('BI-RADS 4 sin subtipo es una fila propia'); + }); + it('el denominador de cada estrato son las cuatro categorías con resultado: Sin biopsia y Sin dato quedan fuera', () => { + const m = base(); + expect(m.filas.map(f => f.den)).toEqual([4, 5, 4, 4, 4, 4]); + expect(m.totales).toEqual({ BENIGNO: 7, RIESGO_B3: 5, IN_SITU: 6, INVASOR: 7 }); + expect(m.conResultado).toBe(25); + }); + it('BI-RADS 4 es una fila independiente: no se reparte entre 4A, 4B y 4C ni se suma a ellos', () => { + // Fails if the 4 without subtype is merged into a subtype: 4A has 5 patients with a result, the 4 has 4. + const m = base(); + expect([m.filas[0].den, m.filas[1].den]).toEqual([4, 5]); + expect(m.filas[0].celdas['BENIGNO'].n).toBe(2); expect(m.filas[1].celdas['BENIGNO'].n).toBe(1); + expect(m.filas.slice(1, 4).reduce((s, f) => s + f.den!, 0)).toBe(13); + }); + it('un cero publicado es un cero válido: cuenta en el denominador y no bloquea la fila', () => { + // BIRADS_4 / RIESGO_B3 is published with n: 0 in the example. + const m = base(); + expect(fila(estrato(), 'BIRADS_4', 'RIESGO_B3')['n']).toBe(0); + expect(m.filas[0].celdas['RIESGO_B3']).toEqual({ n: 0, estado: 'Publicado' }); + expect([m.filas[0].den, m.filas[0].estado]).toEqual([4, 'Publicado']); + }); + it('una celda que la respuesta no trae es «No disponible», no cero: la fila no da tasa y la dona no suma un total parcial', () => { + const d = estrato(); d.filas = d.filas.filter(f => !(f['estrato'] === 'BIRADS_4B' && f['categoria'] === 'INVASOR')); + const m = base(d), sel = seleccionBase(m); + expect(m.filas[2].celdas['INVASOR']).toEqual({ n: null, estado: 'No disponible' }); + expect([m.filas[2].den, m.filas[2].estado]).toEqual([null, 'No disponible']); + expect(tasas(m, sel).map(t => t.k)).toEqual([2, 3, null, 2, 2, 2]); + expect(tasas(m, sel).map(estadoTasa)).toEqual(['', '', 'No disponible', '', '', '']); + expect(m.conResultado).toBeNull(); expect(m.totales['INVASOR']).toBeNull(); + expect(donaHistopatologia(m, sel, 'claro').data).toHaveLength(0); + expect(JSON.stringify(figuraTasas(m, sel, 'claro').layout['annotations'])).not.toContain('0/'); + }); + it('una celda suprimida es «Suprimido»; un total suprimido suprime la fila aunque sus celdas se publiquen', () => { + const d = estrato(); Object.assign(fila(d, 'BIRADS_5', 'IN_SITU'), { n: null, suprimido: 1 }); + const m = base(d); + expect(m.filas[4].celdas['IN_SITU']).toEqual({ n: null, estado: 'Suprimido' }); + expect([m.filas[4].den, m.filas[4].estado]).toEqual([null, 'Suprimido']); + expect(m.conResultado).toBeNull(); + const t = estrato(); Object.assign(t.totales_estrato.find(x => x['estrato'] === 'BIRADS_6')!, { n: null, suprimido: 1 }); + const s = base(t); + expect([s.filas[5].den, s.filas[5].estado, s.filas[5].total]).toEqual([null, 'Suprimido', { n: null, estado: 'Suprimido' }]); + expect(s.filas[0].den).toBe(4); expect(s.conResultado).toBeNull(); + }); + it('un estrato que no se publica no se lee como cero pacientes: sus celdas, tasa y dona no están disponibles', () => { + const d = estrato(); + d.filas = d.filas.filter(f => f['estrato'] !== 'BIRADS_4A'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_4A'); + d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_4A'); + const m = base(d); + expect(m.filas[1].etiqueta).toBe('BI-RADS 4A'); + expect(Object.values(m.filas[1].celdas).every(c => c.n === null && c.estado === 'No disponible')).toBe(true); + expect([m.filas[1].den, m.filas[1].total.estado]).toEqual([null, 'No disponible']); + expect(m.conResultado).toBeNull(); + expect(tasas(m, seleccionBase(m))[1].k).toBeNull(); + }); + it('sin ninguna fila del periodo el modelo está vacío', () => { + const d = estrato(); d.filas = []; d.totales_estrato = []; + expect(base(d).vacio).toBe(true); expect(base().vacio).toBe(false); + }); + it('rechaza lo que no es de esta medida: otro indicador, otro estrato, el C2 general, periodos no pedidos', () => { + expect(() => periodosHistopatologia({ ...estrato(), id: 'cama_eu38a' }, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia({ ...estrato(), estrato: 'grupo_edad' } as IndicadorDatos, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(generalFixture as unknown as IndicadorDatos, 'semestre')).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(estrato(), 'semestre', ['2025-S2'])).toThrow(HistopatologiaIncompatible); + expect(() => periodosHistopatologia(estrato(), 'mes')).toThrow(HistopatologiaIncompatible); + expect(periodosHistopatologia(estrato(), 'semestre', [PERIODO])).toEqual([PERIODO]); + }); + it.each([ + ['un estrato que el contrato no tiene', (d: any) => { fila(d, 'BIRADS_4', 'BENIGNO')['estrato'] = 'BIRADS_7'; }], + ['una categoría desconocida en una fila', (d: any) => { fila(d, 'BIRADS_4', 'BENIGNO')['categoria'] = 'OTRA'; }], + ['una categoría desconocida en el catálogo', (d: any) => { d.categorias['OTRA'] = { etiqueta: 'Otra', color: '#112233', grupo: 'NO_MALIGNO', gravedad: 5 }; }], + ['sin la categoría INVASOR en el catálogo', (d: any) => { delete d.categorias['INVASOR']; }], + ['un estrato desconocido en valores_estrato', (d: any) => { d.valores_estrato.push('BIRADS_7'); }], + ['filas duplicadas', (d: any) => { d.filas.push({ ...d.filas[0] }); }], + ['un grupo distinto de TOTAL', (d: any) => { d.filas[0]['grupo'] = 'OTRO'; }], + ['suprimido distinto de 0 o 1', (d: any) => { d.filas[0]['suprimido'] = 2; }], + ['un total que no es la suma de sus celdas', (d: any) => { d.totales_estrato[0]['n'] = 99; }], + ['un color que no es hexadecimal', (d: any) => { d.categorias['BENIGNO'].color = 'azul'; }], + ['una categoría sin grupo publicado', (d: any) => { d.categorias['BENIGNO'].grupo = 'NADA'; }], + ['sin catálogo de grupos', (d: any) => { delete d.grupos_de_categoria; }], + ])('rechaza %s', (_nombre, daño) => { + // Fails if a payload outside the contract is drawn, which could change a denominator unnoticed. + const d: any = estrato(); daño(d); + expect(() => base(d)).toThrow(HistopatologiaIncompatible); + }); + it('un color nulo en el catálogo usa el gris de respaldo', () => { + const d = estrato(); d.categorias['RIESGO_B3'].color = null; + expect(base(d).categorias[1].color).toBe('#8A9199'); + }); +}); + +describe('Histopatología por BI-RADS: tasas, selección y figuras', () => { + it('la vista base lee «maligno»: In situ más invasor entre las pacientes con resultado, con Wilson al 95 %', () => { + const m = base(), sel = seleccionBase(m); + expect(sel).toEqual({ grupo: 'MALIGNO' }); + expect(tasas(m, sel).map(t => [t.k, t.fila.den])).toEqual([[2, 4], [3, 5], [2, 4], [2, 4], [2, 4], [2, 4]]); + const [bajo, alto] = wilson(3, 5); + expect(tasas(m, sel)[1]).toMatchObject({ valor: 60, bajo, alto }); + expect(lectura(m, sel)).toBe('Pacientes con resultado maligno entre las que tienen resultado de biopsia'); + }); + it('grupo, categoría, segundo clic al grupo y centro a la base', () => { + const m = base(), sel = seleccionBase(m); + const noMaligno = clicHistopatologia(m, sel, 'grupos', 0); + expect(noMaligno).toEqual({ grupo: 'NO_MALIGNO' }); + expect(tasas(m, noMaligno).map(t => t.k)).toEqual([2, 2, 2, 2, 2, 2]); + expect(lectura(m, noMaligno)).toBe('Pacientes con resultado no maligno entre las que tienen resultado de biopsia'); + const b3 = clicHistopatologia(m, noMaligno, 'categorias', 1); + expect(b3).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + expect(tasas(m, b3).map(t => t.k)).toEqual([0, 1, 1, 1, 1, 1]); + expect(lectura(m, b3)).toBe('Proporción con resultado lesión de riesgo (b3)'); + expect(clicHistopatologia(m, b3, 'categorias', 1)).toEqual({ grupo: 'NO_MALIGNO' }); + expect(clicHistopatologia(m, b3, 'categorias', 3)).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); + expect(clicHistopatologia(m, b3, 'centro', 0)).toEqual(sel); + expect(clicHistopatologia(m, b3, 'otra', 0)).toEqual(b3); expect(clicHistopatologia(m, b3, 'grupos', 9)).toEqual(b3); + }); + it('un cero con denominador es una tasa de 0 %, no una ausencia', () => { + const m = base(), b3 = { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }; + const t = tasas(m, b3)[0]; + expect([t.k, t.valor, t.fila.den]).toEqual([0, 0, 4]); expect(t.bajo).toBe(0); expect(t.alto).toBeGreaterThan(0); + expect(estadoTasa(t)).toBe(''); + expect((figuraTasas(m, b3, 'claro').layout['annotations'] as { text: string }[])[0].text).toMatch(/0\/4$/); + }); + it('un estrato sin pacientes con resultado dice «Sin pacientes con resultado de biopsia», sin tasa', () => { + const d = estrato(); + for (const c of ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR']) fila(d, 'BIRADS_6', c)['n'] = 0; + d.totales_estrato.find(t => t['estrato'] === 'BIRADS_6')!['n'] = 2; + const m = base(d), t = tasas(m, seleccionBase(m))[5]; + expect([m.filas[5].den, t.k, t.valor, estadoTasa(t)]).toEqual([0, null, null, 'Sin pacientes con resultado de biopsia']); + }); + it('figura de tasas: una traza, seis categorías con la 4 sin subtipo arriba, etiquetas «% y k/n» y eje en múltiplos de 5', () => { + const m = base(), sel = seleccionBase(m), f = figuraTasas(m, sel, 'claro'); + expect(f.data).toHaveLength(1); expect(f.data[0]['name']).toBe('tasas'); + expect(f.data[0]['y']).toEqual(m.filas.map(r => r.etiqueta)); + expect((f.layout['yaxis'] as { categoryarray: string[] }).categoryarray[5]).toBe('BI-RADS 4 sin subtipo'); + expect(f.data[0]['x']).toEqual([50, 60, 50, 50, 50, 50]); + expect((f.layout['annotations'] as { text: string }[]).map(a => a.text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim())) + .toEqual(['50.0 % 2/4', '60.0 % 3/5', '50.0 % 2/4', '50.0 % 2/4', '50.0 % 2/4', '50.0 % 2/4']); + const range = (f.layout['xaxis'] as { range: number[] }).range; + expect(range).toEqual(rangoTasas(tasas(m, sel))); + expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); + expect(figuraTasas(m, sel, 'oscuro').layout['paper_bgcolor']).toBe('#081839'); + }); + it('dona de dos anillos: grupos dentro, categorías fuera; la selección atenúa sin cambiar valores y el centro dice «k de N con resultado»', () => { + const m = base(), d = donaHistopatologia(m, seleccionBase(m), 'claro'); + expect(d.data.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias']); + expect(d.data[1]['values']).toEqual([12, 13]); expect(d.data[2]['values']).toEqual([7, 5, 6, 7]); + expect(d.data[0]['text']).toEqual(['13
de 25 con resultado']); + const otra = donaHistopatologia(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro'); + expect(otra.data[2]['values']).toEqual(d.data[2]['values']); + const colores = (otra.data[2]['marker'] as { colors: string[] }).colors; + expect(colores[1]).toMatch(/,1\)$/); expect(colores[0]).toMatch(/,0.3\)$/); + expect(otra.data[0]['text']).toEqual(['5
de 25 con resultado']); + }); + it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => { + // The general payload is what the history panel draws; it must not pass for the stratified one. + expect(Object.keys((generalFixture as any).categorias)).toEqual(['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR', 'SIN_BIOPSIA', 'SIN_DATO']); + expect((generalFixture as any).filas.map((f: any) => f.n)).toEqual([7, 5, 6, 7, 6, 6]); + expect((generalFixture as any).estrato).toBeNull(); + }); +}); + +describe('Histopatología por BI-RADS: componente', () => { + const indicador = (catalogoFixture as unknown as Indicador[]).find(item => item.id === 'cama_histopatologia_birads')!; + const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: [PERIODO] }, revision: 1 }; + let f: ReturnType>; + let http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadorHistopatologiaCama, IndicadorCatalogCard], providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.overrideComponent(IndicadorHistopatologiaCama, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + f = TestBed.createComponent(IndicadorHistopatologiaCama); + f.componentRef.setInput('dominio', 'cama'); f.componentRef.setInput('indicador', indicador); + f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied); + }); + afterEach(() => { f.destroy(); http.verify(); }); + const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos'); + function flush(body: unknown = estratoFixture) { + const r = solicitud(); + expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO); + r.flush(body as Record); f.detectChanges(); + } + const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement; + + it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true); + f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading'); + flush(); expect(f.componentInstance.status()).toBe('ready'); + const figures = [...f.nativeElement.querySelectorAll('.figures > .figure')] as HTMLElement[]; + expect(figures.map(s => s.classList.contains('rates') ? 'tasas' : 'dona')).toEqual(['tasas', 'dona']); + expect([...f.nativeElement.querySelectorAll('.keys button')].map((b: Element) => b.textContent!.trim())) + .toEqual(['No maligno', 'Maligno', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('selección: Maligno'); + const table = f.nativeElement.querySelector('table') as HTMLTableElement; + expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual( + ['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']); + expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([ + ['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'], + ['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'], + ['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]); + expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional para datos sintéticos'); + }); + it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => { + f.detectChanges(); flush(); + const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub); + const volver = () => [...f.nativeElement.querySelectorAll('.legend > button')].find((b: Element) => b.textContent!.trim() === 'Volver') as HTMLButtonElement; + expect(volver().disabled).toBe(true); + const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + expect(b3.getAttribute('aria-pressed')).toBe('true'); expect(volver().disabled).toBe(false); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (b3)'); + b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); + boton('Carcinoma invasor').click(); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); + volver().click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); + charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges(); + expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' }); + http.expectNone(() => true); + }); + it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => { + const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 }); + f.detectChanges(); flush(d); + expect(f.componentInstance.status()).toBe('ready'); + expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos'); + expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 4C: Suprimido'); + const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent)); + expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4'); + }); + it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => { + const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6'); + d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6'); + f.detectChanges(); flush(d); + const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement; + expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]); + expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 6: No disponible'); + }); + it('sin filas en el periodo lo dice y conserva la tabla vacía', () => { + const d = estrato(); d.filas = []; d.totales_estrato = []; + f.detectChanges(); flush(d); + expect(f.componentInstance.status()).toBe('empty'); + expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => { + f.detectChanges(); + solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull(); + f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' }); + expect(f.componentInstance.status()).toBe('incompatible'); + expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0); + }); + it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => { + f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges(); + expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true); + }); + it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => { + f.detectChanges(); flush(); + f.componentRef.setInput('tema', 'oscuro'); f.detectChanges(); + expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true); + }); + it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido); + (f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges(); + expect(pedido).toHaveBeenCalledTimes(1); + expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador'); + f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [ + { figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] }); + f.detectChanges(); + const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement; + expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']); + for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente); + }); + + it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => { + f.componentRef.setInput('visible', false); f.detectChanges(); + const card = TestBed.createComponent(IndicadorCatalogCard); + card.componentRef.setInput('dominio', 'cama'); card.componentRef.setInput('indicador', indicador); + card.componentRef.setInput('tema', 'claro'); card.componentRef.setInput('applied', applied); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorHistopatologiaCama))).toHaveLength(1); + expect(card.debugElement.queryAll(By.directive(IndicadorFigurePanel))).toHaveLength(0); + expect(card.nativeElement.querySelector('h2').textContent).toBe(indicador.titulo); + for (const [domain, id] of [['cacu', 'cama_histopatologia_birads'], ['cama', 'cama_biopsias']] as const) { + card.componentRef.setInput('dominio', domain); card.componentRef.setInput('indicador', { ...indicador, id }); card.detectChanges(); + expect(card.debugElement.queryAll(By.directive(IndicadorHistopatologiaCama))).toHaveLength(0); + } + card.destroy(); http.expectNone(() => true); + }); +}); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts new file mode 100644 index 0000000..f52fb11 --- /dev/null +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -0,0 +1,251 @@ +import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models'; +import { c2Theme } from './indicadores-c2-palette'; +import { Celda, wilson } from './indicadores-confirmacion-citologia'; +import { percentNumber, shareText } from './indicadores-format'; +import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; + +// CaMa's histopathological result by BI-RADS (cama_histopatologia_birads): a C2 stratified by `birads`, one +// patient per period. This module turns the published matrix into what the view draws; it owns no HTTP and no +// drawing library, so another source of the same matrix (for example a MeasureReport adapter) only has to +// produce the same payload. The selection of units stays in the backend; here nothing is added, inferred or +// completed: a stratum or a cell that is not published is "No disponible", never zero, and a suppressed cell +// is "Suprimido". A total is only drawn over a complete matrix. +export const ID_HISTOPATOLOGIA = ID_HISTOPATOLOGIA_CAMA; +export const ESTRATO_BIRADS = 'birads'; +// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never +// split among 4A/4B/4C nor added to them. +export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const; +const ETIQUETA_ESTRATO: Readonly> = { + BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6', +}; +// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two +// and MALIGNO the last two, as the catalog says. +export const CON_RESULTADO = ['BENIGNO', 'RIESGO_B3', 'IN_SITU', 'INVASOR'] as const; +// Reported apart, outside the denominator and the donut: no biopsy reported at the cut-off, and a biopsy without grade. +export const APARTE = [ + { id: 'SIN_BIOPSIA', etiqueta: 'Sin biopsia reportada' }, + { id: 'SIN_DATO', etiqueta: 'Sin dato' }, +] as const; +const APARTE_IDS: readonly string[] = APARTE.map(a => a.id); +// The group the base view reads: the malignant results, the true positives of the suspicion. +const CATEGORIA_BASE = 'INVASOR'; +const COLOR_RESPALDO = '#8A9199'; + +export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; } +export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; } +export interface FilaBirads { + id: string; etiqueta: string; + // The four categories with a result. + celdas: Record; + // SIN_BIOPSIA and SIN_DATO, when the catalog publishes them. + aparte: Record; + // Patients of the stratum, as the response publishes them. + total: Celda; + // Patients with a biopsy result: the denominator. Null while any of the four cells is unknown. + den: number | null; estado: Celda['estado']; +} +export interface ModeloHistopatologia { + periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string; + filas: FilaBirads[]; totales: Record; conResultado: number | null; + aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[]; +} +export interface SeleccionHistopatologia { grupo: string; categoria?: string; } +export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; } +export class HistopatologiaIncompatible extends Error {} + +const registro = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); +const texto = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0; +const fail = (message: string): never => { throw new HistopatologiaIncompatible(message); }; +const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); +const miles = (v: number) => v.toLocaleString('es-MX'); +const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; +const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined; + +// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available. +function celda(fila?: Record): Celda { + if (fila?.['suprimido'] === 1) return { n: null, estado: 'Suprimido' }; + return typeof fila?.['n'] === 'number' && Number.isSafeInteger(fila['n']) && fila['n'] >= 0 && fila['suprimido'] === 0 + ? { n: fila['n'], estado: 'Publicado' } : { n: null, estado: 'No disponible' }; +} +const suma = (celdas: Celda[]): number | null => celdas.some(c => c.n === null) ? null : celdas.reduce((s, c) => s + c.n!, 0); +const estadoDe = (celdas: Celda[]): Celda['estado'] => + celdas.some(c => c.estado === 'Suprimido') ? 'Suprimido' : celdas.some(c => c.n === null) ? 'No disponible' : 'Publicado'; +function promedio(colores: string[]): string { + return '#' + [1, 3, 5].map(i => Math.round(colores.reduce((s, c) => s + parseInt(c.slice(i, i + 2), 16), 0) / colores.length) + .toString(16).padStart(2, '0')).join(''); +} +function rgba(hex: string, alfa: number): string { + const v = parseInt(hex.slice(1), 16); + return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`; +} + +/** Validated periods of one stratified response, in request order or sorted. */ +export function periodosHistopatologia(datos: IndicadorDatos, tipo: string, solicitados?: readonly string[]): string[] { + if (datos.id !== ID_HISTOPATOLOGIA || datos.contrato !== 'C2' || datos.tipo_periodo !== tipo || datos['estrato'] !== ESTRATO_BIRADS + || !Array.isArray(datos.periodos) || new Set(datos.periodos).size !== datos.periodos.length + || datos.periodos.some(p => typeof p !== 'string' || !(tipo === 'semestre' ? /^[0-9]{4}-S[12]$/ : /^[0-9]{4}-(0[1-9]|1[0-2])$/).test(p)) + || (solicitados && datos.periodos.some(p => !solicitados.includes(p))) + || datos.filas.some(f => !registro(f) || !datos.periodos.includes(f['periodo'] as string))) { + return fail('Los datos no corresponden a la histopatología por BI-RADS o al periodo aplicado.'); + } + return solicitados ? solicitados.filter(p => datos.periodos.includes(p)) : [...datos.periodos].sort(); +} + +/** One stratified /datos payload -> the matrix of a single period. */ +export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): ModeloHistopatologia { + periodosHistopatologia(datos, datos.tipo_periodo); + const cats = datos['categorias'], nombres = datos['grupos_de_categoria']; + if (!registro(cats) || !registro(nombres)) return fail('Catálogo de categorías incompleto.'); + // A category the view does not know would change the denominator without anyone noticing. + const conocidas: readonly string[] = [...CON_RESULTADO, ...APARTE_IDS]; + if (Object.keys(cats).some(id => !conocidas.includes(id)) || CON_RESULTADO.some(id => !Object.hasOwn(cats, id))) { + return fail('El catálogo no publica las categorías esperadas de la biopsia.'); + } + const categorias: Categoria[] = CON_RESULTADO.map(id => { + const c = cats[id]; + if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && c['color'] !== undefined && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color']))) + || typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Categorías de biopsia incompatibles.'); + return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null | undefined) ?? COLOR_RESPALDO, grupo: c['grupo'] }; + }); + const grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => { + const propias = categorias.filter(c => c.grupo === id); + return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio(propias.map(c => c.color)), categorias: propias.map(c => c.id) }; + }); + if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.'); + const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo; + const aparte = APARTE.filter(a => Object.hasOwn(cats, a.id)).map(a => { + const c = cats[a.id]; + return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta }; + }); + + const indice = new Map>(); + for (const row of datos.filas.filter(f => f['periodo'] === periodo)) { + const c = row['categoria'], e = row['estrato']; + if (!esTotal(row['grupo']) || typeof e !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(e) || typeof c !== 'string' || !conocidas.includes(c) + || ![0, 1].includes(row['suprimido'] as number)) return fail('Fila de histopatología inválida.'); + const key = JSON.stringify([e, c]); + if (indice.has(key)) return fail('Filas de histopatología duplicadas.'); + indice.set(key, row); + } + const publicados = datos['valores_estrato']; + if (publicados !== undefined && (!Array.isArray(publicados) || !publicados.every(v => typeof v === 'string' && (ESTRATOS_BIRADS as readonly string[]).includes(v)))) { + return fail('Estratos de BI-RADS inválidos.'); + } + const etiquetas = registro(datos['etiquetas_estrato']) ? datos['etiquetas_estrato'] : {}; + const totalesPublicados = Array.isArray(datos['totales_estrato']) ? (datos['totales_estrato'] as unknown[]) : []; + if (!totalesPublicados.every(registro)) return fail('Totales de BI-RADS inválidos.'); + const totalesDelPeriodo = (totalesPublicados as Record[]).filter(t => t['periodo'] === periodo); + if (totalesDelPeriodo.some(t => !esTotal(t['grupo']) || typeof t['estrato'] !== 'string' || !(ESTRATOS_BIRADS as readonly string[]).includes(t['estrato']) + || ![0, 1].includes(t['suprimido'] as number))) return fail('Totales de BI-RADS inválidos.'); + + const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => { + const rotulo = texto(etiquetas[id]) ? etiquetas[id] : ETIQUETA_ESTRATO[id]; + // A stratum the response does not publish has cells that are not available: it is never read as zero patients. + const celdas = Object.fromEntries(categorias.map(c => [c.id, celda(indice.get(JSON.stringify([id, c.id])))])); + const otras = Object.fromEntries(aparte.map(a => [a.id, celda(indice.get(JSON.stringify([id, a.id])))])); + const total = celda(totalesDelPeriodo.find(t => t['estrato'] === id)); + const valores = Object.values(celdas); + // The published total of a stratum has to be the sum of its cells, when both are known. + const todas = [...valores, ...Object.values(otras)]; + if (total.n !== null && todas.every(c => c.n !== null) && suma(todas) !== total.n) return fail('El total de ' + rotulo + ' no coincide con la suma de sus celdas.'); + // A suppressed published total suppresses the row, whatever its cells say. + return { id, etiqueta: rotulo, celdas, aparte: otras, total, + den: total.estado === 'Suprimido' ? null : suma(valores), estado: total.estado === 'Suprimido' ? 'Suprimido' : estadoDe(valores) }; + }); + // The donut and its total need the six strata complete: a partial sum would be a different, unpublished figure. + const porCategoria = Object.fromEntries(categorias.map(c => [c.id, filas.some(f => f.den === null) ? null : suma(filas.map(f => f.celdas[c.id]))])); + return { periodo, categorias, grupos, base, filas, totales: porCategoria, + conResultado: suma(categorias.map(c => ({ n: porCategoria[c.id], estado: 'Publicado' as const }))), + aparte, vacio: indice.size === 0 && !totalesDelPeriodo.length, notas: [...new Set(datos.notas ?? [])] }; +} + +export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; } +export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] { + return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? []; +} +export function seleccionEtiqueta(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { + return sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.etiqueta : m.grupos.find(g => g.id === sel.grupo)!.etiqueta; +} +/** A group selects the group; a category selects it and a second click returns to its group; the centre returns to the base. */ +export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, traza: string, indice: number): SeleccionHistopatologia { + if (traza === 'centro') return seleccionBase(m); + if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; } + if (traza !== 'categorias') return sel; + const c = m.categorias[indice]; + if (!c) return sel; + return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id }; +} +/** The axis title says what the rate reads. */ +export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { + if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia'; + if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia'; + return 'Proporción con resultado ' + seleccionEtiqueta(m, sel).toLowerCase(); +} +/** Per BI-RADS stratum: the selected categories over the patients with a biopsy result. No biopsy and no data never enter. */ +export function tasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): Tasa[] { + const ids = seleccionadas(m, sel); + return m.filas.map(fila => { + if (fila.den === null || fila.den === 0) return { fila, k: null, valor: null, bajo: null, alto: null }; + const k = ids.reduce((s, c) => s + fila.celdas[c].n!, 0); + const [bajo, alto] = wilson(k, fila.den); + return { fila, k, valor: 100 * k / fila.den, bajo, alto }; + }); +} +export function estadoTasa(t: Tasa): string { + return t.fila.den === 0 ? 'Sin pacientes con resultado de biopsia' : t.fila.estado === 'Publicado' ? '' : t.fila.estado; +} +/** Axis bounded to what is shown: 5-point margin, multiples of 5, within 0-100. */ +export function rangoTasas(valores: Tasa[]): [number, number] { + const visibles = valores.filter(t => t.bajo !== null && t.alto !== null); + if (!visibles.length) return [0, 100]; + const min = Math.min(...visibles.map(t => t.bajo!)), max = Math.max(...visibles.map(t => t.alto!)); + return [Math.max(0, Math.floor((min - 5) / 5) * 5), Math.min(100, Math.ceil((max + 5) / 5) * 5)]; +} + +/** Rates on the left: one point and horizontal Wilson interval per BI-RADS stratum, one trace always. */ +export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { + const p = c2Theme(tema); + const valores = tasas(m, sel); + const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color; + const y = valores.map(t => t.fila.etiqueta); + return { data: [{ + type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), + marker: { size: 12, color }, cliponaxis: false, + error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6, + array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) }, + customdata: valores.map(t => t.k === null ? [estadoTasa(t), '', '', '', ''] : [shareText(t.k, t.fila.den!), t.k, t.fila.den, percentNumber(t.bajo!), percentNumber(t.alto!)]), + hovertemplate: '%{y}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', + }], layout: { + autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, + margin: { l: 150, r: 96, t: 16, b: 64 }, + yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true }, + xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } }, + annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left', + font: { size: 12, color: p.text }, + text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), + }, config: { displayModeBar: false } }; +} + +/** Donut on the right: result groups inside, categories outside; selection dims, values stay. Empty over an incomplete matrix. */ +export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { + if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} }; + const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado; + const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0); + const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0)); + const exterior = m.categorias.map(c => m.totales[c.id]!); + const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' }; + const hover = { hovertemplate: '%{label}
%{customdata[0]} pacientes con resultado, %{customdata[1]}' }; + const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]); + return { data: [ + { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside', + text: [`${miles(k)}
de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text }, + marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '' }, + { ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] }, + labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), + marker: { colors: m.grupos.map(g => rgba(g.color, g.categorias.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] }, + labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), + marker: { colors: m.categorias.map(c => rgba(c.color, activos.has(c.id) ? 1 : .3)), line: { color: p.background, width: 2 } } }, + ], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } }, + config: { displayModeBar: false } }; +} diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 357e9df..5822ac7 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -296,7 +296,9 @@ export class IndicadoresPage { // CaMa's summary: without the indicators it does not draw, and with the patients' counts on the exams' card. private cardsDeCama(catalog: Indicador[]) { const ids = catalog.map(item => item.id); - return catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids)); + const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids)); + // The histopathology card keeps its place, first, whether pending or published. + return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)]; } // CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator. get histopatologiaPendiente() { diff --git a/src/app/features/indicadores/indicadores.models.ts b/src/app/features/indicadores/indicadores.models.ts index f40a8d4..a683da0 100644 --- a/src/app/features/indicadores/indicadores.models.ts +++ b/src/app/features/indicadores/indicadores.models.ts @@ -17,7 +17,7 @@ export interface Indicador { tipos_periodo: TipoPeriodo[]; filtros?: IndicadorFiltro[]; } -export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado'; +export type DimensionEstrato = 'grupo_edad' | 'estatus_seguimiento' | 'citologia_alto_grado' | 'birads'; export interface IndicadorFiltro { estrato: string; etiqueta: string; valores: { valor: string; etiqueta: string }[]; } export interface DatosScope { estrato?: DimensionEstrato; filtros?: readonly string[]; } export interface EstratoTotal { periodo: string; grupo: string; estrato: string; n: number | null; suprimido: 0 | 1; } diff --git a/src/app/features/indicadores/indicadores.service.ts b/src/app/features/indicadores/indicadores.service.ts index 025e81a..260a74e 100644 --- a/src/app/features/indicadores/indicadores.service.ts +++ b/src/app/features/indicadores/indicadores.service.ts @@ -66,7 +66,7 @@ export class IndicadoresService { } let params = new HttpParams(); if (scope.estrato) { - if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); + if (!['grupo_edad', 'estatus_seguimiento', 'citologia_alto_grado', 'birads'].includes(scope.estrato)) throw new Error('Dimensión no admitida'); params = params.set('estrato', scope.estrato); } if (scope.filtros?.length) params = params.set('filtro', scope.filtros.join(',')); From 7dc420773f1755b6e2db4a2b3ed56e3ea1fb9abe Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 11:13:02 -0600 Subject: [PATCH 18/38] feat(indicadores): CaMa detection and result-to-diagnosis indicators wired with real payloads CAM-01 and CAM-02 already had their KPI cards and history panels waiting for the catalog; they are now covered with the answers WebApi gives for the synthetic base, both visible (lowered suppression threshold) and suppressed (normal threshold). Once published they draw only their KPI card in the summary, as the mockup does, instead of an extra generic figure card; their evolution stays in the history. The stacked history figure now keeps a category the catalog announces even when no row carries it, so a missing category is named under the figure instead of silently disappearing. The integration specs also cover the summary and the history with CAM-01, CAM-02 and CAM-03 published. --- .../cama_dias_resultado_suprimido.json | 63 +++++ .../fixtures/cama_dias_resultado_visible.json | 63 +++++ .../cama_tasa_deteccion_suprimido.json | 59 +++++ .../fixtures/cama_tasa_deteccion_visible.json | 59 +++++ .../indicadores/indicadores-cama-f4c.spec.ts | 223 ++++++++++++++++++ .../indicadores-historico-figures.ts | 4 +- .../features/indicadores/indicadores-kpi.ts | 4 +- 7 files changed, 473 insertions(+), 2 deletions(-) create mode 100644 src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json create mode 100644 src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json create mode 100644 src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json create mode 100644 src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json create mode 100644 src/app/features/indicadores/indicadores-cama-f4c.spec.ts diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json new file mode 100644 index 0000000..2c30a24 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json @@ -0,0 +1,63 @@ +{ + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Días de resultado a diagnóstico" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Datos sintéticos fijos; sin nota hasta el corte no hay observación. Convención provisional." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 71, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:26.219496+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "5e4badce17afe0141e8296c9edd88ff1ce50a21c8c278d1aad5327069830d251", + "parametros": { + "sql": { + "_catalogo": [], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "n": null, + "mediana": null, + "q1": null, + "q3": null, + "n_sin_evento": 0, + "n_excluido": 0, + "suprimido": 1, + "unidad": "dias" + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json new file mode 100644 index 0000000..0f2eb14 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json @@ -0,0 +1,63 @@ +{ + "id": "cama_dias_resultado_diagnostico", + "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "version": "0.1.0", + "contrato": "C3r", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "TOTAL": "Días de resultado a diagnóstico" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Datos sintéticos fijos; sin nota hasta el corte no hay observación. Convención provisional." + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 71, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:38.264922+00:00", + "kit_version": "0.8.0", + "toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7", + "parametros_sha": "f26ecdc2fcef0aa015f8997b7c1aa2053678cb86ca9cff9b1524efaf000971ad", + "parametros": { + "sql": { + "_catalogo": [], + "_grupos": [ + "TOTAL" + ], + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 1 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "TOTAL", + "estrato": null, + "n": 4, + "mediana": 6.5, + "q1": 2.25, + "q3": 12.5, + "n_sin_evento": 0, + "n_excluido": 1, + "suprimido": 0, + "unidad": "dias" + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json new file mode 100644 index 0000000..ab86600 --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json @@ -0,0 +1,59 @@ +{ + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica (demostración sintética)", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "total": "Total" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Detección histopatológica (demostración sintética)" + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 127, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:31.282549+00:00", + "kit_version": "0.8.0", + "toml_sha": "9349fdd093c85bfe9adc86b91ea5350a03be829825645b51ab87a35fccc5d42d", + "parametros_sha": "d909bc4a153b244533acde1f26ce8c4cfaaedf0d277239dd9b1ce9e9f65b23a9", + "parametros": { + "sql": { + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 5 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "total", + "estrato": null, + "numerador": null, + "denominador": null, + "valor": null, + "ic_bajo": null, + "ic_alto": null, + "suprimido": 1, + "n_sin_evento": 0, + "n_excluido": 0 + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json new file mode 100644 index 0000000..4950dac --- /dev/null +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json @@ -0,0 +1,59 @@ +{ + "id": "cama_tasa_deteccion_histopatologica", + "titulo": "Detección histopatológica (demostración sintética)", + "version": "0.1.0", + "contrato": "C1", + "unidad": "examen", + "tipo_periodo": "semestre", + "periodos": [ + "2025-S1" + ], + "estrato": null, + "valores_estrato": [], + "etiquetas_estrato": {}, + "grupos": { + "total": "Total" + }, + "categorias": {}, + "grupos_de_categoria": {}, + "notas": [ + "Detección histopatológica (demostración sintética)" + ], + "reportes": [ + { + "periodo": "2025-S1", + "report_id": 127, + "periodo_inicio": "2025-01-01", + "periodo_fin": "2025-07-01", + "fecha_corte": "2026-11-12", + "generado_en": "2026-11-12T17:00:42.857591+00:00", + "kit_version": "0.8.0", + "toml_sha": "38b2efac7d70f9c0bf37b03b7abd21d48bff4c6d8f6786fccbccfa31a7fcd7e7", + "parametros_sha": "7202a2779ae47c29a7659dd6fdfb77e8895d4d778a772ff13cc2ce93c5a6e871", + "parametros": { + "sql": { + "fecha_corte": "2026-11-12", + "periodo_fin": "2025-07-01", + "periodo_inicio": "2025-01-01" + }, + "umbral_supresion": 1 + } + } + ], + "filas": [ + { + "periodo": "2025-S1", + "grupo": "total", + "estrato": null, + "numerador": 0, + "denominador": 1, + "valor": 0.0, + "ic_bajo": 0.0, + "ic_alto": 79.3450688208, + "suprimido": 0, + "n_sin_evento": 1, + "n_excluido": 0 + } + ], + "totales_estrato": [] +} \ No newline at end of file diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts new file mode 100644 index 0000000..fe9beab --- /dev/null +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -0,0 +1,223 @@ +// Covers the three CaMa indicators WebApi now publishes (CAM-01 tasa de detección, CAM-02 resultado a diagnóstico, +// CAM-03 histopatología por BI-RADS) as they reach the summary and the history. The payloads are what WebApi +// answered for an isolated synthetic base (fixtures/cama_*): `visible` with the suppression threshold lowered so +// the figures show, and `suprimido` with the normal threshold of 5, where the small synthetic counts are hidden. +import { Component } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { MatDialog } from '@angular/material/dialog'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json'; +import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json'; +import diasVisible from './fixtures/cama_dias_resultado_visible.json'; +import diasSuprimido from './fixtures/cama_dias_resultado_suprimido.json'; +import generalFixture from './fixtures/cama_histopatologia_birads_general.json'; +import catalogoFixture from './fixtures/cama_catalogo_f4c.json'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresHistorico } from './indicadores-historico'; +import { historicoFigura } from './indicadores-historico-figures'; +import { CAMA_FUERA_DEL_RESUMEN, CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, KPI_BY_DOMAIN, KpiDefinition, kpiResult } from './indicadores-kpi'; +import { GlobalApplied, IndicadoresMemory } from './indicadores-memory'; +import { Indicador, IndicadorDatos } from './indicadores.models'; + +const applied: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S1'] }, revision: 0 }; +const dato = (v: unknown) => structuredClone(v) as unknown as IndicadorDatos; +const REALES = catalogoFixture as unknown as Indicador[]; + +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.' }); + }); + 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); + expect(r.state).toBe('Dato oculto por tamaño'); expect(r.value).toBeUndefined(); + }); + it('CAM-02 con el umbral de prueba: mediana, Q1 y Q3 tal como las publica el C3r, sin recalcular', () => { + expect(kpiResult(dato(diasVisible), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied)) + .toEqual({ state: 'Disponible', value: 6.5, info: '4 mastografías; Q1 a Q3: 2.25 a 12.5 días.' }); + }); + it('CAM-02 con el umbral normal: suprimido, sin mediana ni cero', () => { + const r = kpiResult(dato(diasSuprimido), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied); + expect(r.state).toBe('Dato oculto por tamaño'); expect(r.value).toBeUndefined(); + }); + it('CAM-01 y CAM-02 sin valores (nulos, no suprimidos) no se vuelven cero', () => { + const c1 = dato(tasaVisible); Object.assign((c1.filas[0]), { valor: null, numerador: null, denominador: null }); + const c3 = dato(diasVisible); Object.assign((c3.filas[0]), { n: null, mediana: null, q1: null, q3: null }); + expect(kpiResult(c1, CAMA_TASA_DETECCION_KPI, 'cama', applied)).toMatchObject({ state: 'Sin valor disponible' }); + expect(kpiResult(c3, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied)).toMatchObject({ state: 'Sin valor disponible' }); + const sinFilas = { ...dato(tasaVisible), periodos: [], filas: [] }; + expect(kpiResult(sinFilas, CAMA_TASA_DETECCION_KPI, 'cama', applied).state).toBe('Sin filas utilizables'); + }); + it('la respuesta de una medida no pasa por la tarjeta de otra, ni de otro periodo', () => { + expect(kpiResult(dato(tasaVisible), CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', applied).state).toBe('Error de contrato'); + expect(kpiResult(dato(diasVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied).state).toBe('Error de contrato'); + expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', { ...applied, tipo: 'mes' }).state).toBe('Error de contrato'); + }); +}); + +describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () => { + it('CAM-01: la línea y su banda de confianza dibujan el cero válido y el cero no se confunde con «sin dato»', () => { + const f = historicoFigura(dato(tasaVisible), 'claro'); + expect(f.contrato).toBe('C1'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]); + const linea = f.figure.data.find(t => t['name'] === 'Porcentaje')!; + expect(linea['y']).toEqual([0]); expect(linea['x']).toEqual(['2025 S1']); + expect(f.figure.data.find(t => t['name'] === 'Intervalo de confianza')!['y']).toEqual([79.3450688208, 0]); + }); + it('CAM-01 y CAM-02 suprimidos: el periodo se sombrea, se nombra y la línea queda sin valor', () => { + for (const d of [tasaSuprimida, diasSuprimido]) { + const f = historicoFigura(dato(d), 'claro'); + expect(f.suprimidos).toEqual(['2025 S1']); expect(f.sinDato).toEqual([]); + expect(f.figure.data.find(t => t['name'] === 'Porcentaje' || t['name'] === 'Mediana')!['y']).toEqual([null]); + expect(f.figure.layout['shapes']).toHaveLength(1); + } + }); + it('CAM-02: la mediana y la banda de cuartiles salen de lo publicado', () => { + const f = historicoFigura(dato(diasVisible), 'claro'); + expect(f.figure.data.find(t => t['name'] === 'Mediana')!['y']).toEqual([6.5]); + expect(f.figure.data.find(t => t['name'] === 'Primer a tercer cuartil')!['y']).toEqual([12.5, 2.25]); + }); + it('CAM-03: el C2 general se apila en las seis categorías del catálogo, con sus colores y en su orden', () => { + const f = historicoFigura(dato(generalFixture), 'claro'); + expect(f.contrato).toBe('C2'); expect(f.suprimidos).toEqual([]); expect(f.sinDato).toEqual([]); + expect(f.figure.data.map(t => [t['name'], (t['y'] as number[])[0]])).toEqual([ + ['Benigno', 7], ['Lesión de riesgo (B3)', 5], ['Carcinoma in situ', 6], ['Carcinoma invasor', 7], ['Sin biopsia reportada', 6], ['Sin dato', 6]]); + expect(f.figure.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', '#D9822B', '#B5482E', '#C9CDD2', '#C9CDD2']); + expect(f.figure.layout['barmode']).toBe('stack'); + expect(f.comoLeer).toContain('pacientes'); + }); + it('CAM-03: una celda suprimida o ausente en el periodo se avisa, y no se dibuja como cero', () => { + const suprimida = dato(generalFixture); Object.assign(suprimida.filas[2], { n: null, suprimido: 1 }); + expect(historicoFigura(suprimida, 'claro').suprimidos).toEqual(['2025 S1']); + const ausente = dato(generalFixture); ausente.filas.splice(3, 1); + const f = historicoFigura(ausente, 'claro'); + expect(f.sinDato).toEqual(['2025 S1']); + expect(f.figure.data.find(t => t['name'] === 'Carcinoma invasor')!['y']).toEqual([null]); + }); +}); + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { figure?: { data: { name?: string }[] }; label?: string; } + +describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => { + let fixture: ReturnType>, http: HttpTestingController; + function montar(visibles: boolean) { + TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: vi.fn() } }] }); + TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES); + fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true); + fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges(); + const respuestas: Record = visibles + ? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture } + : { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture }; + const pedidos: string[] = []; + for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) { + for (const r of ola) { + const id = r.request.url.split('/').at(-2)!; + pedidos.push(r.request.url + (r.request.params.get('periodos') ? '?periodos=' + r.request.params.get('periodos') : '')); + if (r.request.url.endsWith('/periodos')) r.flush({ id, periodos: [{ periodo: '2025-S1', tipo: 'semestre' }] }); + else r.flush(respuestas[id] as Record); + } + fixture.detectChanges(); + } + return pedidos; + } + afterEach(() => { fixture?.destroy(); http.verify(); }); + const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[]; + const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub); + + it('los tres indicadores publicados se piden y se dibujan; los cinco restantes de la lista siguen pendientes', () => { + const pedidos = montar(true); + expect(pedidos.filter(p => p.includes('/datos'))).toEqual([ + '/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1', + '/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1', + '/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b))); + const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']); + expect(titulos.filter(([t]) => ['Resultado histopatológico por categoría BI-RADS', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!))) + .toEqual([['Resultado histopatológico por categoría BI-RADS', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado'], ['Tasa de detección histopatológica', 'dibujado']]); + expect(graficas()).toHaveLength(3); + expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2, 2]); + }); + it('con el umbral normal los dos paneles C1 y C3r avisan el periodo suprimido, y la matriz CAM-03 sigue visible', () => { + montar(false); + const texto = paneles().map(p => p.textContent!); + expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2); + expect(graficas()).toHaveLength(3); + }); +}); + +describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [provideRouter([]), provideHttpClient(), provideHttpClientTesting()] }); + TestBed.inject(IndicadoresMemory).finishInitialKpiPresentation('cama'); + fixture = TestBed.createComponent(IndicadoresPage); http = TestBed.inject(HttpTestingController); + http.expectOne('/tea/indicadores').flush([]); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); vi.unstubAllGlobals(); }); + const propios = (d: KpiDefinition): Indicador => ({ id: d.id, titulo: d.title, contrato: d.contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as Indicador; + const row = { periodo: '2025-S1', estrato: null, suprimido: 0 }; + function cargar(catalogo: Indicador[]) { + fixture.componentInstance.changeDominio('cama'); fixture.detectChanges(); + http.expectOne('/cama/indicadores').flush(catalogo); + for (let ola = http.match(r => r.url.endsWith('/periodos')); ola.length; ola = http.match(r => r.url.endsWith('/periodos'))) { + ola.forEach(r => r.flush({ id: r.request.url.split('/').at(-2), periodos: [{ tipo: 'semestre', periodo: '2025-S1' }] })); + } + fixture.detectChanges(); + const pedidos: string[] = []; + for (let ola = http.match(r => r.url.endsWith('/datos')); ola.length; ola = http.match(r => r.url.endsWith('/datos'))) { + ola.forEach(r => { + const id = r.request.url.split('/').at(-2)!; + pedidos.push(id); + r.flush(id === 'cama_tasa_deteccion_histopatologica' ? tasaVisible : id === 'cama_dias_resultado_diagnostico' ? diasVisible + : id === 'cama_birads_456_paciente' ? { id, contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: { A: {} }, filas: [{ ...row, grupo: 'TOTAL', categoria: 'A', n: 5 }] } + : { id, contrato: 'C3r', tipo_periodo: 'semestre', periodos: ['2025-S1'], categorias: {}, filas: [{ ...row, grupo: 'TOTAL', unidad: 'dias', mediana: 7, n: 5, q1: 3, q3: 9 }] }); + }); + fixture.detectChanges(); + } + return pedidos; + } + const root = () => fixture.nativeElement as HTMLElement; + const kpis = () => [...root().querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[]; + const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[]; + const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES]; + + it('las cuatro tarjetas de oportunidad tienen datos, ninguna pendiente, con los valores publicados', () => { + cargar(completo()); + expect(kpis()).toHaveLength(4); + expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente'); + expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.'); + expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.'); + }); + it('CAM-03 ocupa el lugar de la tarjeta pendiente, primero y con su vista especializada; no se consulta mientras no es visible', () => { + const pedidos = cargar(completo()); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); + const primera = tarjetas()[0]; + expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD'); + expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); + expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS (demostración sintética)'); + expect(pedidos).not.toContain('cama_histopatologia_birads'); + }); + it('CAM-01 y CAM-02 son solo tarjetas de oportunidad: no dibujan una figura propia en el Resumen', () => { + cargar(completo()); + const titulos = tarjetas().map(t => t.querySelector('h2')?.textContent ?? ''); + expect(titulos.some(t => t.includes('Detección histopatológica') || t.includes('resultado a diagnóstico'))).toBe(false); + expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica'); + expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico'); + }); + it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => { + cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); + expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull(); + expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull(); + }); + it('solo CAM-01 y CAM-02 sin CAM-03: dos tarjetas con datos y la de histopatología pendiente', () => { + cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); + expect(kpis()).toHaveLength(4); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-historico-figures.ts b/src/app/features/indicadores/indicadores-historico-figures.ts index 84d9705..1ee9fab 100644 --- a/src/app/features/indicadores/indicadores-historico-figures.ts +++ b/src/app/features/indicadores/indicadores-historico-figures.ts @@ -119,7 +119,9 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo { celdas.set(key, row); categorias.set(id, row['orden']); } - const orden = [...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id); + // A category the catalog announces but no row carries is still a category: its absence is shown as a gap and + // named under the figure, not dropped as if it did not exist, nor drawn as zero. + const orden = [...[...categorias].sort(([, a], [, b]) => a - b).map(([id]) => id), ...Object.keys(catalogo).filter(id => !categorias.has(id))]; const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo]))); const suprimidos = periodos.filter(p => estadoDe(p).some(row => row?.['suprimido'] === 1)); const sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n']))); diff --git a/src/app/features/indicadores/indicadores-kpi.ts b/src/app/features/indicadores/indicadores-kpi.ts index 7e95a06..50ba801 100644 --- a/src/app/features/indicadores/indicadores-kpi.ts +++ b/src/app/features/indicadores/indicadores-kpi.ts @@ -69,7 +69,9 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[] // Published CaMa indicators whose card the summary does not draw. // The summary draws the paired card and the histopathology card; the rest of CaMa's indicators are in Histórico // and in Datos y definiciones, which still list the whole catalog. -export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a']; +// The two published opportunity indicators draw their KPI card only; their evolution is in Histórico. +export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_confirmacion_birads45', 'cama_dias_toma_diagnostico', 'cama_eu38a', + 'cama_tasa_deteccion_histopatologica', 'cama_dias_resultado_diagnostico']; export const ID_HISTOPATOLOGIA_CAMA = 'cama_histopatologia_birads'; // C1 rows of CaCu/CaMa carry the linkId `total`; TEA's ficha names its single group `TOTAL`. const C1_GROUP: Record = { tea: 'TOTAL', cacu: 'total', cama: 'total' }; From 78313adb4a663c0deb2fad3fdb1238190431b2b8 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 11:24:30 -0600 Subject: [PATCH 19/38] style(indicadores): CaMa histopathology rates stay readable at phone width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rates figure lets the category labels size their own margin, shortens the axis title, keeps few ticks and wraps «BI-RADS 4 sin subtipo» when the window is 600 px wide or less, and is redrawn when the window crosses that width. Values and states are unchanged. The reading text keeps the capitals of a category code inside a sentence («lesión de riesgo (B3)»). --- .../indicador-histopatologia-cama.ts | 8 ++++++-- .../indicadores-histopatologia-cama.spec.ts | 14 ++++++++++++-- .../indicadores-histopatologia-cama.ts | 18 ++++++++++++------ 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.ts b/src/app/features/indicadores/indicador-histopatologia-cama.ts index c78083d..a2b3760 100644 --- a/src/app/features/indicadores/indicador-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicador-histopatologia-cama.ts @@ -49,6 +49,10 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { private key = ''; private loaded = false; private pages: ModeloHistopatologia[] = []; + // The rates figure has a phone-width variant; it is redrawn when the window crosses that width. + private readonly estrecho = typeof matchMedia === 'function' ? matchMedia('(max-width: 600px)') : undefined; + private readonly alCambiarAncho = () => this.draw(); + constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); } get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } get selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; } @@ -138,8 +142,8 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { private draw() { if (!this.model || !this.selection) return; this.donutFigure = donaHistopatologia(this.model, this.selection, this.tema); - this.ratesFigure = figuraTasas(this.model, this.selection, this.tema); + this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches); this.changeDetector.markForCheck(); } - ngOnDestroy() { this.subscription?.unsubscribe(); } + ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); } } diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts index 48a7535..822c2a6 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -149,7 +149,7 @@ describe('Histopatología por BI-RADS: tasas, selección y figuras', () => { const b3 = clicHistopatologia(m, noMaligno, 'categorias', 1); expect(b3).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); expect(tasas(m, b3).map(t => t.k)).toEqual([0, 1, 1, 1, 1, 1]); - expect(lectura(m, b3)).toBe('Proporción con resultado lesión de riesgo (b3)'); + expect(lectura(m, b3)).toBe('Proporción con resultado lesión de riesgo (B3)'); expect(clicHistopatologia(m, b3, 'categorias', 1)).toEqual({ grupo: 'NO_MALIGNO' }); expect(clicHistopatologia(m, b3, 'categorias', 3)).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); expect(clicHistopatologia(m, b3, 'centro', 0)).toEqual(sel); @@ -181,6 +181,16 @@ describe('Histopatología por BI-RADS: tasas, selección y figuras', () => { expect(range).toEqual(rangoTasas(tasas(m, sel))); expect(range[0] % 5).toBe(0); expect(range[1] % 5).toBe(0); expect(figuraTasas(m, sel, 'oscuro').layout['paper_bgcolor']).toBe('#081839'); + expect((f.layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje con resultado maligno'); + expect((figuraTasas(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro').layout['xaxis'] as { title: { text: string } }).title.text).toBe('Porcentaje con resultado lesión de riesgo (B3)'); + }); + it('en un ancho de teléfono las etiquetas se parten, el eje conserva pocas marcas y el título corto; los valores no cambian', () => { + const m = base(), sel = seleccionBase(m), ancho = figuraTasas(m, sel, 'claro'), estrecho = figuraTasas(m, sel, 'claro', true); + expect(estrecho.data[0]['x']).toEqual(ancho.data[0]['x']); + const y = estrecho.layout['yaxis'] as { ticktext: string[]; tickvals: string[] }; + expect(y.tickvals).toEqual(m.filas.map(r => r.etiqueta)); expect(y.ticktext[0]).toBe('BI-RADS 4
sin subtipo'); + expect((estrecho.layout['xaxis'] as { title: { text: string }; nticks: number })).toMatchObject({ title: { text: 'Porcentaje' }, nticks: 3 }); + expect((ancho.layout['yaxis'] as Record)['ticktext']).toBeUndefined(); }); it('dona de dos anillos: grupos dentro, categorías fuera; la selección atenúa sin cambiar valores y el centro dice «k de N con resultado»', () => { const m = base(), d = donaHistopatologia(m, seleccionBase(m), 'claro'); @@ -250,7 +260,7 @@ describe('Histopatología por BI-RADS: componente', () => { const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }); expect(b3.getAttribute('aria-pressed')).toBe('true'); expect(volver().disabled).toBe(false); - expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (b3)'); + expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (B3)'); b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); boton('Carcinoma invasor').click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts index f52fb11..b2e0339 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -59,6 +59,8 @@ const fail = (message: string): never => { throw new HistopatologiaIncompatible( const escapar = (v: string) => v.replace(/&/g, '&').replace(//g, '>'); const miles = (v: number) => v.toLocaleString('es-MX'); const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL'; +// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals. +const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1); const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined; // 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available. @@ -179,7 +181,7 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string { if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia'; if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia'; - return 'Proporción con resultado ' + seleccionEtiqueta(m, sel).toLowerCase(); + return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel)); } /** Per BI-RADS stratum: the selected categories over the patients with a biopsy result. No biopsy and no data never enter. */ export function tasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): Tasa[] { @@ -203,7 +205,8 @@ export function rangoTasas(valores: Tasa[]): [number, number] { } /** Rates on the left: one point and horizontal Wilson interval per BI-RADS stratum, one trace always. */ -export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure { +// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits. +export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure { const p = c2Theme(tema); const valores = tasas(m, sel); const color = sel.categoria ? m.categorias.find(c => c.id === sel.categoria)!.color : m.grupos.find(g => g.id === sel.grupo)!.color; @@ -217,11 +220,14 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi hovertemplate: '%{y}
%{customdata[0]} (%{customdata[1]}/%{customdata[2]})
IC 95 %: %{customdata[3]}–%{customdata[4]} %', }], layout: { autosize: true, height: 360, showlegend: false, paper_bgcolor: p.background, plot_bgcolor: p.background, font: { color: p.text }, - margin: { l: 150, r: 96, t: 16, b: 64 }, - yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true }, - xaxis: { range: rangoTasas(valores), ticksuffix: ' %', gridcolor: p.grid, zeroline: false, fixedrange: true, title: { text: lectura(m, sel) } }, + // The labels of the categories size their own margin, so the plot keeps its width on a narrow screen. + margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 }, + yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true, + ...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '
sin subtipo')) } : {}) }, + xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true, + title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } }, annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left', - font: { size: 12, color: p.text }, + font: { size: estrecho ? 11 : 12, color: p.text }, text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), }, config: { displayModeBar: false } }; } From 7a6f87d1413dcbde7e66cd935f8ec219ee033959 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 12 Nov 2026 11:57:47 -0600 Subject: [PATCH 20/38] Remove demonstration notices from CaMa views --- .../features/indicadores/fixtures/cama_catalogo_f4c.json | 6 +++--- .../indicadores/fixtures/cama_dias_resultado_suprimido.json | 4 ++-- .../indicadores/fixtures/cama_dias_resultado_visible.json | 4 ++-- .../fixtures/cama_histopatologia_birads_estrato.json | 4 ++-- .../fixtures/cama_histopatologia_birads_general.json | 4 ++-- .../indicadores/fixtures/cama_tasa_deteccion_suprimido.json | 4 ++-- .../indicadores/fixtures/cama_tasa_deteccion_visible.json | 4 ++-- src/app/features/indicadores/indicadores-cama-f4c.spec.ts | 2 +- .../indicadores/indicadores-histopatologia-cama.spec.ts | 2 +- .../indicadores/indicadores-seguimiento-tabla.spec.ts | 6 ++++-- .../features/indicadores/indicadores-seguimiento-tabla.ts | 4 ---- src/app/features/indicadores/seguimiento-tabla.service.ts | 2 +- 12 files changed, 22 insertions(+), 24 deletions(-) diff --git a/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json index 72d19a0..af53edb 100644 --- a/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json +++ b/src/app/features/indicadores/fixtures/cama_catalogo_f4c.json @@ -1,7 +1,7 @@ [ { "id": "cama_dias_resultado_diagnostico", - "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "titulo": "Tiempo de resultado a diagnóstico", "version": "0.1.0", "contrato": "C3r", "unidad": "examen", @@ -18,7 +18,7 @@ }, { "id": "cama_histopatologia_birads", - "titulo": "Histopatología por BI-RADS (demostración sintética)", + "titulo": "Histopatología por BI-RADS", "version": "0.1.0", "contrato": "C2", "unidad": "paciente", @@ -38,7 +38,7 @@ }, { "id": "cama_tasa_deteccion_histopatologica", - "titulo": "Detección histopatológica (demostración sintética)", + "titulo": "Detección histopatológica", "version": "0.1.0", "contrato": "C1", "unidad": "examen", diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json index 2c30a24..18a0c34 100644 --- a/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_suprimido.json @@ -1,6 +1,6 @@ { "id": "cama_dias_resultado_diagnostico", - "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "titulo": "Tiempo de resultado a diagnóstico", "version": "0.1.0", "contrato": "C3r", "unidad": "examen", @@ -17,7 +17,7 @@ "categorias": {}, "grupos_de_categoria": {}, "notas": [ - "Datos sintéticos fijos; sin nota hasta el corte no hay observación. Convención provisional." + "Sin nota hasta el corte no hay observación. Convención provisional." ], "reportes": [ { diff --git a/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json index 0f2eb14..313c6ae 100644 --- a/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json +++ b/src/app/features/indicadores/fixtures/cama_dias_resultado_visible.json @@ -1,6 +1,6 @@ { "id": "cama_dias_resultado_diagnostico", - "titulo": "Tiempo de resultado a diagnóstico (demostración sintética)", + "titulo": "Tiempo de resultado a diagnóstico", "version": "0.1.0", "contrato": "C3r", "unidad": "examen", @@ -17,7 +17,7 @@ "categorias": {}, "grupos_de_categoria": {}, "notas": [ - "Datos sintéticos fijos; sin nota hasta el corte no hay observación. Convención provisional." + "Sin nota hasta el corte no hay observación. Convención provisional." ], "reportes": [ { diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json index ef5a9eb..7a93d49 100644 --- a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_estrato.json @@ -1,6 +1,6 @@ { "id": "cama_histopatologia_birads", - "titulo": "Histopatología por BI-RADS (demostración sintética)", + "titulo": "Histopatología por BI-RADS", "version": "0.1.0", "contrato": "C2", "unidad": "paciente", @@ -72,7 +72,7 @@ "SIN_DATO": "Sin dato" }, "notas": [ - "Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + "Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." ], "reportes": [ { diff --git a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json index 8b409f0..dac22f7 100644 --- a/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json +++ b/src/app/features/indicadores/fixtures/cama_histopatologia_birads_general.json @@ -1,6 +1,6 @@ { "id": "cama_histopatologia_birads", - "titulo": "Histopatología por BI-RADS (demostración sintética)", + "titulo": "Histopatología por BI-RADS", "version": "0.1.0", "contrato": "C2", "unidad": "paciente", @@ -58,7 +58,7 @@ "SIN_DATO": "Sin dato" }, "notas": [ - "Convención provisional para datos sintéticos; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." + "Convención provisional; BI-RADS 4 sin subtipo es una fila propia. Sin biopsia y sin dato quedan fuera del denominador con resultado." ], "reportes": [ { diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json index ab86600..7deccf8 100644 --- a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_suprimido.json @@ -1,6 +1,6 @@ { "id": "cama_tasa_deteccion_histopatologica", - "titulo": "Detección histopatológica (demostración sintética)", + "titulo": "Detección histopatológica", "version": "0.1.0", "contrato": "C1", "unidad": "examen", @@ -17,7 +17,7 @@ "categorias": {}, "grupos_de_categoria": {}, "notas": [ - "Detección histopatológica (demostración sintética)" + "Detección histopatológica" ], "reportes": [ { diff --git a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json index 4950dac..3fbe1b3 100644 --- a/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json +++ b/src/app/features/indicadores/fixtures/cama_tasa_deteccion_visible.json @@ -1,6 +1,6 @@ { "id": "cama_tasa_deteccion_histopatologica", - "titulo": "Detección histopatológica (demostración sintética)", + "titulo": "Detección histopatológica", "version": "0.1.0", "contrato": "C1", "unidad": "examen", @@ -17,7 +17,7 @@ "categorias": {}, "grupos_de_categoria": {}, "notas": [ - "Detección histopatológica (demostración sintética)" + "Detección histopatológica" ], "reportes": [ { diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts index fe9beab..83ea809 100644 --- a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -201,7 +201,7 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { const primera = tarjetas()[0]; expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD'); expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); - expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS (demostración sintética)'); + expect(primera.querySelector('h2')!.textContent).toBe('Histopatología por BI-RADS'); expect(pedidos).not.toContain('cama_histopatologia_birads'); }); it('CAM-01 y CAM-02 son solo tarjetas de oportunidad: no dibujan una figura propia en el Resumen', () => { diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts index 822c2a6..c767e64 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -250,7 +250,7 @@ describe('Histopatología por BI-RADS: componente', () => { ['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'], ['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]); - expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional para datos sintéticos'); + expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;'); }); it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => { f.detectChanges(); flush(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts index 91da255..bf98e3b 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.spec.ts @@ -60,9 +60,11 @@ describe('Seguimiento de CaMa (tabla)', () => { expect(filas()).toHaveLength(27); expect(root().textContent).toContain('Ventana consultada: 2026-07-21 al 2026-10-20.'); }); - it('«Datos de demostración» se muestra cuando la respuesta es simulada', async () => { + it('accepts the simulated contract without a visible demonstration notice', async () => { await cargado(); - expect(root().querySelector('.simulation')?.textContent).toBe('Datos de demostración'); + expect(fixture.componentInstance.data()?.simulado).toBe(true); + expect(root().querySelector('.simulation')).toBeNull(); + expect(root().textContent).not.toContain('Datos de demostración'); }); it('los detalles salen bajo su valor con su etiqueta y un valor nulo se lee «No disponible», sin línea de detalle', async () => { await cargado(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 5afbbb3..729f20c 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -21,9 +21,6 @@ interface Borrador { corte?: string; meses: 1 | 3 | 6 | 12; page_size: number; f selector: 'app-seguimiento-tabla', imports: [FormsModule], template: ` - @if (data(); as respuesta) { - @if (respuesta.simulado) {

Datos de demostración

} - }
@for (filtro of filtros(); track filtro.clave) { + +
+ @switch (carga().estado) { + @case ('cargando') { } + @case ('pendiente') {

Funcionalidad pendiente de publicación.

} + @case ('no-disponible') { +

La cohorte no está disponible en este momento.

+ + } + @case ('error') { +

{{ $any(carga()).mensaje }}

+ } + } + @if (datos(); as d) { +

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

+

{{ aviso() }}

+ +

Haga clic en una barra publicada para ver sus pacientes en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.

+
+ + + + + @for (g of d.grupos; track g.codigo) { + + + + + + } + +
Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}
CategoríaPacientesSeguimiento
{{ etiqueta(g.codigo) }}{{ g.suprimido ? 'No publicado' : miles(g.n!) }}@if (g.suprimido) { {{ motivo }} } + @else { }
+
+ } +
+ `, + styles: ` + :host { display: block; min-width: 0; } + .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } + h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } + p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } + .nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } + .controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-4); } + label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; } + input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; } + input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } + /* The live region stays in the page, so what is written into it is announced; empty, it takes no room. */ + .aviso { padding: var(--issste-space-2) var(--issste-space-3); border-left: 4px solid var(--issste-accent); font: var(--mat-sys-body-medium); } + .aviso:empty { padding: 0; border: 0; margin: 0; } + app-plotly-chart { margin-top: var(--issste-space-3); } + .tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); } + .tabla-scroll:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + table { width: 100%; min-width: 28rem; border-collapse: collapse; font: var(--mat-sys-body-medium); } + caption { text-align: left; font: var(--mat-sys-title-small); padding-bottom: var(--issste-space-2); } + th, td { padding: var(--issste-space-2) var(--issste-space-3); border-bottom: 1px solid var(--issste-border); text-align: left; vertical-align: top; } + td:nth-child(2) { font-variant-numeric: tabular-nums; } + td:last-child { min-width: 11rem; } + .ver { min-height: 44px; padding: 0 .5rem; border: 0; background: none; color: inherit; text-decoration: underline; cursor: pointer; font: inherit; } + .ver:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; } + .visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } + @media (max-width: 600px) { .panel { padding: var(--issste-space-4); } .controles label, .controles input { width: 100%; } } + `, +}) +export class IndicadoresAnalisis { + readonly dominio = input.required(); + readonly tema = input.required(); + readonly active = input(false); + // The patients of a group, for the page to open them in Seguimiento. + readonly verPacientes = output(); + readonly miles = (v: number) => v.toLocaleString('es-MX'); + readonly etiqueta = etiquetaBirads; + readonly motivo = MOTIVO_GRUPO_SUPRIMIDO; + readonly hoy = hoyIso(); + private readonly service = inject(AnalisisService); + private readonly host = inject>(ElementRef); + private readonly pedidos = new Subject(); + private abierto = false; + private ultimo?: string; + private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number }; + corte = this.hoy; + readonly carga = signal>({ estado: 'cargando' }); + // Why the last click on a bar opened nothing. + readonly aviso = signal(''); + readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; }); + readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; }); + + constructor() { + const destroy = inject(DestroyRef); + const cargar = (corte: string): Observable> => { + let fuente: Observable; + try { fuente = this.service.agregado(this.dominio(), corte); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } + return fuente.pipe( + map((datos): Carga => ({ estado: 'listo', datos })), + catchError(error => of(this.fallo(error))), + startWith>({ estado: 'cargando' })); + }; + this.pedidos.pipe(switchMap(cargar), takeUntilDestroyed(destroy)).subscribe(c => { this.aviso.set(''); this.carga.set(c); }); + effect(() => { + if (!this.active() || this.abierto) return; + untracked(() => { this.abierto = true; this.consultar(); }); + }); + } + + private fallo(error: unknown): Carga { + if (error instanceof HttpErrorResponse) { + if (error.status === 404) return { estado: 'pendiente' }; + if (error.status === 503) return { estado: 'no-disponible' }; + if (error.status === 0) return { estado: 'error', mensaje: 'No se pudo conectar con el servicio. Revisa la conexión y vuelve a intentar.' }; + if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la fecha de corte. Revisa la fecha.' }; + if (error.status >= 500) return { estado: 'error', mensaje: 'El servicio encontró un error interno. Intenta nuevamente más tarde.' }; + } + return { estado: 'error', mensaje: 'La respuesta recibida no tiene el formato esperado. Intenta nuevamente.' }; + } + consultar() { + if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; } + this.ultimo = this.corte; + this.pedidos.next(this.corte); + } + reintentar() { this.pedidos.next(this.ultimo ?? this.corte); } + + // A click on a published bar is the same as its «Ver pacientes» button; a suppressed bar does nothing. + clicGrupo(evento: unknown) { + const codigo = grupoDelClic(evento, this.datos()); + if (!codigo) return; + const fila = Array.from(this.host.nativeElement.querySelectorAll('tr[data-grupo]')).find(tr => tr.getAttribute('data-grupo') === codigo); + this.verGrupo(codigo, fila?.querySelector('button.ver') ?? this.host.nativeElement.querySelector('.plot-viewport')); + } + // The patients of a published group: the page opens them in Seguimiento. Where the user was is kept for the way back. + verGrupo(codigo: string, origen?: EventTarget | null) { + const d = this.datos(); + if (!d) return; + this.aviso.set(motivoSinLista(d, codigo) ?? ''); + const seleccion = seleccionDeGrupo(d, codigo); + if (!seleccion) return; + const el = origen instanceof HTMLElement ? origen : null; + const area = contenedorDeScroll(this.host.nativeElement); + this.retorno = { origen: el, area, arriba: area.scrollTop }; + this.verPacientes.emit(seleccion); + } + /** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */ + restaurar() { + const r = this.retorno; + if (!r) return; + if (r.area.isConnected) r.area.scrollTop = r.arriba; + (r.origen?.isConnected ? r.origen : this.host.nativeElement.querySelector('input[name="corte"]'))?.focus({ preventScroll: true }); + this.retorno = undefined; + } +} diff --git a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts index afdfb84..2a8b833 100644 --- a/src/app/features/indicadores/indicadores-historico-pestana.spec.ts +++ b/src/app/features/indicadores/indicadores-historico-pestana.spec.ts @@ -28,9 +28,9 @@ describe('Pestaña Histórico', () => { http.match(() => true); } - it('CaMa: Resumen, Histórico, Seguimiento y Datos y definiciones, en ese orden', () => { + it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => { abrir('cama', [item('cama_eu38a', 'C3r')]); - expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']); + expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']); expect(root().querySelector('#panel-historico')).not.toBeNull(); }); it.each(['tea', 'cacu'] as const)('%s no tiene la pestaña Histórico', domain => { diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index 356d594..5ec6c7c 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -144,8 +144,15 @@
} + @if (conAnalisis) { +
+ +
+ } +
diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 5822ac7..f028564 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -28,11 +28,13 @@ import { httpMessage } from './indicadores-http'; import { IndicadoresInitialPeriod } from './indicadores-initial-period'; import { IndicadoresDefinitions } from './indicadores-definitions'; import { IndicadoresTracking } from './indicadores-tracking'; +import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; +import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis'; import { IndicadoresHistorico } from './indicadores-historico'; import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente'; import { IndicadorNavegacionItem, IndicadoresNavegacionPanel } from './indicadores-navegacion-panel'; -type DashboardSection = 'resumen' | 'historico' | 'seguimiento' | 'datos'; +type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; const SECCIONES: readonly { id: DashboardSection; label: string }[] = [ { id: 'resumen', label: 'Resumen' }, @@ -40,19 +42,36 @@ const SECCIONES: readonly { id: DashboardSection; label: string }[] = [ { id: 'datos', label: 'Datos y definiciones' }, ]; const SECCIONES_CON_HISTORICO: readonly { id: DashboardSection; label: string }[] = [SECCIONES[0], { id: 'historico', label: 'Histórico' }, SECCIONES[1], SECCIONES[2]]; +// The epidemiological analysis is CaMa's: between its history and its follow-up list. +const SECCIONES_CON_ANALISIS: readonly { id: DashboardSection; label: string }[] = [ + SECCIONES_CON_HISTORICO[0], SECCIONES_CON_HISTORICO[1], { id: 'analisis', label: 'Análisis epidemiológico' }, SECCIONES_CON_HISTORICO[2], SECCIONES_CON_HISTORICO[3]]; @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, OverlayModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresNavegacionPanel, IndicadoresHistorico, IndicadoresAnalisis], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) export class IndicadoresPage { - // The history tab is CaMa's; the other domains keep their three sections. - get sections(): readonly { id: DashboardSection; label: string }[] { return this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; } + // The history and the analysis tabs are CaMa's; the other domains keep their three sections. + get sections(): readonly { id: DashboardSection; label: string }[] { return this.conAnalisis ? SECCIONES_CON_ANALISIS : this.conHistorico ? SECCIONES_CON_HISTORICO : SECCIONES; } get conHistorico() { return this.dominio === 'cama'; } + get conAnalisis() { return this.dominio === 'cama'; } readonly activeSection = signal('resumen'); readonly fichaPacienteAbierta = signal(false); + private readonly analisis = viewChild(IndicadoresAnalisis); + // The patients of a curve or a heatmap cell, opened in Seguimiento; the id makes a repeated click apply again. + // It belongs to the domain it was made in and stays while the user moves between the tabs. + readonly seleccionSeguimiento = signal(undefined); + verPacientes(seleccion: SeleccionPacientes) { + this.seleccionSeguimiento.set({ ...seleccion, id: (this.seleccionSeguimiento()?.id ?? 0) + 1 }); + this.changeSection('seguimiento'); + } + // Back to the analysis: the part, the scroll and the focus where the user left them. + volverAlAnalisis() { + this.changeSection('analisis'); + afterNextRender(() => this.analisis()?.restaurar(), { injector: this.injector }); + } setFichaPacienteAbierta(open: boolean) { this.fichaPacienteAbierta.set(open); if (open) this.closeGraphicNavigation(false, false); @@ -538,6 +557,7 @@ export class IndicadoresPage { if (!isDominio(dominio) || dominio === this.dominio) return; this.closeGraphicNavigation(false, false); this.activeSection.set('resumen'); + this.seleccionSeguimiento.set(undefined); this.searchQuery.set(''); this.filtersEdited(); this.filters = undefined; diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts new file mode 100644 index 0000000..75edebb --- /dev/null +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -0,0 +1,148 @@ +// Covers the journey of breast cancer on the page: Análisis → «Ver pacientes» → Seguimiento on the group → record → +// «Volver al análisis», with the analysis as it was and the focus on the control that opened the list; the selection going +// with the domain; CaCu and TEA keeping their three sections; and the wording of every screen of the journey. +// Fixtures: indicadores-analisis.testing.ts (the aggregate) and fixtures/cama_seguimiento.json (the list). +import { Component, output } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { provideRouter } from '@angular/router'; +import { RouterTestingHarness } from '@angular/router/testing'; +import { routes } from '../../app.routes'; +import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import fixtureData from './fixtures/cama_seguimiento.json'; +import { IndicadoresPage } from './indicadores-page'; +import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis'; +import { IndicadorFigureCard } from './indicador-figure-card'; +import { agregadoJson, CONTEXTO } from './indicadores-analisis.testing'; +import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; +import { Indicador } from './indicadores.models'; + +@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' }) +class ChartStub { readonly plotClick = output(); } + +const catalogoCama: Indicador[] = [{ id: 'published', titulo: 'Nombre publicado', contrato: 'C2', figuras: ['fig_c2_barras'], tipos_periodo: ['mes'] }]; +const base = () => structuredClone(fixtureData) as unknown as Record; +// What the cohort's list answers to the group BI-RADS 5: the whole cohort, the cut-off asked for, the filter applied and the cohort quoted back. +const cohorte = (corte: string) => ({ ...base(), ...CONTEXTO, corte, ventana: { meses: 0, desde: '2025-01-01', hasta: corte }, + filtros: { ...base()['filtros'], birads: 'BIRADS_5' } }); +// Nothing a user can read or a screen reader announces refers to tests, simulation, a development environment or the mock. +const PROHIBIDO = /mock|demostraci|simulad|sint[eé]tic|ficticio|entorno|\bdev\b/i; +function legible(root: HTMLElement): string[] { + const textos = [root.textContent ?? '']; + root.querySelectorAll('[aria-label], [title], [alt]').forEach(el => ['aria-label', 'title', 'alt'].forEach(a => { const v = el.getAttribute(a); if (v) textos.push(v); })); + return textos; +} + +describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () => { + let http: HttpTestingController; + const corte = hoyIso(); + beforeEach(() => { + vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} }); + TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] }); + TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } }); + http = TestBed.inject(HttpTestingController); + }); + afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); }); + + async function entrar() { + const harness = await RouterTestingHarness.create(); + const page = await harness.navigateByUrl('/indicadores/cama', IndicadoresPage); + http.expectOne('/cama/indicadores').flush(catalogoCama); harness.detectChanges(); + const root = harness.routeNativeElement!; + const tab = (id: string) => root.querySelector('#tab-' + id)!; + const panel = (id: string) => root.querySelector('#panel-' + id)!; + const asentar = async () => { harness.detectChanges(); await harness.fixture.whenStable(); harness.detectChanges(); }; + return { harness, page, root, tab, panel, asentar }; + } + async function abrirAnalisis(e: Awaited>) { + e.tab('analisis').click(); e.harness.detectChanges(); + http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte).flush(agregadoJson({ corte })); await e.asentar(); + } + const lista = () => http.expectOne(q => q.url === '/cama/seguimiento'); + const parametros = (r: ReturnType) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); + + it('Ver pacientes abre la lista de ese grupo; la ficha y el regreso conservan la lista, el análisis y el foco', async () => { + // Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded. + const e = await entrar(); + await abrirAnalisis(e); + const origen = e.root.querySelector('#analisis-titulo ~ .tabla-scroll tr[data-grupo="BIRADS_5"] button.ver')!; + origen.focus(); origen.click(); e.harness.detectChanges(); + + // Seguimiento on the whole cohort of the group, at the analysis' cut-off, quoting its cohort and revision. + expect(e.page.activeSection()).toBe('seguimiento'); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte, ...CONTEXTO, birads: 'BIRADS_5' }); + r.flush(cohorte(corte)); await e.asentar(); + expect(e.panel('seguimiento').hidden).toBe(false); expect(e.panel('analisis').hidden).toBe(true); + expect(e.panel('seguimiento').textContent).toContain('Categoría BI-RADS: BI-RADS 5'); + expect(e.panel('seguimiento').textContent).toContain('Toda la cohorte'); + expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección; la lista muestra 27.'); + expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); + + // The record opens over the list and gives it back. + e.root.querySelector('.patient-link')!.click(); await e.asentar(); + expect(e.root.querySelector('#dashboard-title')?.textContent).toBe('Ficha del paciente'); + expect(e.root.querySelector('.section-tabs')).toBeNull(); + expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); + [...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar(); + expect(e.root.querySelector('.section-tabs')).not.toBeNull(); + expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5'); + + // Back to the analysis: same answer, no new request, the focus where the user left it. + [...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar(); + expect(e.page.activeSection()).toBe('analisis'); + expect(e.tab('analisis').getAttribute('aria-selected')).toBe('true'); + expect(e.panel('analisis').hidden).toBe(false); + http.expectNone(q => q.url.startsWith('/cama/analisis')); + expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6); + expect(document.activeElement).toBe(origen); + expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); + + // Seguimiento keeps the selection for the user who goes back to its tab. + e.tab('seguimiento').click(); await e.asentar(); + http.expectNone(q => q.url === '/cama/seguimiento'); + expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5'); + }); + it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => { + // Fails if a stale revision shows rows, or the way back to the analysis is lost with the error. + const e = await entrar(); + await abrirAnalisis(e); + e.root.querySelector('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges(); + lista().flush({ error: 'La cohorte cambió; actualiza el análisis' }, { status: 409, statusText: 'Conflict' }); await e.asentar(); + expect(e.panel('seguimiento').querySelector('[role="alert"]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis'); + expect(e.panel('seguimiento').querySelector('table')).toBeNull(); + expect(e.panel('seguimiento').querySelector('app-seguimiento-exportar')).toBeNull(); + [...e.panel('seguimiento').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Volver al análisis')!.click(); await e.asentar(); + expect(e.panel('analisis').querySelectorAll('tbody tr')).toHaveLength(6); + }); + it('al cambiar de dominio la selección se limpia; CaCu y TEA no tienen Análisis y conservan sus tres secciones', async () => { + // Fails if a selection survives into another domain, or the analysis tab leaks into CaCu or TEA. + const e = await entrar(); + await abrirAnalisis(e); + e.root.querySelector('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges(); + lista().flush(cohorte(corte)); await e.asentar(); + expect(e.page.seleccionSeguimiento()).toBeDefined(); + for (const dominio of ['cacu', 'tea'] as const) { + e.page.changeDominio(dominio); e.harness.detectChanges(); + http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar(); + expect(e.page.seleccionSeguimiento()).toBeUndefined(); + expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']); + expect(e.root.querySelector('#panel-analisis')).toBeNull(); + } + e.page.changeDominio('cama'); e.harness.detectChanges(); + http.expectOne('/cama/indicadores').flush(catalogoCama); await e.asentar(); + expect(e.page.seleccionSeguimiento()).toBeUndefined(); + expect(e.root.querySelector('.seleccion')).toBeNull(); + }); + it('la pestaña Análisis sin endpoint publicado dice que está pendiente, sin ocultarlo ni mostrarlo como error', async () => { + // Fails if the missing endpoint is hidden or shown as a broken page, or the wording leaks the environment. + const e = await entrar(); + e.tab('analisis').click(); e.harness.detectChanges(); + http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); await e.asentar(); + expect(e.panel('analisis').textContent).toContain('Funcionalidad pendiente de publicación'); + expect(e.panel('analisis').querySelector('[role="alert"]')).toBeNull(); + expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); + }); +}); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index c8be460..0a41c2e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -37,8 +37,8 @@ describe('Secciones compartidas por dominio', () => { http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges(); const root = harness.routeNativeElement!; const tabs = Array.from(root.querySelectorAll('[role="tab"]')); - // CaMa also has Histórico, between Resumen and Seguimiento. - const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']; + // CaMa also has Histórico and Análisis epidemiológico, between Resumen and Seguimiento; CaCu and TEA keep their three. + const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']; expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas); expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0))); expect(root.querySelector('[role="tablist"]')?.getAttribute('aria-label')).toContain(page.domainLabels[domain]); From 2b0f6dfbed3e4162a7c96c1a417897c7a1dc9bb5 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 14:29:45 -0600 Subject: [PATCH 27/38] feat(cama): readable BI-RADS and age labels, the biopsy report date, and no export of a list that does not match its group MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Contract review against WebApi 1d5f1e0 (webapi/cama_analysis.py, cama_cohort.py, docs/cama-cohort-api.md). - The cohort's list is rewritten once on arrival so the table, the record and the PDF/XLSX show "BI-RADS 5" and "50 a 59 años" (also "Menores de 40 años", "70 años o más", "Sin dato"); the codes stay in `_codigo` and in the filter options, which are what the requests send. Only codes whose meaning the API's own code confirms are labelled; biopsy grades are left as they arrive. - The record calls the biopsy date what the list calls it ("Fecha de reporte"): in the cohort it is the date of the biopsy report, which can be known while its result is not. - With the same cohort revision, cut-off and filter the aggregate and the list are counted from the same rows, so a different total breaks the contract: the list shows an alert and its PDF/XLSX buttons are disabled. - When no category is published the analysis says so and keeps "No publicado": the answer cannot tell an empty cohort from categories under the threshold. - Tests: the chosen cut-off reaches the aggregate, the list, the record and every page of the file. Co-Authored-By: Claude Sonnet 5.5 --- .../features/indicadores/etiquetas-cohorte.ts | 18 +++ .../indicadores-analisis-figuras.ts | 4 +- .../indicadores/indicadores-analisis.spec.ts | 9 ++ .../indicadores-analisis.testing.ts | 27 ++++ .../indicadores/indicadores-analisis.ts | 8 +- .../indicadores-cohorte-etiquetas.spec.ts | 131 ++++++++++++++++++ .../indicadores-recorrido-analisis.spec.ts | 34 ++++- .../indicadores-seguimiento-seleccion.spec.ts | 10 +- .../indicadores-seguimiento-tabla.ts | 14 +- .../cama/cama-patient-card.html | 2 +- .../paciente-detalle/cama/cama-patient-pdf.ts | 2 +- .../cama/cama-patient.models.ts | 11 +- .../indicadores/seguimiento-tabla.service.ts | 29 +++- 13 files changed, 281 insertions(+), 18 deletions(-) create mode 100644 src/app/features/indicadores/etiquetas-cohorte.ts create mode 100644 src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts new file mode 100644 index 0000000..09dae04 --- /dev/null +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -0,0 +1,18 @@ +// How the codes of the breast cohort are written for the user. Only codes whose meaning the API's own code confirms: +// the BI-RADS categories (kit: BIRADS_4, 4A, 4B, 4C, 5, 6) and the age groups of the cohort reader (`_age_group` of +// webapi/cama_cohort.py: under 40, each decade from 40 to 69, 70 or more, and no data when the birth date is missing +// or later than the cut-off). Requests keep the codes; only what is shown changes. +const EDADES: Readonly> = { + MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato', +}; +const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/; + +/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ +export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; +/** «50-59» as «50 a 59 años». Any other text is returned as it came. */ +export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; + +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad }; + +/** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ +export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/indicadores-analisis-figuras.ts b/src/app/features/indicadores/indicadores-analisis-figuras.ts index 50e5d03..a35369e 100644 --- a/src/app/features/indicadores/indicadores-analisis-figuras.ts +++ b/src/app/features/indicadores/indicadores-analisis-figuras.ts @@ -1,9 +1,9 @@ import { PlotlyFigure, Tema } from './indicadores.models'; import { C2_PALETTE, c2Theme } from './indicadores-c2-palette'; import { AnalisisAgregado } from './indicadores-analisis.service'; +import { etiquetaBirads } from './etiquetas-cohorte'; -/** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». */ -export const etiquetaBirads = (codigo: string) => /^BIRADS_/.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; +export { etiquetaBirads }; const miles = (v: number) => v.toLocaleString('es-MX'); /** The code of the published bar that was clicked, from its `customdata`; a suppressed bar or an empty click gives nothing. */ diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts index c4464c9..9a9629a 100644 --- a/src/app/features/indicadores/indicadores-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-analisis.spec.ts @@ -136,6 +136,15 @@ describe('Pestaña Análisis epidemiológico', () => { http.expectNone(() => true); expect(root().querySelector('[role=alert]')?.textContent).toContain('Revisa la fecha de corte'); }); + it('si ninguna categoría se publica, lo dice y conserva «No publicado»: la respuesta no distingue una cohorte vacía de grupos pequeños', () => { + // Fails if an empty cohort is announced when the answer cannot tell it, or the explanation of the suppression is lost. + abrir(); + const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true })); + pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges(); + expect(text()).toContain('Ninguna categoría alcanza el mínimo de 5 pacientes para publicarse a esta fecha de corte.'); + expect(text()).not.toContain('Sin pacientes'); + expect(Array.from(root().querySelectorAll('tbody tr')).every(f => f.children[1].textContent!.trim() === 'No publicado' && !f.querySelector('button'))).toBe(true); + }); it('un grupo suprimido no tiene botón y dice por qué; el publicado tiene su botón accesible', () => { // Fails if the table offers the patients of a hidden group. abrir(); pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-analisis.testing.ts b/src/app/features/indicadores/indicadores-analisis.testing.ts index 1bf6388..8c11455 100644 --- a/src/app/features/indicadores/indicadores-analisis.testing.ts +++ b/src/app/features/indicadores/indicadores-analisis.testing.ts @@ -16,5 +16,32 @@ export const agregado = (extra: Partial = {}): AnalisisAgregad ], ...extra, }); +/** + * The answer of the cohort's list as the API sends it: only the two filters it announces, with the code as their label, + * the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown), + * and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off. + */ +export function listaCohorte(o: { corte?: string; filtros?: Record; page?: number; size?: number; n?: number; meses?: number } = {}): Record { + const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0 } = o; + const todos = Array.from({ length: n }, (_, i) => ({ + id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01', + biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null, + })); + const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c })); + return { + simulado: true, ...CONTEXTO, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha', + filtros: { birads: null, grupo_edad: null, ...filtros }, + filtros_disponibles: [ + { clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) }, + { clave: 'grupo_edad', etiqueta: 'Grupo de edad', opciones: opciones(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']) }], + columnas: [ + { clave: 'id_seudonimo', etiqueta: 'Identificador seudónimo' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, + { clave: 'birads', etiqueta: 'Última mastografía', detalles: [{ clave: 'mastografia_fecha', etiqueta: 'Fecha' }] }, + { clave: 'biopsia', etiqueta: 'Resultado histopatológico', detalles: [{ clave: 'biopsia_fecha', etiqueta: 'Fecha de reporte' }] }], + paginacion: { page, page_size: size, total_items: n, total_pages: Math.max(1, Math.ceil(n / size)) }, + items: todos.slice((page - 1) * size, page * size), + }; +} + /** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */ export const agregadoJson = (extra: Record = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra }); diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index edde907..7898b46 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -7,7 +7,8 @@ import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { isoDate } from './cacu-seguimiento.models'; -import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; +import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; +import { etiquetaBirads } from './etiquetas-cohorte'; import { AnalisisAgregado, AnalisisService, ContextoCohorte } from './indicadores-analisis.service'; import { Dominio, Tema } from './indicadores.models'; @@ -78,6 +79,9 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement { } @if (datos(); as d) {

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

+ @if (todasSuprimidas()) { +

Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.

+ }

{{ aviso() }}

@@ -150,6 +154,8 @@ export class IndicadoresAnalisis { // Why the last click on a bar opened nothing. readonly aviso = signal(''); readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; }); + // The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published. + readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido)); readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; }); constructor() { diff --git a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts new file mode 100644 index 0000000..ece261f --- /dev/null +++ b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts @@ -0,0 +1,131 @@ +// Covers how the breast cohort is written for the user (BI-RADS and age groups), that the requests keep the codes, that +// the cut-off the user chose reaches the list, the record and the files, and what the record says of a biopsy whose +// report date is known while its result is not. Fixture: listaCohorte() in indicadores-analisis.testing.ts. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; +import { Observable, of } from 'rxjs'; +import { strFromU8, unzipSync } from 'fflate'; +import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; +import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf'; +import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; +import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad } from './etiquetas-cohorte'; +import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; +import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; +import { fetchAllTracking, queryOf } from './export/tracking-export-source'; +import { trackingDocument } from './export/tracking-pdf'; +import { buildTrackingXlsx } from './export/tracking-xlsx'; + +const CORTE_ELEGIDO = '2026-09-01'; +const textos = (nodo: unknown, salida: string[] = []): string[] => { + if (typeof nodo === 'string') salida.push(nodo); else if (Array.isArray(nodo)) nodo.forEach(n => textos(n, salida)); else if (nodo && typeof nodo === 'object') Object.values(nodo).forEach(n => textos(n, salida)); + return salida; +}; + +describe('Etiquetas de la cohorte', () => { + it('escribe las categorías BI-RADS y los grupos de edad como en la clínica, y deja lo demás como llegó', () => { + // Fails if a confirmed code is shown raw, or a code whose meaning is not confirmed is invented. + expect(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'].map(etiquetaBirads)).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); + expect(['MENOR_40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO'].map(etiquetaEdad)).toEqual( + ['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); + expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO'); + expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA'); + }); + it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => { + // Fails if the table, the record and the files can still show the code, or the code is lost for the requests. + const r = seguimientoTablaResponse(listaCohorte()); + expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]); + expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); + expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' }); + expect(r.filtros).toEqual({ birads: null, grupo_edad: null }); + const plana = listaCohorte(); delete plana['cohorte']; + expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' }); + }); +}); + +describe('La lista de la cohorte con etiquetas legibles y el corte elegido', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('active', false); + fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento'); + const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); + async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } + const seleccion = (esperados = 6): SeleccionSeguimiento => ({ filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE_ELEGIDO, esperados, contexto: CONTEXTO, id: 1 }); + const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; + const celdas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent!.replace(/\s+/g, ' ').trim())); + + it('muestra BI-RADS y grupos de edad legibles en las filas y en los filtros, pero la petición sigue enviando los códigos', async () => { + // Fails if the user reads codes, or a filter chosen by its label is sent as text instead of its code. + fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion()); fixture.detectChanges(); + let r = solicitud(); + expect(parametros(r)).toMatchObject({ corte: CORTE_ELEGIDO, birads: 'BIRADS_5', meses: '0', ...CONTEXTO }); + r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await asentar(); + expect(celdas()[1].slice(1, 3)).toEqual(['60 a 69 años', 'BI-RADS 5 Fecha: 2025-02-01']); + expect(root().textContent).not.toMatch(/BIRADS_5|60-69/); + expect([...campo('Grupo de edad').querySelectorAll('option')].map(o => o.text.trim())).toEqual(['Todos', 'Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); + const s = campo('Grupo de edad').querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === '60 a 69 años')!.value; + s.dispatchEvent(new Event('change')); await asentar(); + [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); fixture.detectChanges(); + r = solicitud(); + expect(parametros(r)).toMatchObject({ grupo_edad: '60-69', birads: 'BIRADS_5', corte: CORTE_ELEGIDO }); + r.flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5', grupo_edad: '60-69' } })); + }); + it('el corte elegido en el análisis llega a la lista, a la ficha y a todas las páginas de la exportación', async () => { + // Fails if the list, the record or a page of the file is read at another cut-off than the one the user chose. + fixture.componentRef.setInput('active', true); fixture.componentRef.setInput('seleccion', seleccion(450)); fixture.detectChanges(); + solicitud().flush(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); await asentar(); + // The record, opened from the row that was clicked. + (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE_ELEGIDO}.`); + // The files: every page asks for the same cut-off, and the answer must give it back. + const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO, filtros: { birads: 'BIRADS_5' }, n: 450 })); + const pedidas: SeguimientoTablaQuery[] = []; + const servicio = { consultar: (_d: string, q: SeguimientoTablaQuery): Observable => { + pedidas.push(q); return of(seguimientoTablaResponse(listaCohorte({ corte: q.corte, filtros: q.filtros as Record, page: q.page, size: q.page_size, n: 450 }))); } } as unknown as SeguimientoTablaService; + expect(queryOf(respuesta)).toMatchObject({ corte: CORTE_ELEGIDO, meses: 0, filtros: { birads: 'BIRADS_5' }, contexto: CONTEXTO }); + await new Promise((ok, fallo) => fetchAllTracking(servicio, 'cama', queryOf(respuesta), 1000).subscribe({ error: fallo, complete: ok })); + expect(pedidas.map(q => q.corte)).toEqual([CORTE_ELEGIDO, CORTE_ELEGIDO, CORTE_ELEGIDO]); + }); +}); + +describe('Ficha y archivos de una fila con biopsia reportada y resultado desconocido', () => { + const respuesta = seguimientoTablaResponse(listaCohorte({ corte: CORTE_ELEGIDO })); + const fila = (i: number) => respuesta.items[i]; + const NOW = new Date(Date.UTC(2026, 10, 13, 18, 0)); + + it('la ficha dice «Fecha de reporte», conserva «No disponible» para el resultado, el estatus y la prioridad, y escribe BI-RADS y edad legibles', () => { + // Fails if the date of a biopsy report is called the date of the biopsy, or an unknown result is filled in. + const resumen = toCamaPatientSummary(fila(2), CORTE_ELEGIDO, respuesta.columnas)!; + expect(resumen).toMatchObject({ birads: 'BI-RADS 5', ageGroup: '50 a 59 años', histopathology: null, biopsyDate: '2025-02-15', biopsyDateLabel: 'Fecha de reporte', status: null, priority: null }); + TestBed.configureTestingModule({ providers: [provideHttpClient()] }); + const card = TestBed.createComponent(CamaPatientCard); + card.componentRef.setInput('summary', resumen); card.detectChanges(); + const t = (card.nativeElement.textContent as string).replace(/\s+/g, ' '); + expect(t).toContain('Resultado: No disponible'); expect(t).toContain('Fecha de reporte: 2025-02-15'); + expect(t).toContain('Categoría BI-RADS: BI-RADS 5'); expect(t).toContain('50 a 59 años'); + expect(t).toMatch(/Estatus de seguimiento\s*No disponible/); expect(t).toMatch(/Prioridad\s*No disponible/); expect(t).toMatch(/Días de mastografía a diagnóstico\s*No disponible/); + expect(t).not.toContain('Fecha de biopsia'); + const pdf = textos(camaPatientDocument(resumen, NOW, 'data:image/png;base64,AAAA')); + expect(pdf).toContain('Fecha de reporte'); expect(pdf).not.toContain('Fecha de biopsia'); + // A list whose columns do not rename the date keeps the record's own wording. + expect(toCamaPatientSummary(fila(2), CORTE_ELEGIDO)!.biopsyDateLabel).toBeUndefined(); + }); + it('los archivos escriben las etiquetas, no los códigos, y la fila con fecha de reporte sin resultado sale con la celda vacía', async () => { + // Fails if a file carries codes the user cannot read, or invents a result for a report whose result is unknown. + const snapshot = { corte: respuesta.corte, ventana: respuesta.ventana, filtros: respuesta.filtros, filtros_disponibles: respuesta.filtros_disponibles, columnas: respuesta.columnas, items: respuesta.items, seleccion: 'Categoría BI-RADS: BI-RADS 5' }; + const pdf = textos(trackingDocument(snapshot, NOW, 'data:image/png;base64,AAAA')); + expect(pdf).toContain('BI-RADS 5'); expect(pdf).toContain('50 a 59 años'); expect(pdf.some(t => /BIRADS_|50-59/.test(t))).toBe(false); + expect(pdf).toContain('Fecha de reporte: 2025-02-15'); + const hojas = unzipSync(new Uint8Array(await (await buildTrackingXlsx(snapshot, NOW)).arrayBuffer())); + const cadenas = strFromU8(hojas['xl/sharedStrings.xml']).replace(/<[^>]+>/g, '|'); + expect(cadenas).toContain('|BI-RADS 5|'); expect(cadenas).toContain('|60 a 69 años|'); expect(cadenas).not.toMatch(/BIRADS_|\|50-59\|/); + expect(cadenas).toContain('Resultado histopatológico: Fecha de reporte'); + }); +}); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 75edebb..86e447c 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -14,7 +14,7 @@ import fixtureData from './fixtures/cama_seguimiento.json'; import { IndicadoresPage } from './indicadores-page'; import { IndicadoresAnalisis, hoyIso } from './indicadores-analisis'; import { IndicadorFigureCard } from './indicador-figure-card'; -import { agregadoJson, CONTEXTO } from './indicadores-analisis.testing'; +import { agregadoJson, CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { kpiQueriesProvider, periodAvailabilityProvider } from './indicadores-periodos.testing'; import { Indicador } from './indicadores.models'; @@ -78,7 +78,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = expect(e.panel('seguimiento').hidden).toBe(false); expect(e.panel('analisis').hidden).toBe(true); expect(e.panel('seguimiento').textContent).toContain('Categoría BI-RADS: BI-RADS 5'); expect(e.panel('seguimiento').textContent).toContain('Toda la cohorte'); - expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección; la lista muestra 27.'); + expect(e.panel('seguimiento').textContent).toContain('El análisis cuenta 6 pacientes en esta selección y la lista muestra 27. No coinciden'); expect(legible(e.root).filter(t => PROHIBIDO.test(t))).toEqual([]); // The record opens over the list and gives it back. @@ -105,6 +105,36 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = http.expectNone(q => q.url === '/cama/seguimiento'); expect(e.panel('seguimiento').textContent).toContain('BI-RADS 5'); }); + it('el corte que el usuario elige llega al agregado, al listado, a la ficha y al archivo descargado', async () => { + // Fails if any step of the journey is read at another cut-off than the chosen one, or the file does not say it. + const ELEGIDO = '2026-09-01'; + const descargas: string[] = []; + vi.spyOn(URL, 'createObjectURL').mockImplementation(() => 'blob:test'); vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined); + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { descargas.push(this.download); }); + const e = await entrar(); + await abrirAnalisis(e); + const entrada = e.root.querySelector('#panel-analisis input[name="corte"]')!; + entrada.value = ELEGIDO; entrada.dispatchEvent(new Event('input')); await e.asentar(); + [...e.panel('analisis').querySelectorAll('button')].find(b => b.textContent!.trim() === 'Consultar')!.click(); e.harness.detectChanges(); + http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === ELEGIDO).flush(agregadoJson({ corte: ELEGIDO })); await e.asentar(); + e.root.querySelector('tr[data-grupo="BIRADS_5"] button.ver')!.click(); e.harness.detectChanges(); + const r = lista(); + expect(parametros(r)).toMatchObject({ corte: ELEGIDO, meses: '0', birads: 'BIRADS_5', ...CONTEXTO }); + r.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' } })); await e.asentar(); + expect(e.panel('seguimiento').textContent).toContain(`corte ${ELEGIDO}`); + // The record. + e.root.querySelector('.patient-link')!.click(); await e.asentar(); + expect(e.root.querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${ELEGIDO}.`); + [...e.root.querySelectorAll('button')].find(b => b.textContent!.includes('Regresar'))!.click(); await e.asentar(); + // The file: the pages are read at the same cut-off, and the file says so. + [...e.panel('seguimiento').querySelectorAll('app-seguimiento-exportar button')].find(b => b.textContent!.includes('Excel'))!.dispatchEvent(new Event('click')); + const pagina = http.expectOne(q => q.url === '/cama/seguimiento'); + expect(parametros(pagina)).toMatchObject({ corte: ELEGIDO, page_size: '200', meses: '0', birads: 'BIRADS_5', ...CONTEXTO }); + pagina.flush(listaCohorte({ corte: ELEGIDO, filtros: { birads: 'BIRADS_5' }, size: 200 })); + for (let i = 0; i < 30 && !descargas.length; i++) { await new Promise(res => setTimeout(res, 20)); e.harness.detectChanges(); } + expect(descargas).toHaveLength(1); + expect(descargas[0]).toMatch(/^seguimiento-cancer-de-mama-seleccion_corte-2026-09-01_/); + }); it('si la cohorte cambió desde el análisis (409), la lista lo dice sin mostrar filas y el análisis sigue como estaba', async () => { // Fails if a stale revision shows rows, or the way back to the analysis is lost with the error. const e = await entrar(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 8e61316..9770bd1 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -75,14 +75,18 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); expect(root().querySelector('.seleccion')).toBeNull(); }); - it('avisa cuando la lista no tiene tantos pacientes como contó el análisis, y calla cuando coinciden', async () => { - // Fails if a difference between the analysis' count and the list goes unsaid. + it('si la lista no tiene tantos pacientes como contó el análisis para la misma selección y revisión, lo avisa y no deja exportarla; si coinciden, calla y exporta', async () => { + // Fails if a list that breaks the contract can be exported as if it were the group that was counted. abrirCon(seleccion(1, { esperados: 30 })); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); - expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección; la lista muestra 27.'); + expect(root().querySelector('.diferencia')?.getAttribute('role')).toBe('alert'); + expect(root().querySelector('.diferencia')?.textContent).toContain('El análisis cuenta 30 pacientes en esta selección y la lista muestra 27. No coinciden, por lo que este resultado no se puede exportar.'); + expect([...exportar()!.querySelectorAll('button')].every(b => b.disabled)).toBe(true); + expect(root().querySelector('table')).not.toBeNull(); fixture.componentRef.setInput('seleccion', seleccion(2, { esperados: 27 })); fixture.detectChanges(); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); expect(root().querySelector('.diferencia')).toBeNull(); + expect([...exportar()!.querySelectorAll('button')].some(b => !b.disabled)).toBe(true); }); it('una respuesta que pierde el filtro, cambia la ventana o el corte, o no es la cohorte ni la revisión pedidas no se dibuja ni se puede exportar', async () => { diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 55d4f57..c332f70 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -48,7 +48,7 @@ const mismosFiltros = (a: Record, b: Record

Seguimiento de {{ domainLabel }}

@if (data(); as respuesta) { - + } @if (seleccionMostrada(); as sel) { @@ -61,7 +61,7 @@ const mismosFiltros = (a: Record, b: RecordVolver al análisis - @if (diferencia(); as d) {

{{ d }}

} + @if (diferencia(); as d) { } }
@@ -185,11 +185,15 @@ export class IndicadoresSeguimientoTabla implements OnChanges { /** «Toda la cohorte» is offered while the analysis' cohort is active (or the form still holds it), never as a plain window. */ ventanas() { return this.contextoActivo || this.draft.meses === 0 ? MESES_VENTANA : MESES_VENTANA.filter(m => m !== 0); } - /** What the list says when it does not hold as many patients as the analysis counted for the selection. */ + /** + * What the list says when it does not hold as many patients as the analysis counted for the selection. With the same + * cohort revision, cut-off and filter the server counts both from the same rows, so a difference breaks the contract: + * the list stays visible, but it is not exported as if it were the group that was counted. + */ diferencia() { const esperados = this.activa?.esperados, total = this.data()?.paginacion.total_items; if (!this.seleccionExacta() || this.estado() !== 'ready' || esperados == null || total === undefined || esperados === total) return undefined; - return `El análisis cuenta ${esperados} pacientes en esta selección; la lista muestra ${total}.`; + return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`; } constructor() { @@ -296,7 +300,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { // A click on the row opens the record unless it landed on another control; the id button always does. if (evento.currentTarget instanceof HTMLTableRowElement && origen?.closest('button, a, input, select, textarea')) return; const corte = this.data()?.corte; - const resumen = corte ? toCamaPatientSummary(item, corte) : null; + const resumen = corte ? toCamaPatientSummary(item, corte, this.data()?.columnas) : null; if (!resumen || this.estado() !== 'ready') return; evento.stopPropagation(); this.controlFicha = evento.currentTarget instanceof HTMLElement ? evento.currentTarget : undefined; diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 842051a..4c5807f 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -29,7 +29,7 @@

Histopatología

    -
  • Resultado histopatológicoResultado: {{ p.histopathology ?? notAvailable }}Fecha de biopsia: {{ p.biopsyDate ?? notAvailable }}
  • +
  • Resultado histopatológicoResultado: {{ p.histopathology ?? notAvailable }}{{ p.biopsyDateLabel ?? 'Fecha de biopsia' }}: {{ p.biopsyDate ?? notAvailable }}
diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts index 4a1910c..1251ee4 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts @@ -26,7 +26,7 @@ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo ['Días de mastografía a diagnóstico', patient.daysMammographyToDiagnosis], ]), ...section('Mastografía', [['Categoría BI-RADS', patient.birads], ['Fecha de la mastografía', patient.mammographyDate]]), - ...section('Histopatología', [['Resultado histopatológico', patient.histopathology], ['Fecha de biopsia', patient.biopsyDate]]), + ...section('Histopatología', [['Resultado histopatológico', patient.histopathology], [patient.biopsyDateLabel ?? 'Fecha de biopsia', patient.biopsyDate]]), ...section('Pronóstico y recomendaciones', [ ...PROGNOSIS_PLACEHOLDERS.map(p => [p.label, PROGNOSIS_UNAVAILABLE] as [string, string]), ['Recomendaciones', RECOMMENDATIONS_UNAVAILABLE], diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index a263b6c..f11d59f 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -16,6 +16,8 @@ export interface CamaPatientSummary { mammographyDate: string | null; histopathology: string | null; biopsyDate: string | null; + /** What the list calls that date: the cohort's list gives the date of the biopsy report, which can be known before its result is. */ + biopsyDateLabel?: string; daysMammographyToDiagnosis: number | null; } @@ -30,10 +32,14 @@ export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.'; const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null); -/** The patient summary of a follow-up row, or `null` when the row has no identifier to show. */ -export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPatientSummary | null { +/** + * The patient summary of a follow-up row, or `null` when the row has no identifier to show. `columnas` are the ones the + * list announced: the label it gives to the biopsy date is kept, so the record says the same as the list. + */ +export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null { const pseudonymId = text(row['id_seudonimo']); if (!pseudonymId) return null; + const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta; const days = row['dias_mastografia_diagnostico']; return { pseudonymId, @@ -45,6 +51,7 @@ export function toCamaPatientSummary(row: TrackingRow, cutoff: string): CamaPati mammographyDate: text(row['mastografia_fecha']), histopathology: text(row['biopsia']), biopsyDate: text(row['biopsia_fecha']), + ...(etiquetaFecha ? { biopsyDateLabel: etiquetaFecha } : {}), daysMammographyToDiagnosis: typeof days === 'number' && Number.isFinite(days) ? days : null, }; } diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index 6bec678..e7a9637 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate } from './cacu-seguimiento.models'; +import { etiquetaDeFiltro } from './etiquetas-cohorte'; 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 @@ -94,9 +95,35 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse { || !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) { throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); } - return v as unknown as SeguimientoTablaResponse; + const respuesta = v as unknown as SeguimientoTablaResponse; + return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta; } +/** + * 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 + * in `_codigo` and in the filters' options, which are what the requests send. + */ +export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaResponse { + const claves = Object.keys(ETIQUETADAS); + return { + ...r, + filtros_disponibles: r.filtros_disponibles.map(f => claves.includes(f.clave) + ? { ...f, opciones: f.opciones.map(o => o.etiqueta === o.codigo ? { ...o, etiqueta: etiquetaDeFiltro(f.clave, o.codigo) } : o) } : f), + items: r.items.map(item => { + const nuevo = { ...item }; + for (const k of claves) { + const valor = item[k]; + if (typeof valor !== 'string' || etiquetaDeFiltro(k, valor) === valor) continue; + if (nuevo[k + '_codigo'] === undefined) nuevo[k + '_codigo'] = valor; + nuevo[k] = etiquetaDeFiltro(k, valor); + } + return nuevo; + }), + }; +} +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; + @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService { private readonly http = inject(HttpClient); From c06cce20dfe2718f0a009a8c0af4a58d12b5671a Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:17:14 -0600 Subject: [PATCH 28/38] Pass synthetic cohort access through the server proxy --- Dockerfile | 3 ++- nginx.conf | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 2b54235..c559aef 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,6 +7,7 @@ COPY . . RUN npx ng build --configuration production FROM nginx:1.27-alpine -COPY nginx.conf /etc/nginx/conf.d/default.conf +ENV CAMA_COHORT_ACCESS_TOKEN="" +COPY nginx.conf /etc/nginx/templates/default.conf.template COPY --from=build /app/dist/WebApp/browser /usr/share/nginx/html EXPOSE 80 diff --git a/nginx.conf b/nginx.conf index 4c46b13..30dc742 100644 --- a/nginx.conf +++ b/nginx.conf @@ -14,6 +14,9 @@ server { location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) { proxy_pass http://webapi:5000; + # The synthetic cohort token is supplied by the container environment, + # never by the browser. Override any client-supplied header. + proxy_set_header X-Cama-Cohort-Token "${CAMA_COHORT_ACCESS_TOKEN}"; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; From 7971a49dcda5f9759f6cf4693c1c725153172edb Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:18:11 -0600 Subject: [PATCH 29/38] feat(cama): regular follow-up read from the cohort, with the revision refreshed on a new cut-off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The follow-up tab of breast cancer now reads the cohort the analysis publishes: it asks for the cohort's revision at today's cut-off and lists the whole cohort quoting it. Where the server does not publish the cohort (404 or 503 on its aggregate) the plain follow-up list is read. - Another cut-off in the form asks for that cut-off's revision before the list; a revision that changes under the list (409) is asked for again once and the same query repeated, and a conflict that persists is reported. - "Quitar selección" returns to the whole cohort instead of another source. - An empty whole cohort says "Sin pacientes para el corte seleccionado"; filters and windows keep the text of the filters. - Filters, cut-off, page and rows are kept while a record is opened and closed. - Page specs that open CaMa follow-up answer the aggregate first. --- .../indicadores-analisis.service.ts | 6 + .../indicadores-analisis.testing.ts | 6 +- .../indicadores/indicadores-analisis.ts | 8 +- .../indicadores-initial-integration.spec.ts | 4 + .../indicadores/indicadores-sections.spec.ts | 2 + .../indicadores-seguimiento-cohorte.spec.ts | 159 ++++++++++++++++++ .../indicadores-seguimiento-ficha.spec.ts | 2 + .../indicadores-seguimiento-seleccion.spec.ts | 15 +- .../indicadores-seguimiento-tabla.ts | 122 +++++++++++--- .../indicadores/indicadores-tracking.html | 2 +- 10 files changed, 285 insertions(+), 41 deletions(-) create mode 100644 src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts diff --git a/src/app/features/indicadores/indicadores-analisis.service.ts b/src/app/features/indicadores/indicadores-analisis.service.ts index 3a25e35..16df001 100644 --- a/src/app/features/indicadores/indicadores-analisis.service.ts +++ b/src/app/features/indicadores/indicadores-analisis.service.ts @@ -17,6 +17,12 @@ export interface AnalisisAgregado { /** What a patients' list must quote back to open a group of the aggregate. */ export interface ContextoCohorte { cohorte: string; escenario: string; revision: string; } +/** Today as the date input writes it, in the user's own calendar day. */ +export function hoyIso(ahora = new Date()) { + const dos = (n: number) => String(n).padStart(2, '0'); + return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`; +} + const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const text = (v: unknown): v is string => typeof v === 'string' && v.length > 0; // Keys that only patient-level data would carry: the answer is rejected if any appears, at any depth. diff --git a/src/app/features/indicadores/indicadores-analisis.testing.ts b/src/app/features/indicadores/indicadores-analisis.testing.ts index 8c11455..1d9380e 100644 --- a/src/app/features/indicadores/indicadores-analisis.testing.ts +++ b/src/app/features/indicadores/indicadores-analisis.testing.ts @@ -21,15 +21,15 @@ export const agregado = (extra: Partial = {}): AnalisisAgregad * the codes as the values of the rows, the biopsy date being the date of the report (the result can still be unknown), * and the cohort quoted back. `n` rows M-0001…; the third row has a reported biopsy whose result is not known at the cut-off. */ -export function listaCohorte(o: { corte?: string; filtros?: Record; page?: number; size?: number; n?: number; meses?: number } = {}): Record { - const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0 } = o; +export function listaCohorte(o: { corte?: string; filtros?: Record; page?: number; size?: number; n?: number; meses?: number; revision?: string } = {}): Record { + const { corte = CORTE, filtros = {}, page = 1, size = 50, n = 6, meses = 0, revision = REVISION } = o; const todos = Array.from({ length: n }, (_, i) => ({ id_seudonimo: `M-${String(i + 1).padStart(4, '0')}`, grupo_edad: i % 2 ? '60-69' : '50-59', birads: 'BIRADS_5', mastografia_fecha: '2025-02-01', biopsia: i === 0 ? 'BENIGNO' : null, biopsia_fecha: i === 0 || i === 2 ? '2025-02-15' : null, })); const opciones = (codigos: string[]) => codigos.map(c => ({ codigo: c, etiqueta: c })); return { - simulado: true, ...CONTEXTO, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha', + simulado: true, ...CONTEXTO, revision, corte, ventana: { meses, desde: '2025-02-01', hasta: corte }, campo_ventana: 'mastografia_fecha', filtros: { birads: null, grupo_edad: null, ...filtros }, filtros_disponibles: [ { clave: 'birads', etiqueta: 'Categoría BI-RADS', opciones: opciones(['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6']) }, diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index 7898b46..d727124 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -9,7 +9,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { isoDate } from './cacu-seguimiento.models'; import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; import { etiquetaBirads } from './etiquetas-cohorte'; -import { AnalisisAgregado, AnalisisService, ContextoCohorte } from './indicadores-analisis.service'; +import { AnalisisAgregado, AnalisisService, ContextoCohorte, hoyIso } from './indicadores-analisis.service'; import { Dominio, Tema } from './indicadores.models'; type Carga = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' }; @@ -23,11 +23,7 @@ export interface SeleccionPacientes { filtros: Record; etiqueta: export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.'; -/** Today as the date input writes it, in the user's own calendar day. */ -export function hoyIso(ahora = new Date()) { - const dos = (n: number) => String(n).padStart(2, '0'); - return `${ahora.getFullYear()}-${dos(ahora.getMonth() + 1)}-${dos(ahora.getDate())}`; -} +export { hoyIso }; /** Why a group cannot open its patients, or nothing when it can: only a published group does. */ export function motivoSinLista(agregado: AnalisisAgregado, codigo: string): string | undefined { diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 267d869..34bef33 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,6 +84,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); + // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. + for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); @@ -104,6 +106,8 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); + // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. + for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 0a41c2e..272ed9b 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -55,6 +55,8 @@ describe('Secciones compartidas por dominio', () => { pestana('seguimiento').click(); harness.detectChanges(); // CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404). if (domain !== 'tea') { + // CaMa asks for the cohort's revision first and reads the plain list when the cohort is not published. + if (domain === 'cama') { http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Pending' }); } http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts new file mode 100644 index 0000000..00f5196 --- /dev/null +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -0,0 +1,159 @@ +// Covers the habitual access to Seguimiento of breast cancer: the list is read from the cohort the analysis publishes +// (its revision first, then the whole cohort at the cut-off), falls back to the plain follow-up list where the server does +// not publish it, asks for the revision again when the cut-off changes or the cohort changes under the list, and keeps the +// filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; +import fixtureData from './fixtures/cama_seguimiento.json'; +import { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; +import { hoyIso } from './indicadores-analisis.service'; +import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; + +const OTRA = 'a'.repeat(64); +const base = () => structuredClone(fixtureData) as unknown as Record; + +describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { + let fixture: ReturnType>, http: HttpTestingController; + const hoy = hoyIso(); + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); + fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', false); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const agregado = (corte = hoy) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte); + const lista = () => http.expectOne(r => r.url === '/cama/seguimiento'); + const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); + async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } + const abrir = () => { fixture.componentRef.setInput('active', true); fixture.detectChanges(); }; + const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement | undefined; + const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!; + const ventanas = () => [...campo('Ventana de meses').querySelectorAll('option')].map(o => o.text.trim()); + async function escribir(nombre: string, valor: string) { + const c = root().querySelector(`input[name="${nombre}"]`) as HTMLInputElement; c.value = valor; c.dispatchEvent(new Event('input')); await asentar(); + } + async function elegir(etiqueta: string, valor: string) { + const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar(); + } + // The cohort's answer opens the list on the whole cohort. + async function abierta(corte = hoy) { + abrir(); agregado(corte).flush(agregadoJson({ corte })); + lista().flush(listaCohorte({ corte, n: 27 })); await asentar(); + } + + it('al abrir pide la revisión de la cohorte a la fecha de hoy y luego toda la cohorte citándola, sin banner de selección', async () => { + // Fails if the habitual access still reads another source, opens on a window of months, or shows an analysis banner. + http.expectNone(() => true); + abrir(); + agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: hoy, ...CONTEXTO }); + r.flush(listaCohorte({ corte: hoy, n: 27 })); await asentar(); + expect(root().querySelector('.seleccion')).toBeNull(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); + expect(root().textContent).toContain(`Ventana consultada: Toda la cohorte, al ${hoy}.`); + expect(root().querySelectorAll('tbody tr')).toHaveLength(27); + expect(root().querySelector('app-seguimiento-exportar')).not.toBeNull(); + expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); + }); + it('si el servidor no publica la cohorte (404 o 503), lee la lista de seguimiento sin cohorte, sin «Toda la cohorte»', async () => { + // Fails if a deployment without the cohort provider loses its follow-up list. + for (const status of [404, 503]) { + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); + agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges(); + const r = lista(); + expect(parametros(r), String(status)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush(base()); await asentar(); + expect(ventanas(), String(status)).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + expect(root().querySelectorAll('tbody tr').length, String(status)).toBeGreaterThan(0); + http.verify(); + } + }); + it('un error del agregado se dice y el reintento vuelve a pedir la revisión', async () => { + // Fails if a failing aggregate leaves a blank list or the retry reads the list without a revision. + abrir(); + agregado().flush('detalle interno', { status: 500, statusText: 'Error' }); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('No se pudo consultar el seguimiento'); + expect(root().textContent).not.toContain('detalle interno'); + boton('Reintentar seguimiento')!.click(); fixture.detectChanges(); + http.expectNone(r => r.url === '/cama/seguimiento'); + // the retry repeats the query as it was: with the revision asked for first + agregado(); + }); + it('si el usuario cambia el corte, pide la revisión de ese corte antes de la lista y la cita', async () => { + // Fails if a list at another cut-off is asked for with the revision of the previous one. + await abierta(); + await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges(); + agregado('2026-09-01').flush(agregadoJson({ corte: '2026-09-01', revision: OTRA })); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toMatchObject({ corte: '2026-09-01', revision: OTRA, meses: '0' }); + r.flush(listaCohorte({ corte: '2026-09-01', n: 27, revision: OTRA })); await asentar(); + expect(root().querySelectorAll('tbody tr')).toHaveLength(27); + }); + it('si la cohorte cambia bajo la lista (409), pide la revisión de nuevo una vez y repite la misma consulta; un segundo 409 sí se dice', async () => { + // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. + await abierta(); + boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); + agregado(hoy).flush(agregadoJson({ corte: hoy, revision: OTRA })); fixture.detectChanges(); + let r = lista(); + expect(parametros(r)).toMatchObject({ revision: OTRA, corte: hoy }); + r.flush(listaCohorte({ corte: hoy, n: 27, revision: OTRA })); await asentar(); + expect(root().querySelector('[role=alert]')).toBeNull(); + // A conflict that persists is reported, not retried forever. + boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); + agregado(hoy).flush(agregadoJson({ corte: hoy, revision: REVISION })); fixture.detectChanges(); + r = lista(); r.flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis'); + expect(root().querySelector('table')).toBeNull(); + }); + it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => { + // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow filter as an empty cohort. + abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 0 })); await asentar(); + expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.'); + expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true); + await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + }); + it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => { + // Fails if opening the record resets the form, the page or the rows the user was reading. + abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10 })); await asentar(); + await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); + boton('Siguiente')!.click(); fixture.detectChanges(); + const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: hoy, ...CONTEXTO }); + r.flush(listaCohorte({ corte: hoy, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); + const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim()); + (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${hoy}.`); + ([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar(); + http.expectNone(() => true); + expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); + const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement; + expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años'); + expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(hoy); + }); + it('con una selección del análisis, «Quitar selección» regresa a este mismo acceso habitual', async () => { + // Fails if leaving the selection drops the user into a different source than the one the tab opens on. + abrir(); agregado().flush(agregadoJson({ corte: CORTE })); lista().flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id: 1 }); + fixture.detectChanges(); + lista().flush(listaCohorte({ corte: CORTE, n: 27, filtros: { birads: 'BIRADS_5' } })); await asentar(); + expect(root().querySelector('.seleccion')).not.toBeNull(); + boton('Quitar selección')!.click(); fixture.detectChanges(); + const r = lista(); expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + expect(root().querySelector('.seleccion')).toBeNull(); + }); +}); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index f6ab443..e385e79 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -108,6 +108,8 @@ describe('Seguimiento: ficha de CaMa y cambio de dominio', () => { fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v)); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); + // Without the cohort published the list reads the plain follow-up endpoint. + http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina()); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 9770bd1..2f00a32 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -6,7 +6,7 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; -import { CONTEXTO, CORTE } from './indicadores-analisis.testing'; +import { agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; @@ -118,6 +118,8 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); + // Another cut-off is another cohort at that date: its revision is asked for first. + http.expectOne(a => a.url === '/cama/analisis/indicadores' && a.params.get('corte') === c.value).flush(agregadoJson({ corte: c.value })); fixture.detectChanges(); const r = solicitud(); expect(r.request.params.get('corte'), String(status)).toBe(c.value); r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); @@ -193,17 +195,18 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); - it('«Quitar selección» sale de la cohorte: 3 meses, sin filtros y sin citar la revisión', async () => { - // Fails if removing the selection leaves its filters, the whole cohort or the cohort's revision behind. + it('«Quitar selección» vuelve a la cohorte completa, sin filtros ni nombre, y sigue citando su revisión', async () => { + // Fails if removing the selection leaves its filter behind, or leaves the cohort for another source. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Quitar selección')!.click(); fixture.detectChanges(); const r = solicitud(); - expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); - r.flush({ ...base(), filtros: { estatus: null, birads: null, grupo_edad: null, prioridad: null } }); await asentar(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(cohorte({})); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); - expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + expect(ventanas()).toContain('Toda la cohorte'); + expect(exportar()).not.toBeNull(); }); it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => { // Fails if a selection (or its cohort) made in one domain survives into another. diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index c332f70..7f5dd0a 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio } from './indicadores.models'; +import { AnalisisService, hoyIso } from './indicadores-analisis.service'; import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; @@ -13,9 +14,12 @@ import { } from './seguimiento-tabla.service'; type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error'; -type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string }; -/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */ -type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string }; +type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number }; +/** + * A request with the name of the selection it belongs to, so the answer and its name can never be told apart. + * `refrescar`: the cohort's revision is asked for first (at the query's cut-off, or today's), because the list is read from the cohort. + */ +type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string; refrescar?: boolean; reintento?: boolean }; // What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the // list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click. export interface SeleccionSeguimiento { @@ -101,7 +105,7 @@ const mismosFiltros = (a: Record, b: Record@if (c.clave === 'id_seudonimo') { } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } } } - } @empty { No hay registros para los filtros aplicados. } + } @empty { {{ textoVacio(respuesta) }} } @@ -150,7 +154,13 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() domainLabel = ''; // The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again. @Input() seleccion?: SeleccionSeguimiento; + /** + * Read the list from the cohort the analysis publishes (the agreed contract): the cohort's revision is asked for, then the whole + * cohort is listed at the cut-off. Where the server does not publish it (404 or 503) the plain follow-up list is read. + */ + @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); + private readonly analisis = inject(AnalisisService); private readonly injector = inject(Injector); /** Tells the page that an individual record replaced the list, so it can retitle itself. */ readonly fichaAbierta = output(); @@ -196,26 +206,65 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`; } + // The cut-off the cohort's revision was asked at: another cut-off needs another revision. + private contextoCorte?: string; + // The server does not publish the cohort (404 or 503 on its aggregate): the plain follow-up list is read. + private sinCohorte = false; + // A cohort that changed under a plain list is read again once, with its new revision, before it is reported. + private reintentoHecho = false; + + /** The list of one query, as the server answers it (without the loading state). */ + private lista(c: Consulta): Observable { + const { q, etiqueta } = c; + let peticion: Observable; + // An invalid query never leaves the browser; it reads like the server's own 400. + try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); } + return peticion.pipe( + // A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped, + // because its rows would pass for the analysis' group. A plain query shows what the answer says it applied. + map((data): Resultado => { + if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta'); + return { estado: 'ready', data, mensaje: '', etiqueta }; + }), + catchError(error => of(this.fallo(error, q)))); + } + + /** The query with the cohort's revision at its cut-off (today's when none), or the plain list when the server does not publish the cohort. */ + private refrescar(c: Consulta): Observable { + let agregado; + try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } + return agregado.pipe( + map((a): Consulta => { + this.contextoActivo = { cohorte: a.cohorte, escenario: a.escenario, revision: a.revision }; this.contextoCorte = a.corte; + return { ...c, refrescar: false, q: { ...c.q, corte: a.corte, contexto: this.contextoActivo } }; + }), + catchError((error): Observable => { + if (!this.contextoActivo && error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) { + this.sinCohorte = true; this.draft = { ...this.draft, meses: 3 }; + return of({ ...c, refrescar: false, q: { ...c.q, meses: 3, corte: undefined, contexto: undefined } }); + } + return of(this.fallo(error, c.q)); + })); + } + constructor() { this.consultas.pipe( switchMap((c): Observable => { if (!c) return of({ estado: 'idle', mensaje: '' }); - const { q, etiqueta } = c; - let peticion: Observable; - // An invalid query never leaves the browser; it reads like the server's own 400. - try { peticion = this.service.consultar(this.dominio, q); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha, la ventana, el tamaño de página y los filtros seleccionados.' }); } - return peticion.pipe( - // A selection names its patients: an answer that does not apply its window, cut-off and every filter is dropped, - // because its rows would pass for the analysis' group. A plain query shows what the answer says it applied. - map((data): Resultado => { - if ((etiqueta || q.contexto) && !consultaAplicada(q, data)) throw new SeguimientoNoCoincide('La respuesta no corresponde a la consulta'); - return { estado: 'ready', data, mensaje: '', etiqueta }; - }), - catchError(error => of(this.fallo(error, q))), + const preparada = c.refrescar ? this.refrescar(c) : of(c); + return preparada.pipe( + switchMap(x => 'estado' in x ? of(x) : this.lista(x)), startWith({ estado: 'loading', mensaje: '' })); }), takeUntilDestroyed(inject(DestroyRef)), ).subscribe(r => { + // The cohort changed under a plain list: the revision is asked for again, once, before the user hears of it. + if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) { + this.reintentoHecho = true; + this.consultas.next({ q: { ...this.applied, contexto: undefined }, refrescar: true, etiqueta: this.appliedEtiqueta }); + return; + } + if (r.estado === 'ready') this.reintentoHecho = false; this.estado.set(r.estado); this.mensaje.set(r.mensaje); if (r.estado === 'idle') { this.data.set(undefined); this.etiquetaDatos.set(undefined); this.filtros.set([]); } @@ -233,11 +282,13 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 }; // The selection belongs to the domain it was made in. this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined; + this.contextoCorte = undefined; this.sinCohorte = false; this.reintentoHecho = false; this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined); } const sel = this.seleccion; if (this.active && sel && sel.id !== this.seleccionAplicada) { - this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; + this.seleccionAplicada = sel.id; this.iniciado = true; this.activa = sel; this.contextoActivo = sel.contexto; this.contextoCorte = sel.corte; + this.reintentoHecho = false; // Whatever was on screen belongs to another query: it goes before the selection is asked for. this.data.set(undefined); this.etiquetaDatos.set(undefined); if (this.ficha()) { this.ficha.set(undefined); this.controlFicha = undefined; this.fichaAbierta.emit(false); } @@ -245,10 +296,20 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.aplicar(sel.etiqueta); return; } - if (this.active && !this.iniciado) { this.iniciado = true; this.consultas.next({ q: this.applied }); } + if (this.active && !this.iniciado) { + this.iniciado = true; + if (this.cohorte && !this.sinCohorte) { + // The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it. + this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size }; + this.consultas.next({ q: this.applied, refrescar: true }); + } else this.consultas.next({ q: this.applied }); + } } private fallo(error: unknown, q: SeguimientoTablaQuery): Resultado { + return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined }; + } + private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado { // A first page that does not exist yet is the list's own pending state; a later page that fails is an error. if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' }; if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' }; @@ -275,26 +336,32 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const filtros = Object.fromEntries(Object.entries(this.draft.filtros).filter(([, v]) => !!v)) as Record; const activa = this.activa, contexto = this.contextoActivo; const exacta = !!seleccion || (!!activa && this.draft.meses === 0 && mismosFiltros(filtros, activa.filtros) && (!activa.corte || this.draft.corte === activa.corte)); - // In the analysis' cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months. - const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto ? ETIQUETA_COHORTE : undefined); + // In the cohort the form refines the same cohort (and quotes its revision); outside it, a plain query has a window of months. + // The banner names the analysis' selection, or the cohort of the analysis once the user has refined it. + const etiqueta = seleccion ?? (exacta ? activa!.etiqueta : contexto && activa ? ETIQUETA_COHORTE : undefined); if (!contexto && this.draft.meses === 0) this.draft = { ...this.draft, meses: 3 }; this.seleccionMostrada.set(etiqueta); this.seleccionExacta.set(!!etiqueta && exacta); this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined); this.appliedEtiqueta = etiqueta; - const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, contexto }; + // Another cut-off is another cohort at that date: its revision is asked for before the list. + const refrescar = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; + const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, + contexto: refrescar ? undefined : contexto }; // A new query of the cohort starts from nothing on screen: what was there belongs to the previous one. if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); } this.applied = q; - this.consultas.next({ q, etiqueta }); + this.consultas.next({ q, etiqueta, refrescar }); } + // Leaving the analysis' selection returns to the whole cohort (the habitual list), not to another source. quitarSeleccion() { - this.draft = { ...this.draft, meses: 3, filtros: {} }; - this.activa = undefined; this.contextoActivo = undefined; + this.draft = { ...this.draft, meses: this.contextoActivo ? 0 : 3, filtros: {} }; + this.activa = undefined; this.aplicar(); } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } - reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); } + // A retry repeats the query as it was; one that failed before the cohort's revision was known asks for it again first. + reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.sinCohorte && !this.applied.contexto }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. @@ -313,6 +380,11 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const control = this.controlFicha; afterNextRender(() => { if (control?.isConnected) control.focus({ preventScroll: true }); }, { injector: this.injector }); } + // The cohort answers an empty page only for a whole cohort without filters that has no patient at the cut-off. + textoVacio(r: SeguimientoTablaResponse) { + const sinFiltros = Object.values(r.filtros).every(v => !v); + return r.cohorte && r.ventana.meses === 0 && sinFiltros ? 'Sin pacientes para el corte seleccionado.' : 'No hay registros para los filtros aplicados.'; + } detalles(c: SeguimientoColumna) { return c.detalles ?? []; } texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); } } diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 1b537dc..c32f06c 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -6,7 +6,7 @@
@if (dominio !== 'cama') {

Seguimiento de {{ domainLabel }}

} @if (dominio === 'cama') { - } @else if (dominio !== 'cacu') {

El seguimiento aún no está disponible.

From 18e92607058369a150214597a1a9cd79f9b9b203 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:32:39 -0600 Subject: [PATCH 30/38] Keep breast follow-up on the selected cohort --- .../features/indicadores/etiquetas-cohorte.ts | 12 ++++++---- .../indicadores-cohorte-etiquetas.spec.ts | 7 +++++- .../indicadores-seguimiento-cohorte.spec.ts | 18 ++++++-------- .../indicadores-seguimiento-ficha.spec.ts | 9 ++++--- .../indicadores-seguimiento-tabla.ts | 24 +++++++++---------- .../indicadores/seguimiento-tabla.service.ts | 2 +- 6 files changed, 38 insertions(+), 34 deletions(-) diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts index 09dae04..f7bdef8 100644 --- a/src/app/features/indicadores/etiquetas-cohorte.ts +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -1,18 +1,20 @@ -// How the codes of the breast cohort are written for the user. Only codes whose meaning the API's own code confirms: -// the BI-RADS categories (kit: BIRADS_4, 4A, 4B, 4C, 5, 6) and the age groups of the cohort reader (`_age_group` of -// webapi/cama_cohort.py: under 40, each decade from 40 to 69, 70 or more, and no data when the birth date is missing -// or later than the cut-off). Requests keep the codes; only what is shown changes. +// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received. const EDADES: Readonly> = { MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato', }; const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/; +const HISTOLOGIA: Readonly> = { + BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', + CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido', +}; /** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS ' + codigo.slice(7) : codigo; /** «50-59» as «50 a 59 años». Any other text is returned as it came. */ export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; +export const etiquetaHistologia = (codigo: string) => HISTOLOGIA[codigo] ?? codigo; -const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad }; +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaHistologia }; /** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts index ece261f..82fba5a 100644 --- a/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts +++ b/src/app/features/indicadores/indicadores-cohorte-etiquetas.spec.ts @@ -9,7 +9,7 @@ import { strFromU8, unzipSync } from 'fflate'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { camaPatientDocument } from './paciente-detalle/cama/cama-patient-pdf'; import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; -import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad } from './etiquetas-cohorte'; +import { etiquetaBirads, etiquetaDeFiltro, etiquetaEdad, etiquetaHistologia } from './etiquetas-cohorte'; import { CONTEXTO, listaCohorte } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; @@ -31,6 +31,8 @@ describe('Etiquetas de la cohorte', () => { ['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); expect(etiquetaBirads('BIRADS_7')).toBe('BIRADS_7'); expect(etiquetaEdad('OTRO')).toBe('OTRO'); expect(etiquetaDeFiltro('birads', 'BIRADS_5')).toBe('BI-RADS 5'); expect(etiquetaDeFiltro('prioridad', 'ALTA')).toBe('ALTA'); + expect(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'DESCONOCIDO', 'OTRO'].map(etiquetaHistologia)) + .toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Desconocido', 'OTRO']); }); it('la respuesta de una cohorte se escribe una vez: opciones y filas legibles, con el código guardado, y una lista sin cohorte no cambia', () => { // Fails if the table, the record and the files can still show the code, or the code is lost for the requests. @@ -38,6 +40,9 @@ describe('Etiquetas de la cohorte', () => { expect(r.filtros_disponibles[0].opciones.map(o => [o.codigo, o.etiqueta]).slice(0, 2)).toEqual([['BIRADS_4', 'BI-RADS 4'], ['BIRADS_4A', 'BI-RADS 4A']]); expect(r.filtros_disponibles[1].opciones.map(o => o.etiqueta)).toEqual(['Menores de 40 años', '40 a 49 años', '50 a 59 años', '60 a 69 años', '70 años o más', 'Sin dato']); expect(r.items[0]).toMatchObject({ birads: 'BI-RADS 5', birads_codigo: 'BIRADS_5', grupo_edad: '50 a 59 años', grupo_edad_codigo: '50-59' }); + const histo = listaCohorte(); + (histo['items'] as Record[])[0]['biopsia'] = 'CARCINOMA_INVASOR'; + expect(seguimientoTablaResponse(histo).items[0]).toMatchObject({ biopsia: 'Carcinoma invasor', biopsia_codigo: 'CARCINOMA_INVASOR' }); expect(r.filtros).toEqual({ birads: null, grupo_edad: null }); const plana = listaCohorte(); delete plana['cohorte']; expect(seguimientoTablaResponse(plana).items[0]).toMatchObject({ birads: 'BIRADS_5', grupo_edad: '50-59' }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts index 00f5196..4d22e84 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -1,17 +1,15 @@ // Covers the habitual access to Seguimiento of breast cancer: the list is read from the cohort the analysis publishes -// (its revision first, then the whole cohort at the cut-off), falls back to the plain follow-up list where the server does -// not publish it, asks for the revision again when the cut-off changes or the cohort changes under the list, and keeps the +// (its revision first, then the whole cohort at the cut-off), fails closed when the cohort is unavailable, asks for the +// revision again when the cut-off changes or the cohort changes under the list, and keeps the // filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; -import fixtureData from './fixtures/cama_seguimiento.json'; import { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; import { hoyIso } from './indicadores-analisis.service'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; const OTRA = 'a'.repeat(64); -const base = () => structuredClone(fixtureData) as unknown as Record; describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { let fixture: ReturnType>, http: HttpTestingController; @@ -59,19 +57,17 @@ describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { expect(root().querySelector('app-seguimiento-exportar')).not.toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); }); - it('si el servidor no publica la cohorte (404 o 503), lee la lista de seguimiento sin cohorte, sin «Toda la cohorte»', async () => { - // Fails if a deployment without the cohort provider loses its follow-up list. + it('si la cohorte no está disponible (404 o 503), informa el error sin cambiar de fuente', async () => { + // Fails if an unavailable cohort can silently broaden or replace the population. for (const status of [404, 503]) { TestBed.resetTestingModule(); TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges(); - const r = lista(); - expect(parametros(r), String(status)).toEqual({ meses: '3', page: '1', page_size: '50' }); - r.flush(base()); await asentar(); - expect(ventanas(), String(status)).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); - expect(root().querySelectorAll('tbody tr').length, String(status)).toBeGreaterThan(0); + await asentar(); + http.expectNone(r => r.url === '/cama/seguimiento'); + expect(root().querySelector('[role=alert]')?.textContent, String(status)).toContain('La cohorte no está disponible'); http.verify(); } }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index e385e79..8575131 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -5,6 +5,8 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; +import { agregadoJson, listaCohorte } from './indicadores-analisis.testing'; +import { hoyIso } from './indicadores-analisis.service'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; import { IndicadoresTracking } from './indicadores-tracking'; @@ -108,9 +110,10 @@ describe('Seguimiento: ficha de CaMa y cambio de dominio', () => { fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v)); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - // Without the cohort published the list reads the plain follow-up endpoint. - http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); - http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina()); + // The record is opened from the same cohort that the analysis publishes. + const corte = hoyIso(); + http.expectOne(r => r.url === '/cama/analisis/indicadores').flush(agregadoJson({ corte })); + http.expectOne(r => r.url === '/cama/seguimiento').flush(listaCohorte({ corte, n: 6 })); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); await fixture.whenStable(); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 7f5dd0a..0b454fa 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -9,7 +9,7 @@ import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { - consultaAplicada, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, contextoDe, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; @@ -156,7 +156,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() seleccion?: SeleccionSeguimiento; /** * Read the list from the cohort the analysis publishes (the agreed contract): the cohort's revision is asked for, then the whole - * cohort is listed at the cut-off. Where the server does not publish it (404 or 503) the plain follow-up list is read. + * cohort is listed at the cut-off. An unavailable cohort is reported without switching sources. */ @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); @@ -208,8 +208,6 @@ export class IndicadoresSeguimientoTabla implements OnChanges { // The cut-off the cohort's revision was asked at: another cut-off needs another revision. private contextoCorte?: string; - // The server does not publish the cohort (404 or 503 on its aggregate): the plain follow-up list is read. - private sinCohorte = false; // A cohort that changed under a plain list is read again once, with its new revision, before it is reported. private reintentoHecho = false; @@ -229,7 +227,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { catchError(error => of(this.fallo(error, q)))); } - /** The query with the cohort's revision at its cut-off (today's when none), or the plain list when the server does not publish the cohort. */ + /** The query with the cohort's revision at its cut-off (today's when none). */ private refrescar(c: Consulta): Observable { let agregado; try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } @@ -239,10 +237,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return { ...c, refrescar: false, q: { ...c.q, corte: a.corte, contexto: this.contextoActivo } }; }), catchError((error): Observable => { - if (!this.contextoActivo && error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) { - this.sinCohorte = true; this.draft = { ...this.draft, meses: 3 }; - return of({ ...c, refrescar: false, q: { ...c.q, meses: 3, corte: undefined, contexto: undefined } }); - } + if (error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) + return of({ estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }); return of(this.fallo(error, c.q)); })); } @@ -282,7 +278,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 }; // The selection belongs to the domain it was made in. this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined; - this.contextoCorte = undefined; this.sinCohorte = false; this.reintentoHecho = false; + this.contextoCorte = undefined; this.reintentoHecho = false; this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined); } const sel = this.seleccion; @@ -298,7 +294,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } if (this.active && !this.iniciado) { this.iniciado = true; - if (this.cohorte && !this.sinCohorte) { + if (this.cohorte) { // The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it. this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size }; this.consultas.next({ q: this.applied, refrescar: true }); @@ -311,6 +307,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado { // A first page that does not exist yet is the list's own pending state; a later page that fails is an error. + if (error instanceof HttpErrorResponse && error.status === 404 && this.cohorte) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }; if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' }; if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' }; // A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured. @@ -327,7 +324,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const claves = new Set(data.filtros_disponibles.map(f => f.clave)); this.draft = { ...this.draft, corte: data.corte, filtros: Object.fromEntries(Object.entries(this.draft.filtros).filter(([k]) => claves.has(k))) }; this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size, - filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) }; + filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), + contexto: contextoDe(data) }; this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; } // The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort @@ -361,7 +359,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } // A retry repeats the query as it was; one that failed before the cohort's revision was known asks for it again first. - reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.sinCohorte && !this.applied.contexto }); } + reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.applied.contexto }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index e7a9637..f523b2f 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -122,7 +122,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR }), }; } -const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true }; @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService { From 0acee49de2098b2f9d06607f7d374091a5f4b764 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:43:02 -0600 Subject: [PATCH 31/38] fix(cama): regular follow-up opens on the 3-month window and adopts the cohort the server returns The follow-up list asks for the regular window without quoting a revision; when the answer names a cohort the next pages and the files quote it. A new cut-off or a revision that changed under the list is asked for again without the old revision (once, then reported). Leaving the analysis' selection returns to the regular window. A server that does not answer from the cohort keeps the plain list. Histopathology codes are written with the catalog labels (Benigno, Carcinoma in situ, Carcinoma invasor, Desconocido); other values stay as they arrive. --- .../features/indicadores/etiquetas-cohorte.ts | 6 +- .../indicadores-initial-integration.spec.ts | 4 - .../indicadores/indicadores-sections.spec.ts | 2 - .../indicadores-seguimiento-cohorte.spec.ts | 158 +++++++++--------- .../indicadores-seguimiento-ficha.spec.ts | 2 - .../indicadores-seguimiento-seleccion.spec.ts | 13 +- .../indicadores-seguimiento-tabla.ts | 77 +++------ .../indicadores/indicadores-tracking.html | 2 +- .../indicadores/seguimiento-tabla.service.ts | 2 +- 9 files changed, 110 insertions(+), 156 deletions(-) diff --git a/src/app/features/indicadores/etiquetas-cohorte.ts b/src/app/features/indicadores/etiquetas-cohorte.ts index 09dae04..c67ecd6 100644 --- a/src/app/features/indicadores/etiquetas-cohorte.ts +++ b/src/app/features/indicadores/etiquetas-cohorte.ts @@ -5,6 +5,8 @@ const EDADES: Readonly> = { MENOR_40: 'Menores de 40 años', '40-49': '40 a 49 años', '50-59': '50 a 59 años', '60-69': '60 a 69 años', '70+': '70 años o más', SIN_DATO: 'Sin dato', }; +// The CaMa catalog's labels for the histopathology codes the list carries; a code it does not list stays as it arrives. +const BIOPSIA: Readonly> = { BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', DESCONOCIDO: 'Desconocido' }; const BIRADS = /^BIRADS_(4[ABC]?|5|6)$/; /** «BIRADS_4A» as it is written in the clinic: «BI-RADS 4A». Any other text is returned as it came. */ @@ -12,7 +14,9 @@ export const etiquetaBirads = (codigo: string) => BIRADS.test(codigo) ? 'BI-RADS /** «50-59» as «50 a 59 años». Any other text is returned as it came. */ export const etiquetaEdad = (codigo: string) => EDADES[codigo] ?? codigo; -const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad }; +/** «CARCINOMA_INVASOR» as «Carcinoma invasor». */ +export const etiquetaBiopsia = (codigo: string) => BIOPSIA[codigo] ?? codigo; +const POR_CLAVE: Readonly string>> = { birads: etiquetaBirads, grupo_edad: etiquetaEdad, biopsia: etiquetaBiopsia }; /** The label of a value of a filter of the cohort's list, or the value itself when its meaning is not confirmed. */ export const etiquetaDeFiltro = (clave: string, codigo: string) => (POR_CLAVE[clave] ?? ((c: string) => c))(codigo); diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 34bef33..267d869 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,8 +84,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); - // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. - for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); @@ -106,8 +104,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); - // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. - for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 272ed9b..0a41c2e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -55,8 +55,6 @@ describe('Secciones compartidas por dominio', () => { pestana('seguimiento').click(); harness.detectChanges(); // CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404). if (domain !== 'tea') { - // CaMa asks for the cohort's revision first and reads the plain list when the cohort is not published. - if (domain === 'cama') { http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Pending' }); } http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts index 00f5196..e60b013 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -1,30 +1,27 @@ -// Covers the habitual access to Seguimiento of breast cancer: the list is read from the cohort the analysis publishes -// (its revision first, then the whole cohort at the cut-off), falls back to the plain follow-up list where the server does -// not publish it, asks for the revision again when the cut-off changes or the cohort changes under the list, and keeps the -// filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts. +// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server +// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed +// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the +// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; -import { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; -import { hoyIso } from './indicadores-analisis.service'; +import { CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; const OTRA = 'a'.repeat(64); const base = () => structuredClone(fixtureData) as unknown as Record; -describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { +describe('Seguimiento de CaMa: acceso habitual', () => { let fixture: ReturnType>, http: HttpTestingController; - const hoy = hoyIso(); beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); - fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', false); fixture.detectChanges(); + fixture.componentRef.setInput('active', false); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; - const agregado = (corte = hoy) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte); const lista = () => http.expectOne(r => r.url === '/cama/seguimiento'); const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } @@ -38,122 +35,121 @@ describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { async function elegir(etiqueta: string, valor: string) { const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar(); } - // The cohort's answer opens the list on the whole cohort. - async function abierta(corte = hoy) { - abrir(); agregado(corte).flush(agregadoJson({ corte })); - lista().flush(listaCohorte({ corte, n: 27 })); await asentar(); + // The list opens on the regular window of 3 months and the cohort answers with its revision. + async function abierta(extra: Parameters[0] = {}) { + abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); await asentar(); } - it('al abrir pide la revisión de la cohorte a la fecha de hoy y luego toda la cohorte citándola, sin banner de selección', async () => { - // Fails if the habitual access still reads another source, opens on a window of months, or shows an analysis banner. + it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => { + // Fails if the habitual access asks for another window, or needs a revision it cannot have yet, or shows an analysis banner. http.expectNone(() => true); abrir(); - agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); const r = lista(); - expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: hoy, ...CONTEXTO }); - r.flush(listaCohorte({ corte: hoy, n: 27 })); await asentar(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); - expect(root().textContent).toContain(`Ventana consultada: Toda la cohorte, al ${hoy}.`); - expect(root().querySelectorAll('tbody tr')).toHaveLength(27); - expect(root().querySelector('app-seguimiento-exportar')).not.toBeNull(); - expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); + expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.'); + // The next page quotes the cohort the first answer named, with the same window and cut-off. + boton('Siguiente')!.click(); fixture.detectChanges(); + const p2 = lista(); + expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO }); + p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar(); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); }); - it('si el servidor no publica la cohorte (404 o 503), lee la lista de seguimiento sin cohorte, sin «Toda la cohorte»', async () => { - // Fails if a deployment without the cohort provider loses its follow-up list. - for (const status of [404, 503]) { - TestBed.resetTestingModule(); - TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); - fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); - fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges(); - const r = lista(); - expect(parametros(r), String(status)).toEqual({ meses: '3', page: '1', page_size: '50' }); - r.flush(base()); await asentar(); - expect(ventanas(), String(status)).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); - expect(root().querySelectorAll('tbody tr').length, String(status)).toBeGreaterThan(0); - http.verify(); - } + it('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => { + // Fails if the whole cohort is asked for without the revision the server requires for it. + await abierta(); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar(); + expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.'); + expect(root().querySelector('nav')?.textContent).toContain('43 registros'); }); - it('un error del agregado se dice y el reintento vuelve a pedir la revisión', async () => { - // Fails if a failing aggregate leaves a blank list or the retry reads the list without a revision. - abrir(); - agregado().flush('detalle interno', { status: 500, statusText: 'Error' }); await asentar(); - expect(root().querySelector('[role=alert]')?.textContent).toContain('No se pudo consultar el seguimiento'); - expect(root().textContent).not.toContain('detalle interno'); - boton('Reintentar seguimiento')!.click(); fixture.detectChanges(); - http.expectNone(r => r.url === '/cama/seguimiento'); - // the retry repeats the query as it was: with the revision asked for first - agregado(); + it('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => { + // Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know. + abrir(); lista().flush(base()); await asentar(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).not.toHaveProperty('revision'); }); - it('si el usuario cambia el corte, pide la revisión de ese corte antes de la lista y la cita', async () => { + it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', async () => { // Fails if a list at another cut-off is asked for with the revision of the previous one. await abierta(); await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges(); - agregado('2026-09-01').flush(agregadoJson({ corte: '2026-09-01', revision: OTRA })); fixture.detectChanges(); const r = lista(); - expect(parametros(r)).toMatchObject({ corte: '2026-09-01', revision: OTRA, meses: '0' }); - r.flush(listaCohorte({ corte: '2026-09-01', n: 27, revision: OTRA })); await asentar(); - expect(root().querySelectorAll('tbody tr')).toHaveLength(27); - }); - it('si la cohorte cambia bajo la lista (409), pide la revisión de nuevo una vez y repite la misma consulta; un segundo 409 sí se dice', async () => { - // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. - await abierta(); + expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA }); + }); + it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; un segundo 409 sí se dice', async () => { + // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. + await abierta({ size: 10 }); + boton('Siguiente')!.click(); fixture.detectChanges(); lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); - agregado(hoy).flush(agregadoJson({ corte: hoy, revision: OTRA })); fixture.detectChanges(); - let r = lista(); - expect(parametros(r)).toMatchObject({ revision: OTRA, corte: hoy }); - r.flush(listaCohorte({ corte: hoy, n: 27, revision: OTRA })); await asentar(); + const r = lista(); + expect(parametros(r)).toMatchObject({ page: '2', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, revision: OTRA })); await asentar(); expect(root().querySelector('[role=alert]')).toBeNull(); // A conflict that persists is reported, not retried forever. boton('Consultar')!.click(); fixture.detectChanges(); lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); - agregado(hoy).flush(agregadoJson({ corte: hoy, revision: REVISION })); fixture.detectChanges(); - r = lista(); r.flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); + lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis'); expect(root().querySelector('table')).toBeNull(); }); it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => { - // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow filter as an empty cohort. - abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 0 })); await asentar(); + // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort. + await abierta({ n: 0 }); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ meses: 0, n: 0 })); await asentar(); expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.'); expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true); await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); + lista().flush(listaCohorte({ meses: 0, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); }); it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => { // Fails if opening the record resets the form, the page or the rows the user was reading. - abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10 })); await asentar(); + await abierta({ size: 10 }); await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); + lista().flush(listaCohorte({ meses: 3, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); boton('Siguiente')!.click(); fixture.detectChanges(); - const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: hoy, ...CONTEXTO }); - r.flush(listaCohorte({ corte: hoy, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); + const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim()); (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); - expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${hoy}.`); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`); ([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar(); http.expectNone(() => true); expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes); expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement; expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años'); - expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(hoy); + expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE); }); - it('con una selección del análisis, «Quitar selección» regresa a este mismo acceso habitual', async () => { - // Fails if leaving the selection drops the user into a different source than the one the tab opens on. - abrir(); agregado().flush(agregadoJson({ corte: CORTE })); lista().flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); - fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id: 1 }); + it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => { + // Fails if leaving the selection keeps its filter, its window or the old revision. + await abierta(); + fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 }); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: CORTE, n: 27, filtros: { birads: 'BIRADS_5' } })); await asentar(); + lista().flush(listaCohorte({ meses: 0, n: 43, filtros: { birads: 'BIRADS_5' } })); await asentar(); expect(root().querySelector('.seleccion')).not.toBeNull(); boton('Quitar selección')!.click(); fixture.detectChanges(); - const r = lista(); expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); - r.flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); }); + it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => { + // Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost. + abrir(); + const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; }); + lista().flush(r); await asentar(); + expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']); + }); }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index e385e79..f6ab443 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -108,8 +108,6 @@ describe('Seguimiento: ficha de CaMa y cambio de dominio', () => { fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v)); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - // Without the cohort published the list reads the plain follow-up endpoint. - http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Not Found' }); http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina()); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 2f00a32..7691581 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -6,7 +6,7 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; -import { agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; +import { CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; @@ -118,8 +118,6 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); - // Another cut-off is another cohort at that date: its revision is asked for first. - http.expectOne(a => a.url === '/cama/analisis/indicadores' && a.params.get('corte') === c.value).flush(agregadoJson({ corte: c.value })); fixture.detectChanges(); const r = solicitud(); expect(r.request.params.get('corte'), String(status)).toBe(c.value); r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); @@ -195,17 +193,16 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); - it('«Quitar selección» vuelve a la cohorte completa, sin filtros ni nombre, y sigue citando su revisión', async () => { - // Fails if removing the selection leaves its filter behind, or leaves the cohort for another source. + it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => { + // Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Quitar selección')!.click(); fixture.detectChanges(); const r = solicitud(); - expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); - r.flush(cohorte({})); await asentar(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); - expect(ventanas()).toContain('Toda la cohorte'); expect(exportar()).not.toBeNull(); }); it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => { diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 7f5dd0a..7eb41d7 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -4,22 +4,18 @@ import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio } from './indicadores.models'; -import { AnalisisService, hoyIso } from './indicadores-analisis.service'; import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { - consultaAplicada, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error'; type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number }; -/** - * A request with the name of the selection it belongs to, so the answer and its name can never be told apart. - * `refrescar`: the cohort's revision is asked for first (at the query's cut-off, or today's), because the list is read from the cohort. - */ -type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string; refrescar?: boolean; reintento?: boolean }; +/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */ +type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string }; // What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the // list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click. export interface SeleccionSeguimiento { @@ -154,13 +150,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() domainLabel = ''; // The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again. @Input() seleccion?: SeleccionSeguimiento; - /** - * Read the list from the cohort the analysis publishes (the agreed contract): the cohort's revision is asked for, then the whole - * cohort is listed at the cut-off. Where the server does not publish it (404 or 503) the plain follow-up list is read. - */ - @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); - private readonly analisis = inject(AnalisisService); private readonly injector = inject(Injector); /** Tells the page that an individual record replaced the list, so it can retitle itself. */ readonly fichaAbierta = output(); @@ -206,11 +196,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`; } - // The cut-off the cohort's revision was asked at: another cut-off needs another revision. + // The cut-off of the cohort's revision: another cut-off is another cohort at that date, so its revision is not quoted. private contextoCorte?: string; - // The server does not publish the cohort (404 or 503 on its aggregate): the plain follow-up list is read. - private sinCohorte = false; - // A cohort that changed under a plain list is read again once, with its new revision, before it is reported. + // A cohort that changed under a plain list is read again once, without the old revision, before it is reported. private reintentoHecho = false; /** The list of one query, as the server answers it (without the loading state). */ @@ -229,39 +217,18 @@ export class IndicadoresSeguimientoTabla implements OnChanges { catchError(error => of(this.fallo(error, q)))); } - /** The query with the cohort's revision at its cut-off (today's when none), or the plain list when the server does not publish the cohort. */ - private refrescar(c: Consulta): Observable { - let agregado; - try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } - return agregado.pipe( - map((a): Consulta => { - this.contextoActivo = { cohorte: a.cohorte, escenario: a.escenario, revision: a.revision }; this.contextoCorte = a.corte; - return { ...c, refrescar: false, q: { ...c.q, corte: a.corte, contexto: this.contextoActivo } }; - }), - catchError((error): Observable => { - if (!this.contextoActivo && error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) { - this.sinCohorte = true; this.draft = { ...this.draft, meses: 3 }; - return of({ ...c, refrescar: false, q: { ...c.q, meses: 3, corte: undefined, contexto: undefined } }); - } - return of(this.fallo(error, c.q)); - })); - } - constructor() { this.consultas.pipe( switchMap((c): Observable => { if (!c) return of({ estado: 'idle', mensaje: '' }); - const preparada = c.refrescar ? this.refrescar(c) : of(c); - return preparada.pipe( - switchMap(x => 'estado' in x ? of(x) : this.lista(x)), - startWith({ estado: 'loading', mensaje: '' })); + return this.lista(c).pipe(startWith({ estado: 'loading', mensaje: '' })); }), takeUntilDestroyed(inject(DestroyRef)), ).subscribe(r => { - // The cohort changed under a plain list: the revision is asked for again, once, before the user hears of it. + // The cohort changed under a plain list: the same query is asked again, once, without the old revision, before the user hears of it. if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) { this.reintentoHecho = true; - this.consultas.next({ q: { ...this.applied, contexto: undefined }, refrescar: true, etiqueta: this.appliedEtiqueta }); + this.consultas.next({ q: { ...this.applied, contexto: undefined }, etiqueta: this.appliedEtiqueta }); return; } if (r.estado === 'ready') this.reintentoHecho = false; @@ -282,7 +249,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.draft = { meses: 3, page_size: 50, filtros: {} }; this.applied = { meses: 3, page: 1, page_size: 50 }; // The selection belongs to the domain it was made in. this.appliedEtiqueta = undefined; this.activa = undefined; this.contextoActivo = undefined; this.seleccionAplicada = undefined; - this.contextoCorte = undefined; this.sinCohorte = false; this.reintentoHecho = false; + this.contextoCorte = undefined; this.reintentoHecho = false; this.seleccionMostrada.set(undefined); this.seleccionExacta.set(false); this.corteSeleccion.set(undefined); this.etiquetaDatos.set(undefined); } const sel = this.seleccion; @@ -298,11 +265,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } if (this.active && !this.iniciado) { this.iniciado = true; - if (this.cohorte && !this.sinCohorte) { - // The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it. - this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size }; - this.consultas.next({ q: this.applied, refrescar: true }); - } else this.consultas.next({ q: this.applied }); + this.consultas.next({ q: this.applied }); } } @@ -329,6 +292,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size, filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) }; this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; + // A list read from the cohort says which one (and its revision): the next pages and the files quote it. + this.contextoActivo = contextoDe(data); this.contextoCorte = data.corte; + this.applied = { ...this.applied, contexto: this.contextoActivo }; } // The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort // included; anything else is the user's own query, with a window of months. @@ -344,24 +310,23 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.seleccionExacta.set(!!etiqueta && exacta); this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined); this.appliedEtiqueta = etiqueta; - // Another cut-off is another cohort at that date: its revision is asked for before the list. - const refrescar = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; + // Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one. + const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, - contexto: refrescar ? undefined : contexto }; + contexto: otroCorte ? undefined : contexto }; // A new query of the cohort starts from nothing on screen: what was there belongs to the previous one. if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); } this.applied = q; - this.consultas.next({ q, etiqueta, refrescar }); + this.consultas.next({ q, etiqueta }); } - // Leaving the analysis' selection returns to the whole cohort (the habitual list), not to another source. + // Leaving the analysis' selection returns to the habitual list: the regular window, no filters, the cohort's new revision. quitarSeleccion() { - this.draft = { ...this.draft, meses: this.contextoActivo ? 0 : 3, filtros: {} }; - this.activa = undefined; + this.draft = { ...this.draft, meses: 3, filtros: {} }; + this.activa = undefined; this.contextoActivo = undefined; this.aplicar(); } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } - // A retry repeats the query as it was; one that failed before the cohort's revision was known asks for it again first. - reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.sinCohorte && !this.applied.contexto }); } + reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index c32f06c..1b537dc 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -6,7 +6,7 @@
@if (dominio !== 'cama') {

Seguimiento de {{ domainLabel }}

} @if (dominio === 'cama') { - } @else if (dominio !== 'cacu') {

El seguimiento aún no está disponible.

diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index e7a9637..f523b2f 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -122,7 +122,7 @@ export function etiquetarCohorte(r: SeguimientoTablaResponse): SeguimientoTablaR }), }; } -const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true }; +const ETIQUETADAS: Readonly> = { birads: true, grupo_edad: true, biopsia: true }; @Injectable({ providedIn: 'root' }) export class SeguimientoTablaService { From 3783505dbdbbda340560f78d5b77d8707fd91bd4 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 15:44:01 -0600 Subject: [PATCH 32/38] Use the regular window for breast follow-up --- .../indicadores-initial-integration.spec.ts | 4 - .../indicadores/indicadores-sections.spec.ts | 7 +- .../indicadores-seguimiento-cohorte.spec.ts | 165 +++++++++--------- .../indicadores-seguimiento-ficha.spec.ts | 7 +- .../indicadores-seguimiento-seleccion.spec.ts | 13 +- .../indicadores-seguimiento-tabla.ts | 76 +++----- .../indicadores/indicadores-tracking.html | 2 +- 7 files changed, 117 insertions(+), 157 deletions(-) diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 34bef33..267d869 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -84,8 +84,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid const ongoing = request(periods[0]); for (const section of ['seguimiento', 'datos', 'resumen', 'datos'] as const) { page.changeSection(section); fixture.detectChanges(); - // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. - for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.initialPeriodState()).toBe('loading'); expect(ongoing.cancelled).toBe(false); @@ -106,8 +104,6 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid editor().select([periods[2]]); fixture.detectChanges(); for (let i = 0; i < 3; i++) for (const section of ['seguimiento', 'datos', 'resumen'] as const) { page.changeSection(section); fixture.detectChanges(); - // Seguimiento of breast cancer asks for the cohort's revision first; without the cohort published it reads the plain list. - for (const req of http.match(r => r.url.endsWith('/analisis/indicadores'))) req.flush({}, { status: 404, statusText: 'Pending' }); for (const req of http.match(r => r.url.endsWith('/seguimiento'))) req.flush({}, { status: 404, statusText: 'Pending' }); expect(page.filters).toBe(state); expect(page.filters!.applied).toBe(applied); expect(editor().selectedPeriods).toEqual([periods[2]]); diff --git a/src/app/features/indicadores/indicadores-sections.spec.ts b/src/app/features/indicadores/indicadores-sections.spec.ts index 272ed9b..9509c7e 100644 --- a/src/app/features/indicadores/indicadores-sections.spec.ts +++ b/src/app/features/indicadores/indicadores-sections.spec.ts @@ -55,20 +55,17 @@ describe('Secciones compartidas por dominio', () => { pestana('seguimiento').click(); harness.detectChanges(); // CaCu and CaMa request their own follow-up when the tab opens; the lab WebApi has neither yet (404). if (domain !== 'tea') { - // CaMa asks for the cohort's revision first and reads the plain list when the cohort is not published. - if (domain === 'cama') { http.expectOne(r => r.url === '/cama/analisis/indicadores').flush({}, { status: 404, statusText: 'Pending' }); } http.expectOne(r => r.url === '/' + domain + '/seguimiento').flush({}, { status: 404, statusText: 'Pending' }); harness.detectChanges(); } const tracking = root.querySelector('#panel-seguimiento')!; expect(tracking.hidden).toBe(false); - expect(tracking.textContent).toContain('El seguimiento aún no está disponible'); + expect(tracking.textContent).toContain(domain === 'cama' ? 'La cohorte no está disponible' : 'El seguimiento aún no está disponible'); if (domain === 'cacu') { expect(tracking.querySelector('tbody')).toBeNull(); expect(tracking.querySelector('input[type=date]')).not.toBeNull(); } else if (domain === 'cama') { - // Pending integration: the form is gone with no table, and the retry is offered. - expect(tracking.textContent).toContain('Funcionalidad pendiente de publicación'); + // An unavailable cohort has no table and offers a retry. expect(tracking.querySelector('table')).toBeNull(); expect(tracking.querySelector('app-seguimiento-tabla')).not.toBeNull(); expect(Array.from(tracking.querySelectorAll('button')).map(b => b.textContent?.trim())).toContain('Reintentar seguimiento'); diff --git a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts index 4d22e84..a96a7d3 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-cohorte.spec.ts @@ -1,28 +1,27 @@ -// Covers the habitual access to Seguimiento of breast cancer: the list is read from the cohort the analysis publishes -// (its revision first, then the whole cohort at the cut-off), fails closed when the cohort is unavailable, asks for the -// revision again when the cut-off changes or the cohort changes under the list, and keeps the -// filters, the cut-off and the page while the record is opened and closed. Fixtures: indicadores-analisis.testing.ts. +// Covers the habitual access to Seguimiento of breast cancer: the list opens on the regular window and, when the server +// answers from the cohort, adopts the cohort and its revision for the next pages and the files; a cut-off or a changed +// revision is asked for without the old revision; and the filters, the cut-off, the page and the rows are kept while the +// record is opened and closed. Fixtures: indicadores-analisis.testing.ts (listaCohorte) and fixtures/cama_seguimiento.json. import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; -import { agregadoJson, CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; -import { hoyIso } from './indicadores-analisis.service'; +import fixtureData from './fixtures/cama_seguimiento.json'; +import { CONTEXTO, CORTE, listaCohorte, REVISION } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; const OTRA = 'a'.repeat(64); +const base = () => structuredClone(fixtureData) as unknown as Record; -describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { +describe('Seguimiento de CaMa: acceso habitual', () => { let fixture: ReturnType>, http: HttpTestingController; - const hoy = hoyIso(); beforeEach(() => { TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); - fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', false); fixture.detectChanges(); + fixture.componentRef.setInput('active', false); fixture.detectChanges(); }); afterEach(() => { fixture.destroy(); http.verify(); }); const root = () => fixture.nativeElement as HTMLElement; - const agregado = (corte = hoy) => http.expectOne(r => r.url === '/cama/analisis/indicadores' && r.params.get('corte') === corte); const lista = () => http.expectOne(r => r.url === '/cama/seguimiento'); const parametros = (r: TestRequest) => Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); } @@ -36,120 +35,128 @@ describe('Seguimiento de CaMa: acceso habitual desde la cohorte', () => { async function elegir(etiqueta: string, valor: string) { const s = campo(etiqueta).querySelector('select')!; s.value = [...s.options].find(o => o.text.trim() === valor)!.value; s.dispatchEvent(new Event('change')); await asentar(); } - // The cohort's answer opens the list on the whole cohort. - async function abierta(corte = hoy) { - abrir(); agregado(corte).flush(agregadoJson({ corte })); - lista().flush(listaCohorte({ corte, n: 27 })); await asentar(); + // The list opens on the regular window of 3 months and the cohort answers with its revision. + async function abierta(extra: Parameters[0] = {}) { + abrir(); lista().flush(listaCohorte({ meses: 3, n: 27, ...extra })); await asentar(); } - it('al abrir pide la revisión de la cohorte a la fecha de hoy y luego toda la cohorte citándola, sin banner de selección', async () => { - // Fails if the habitual access still reads another source, opens on a window of months, or shows an analysis banner. + it.each([404, 503])('informa que la cohorte no está disponible ante %s y no cambia de fuente', async status => { + // Fails if an unavailable source is reported as an empty list or another source is queried. + abrir(); lista().flush({ error: 'x' }, { status, statusText: 'Unavailable' }); await asentar(); + expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte no está disponible'); + http.expectNone(r => r.url === '/cama/seguimiento'); + }); + + it('abre en la ventana habitual de 3 meses sin citar ninguna revisión, y adopta la cohorte que el servidor devuelve', async () => { + // Fails if the habitual access asks for another window, or needs a revision it cannot have yet, or shows an analysis banner. http.expectNone(() => true); abrir(); - agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); const r = lista(); - expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: hoy, ...CONTEXTO }); - r.flush(listaCohorte({ corte: hoy, n: 27 })); await asentar(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50' }); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10 })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses', 'Toda la cohorte']); - expect(root().textContent).toContain(`Ventana consultada: Toda la cohorte, al ${hoy}.`); - expect(root().querySelectorAll('tbody tr')).toHaveLength(27); - expect(root().querySelector('app-seguimiento-exportar')).not.toBeNull(); - expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); + expect(root().textContent).toContain('Ventana consultada: 2025-02-01 al 2026-10-20.'); + // The next page quotes the cohort the first answer named, with the same window and cut-off. + boton('Siguiente')!.click(); fixture.detectChanges(); + const p2 = lista(); + expect(parametros(p2)).toEqual({ meses: '3', page: '2', page_size: '10', corte: CORTE, ...CONTEXTO }); + p2.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2 })); await asentar(); + expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); }); - it('si la cohorte no está disponible (404 o 503), informa el error sin cambiar de fuente', async () => { - // Fails if an unavailable cohort can silently broaden or replace the population. - for (const status of [404, 503]) { - TestBed.resetTestingModule(); - TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); - fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); - fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('cohorte', true); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - agregado().flush({ error: 'x' }, { status, statusText: 'x' }); fixture.detectChanges(); - await asentar(); - http.expectNone(r => r.url === '/cama/seguimiento'); - expect(root().querySelector('[role=alert]')?.textContent, String(status)).toContain('La cohorte no está disponible'); - http.verify(); - } + it('«Toda la cohorte» pide la ventana 0 citando la cohorte', async () => { + // Fails if the whole cohort is asked for without the revision the server requires for it. + await abierta(); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + const r = lista(); + expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 0, n: 43 })); await asentar(); + expect(root().textContent).toContain('Ventana consultada: Toda la cohorte, al 2026-10-20.'); + expect(root().querySelector('nav')?.textContent).toContain('43 registros'); }); - it('un error del agregado se dice y el reintento vuelve a pedir la revisión', async () => { - // Fails if a failing aggregate leaves a blank list or the retry reads the list without a revision. - abrir(); - agregado().flush('detalle interno', { status: 500, statusText: 'Error' }); await asentar(); - expect(root().querySelector('[role=alert]')?.textContent).toContain('No se pudo consultar el seguimiento'); - expect(root().textContent).not.toContain('detalle interno'); - boton('Reintentar seguimiento')!.click(); fixture.detectChanges(); - http.expectNone(r => r.url === '/cama/seguimiento'); - // the retry repeats the query as it was: with the revision asked for first - agregado(); + it('un servidor sin cohorte responde la lista de siempre: sin «Toda la cohorte» y sin citar nada', async () => { + // Fails if a deployment without the cohort provider loses its follow-up list or is sent parameters it does not know. + abrir(); lista().flush(base()); await asentar(); + expect(ventanas()).toEqual(['1 mes', '3 meses', '6 meses', '12 meses']); + boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).not.toHaveProperty('revision'); }); - it('si el usuario cambia el corte, pide la revisión de ese corte antes de la lista y la cita', async () => { + it('si el usuario cambia el corte, la consulta no cita la revisión del corte anterior y adopta la nueva', async () => { // Fails if a list at another cut-off is asked for with the revision of the previous one. await abierta(); await escribir('corte', '2026-09-01'); boton('Consultar')!.click(); fixture.detectChanges(); - agregado('2026-09-01').flush(agregadoJson({ corte: '2026-09-01', revision: OTRA })); fixture.detectChanges(); const r = lista(); - expect(parametros(r)).toMatchObject({ corte: '2026-09-01', revision: OTRA, meses: '0' }); - r.flush(listaCohorte({ corte: '2026-09-01', n: 27, revision: OTRA })); await asentar(); - expect(root().querySelectorAll('tbody tr')).toHaveLength(27); - }); - it('si la cohorte cambia bajo la lista (409), pide la revisión de nuevo una vez y repite la misma consulta; un segundo 409 sí se dice', async () => { - // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. - await abierta(); + expect(parametros(r)).toMatchObject({ corte: '2026-09-01', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, corte: '2026-09-01', revision: OTRA })); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); + expect(parametros(lista())).toMatchObject({ corte: '2026-09-01', revision: OTRA }); + }); + it('si la cohorte cambia bajo la lista (409), repite la misma consulta una vez sin la revisión vieja; un segundo 409 sí se dice', async () => { + // Fails if the user is told to start again for a change the page can absorb, or a persistent conflict loops. + await abierta({ size: 10 }); + boton('Siguiente')!.click(); fixture.detectChanges(); lista().flush({ error: 'La cohorte cambió' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); - agregado(hoy).flush(agregadoJson({ corte: hoy, revision: OTRA })); fixture.detectChanges(); - let r = lista(); - expect(parametros(r)).toMatchObject({ revision: OTRA, corte: hoy }); - r.flush(listaCohorte({ corte: hoy, n: 27, revision: OTRA })); await asentar(); + const r = lista(); + expect(parametros(r)).toMatchObject({ page: '2', meses: '3' }); + expect(parametros(r)).not.toHaveProperty('revision'); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, revision: OTRA })); await asentar(); expect(root().querySelector('[role=alert]')).toBeNull(); // A conflict that persists is reported, not retried forever. boton('Consultar')!.click(); fixture.detectChanges(); lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); fixture.detectChanges(); - agregado(hoy).flush(agregadoJson({ corte: hoy, revision: REVISION })); fixture.detectChanges(); - r = lista(); r.flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); + lista().flush({ error: 'x' }, { status: 409, statusText: 'Conflict' }); await asentar(); expect(root().querySelector('[role=alert]')?.textContent).toContain('La cohorte cambió desde que se calculó el análisis'); expect(root().querySelector('table')).toBeNull(); }); it('una cohorte sin pacientes al corte lo dice; con filtros o con una ventana de meses, el texto es el de los filtros', async () => { - // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow filter as an empty cohort. - abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 0 })); await asentar(); + // Fails if an empty whole cohort is reported as a filter that matched nothing, or a narrow window as an empty cohort. + await abierta({ n: 0 }); + expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); + await elegir('Ventana de meses', 'Toda la cohorte'); boton('Consultar')!.click(); fixture.detectChanges(); + lista().flush(listaCohorte({ meses: 0, n: 0 })); await asentar(); expect(root().querySelector('tbody')?.textContent).toContain('Sin pacientes para el corte seleccionado.'); expect([...root().querySelectorAll('app-seguimiento-exportar button')].filter(b => b.textContent!.includes('Exportar')).every(b => (b as HTMLButtonElement).disabled)).toBe(true); await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); + lista().flush(listaCohorte({ meses: 0, n: 0, filtros: { grupo_edad: '50-59' } })); await asentar(); expect(root().querySelector('tbody')?.textContent).toContain('No hay registros para los filtros aplicados.'); }); it('abrir la ficha y regresar conserva los filtros elegidos, el corte, la página y la lista', async () => { // Fails if opening the record resets the form, the page or the rows the user was reading. - abrir(); agregado().flush(agregadoJson({ corte: hoy })); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10 })); await asentar(); + await abierta({ size: 10 }); await elegir('Grupo de edad', '50 a 59 años'); boton('Consultar')!.click(); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: hoy, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); + lista().flush(listaCohorte({ meses: 3, n: 27, size: 10, filtros: { grupo_edad: '50-59' } })); await asentar(); boton('Siguiente')!.click(); fixture.detectChanges(); - const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: hoy, ...CONTEXTO }); - r.flush(listaCohorte({ corte: hoy, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); + const r = lista(); expect(parametros(r)).toMatchObject({ page: '2', grupo_edad: '50-59', corte: CORTE, ...CONTEXTO }); + r.flush(listaCohorte({ meses: 3, n: 27, size: 10, page: 2, filtros: { grupo_edad: '50-59' } })); await asentar(); const filasAntes = [...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim()); (root().querySelector('.patient-link') as HTMLButtonElement).click(); await asentar(); - expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${hoy}.`); + expect(root().querySelector('app-cama-patient-card')?.textContent).toContain(`Fecha de corte: ${CORTE}.`); ([...root().querySelectorAll('button')].find(b => b.textContent!.includes('Regresar')) as HTMLButtonElement).click(); await asentar(); http.expectNone(() => true); expect([...root().querySelectorAll('tbody tr')].map(tr => tr.querySelector('td')!.textContent!.trim())).toEqual(filasAntes); expect(root().querySelector('nav')?.textContent).toContain('Página 2 de 3'); const edad = campo('Grupo de edad').querySelector('select') as HTMLSelectElement; expect(edad.options[edad.selectedIndex].text.trim()).toBe('50 a 59 años'); - expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(hoy); + expect((root().querySelector('input[name="corte"]') as HTMLInputElement).value).toBe(CORTE); }); - it('con una selección del análisis, «Quitar selección» regresa a este mismo acceso habitual', async () => { - // Fails if leaving the selection drops the user into a different source than the one the tab opens on. - abrir(); agregado().flush(agregadoJson({ corte: CORTE })); lista().flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); - fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 27, contexto: CONTEXTO, id: 1 }); + it('con una selección del análisis, «Quitar selección» regresa a la lista habitual: 3 meses, sin filtros ni revisión citada', async () => { + // Fails if leaving the selection keeps its filter, its window or the old revision. + await abierta(); + fixture.componentRef.setInput('seleccion', { filtros: { birads: 'BIRADS_5' }, etiqueta: 'Categoría BI-RADS: BI-RADS 5', corte: CORTE, esperados: 43, contexto: { ...CONTEXTO, revision: REVISION }, id: 1 }); fixture.detectChanges(); - lista().flush(listaCohorte({ corte: CORTE, n: 27, filtros: { birads: 'BIRADS_5' } })); await asentar(); + lista().flush(listaCohorte({ meses: 0, n: 43, filtros: { birads: 'BIRADS_5' } })); await asentar(); expect(root().querySelector('.seleccion')).not.toBeNull(); boton('Quitar selección')!.click(); fixture.detectChanges(); - const r = lista(); expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); - r.flush(listaCohorte({ corte: CORTE, n: 27 })); await asentar(); + const r = lista(); expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(listaCohorte({ meses: 3, n: 27 })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); }); + it('la biopsia se escribe con las etiquetas del catálogo y un valor desconocido queda como llegó', async () => { + // Fails if a source code is remapped to a diagnosis the catalog does not name, or the code is lost. + abrir(); + const r = listaCohorte({ meses: 3, n: 4 }); const v = ['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'OTRO_VALOR']; r['items'].forEach((i: any, k: number) => { i['biopsia'] = v[k]; }); + lista().flush(r); await asentar(); + expect([...root().querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.replace(/\s+/g, ' ').trim().split(' Fecha')[0])).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'OTRO_VALOR']); + }); }); diff --git a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts index 8575131..f6ab443 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-ficha.spec.ts @@ -5,8 +5,6 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; -import { agregadoJson, listaCohorte } from './indicadores-analisis.testing'; -import { hoyIso } from './indicadores-analisis.service'; import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; import { IndicadoresTracking } from './indicadores-tracking'; @@ -110,10 +108,7 @@ describe('Seguimiento: ficha de CaMa y cambio de dominio', () => { fixture.componentInstance.fichaPacienteAbierta.subscribe(v => abierta.push(v)); fixture.componentRef.setInput('domainLabel', 'cáncer de mama'); fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); - // The record is opened from the same cohort that the analysis publishes. - const corte = hoyIso(); - http.expectOne(r => r.url === '/cama/analisis/indicadores').flush(agregadoJson({ corte })); - http.expectOne(r => r.url === '/cama/seguimiento').flush(listaCohorte({ corte, n: 6 })); + http.expectOne(r => r.url === '/cama/seguimiento').flush(pagina()); await fixture.whenStable(); fixture.detectChanges(); (fixture.nativeElement as HTMLElement).querySelector('.patient-link')!.click(); await fixture.whenStable(); fixture.detectChanges(); diff --git a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts index 2f00a32..7691581 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-seleccion.spec.ts @@ -6,7 +6,7 @@ import { TestBed } from '@angular/core/testing'; import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, TestRequest, provideHttpClientTesting } from '@angular/common/http/testing'; import fixtureData from './fixtures/cama_seguimiento.json'; -import { agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing'; +import { CONTEXTO, CORTE } from './indicadores-analisis.testing'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; const base = () => structuredClone(fixtureData) as unknown as Record; @@ -118,8 +118,6 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { const c = root().querySelector('input[name="corte"]') as HTMLInputElement; c.value = `2026-01-0${status === 403 ? 1 : status === 409 ? 2 : 3}`; c.dispatchEvent(new Event('input')); await asentar(); boton('Consultar')!.click(); fixture.detectChanges(); - // Another cut-off is another cohort at that date: its revision is asked for first. - http.expectOne(a => a.url === '/cama/analisis/indicadores' && a.params.get('corte') === c.value).flush(agregadoJson({ corte: c.value })); fixture.detectChanges(); const r = solicitud(); expect(r.request.params.get('corte'), String(status)).toBe(c.value); r.flush({ error: 'detalle interno' }, { status, statusText: 'x' }); await asentar(); @@ -195,17 +193,16 @@ describe('Seguimiento de CaMa abierto desde el análisis', () => { expect(root().querySelector('.diferencia')).toBeNull(); expect(ventanas()).toContain('Toda la cohorte'); }); - it('«Quitar selección» vuelve a la cohorte completa, sin filtros ni nombre, y sigue citando su revisión', async () => { - // Fails if removing the selection leaves its filter behind, or leaves the cohort for another source. + it('«Quitar selección» vuelve a la lista habitual: 3 meses, sin filtros ni nombre, y sin citar la revisión anterior', async () => { + // Fails if removing the selection leaves its filter, the whole-cohort window or the old revision behind. abrirCon(seleccion(1)); solicitud().flush(cohorte({ birads: 'BIRADS_5' })); await asentar(); boton('Quitar selección')!.click(); fixture.detectChanges(); const r = solicitud(); - expect(parametros(r)).toEqual({ meses: '0', page: '1', page_size: '50', corte: CORTE, ...CONTEXTO }); - r.flush(cohorte({})); await asentar(); + expect(parametros(r)).toEqual({ meses: '3', page: '1', page_size: '50', corte: CORTE }); + r.flush(cohorte({}, 1, 50, { ventana: { meses: 3, desde: '2026-07-21', hasta: CORTE } })); await asentar(); expect(root().querySelector('.seleccion')).toBeNull(); expect(fixture.componentInstance.etiquetaDatos()).toBeUndefined(); - expect(ventanas()).toContain('Toda la cohorte'); expect(exportar()).not.toBeNull(); }); it('al cambiar de dominio la selección y la cohorte se limpian con la lista', async () => { diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index 0b454fa..a63cde9 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -4,22 +4,18 @@ import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio } from './indicadores.models'; -import { AnalisisService, hoyIso } from './indicadores-analisis.service'; import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; import { - consultaAplicada, contextoDe, ContextoLista, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, + consultaAplicada, ContextoLista, contextoDe, etiquetaVentana, MESES_VENTANA, MesesVentana, PAGE_SIZE_MAX, SeguimientoColumna, SeguimientoInvalido, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, SeguimientoValor, } from './seguimiento-tabla.service'; type Estado = 'idle' | 'loading' | 'ready' | 'pending' | 'error'; type Resultado = { estado: Estado; data?: SeguimientoTablaResponse; mensaje: string; etiqueta?: string; estatus?: number }; -/** - * A request with the name of the selection it belongs to, so the answer and its name can never be told apart. - * `refrescar`: the cohort's revision is asked for first (at the query's cut-off, or today's), because the list is read from the cohort. - */ -type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string; refrescar?: boolean; reintento?: boolean }; +/** A request with the name of the selection it belongs to, so the answer and its name can never be told apart. */ +type Consulta = { q: SeguimientoTablaQuery; etiqueta?: string }; // What the analysis sends: the whole published group, the cut-off it was computed at, the cohort (and its revision) the // list must quote back, how to name it, how many patients the analysis counts there and an id that changes with each click. export interface SeleccionSeguimiento { @@ -154,13 +150,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { @Input() domainLabel = ''; // The patients of a curve or a heatmap cell of the analysis; a new `id` applies it again. @Input() seleccion?: SeleccionSeguimiento; - /** - * Read the list from the cohort the analysis publishes (the agreed contract): the cohort's revision is asked for, then the whole - * cohort is listed at the cut-off. An unavailable cohort is reported without switching sources. - */ - @Input() cohorte = false; private readonly service = inject(SeguimientoTablaService); - private readonly analisis = inject(AnalisisService); private readonly injector = inject(Injector); /** Tells the page that an individual record replaced the list, so it can retitle itself. */ readonly fichaAbierta = output(); @@ -206,9 +196,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return `El análisis cuenta ${esperados} pacientes en esta selección y la lista muestra ${total}. No coinciden, por lo que este resultado no se puede exportar.`; } - // The cut-off the cohort's revision was asked at: another cut-off needs another revision. + // The cut-off of the cohort's revision: another cut-off is another cohort at that date, so its revision is not quoted. private contextoCorte?: string; - // A cohort that changed under a plain list is read again once, with its new revision, before it is reported. + // A cohort that changed under a plain list is read again once, without the old revision, before it is reported. private reintentoHecho = false; /** The list of one query, as the server answers it (without the loading state). */ @@ -227,37 +217,18 @@ export class IndicadoresSeguimientoTabla implements OnChanges { catchError(error => of(this.fallo(error, q)))); } - /** The query with the cohort's revision at its cut-off (today's when none). */ - private refrescar(c: Consulta): Observable { - let agregado; - try { agregado = this.analisis.agregado(this.dominio, c.q.corte || hoyIso()); } catch { return of({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); } - return agregado.pipe( - map((a): Consulta => { - this.contextoActivo = { cohorte: a.cohorte, escenario: a.escenario, revision: a.revision }; this.contextoCorte = a.corte; - return { ...c, refrescar: false, q: { ...c.q, corte: a.corte, contexto: this.contextoActivo } }; - }), - catchError((error): Observable => { - if (error instanceof HttpErrorResponse && (error.status === 404 || error.status === 503)) - return of({ estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }); - return of(this.fallo(error, c.q)); - })); - } - constructor() { this.consultas.pipe( switchMap((c): Observable => { if (!c) return of({ estado: 'idle', mensaje: '' }); - const preparada = c.refrescar ? this.refrescar(c) : of(c); - return preparada.pipe( - switchMap(x => 'estado' in x ? of(x) : this.lista(x)), - startWith({ estado: 'loading', mensaje: '' })); + return this.lista(c).pipe(startWith({ estado: 'loading', mensaje: '' })); }), takeUntilDestroyed(inject(DestroyRef)), ).subscribe(r => { - // The cohort changed under a plain list: the revision is asked for again, once, before the user hears of it. + // The cohort changed under a plain list: the same query is asked again, once, without the old revision, before the user hears of it. if (r.estatus === 409 && !this.activa && this.contextoActivo && !this.reintentoHecho) { this.reintentoHecho = true; - this.consultas.next({ q: { ...this.applied, contexto: undefined }, refrescar: true, etiqueta: this.appliedEtiqueta }); + this.consultas.next({ q: { ...this.applied, contexto: undefined }, etiqueta: this.appliedEtiqueta }); return; } if (r.estado === 'ready') this.reintentoHecho = false; @@ -294,11 +265,7 @@ export class IndicadoresSeguimientoTabla implements OnChanges { } if (this.active && !this.iniciado) { this.iniciado = true; - if (this.cohorte) { - // The habitual access: the whole cohort at today's cut-off, with the revision the server publishes for it. - this.draft = { ...this.draft, meses: 0 }; this.applied = { meses: 0, page: 1, page_size: this.applied.page_size }; - this.consultas.next({ q: this.applied, refrescar: true }); - } else this.consultas.next({ q: this.applied }); + this.consultas.next({ q: this.applied }); } } @@ -306,8 +273,8 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return { ...this.falloBase(error, q), estatus: error instanceof HttpErrorResponse ? error.status : undefined }; } private falloBase(error: unknown, q: SeguimientoTablaQuery): Resultado { + if (error instanceof HttpErrorResponse && error.status === 404 && this.dominio === 'cama') return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }; // A first page that does not exist yet is the list's own pending state; a later page that fails is an error. - if (error instanceof HttpErrorResponse && error.status === 404 && this.cohorte) return { estado: 'error', mensaje: 'La cohorte no está disponible en este momento. Intenta nuevamente más tarde.' }; if (error instanceof HttpErrorResponse && error.status === 404 && q.page === 1) return { estado: 'pending', mensaje: '' }; if (error instanceof HttpErrorResponse && error.status === 400) return { estado: 'error', mensaje: 'Revisa la fecha, la ventana y los filtros seleccionados.' }; // A cohort's list: the group was too small to publish or access was not granted; the cohort changed after the count; or it is not configured. @@ -324,9 +291,11 @@ export class IndicadoresSeguimientoTabla implements OnChanges { const claves = new Set(data.filtros_disponibles.map(f => f.clave)); this.draft = { ...this.draft, corte: data.corte, filtros: Object.fromEntries(Object.entries(this.draft.filtros).filter(([k]) => claves.has(k))) }; this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, page: data.paginacion.page, page_size: data.paginacion.page_size, - filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])), - contexto: contextoDe(data) }; + filtros: Object.fromEntries(Object.entries(data.filtros).filter(([, v]) => v !== null).map(([k, v]) => [k, v as string])) }; this.draft.meses = data.ventana.meses; this.draft.page_size = data.paginacion.page_size; + // A list read from the cohort says which one (and its revision): the next pages and the files quote it. + this.contextoActivo = contextoDe(data); this.contextoCorte = data.corte; + this.applied = { ...this.applied, contexto: this.contextoActivo }; } // The form applies what it holds. The banner stays only while that is still the analysis' selection, whole cohort // included; anything else is the user's own query, with a window of months. @@ -342,24 +311,23 @@ export class IndicadoresSeguimientoTabla implements OnChanges { this.seleccionExacta.set(!!etiqueta && exacta); this.corteSeleccion.set(etiqueta ? this.draft.corte || activa?.corte : undefined); this.appliedEtiqueta = etiqueta; - // Another cut-off is another cohort at that date: its revision is asked for before the list. - const refrescar = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; + // Another cut-off is another cohort at that date: its revision is not quoted, the answer brings the new one. + const otroCorte = !!contexto && !seleccion && !!this.draft.corte && this.draft.corte !== this.contextoCorte; const q: SeguimientoTablaQuery = { corte: this.draft.corte || undefined, meses: this.draft.meses, page: 1, page_size: Number(this.draft.page_size), filtros, - contexto: refrescar ? undefined : contexto }; + contexto: otroCorte ? undefined : contexto }; // A new query of the cohort starts from nothing on screen: what was there belongs to the previous one. if (contexto) { this.data.set(undefined); this.etiquetaDatos.set(undefined); } this.applied = q; - this.consultas.next({ q, etiqueta, refrescar }); + this.consultas.next({ q, etiqueta }); } - // Leaving the analysis' selection returns to the whole cohort (the habitual list), not to another source. + // Leaving the analysis' selection returns to the habitual list: the regular window, no filters, the cohort's new revision. quitarSeleccion() { - this.draft = { ...this.draft, meses: this.contextoActivo ? 0 : 3, filtros: {} }; - this.activa = undefined; + this.draft = { ...this.draft, meses: 3, filtros: {} }; + this.activa = undefined; this.contextoActivo = undefined; this.aplicar(); } ir(page: number) { if (page >= 1) this.consultas.next({ q: this.applied = { ...this.applied, page }, etiqueta: this.appliedEtiqueta }); } - // A retry repeats the query as it was; one that failed before the cohort's revision was known asks for it again first. - reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta, refrescar: this.cohorte && !this.applied.contexto }); } + reintentar() { this.consultas.next({ q: this.applied, etiqueta: this.appliedEtiqueta }); } abrirFicha(item: Record, evento: Event) { const origen = evento.target instanceof HTMLElement ? evento.target : null; // A click on the row opens the record unless it landed on another control; the id button always does. diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index c32f06c..1b537dc 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -6,7 +6,7 @@
@if (dominio !== 'cama') {

Seguimiento de {{ domainLabel }}

} @if (dominio === 'cama') { - } @else if (dominio !== 'cacu') {

El seguimiento aún no está disponible.

From edb868f3727481e57998982c254442e2e6ef24cf Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 11 Nov 2026 23:25:08 -0600 Subject: [PATCH 33/38] Patient record reads its risk from GET /cacu/pacientes//riesgo, by the id the follow-up list shows --- .../paciente-detalle/paciente-detalle.html | 2 +- .../paciente-detalle/paciente-detalle.spec.ts | 5 +++-- .../paciente-registro-integracion.spec.ts | 6 +++-- .../paciente-riesgo-tabla.html | 1 - .../paciente-detalle/paciente-riesgo-tabla.ts | 10 +++++++-- .../paciente-riesgo.models.ts | 4 ++-- .../paciente-riesgo.provider.ts | 16 ++++++++++---- .../paciente-detalle/paciente-riesgo.spec.ts | 14 +++++++----- .../paciente-detalle/paciente-riesgo.state.ts | 22 ++++++++++++------- 9 files changed, 53 insertions(+), 27 deletions(-) diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html index d3d931a..00f6bd0 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html @@ -79,7 +79,7 @@

Riesgos y recomendaciones

- +
} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts index ecd3f67..7f6ad00 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -108,7 +108,8 @@ describe('Ficha individual desde Seguimiento CaCu', () => { let root: HTMLElement; beforeEach(() => { - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), + { provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] }); fixture = TestBed.createComponent(IndicadoresTracking); root = fixture.nativeElement; http = TestBed.inject(HttpTestingController); @@ -247,7 +248,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => { expect(tarjeta.textContent).toContain('Información simulada'); expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3); expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo); - expect(obtener).toHaveBeenCalledExactlyOnceWith(); + expect(obtener).toHaveBeenCalledExactlyOnceWith(pacientes[0].id_seudonimo); volver(); const otra = abrir(1); expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.'); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index dfdb390..853caeb 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -7,12 +7,13 @@ import { MatSelectHarness } from '@angular/material/select/testing'; import { MatInputHarness } from '@angular/material/input/testing'; import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing'; import { MatDialog } from '@angular/material/dialog'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, of } from 'rxjs'; import fixtureData from '../fixtures/cacu_seguimiento.json'; import { seguimientoResponse } from '../cacu-seguimiento.service'; import { IndicadoresTracking } from '../indicadores-tracking'; import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; import { PacienteDetalleState } from './paciente-detalle.state'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { PacienteRegistroDialog } from './paciente-registro-dialog'; import { PacienteRegistrosSesion } from './paciente-registros-sesion'; import { TipoRegistroTemporal } from './paciente-registro.models'; @@ -31,7 +32,8 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { let dialog: MatDialog; beforeEach(() => { - TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }); + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), + { provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: () => of(null) } }] }); http = TestBed.inject(HttpTestingController); dialog = TestBed.inject(MatDialog); montarTracking(); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html index a5e3c7e..faa62eb 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.html @@ -4,7 +4,6 @@ @case ('cargando') {

Cargando riesgo individual…

} @case ('no-disponible') {

Riesgo individual no disponible para esta paciente.

-

La consulta de riesgo individual aún no está habilitada.

} @case ('error') {

No se pudo validar o cargar el riesgo individual.

} @case ('disponible') { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index ed650ff..2b69b01 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -1,4 +1,4 @@ -import { Component, inject } from '@angular/core'; +import { Component, effect, inject, input } from '@angular/core'; import { DecimalPipe } from '@angular/common'; import { PacienteRiesgoState } from './paciente-riesgo.state'; import { tieneIntervalo } from './paciente-riesgo.validation'; @@ -11,6 +11,12 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; styleUrl: './paciente-riesgo-tabla.scss', }) export class PacienteRiesgoTabla { - readonly estado = inject(PacienteRiesgoState).estado; + readonly idSeudonimo = input.required(); + private readonly state = inject(PacienteRiesgoState); + readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; + + constructor() { + effect(() => this.state.idSeudonimo.set(this.idSeudonimo())); + } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 832a217..0ff9cec 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -40,9 +40,9 @@ export interface RiesgoPacienteCacu { riesgo: LoteRiesgoCacu | null; } -/** Deliberately no patient argument until secure identity resolution is authorized. */ +/** `null` when the patient has no risk data. */ export interface PacienteRiesgoProvider { - obtener(): Observable; + obtener(idSeudonimo: string): Observable; } export type PacienteRiesgoEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index c04a30a..70a3092 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -1,8 +1,16 @@ -import { InjectionToken } from '@angular/core'; -import { of } from 'rxjs'; +import { HttpClient, HttpErrorResponse } from '@angular/common/http'; +import { inject, InjectionToken } from '@angular/core'; +import { catchError, of, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; -// No HTTP, fixtures or identity conversion. A real adapter requires separate authorization. +// The follow-up list identifies each patient by the `pac_id` of the risk batches; a 404 is a patient without risk data. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { - providedIn: 'root', factory: () => ({ obtener: () => of(null) }), + providedIn: 'root', factory: () => { + const http = inject(HttpClient); + return { + obtener: (idSeudonimo: string) => http.get(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe( + catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), + ), + }; + }, }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 1cee25a..20caa5f 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -12,6 +12,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); const fixture = TestBed.createComponent(PacienteRiesgoTabla); + fixture.componentRef.setInput('idSeudonimo', '42'); + fixture.detectChanges(); fixture.detectChanges(); return fixture; } @@ -20,14 +22,15 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { TestBed.inject(HttpTestingController).verify(); }); - it('ejecución normal sin fixtures, HTTP, identidad o controles de preview', () => { + it('pide el riesgo por el pac_id de los lotes a la WebApi y trata un 404 como no disponible', () => { const f = setup(), root: HTMLElement = f.nativeElement; + TestBed.inject(HttpTestingController).expectOne('/cacu/pacientes/42/riesgo') + .flush({ error: 'no existe' }, { status: 404, statusText: 'Not Found' }); + f.detectChanges(); expect(root.textContent).toContain('Riesgo individual no disponible para esta paciente.'); - expect(root.textContent).toContain('aún no está habilitada'); expect(root.textContent).toContain('Recomendaciones no disponibles'); expect(root.textContent).not.toMatch(/simulad|ilustrativ|modelo-cacu|CIN3|2\.4|6\.8/); expect(root.querySelectorAll('table, button, input, select, a')).toHaveLength(0); - TestBed.inject(PACIENTE_RIESGO_PROVIDER).obtener().subscribe(v => expect(v).toBeNull()); }); it('renderiza el ejemplo contractual, estados, metadatos y porcentajes sin alterar los datos', () => { @@ -35,7 +38,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { data.riesgo!.horizontes[1].estado = 'preliminary'; const baseline = structuredClone(data); const f = setup({ obtener }), root: HTMLElement = f.nativeElement; - expect(obtener).toHaveBeenCalledExactlyOnceWith(); + expect(obtener).toHaveBeenCalledExactlyOnceWith('42'); expect(root.querySelectorAll('thead th')).toHaveLength(4); expect([...root.querySelectorAll('thead th')].every(th => th.getAttribute('scope') === 'col')).toBe(true); expect(root.querySelectorAll('tbody th[scope="row"]')).toHaveLength(3); @@ -134,7 +137,8 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { data.riesgo!.horizontes[0].probabilidad = 1; f.detectChanges(); expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); f.destroy(); - const otra = TestBed.createComponent(PacienteRiesgoTabla); otra.detectChanges(); + const otra = TestBed.createComponent(PacienteRiesgoTabla); + otra.componentRef.setInput('idSeudonimo', 'P-OTRA'); otra.detectChanges(); expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(otra.nativeElement.querySelector('table')).toBeNull(); expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 5a109fa..9a9e868 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -1,16 +1,22 @@ -import { inject, Injectable } from '@angular/core'; -import { toSignal } from '@angular/core/rxjs-interop'; -import { catchError, defer, map, of } from 'rxjs'; +import { Injectable, inject, signal } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { catchError, defer, map, of, startWith, switchMap } from 'rxjs'; import { PacienteRiesgoEstado } from './paciente-riesgo.models'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { riesgoPacienteResponse } from './paciente-riesgo.validation'; +const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' }; + @Injectable() export class PacienteRiesgoState { private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); - readonly estado = toSignal(defer(() => this.provider.obtener()).pipe( - map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } - : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), - catchError(() => of({ tipo: 'error' })), - ), { initialValue: { tipo: 'cargando' } as PacienteRiesgoEstado }); + readonly idSeudonimo = signal(null); + readonly estado = toSignal(toObservable(this.idSeudonimo).pipe( + switchMap(id => id === null ? of(CARGANDO) : defer(() => this.provider.obtener(id)).pipe( + map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } + : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), + catchError(() => of({ tipo: 'error' })), + startWith(CARGANDO), + )), + ), { initialValue: CARGANDO }); } From caf5f954b7ba99a63be269e2225334c7e8b9b145 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 18:19:26 -0600 Subject: [PATCH 34/38] Proxy patient routes without the cohort access token --- Dockerfile | 3 +-- nginx.conf | 3 --- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index c559aef..2b54235 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,7 +7,6 @@ COPY . . RUN npx ng build --configuration production FROM nginx:1.27-alpine -ENV CAMA_COHORT_ACCESS_TOKEN="" -COPY nginx.conf /etc/nginx/templates/default.conf.template +COPY nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/dist/WebApp/browser /usr/share/nginx/html EXPOSE 80 diff --git a/nginx.conf b/nginx.conf index 30dc742..4c46b13 100644 --- a/nginx.conf +++ b/nginx.conf @@ -14,9 +14,6 @@ server { location ~ ^/(api|imports|data|cacu|cama|tea|governance|reportes|health)(/|$) { proxy_pass http://webapi:5000; - # The synthetic cohort token is supplied by the container environment, - # never by the browser. Override any client-supplied header. - proxy_set_header X-Cama-Cohort-Token "${CAMA_COHORT_ACCESS_TOKEN}"; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; From 3b246b4f1f94b4b4259816da5824d8a9a02f2d22 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 18:19:27 -0600 Subject: [PATCH 35/38] Identify follow-up patients by pac_id Rows name their patient with pac_id (a decimal string) or the legacy id_seudonimo. pac_id wins; an invalid pac_id is never replaced by the legacy field, and a page that repeats a patient or mixes both fields is not drawn or exported. The table, patient record, PDF and spreadsheet follow the announced identifier column and label. CaCu requests risk only with a pac_id. --- .../indicadores/cacu-seguimiento.models.ts | 4 +- .../indicadores/cacu-seguimiento.service.ts | 5 +- .../export/tracking-export-source.ts | 5 +- .../indicadores-seguimiento-tabla.ts | 10 +- .../indicadores/indicadores-tracking.html | 8 +- .../indicadores/indicadores-tracking.ts | 5 + .../cama/cama-patient-card.html | 4 +- .../cama/cama-patient-card.spec.ts | 4 +- .../cama/cama-patient-pdf.spec.ts | 2 +- .../paciente-detalle/cama/cama-patient-pdf.ts | 4 +- .../cama/cama-patient.models.ts | 20 +- .../paciente-detalle/paciente-detalle.html | 6 +- .../paciente-detalle.models.ts | 6 +- .../paciente-detalle.provider.ts | 4 +- .../paciente-detalle/paciente-detalle.spec.ts | 28 +-- .../paciente-detalle.state.ts | 15 +- .../paciente-detalle/paciente-detalle.ts | 12 +- .../paciente-registro-dialog.html | 2 +- .../paciente-registro-dialog.ts | 3 +- .../paciente-registro-integracion.spec.ts | 11 +- .../paciente-registro.models.ts | 6 +- .../paciente-registro.spec.ts | 7 +- .../paciente-registros-sesion.ts | 14 +- .../paciente-detalle/paciente-riesgo-tabla.ts | 5 +- .../paciente-riesgo.models.ts | 2 +- .../paciente-riesgo.provider.ts | 4 +- .../paciente-detalle/paciente-riesgo.spec.ts | 4 +- .../paciente-detalle/paciente-riesgo.state.ts | 7 +- .../indicadores/paciente-identidad.spec.ts | 215 ++++++++++++++++++ .../indicadores/paciente-identidad.ts | 54 +++++ .../indicadores/seguimiento-tabla.service.ts | 5 +- 31 files changed, 392 insertions(+), 89 deletions(-) create mode 100644 src/app/features/indicadores/paciente-identidad.spec.ts create mode 100644 src/app/features/indicadores/paciente-identidad.ts diff --git a/src/app/features/indicadores/cacu-seguimiento.models.ts b/src/app/features/indicadores/cacu-seguimiento.models.ts index d6f1b6c..bba0ea8 100644 --- a/src/app/features/indicadores/cacu-seguimiento.models.ts +++ b/src/app/features/indicadores/cacu-seguimiento.models.ts @@ -1,7 +1,9 @@ export interface SeguimientoQuery { corte?: string; meses: 1 | 3 | 6 | 12; estatus?: string; page: number; page_size: number; } export interface SeguimientoStatus { codigo: string; etiqueta: string; } +// A row names its patient with `pac_id` (a decimal string) or the legacy `id_seudonimo`. export interface SeguimientoPaciente { - id_seudonimo: string; + pac_id?: string; + id_seudonimo?: string; grupo_edad: string; estatus: SeguimientoStatus; ultima_citologia: { fecha: string; bethesda: string | null; calidad: string | null } | null; diff --git a/src/app/features/indicadores/cacu-seguimiento.service.ts b/src/app/features/indicadores/cacu-seguimiento.service.ts index a9d9924..53cf2da 100644 --- a/src/app/features/indicadores/cacu-seguimiento.service.ts +++ b/src/app/features/indicadores/cacu-seguimiento.service.ts @@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate, SeguimientoQuery, SeguimientoResponse } from './cacu-seguimiento.models'; +import { identidadDe, identidadesDe } from './paciente-identidad'; const record = (v: unknown): v is Record => !!v && typeof v === 'object' && !Array.isArray(v); const status = (v: unknown) => record(v) && typeof v['codigo'] === 'string' && typeof v['etiqueta'] === 'string'; const integer = (v: unknown, min = 0) => typeof v === 'number' && Number.isSafeInteger(v) && v >= min; @@ -19,12 +20,12 @@ export function seguimientoResponse(v: unknown): SeguimientoResponse { || !Array.isArray(v['reglas']) || !v['reglas'].every(r => record(r) && typeof r['clave'] === 'string' && Object.hasOwn(r, 'valor') && ['provisional','confirmado'].includes(r['estado'] as string)) || !record(p) || !integer(p['page'], 1) || !integer(p['page_size'], 1) || (p['page_size'] as number) > 200 || !integer(p['total_items']) || !integer(p['total_pages']) || !Array.isArray(v['items']) || v['items'].length > (p['page_size'] as number) || !v['items'].every(item => { - if (!record(item) || typeof item['id_seudonimo'] !== 'string' || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; + if (!record(item) || !identidadDe(item) || typeof item['grupo_edad'] !== 'string' || !status(item['estatus'])) return false; const c = item['ultima_citologia'], h = item['ultimo_vph']; return (c === null || record(c) && isoDate(c['fecha']) && (c['bethesda'] === null || typeof c['bethesda'] === 'string') && (c['calidad'] === null || typeof c['calidad'] === 'string')) && (h === null || record(h) && isoDate(h['fecha']) && typeof h['resultado'] === 'string' && (h['genotipo_16_18'] === null || typeof h['genotipo_16_18'] === 'boolean')) && (item['dias_toma_diagnostico'] === null || integer(item['dias_toma_diagnostico'])) && (item['prioridad'] === null || status(item['prioridad'])); - })) throw new Error('Respuesta de seguimiento inválida'); + }) || !identidadesDe(v['items'])) throw new Error('Respuesta de seguimiento inválida'); return v as unknown as SeguimientoResponse; } @Injectable({ providedIn: 'root' }) diff --git a/src/app/features/indicadores/export/tracking-export-source.ts b/src/app/features/indicadores/export/tracking-export-source.ts index a778405..c88b023 100644 --- a/src/app/features/indicadores/export/tracking-export-source.ts +++ b/src/app/features/indicadores/export/tracking-export-source.ts @@ -1,5 +1,6 @@ import { concatWith, defer, from, map, mergeMap, Observable, of, startWith, switchMap, tap } from 'rxjs'; import { Dominio } from '../indicadores.models'; +import { identidadesDe } from '../paciente-identidad'; import { consultaAplicada, contextoDe, PAGE_SIZE_MAX, SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService } from '../seguimiento-tabla.service'; import { ExportInconsistent, ExportLimitExceeded, TrackingExportEvent, TrackingRow } from './tracking-export.models'; @@ -50,8 +51,8 @@ export function fetchAllTracking(service: SeguimientoTablaService, dominio: Domi startWith({ kind: 'progress', fetched: first.items.length, total }), concatWith(defer(() => { const items = [...collected.entries()].sort(([a], [b]) => a - b).flatMap(([, rows]) => rows); - const ids = new Set(items.map(item => item['id_seudonimo'])); - if (items.length !== total || ids.size !== total) throw new ExportInconsistent('The pages do not add up to the announced total'); + // Every row has the identity the table shows, and no patient (or episode) appears on two pages. + if (items.length !== total || !identidadesDe(items)) throw new ExportInconsistent('The pages do not add up to the announced total'); return of({ kind: 'done', snapshot: { corte: first.corte, ventana: first.ventana, filtros: first.filtros, filtros_disponibles: first.filtros_disponibles, columnas: first.columnas, items }, diff --git a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts index a63cde9..db63208 100644 --- a/src/app/features/indicadores/indicadores-seguimiento-tabla.ts +++ b/src/app/features/indicadores/indicadores-seguimiento-tabla.ts @@ -4,6 +4,7 @@ import { HttpErrorResponse } from '@angular/common/http'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { Dominio } from './indicadores.models'; +import { columnaEnlace, IdentidadPaciente, identidadDe } from './paciente-identidad'; import { TrackingExportBar } from './export/tracking-export-bar'; import { CamaPatientCard } from './paciente-detalle/cama/cama-patient-card'; import { CamaPatientSummary, toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models'; @@ -95,10 +96,10 @@ const mismosFiltros = (a: Record, b: RecordResultados disponibles por paciente @for (c of respuesta.columnas; track c.clave) { {{ c.etiqueta }} } - @for (item of respuesta.items; track item['id_seudonimo']) { - + @for (item of respuesta.items; track identidad(item).id) { + @for (c of respuesta.columnas; track c.clave) { - @if (c.clave === 'id_seudonimo') { } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } } + @if (c.clave === claveEnlace(respuesta, item)) { } @else { {{ texto(item[c.clave]) }} }@for (d of detalles(c); track d.clave) { @if (item[d.clave] !== null && item[d.clave] !== undefined) { {{ d.etiqueta }}: {{ texto(item[d.clave]) }} } } } } @empty { {{ textoVacio(respuesta) }} } @@ -352,6 +353,9 @@ export class IndicadoresSeguimientoTabla implements OnChanges { return r.cohorte && r.ventana.meses === 0 && sinFiltros ? 'Sin pacientes para el corte seleccionado.' : 'No hay registros para los filtros aplicados.'; } detalles(c: SeguimientoColumna) { return c.detalles ?? []; } + // Every row of a shown answer has an identity: the answer is validated before it reaches the view. + identidad(item: Record): IdentidadPaciente { return identidadDe(item)!; } + claveEnlace(r: SeguimientoTablaResponse, item: Record) { return columnaEnlace(r.columnas, this.identidad(item).campo); } texto(v: SeguimientoValor | undefined) { return v === null || v === undefined ? 'No disponible' : String(v); } } diff --git a/src/app/features/indicadores/indicadores-tracking.html b/src/app/features/indicadores/indicadores-tracking.html index 1b537dc..b6c3e8e 100644 --- a/src/app/features/indicadores/indicadores-tracking.html +++ b/src/app/features/indicadores/indicadores-tracking.html @@ -41,11 +41,11 @@
- + - @for (item of response.items; track item.id_seudonimo) { - - + @for (item of response.items; track identidad(item).id) { + + diff --git a/src/app/features/indicadores/indicadores-tracking.ts b/src/app/features/indicadores/indicadores-tracking.ts index 2547a5a..d2c1ae2 100644 --- a/src/app/features/indicadores/indicadores-tracking.ts +++ b/src/app/features/indicadores/indicadores-tracking.ts @@ -10,6 +10,7 @@ import { PacienteDetalleComponent } from './paciente-detalle/paciente-detalle'; import { IndicadoresSeguimientoTabla, SeleccionSeguimiento } from './indicadores-seguimiento-tabla'; import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'; import { Dominio } from './indicadores.models'; +import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad'; import { IndicadoresService } from './indicadores.service'; @Component({ @@ -97,6 +98,10 @@ export class IndicadoresTracking implements OnChanges { if (!this.data || page < 1 || page > this.data.paginacion.total_pages) return; this.load({ ...this.applied, page }); } + // Every row of a shown answer has an identity: the answer is validated before it reaches the view. + identidad(paciente: SeguimientoPaciente): IdentidadPaciente { return identidadDe(paciente)!; } + // The rows of a page identify their patient by one field; an empty page keeps the legacy wording. + etiquetaIdentidad(respuesta: SeguimientoResponse) { return ETIQUETA_IDENTIDAD[respuesta.items[0] ? this.identidad(respuesta.items[0]).campo : 'id_seudonimo']; } abrirPaciente(paciente: SeguimientoPaciente, evento: Event) { if (this.dominio !== 'cacu' || this.status !== 'ready' || !this.data?.items.includes(paciente)) return; evento.stopPropagation(); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html index 4c5807f..1fef561 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.html @@ -6,10 +6,10 @@ @if (failed()) { }
-

Paciente {{ p.pseudonymId }}

+

Paciente {{ p.patientId }}

Fecha de corte: {{ p.cutoff }}.

-
Identificador seudónimo
{{ p.pseudonymId }}
+
{{ p.idLabel }}
{{ p.patientId }}
Grupo de edad
{{ p.ageGroup ?? notAvailable }}
Estatus de seguimiento
{{ p.status ?? notAvailable }}
Prioridad
{{ p.priority ?? notAvailable }}
diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts index 9792500..4b413d7 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-card.spec.ts @@ -16,7 +16,7 @@ describe('Ficha CaMa: resumen', () => { it('reads every field the follow-up row carries', () => { const row = complete(); expect(toCamaPatientSummary(row, '2026-10-20')).toEqual({ - pseudonymId: row['id_seudonimo'], cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'], + patientId: row['id_seudonimo'], idField: 'id_seudonimo', idLabel: 'Identificador seudónimo', cutoff: '2026-10-20', ageGroup: row['grupo_edad'], status: row['estatus'], priority: row['prioridad'], birads: row['birads'], mammographyDate: row['mastografia_fecha'], histopathology: row['biopsia'], biopsyDate: row['biopsia_fecha'], daysMammographyToDiagnosis: row['dias_mastografia_diagnostico'], }); @@ -102,7 +102,7 @@ describe('Ficha CaMa: componente', () => { for (let i = 0; i < 100 && !downloads.length; i++) await new Promise(r => setTimeout(r, 50)); expect(downloads).toHaveLength(1); expect(downloads[0]).toMatch(/^ficha-cancer-de-mama_corte-2026-10-20_\d{8}-\d{4}\.pdf$/); - expect(downloads[0]).not.toContain(summary.pseudonymId); + expect(downloads[0]).not.toContain(summary.patientId); vi.restoreAllMocks(); }, 30000); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts index cbb3188..fc49e84 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.spec.ts @@ -35,7 +35,7 @@ describe('Ficha CaMa: PDF individual', () => { it('prints each field of the record under its label', () => { const p = complete(); const found = texts(definition(p)['content']); - for (const t of [`Paciente ${p.pseudonymId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis), + for (const t of [`Paciente ${p.patientId}`, 'Fecha de corte: 2026-10-20', p.status!, p.priority!, p.birads!, p.mammographyDate!, p.histopathology!, p.biopsyDate!, String(p.daysMammographyToDiagnosis), 'Categoría BI-RADS', 'Fecha de la mastografía', 'Resultado histopatológico', 'Fecha de biopsia', 'Días de mastografía a diagnóstico']) expect(found).toContain(t); }); diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts index 1251ee4..bb7c405 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient-pdf.ts @@ -16,10 +16,10 @@ const section = (title: string, rows: [string, string | number | null][]) => [ /** The document definition of one patient's record. Exported so its content can be checked without rendering. */ export function camaPatientDocument(patient: CamaPatientSummary, now: Date, logo?: string): PdfDefinition { return institutionalDocument({ title: PATIENT_TITLE, logo, now, orientation: 'portrait' }, [ - { text: `Paciente ${patient.pseudonymId}`, style: 'h1' }, + { text: `Paciente ${patient.patientId}`, style: 'h1' }, { text: `Fecha de corte: ${patient.cutoff}`, style: 'muted' }, ...section('Resumen', [ - ['Identificador seudónimo', patient.pseudonymId], + [patient.idLabel, patient.patientId], ['Grupo de edad', patient.ageGroup], ['Estatus de seguimiento', patient.status], ['Prioridad', patient.priority], diff --git a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts index f11d59f..311f9b6 100644 --- a/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts +++ b/src/app/features/indicadores/paciente-detalle/cama/cama-patient.models.ts @@ -1,13 +1,17 @@ import { TrackingRow } from '../../export/tracking-export.models'; +import { CampoIdentidad, ETIQUETA_IDENTIDAD, identidadDe } from '../../paciente-identidad'; export const NOT_AVAILABLE = 'No disponible'; /** - * What the CaMa follow-up list says about one patient, read from the row that was clicked. `pseudonymId` is the - * synthetic `M-…` identifier of the list; it is not a platform identifier and is never sent anywhere. + * What the CaMa follow-up list says about one patient, read from the row that was clicked. `patientId` is the + * identifier the row carries (`idField` says which field); the record only shows it. */ export interface CamaPatientSummary { - pseudonymId: string; + patientId: string; + idField: CampoIdentidad; + /** What the identifier is called on screen and in the file. */ + idLabel: string; cutoff: string; ageGroup: string | null; status: string | null; @@ -33,16 +37,18 @@ export const RECOMMENDATIONS_UNAVAILABLE = 'Recomendaciones no disponibles.'; const text = (v: unknown) => (typeof v === 'string' && v.length > 0 ? v : null); /** - * The patient summary of a follow-up row, or `null` when the row has no identifier to show. `columnas` are the ones the + * The patient summary of a follow-up row, or `null` when the row has no identity that can be trusted. `columnas` are the ones the * list announced: the label it gives to the biopsy date is kept, so the record says the same as the list. */ export function toCamaPatientSummary(row: TrackingRow, cutoff: string, columnas: readonly { clave: string; detalles?: readonly { clave: string; etiqueta: string }[] }[] = []): CamaPatientSummary | null { - const pseudonymId = text(row['id_seudonimo']); - if (!pseudonymId) return null; + const identity = identidadDe(row); + if (!identity) return null; const etiquetaFecha = columnas.flatMap(c => c.detalles ?? []).find(d => d.clave === 'biopsia_fecha')?.etiqueta; const days = row['dias_mastografia_diagnostico']; return { - pseudonymId, + patientId: identity.id, + idField: identity.campo, + idLabel: ETIQUETA_IDENTIDAD[identity.campo], cutoff, ageGroup: text(row['grupo_edad']), status: text(row['estatus']), diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html index 00f6bd0..06b31d1 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.html @@ -1,10 +1,10 @@ @if (estado.tipo !== 'cerrado') {
-

Paciente {{ estado.resumen.id_seudonimo }}

+

Paciente {{ estado.resumen.identidad.id }}

Fecha de corte: {{ estado.resumen.corte }}.

-
Identificador seudónimo
{{ estado.resumen.id_seudonimo }}
+
{{ etiquetaIdentidad }}
{{ estado.resumen.identidad.id }}
Grupo de edad
{{ estado.resumen.grupoEdad ?? 'No disponible' }}
Estatus de seguimiento
{{ estado.resumen.estatus ?? 'No disponible' }}
Días de toma a diagnóstico
{{ estado.resumen.diasTomaDiagnostico ?? 'No disponible' }}
@@ -79,7 +79,7 @@

Riesgos y recomendaciones

- +
} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts index fe7b778..bbbde94 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.models.ts @@ -1,8 +1,9 @@ import { Observable } from 'rxjs'; +import { IdentidadPaciente } from '../paciente-identidad'; /** Snapshot of the received row, independent of the Seguimiento transport contract. */ export interface PacienteResumen { - id_seudonimo: string; + identidad: IdentidadPaciente; grupoEdad: string | null; estatus: string | null; corte: string; @@ -27,7 +28,8 @@ export interface PacienteDetalle { } export interface PacienteDetalleProvider { - obtener(idSeudonimo: string): Observable; + /** `id` is the patient identifier of the row; a patient the provider does not know is `null`. */ + obtener(id: string): Observable; } export type PacienteDetalleEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts index c7e6601..bf3e563 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.provider.ts @@ -5,9 +5,9 @@ import { PacienteDetalleProvider } from './paciente-detalle.models'; @Injectable({ providedIn: 'root' }) export class PacienteDetalleMockProvider implements PacienteDetalleProvider { - obtener(idSeudonimo: string) { + obtener(id: string) { return defer(() => { - const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === idSeudonimo); + const detalle = PACIENTES_DETALLE_SINTETICOS.find(item => item.id_seudonimo === id); // Each read owns its data; consumers cannot mutate another selection or the fixtures. return of(detalle ? structuredClone(detalle) : null); }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts index 7f6ad00..c9eb230 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.spec.ts @@ -3,6 +3,7 @@ import { provideHttpClient } from '@angular/common/http'; import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; import { Subject, of, throwError } from 'rxjs'; import fixtureData from '../fixtures/cacu_seguimiento.json'; +import { SeguimientoPaciente } from '../cacu-seguimiento.models'; import { seguimientoResponse } from '../cacu-seguimiento.service'; import { IndicadoresTracking } from '../indicadores-tracking'; import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; @@ -10,9 +11,9 @@ import { PacienteDetalle, PacienteDetalleProvider } from './paciente-detalle.mod import { PACIENTE_DETALLE_PROVIDER, PacienteDetalleMockProvider } from './paciente-detalle.provider'; import { PacienteDetalleState } from './paciente-detalle.state'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; -import { riesgoCacuEjemplo } from './paciente-riesgo.testing'; -const pacientes = seguimientoResponse(fixtureData).items; +// The fixture is the legacy contract: every row has id_seudonimo. +const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[]; describe('Proveedor de detalle sintético', () => { it('funciona sin HttpClient y busca únicamente el seudónimo exacto', () => { @@ -59,7 +60,7 @@ describe('Estado de selección del paciente', () => { const estado = state.estado(); expect(estado.tipo).toBe('no-disponible'); if (estado.tipo !== 'cerrado') { - expect(estado.resumen.id_seudonimo).toBe('001'); + expect(estado.resumen.identidad.id).toBe('001'); expect(estado.resumen.vph?.resultado).toBe('NEGATIVO'); expect(estado.resumen.vph?.genotipo16y18).toBeNull(); expect(estado.resumen.diasTomaDiagnostico).toBe(0); @@ -167,7 +168,7 @@ describe('Ficha individual desde Seguimiento CaCu', () => { fixture.detectChanges(); const estado = fixture.componentInstance.pacienteDetalle.estado(); expect(estado.tipo).toBe('disponible'); - if (estado.tipo === 'disponible') expect(estado.resumen.id_seudonimo).toBe(pacientes[1].id_seudonimo); + if (estado.tipo === 'disponible') expect(estado.resumen.identidad.id).toBe(pacientes[1].id_seudonimo); volver(); expect(row).toBe(document.activeElement); http.expectNone(() => true); @@ -239,20 +240,15 @@ describe('Ficha individual desde Seguimiento CaCu', () => { http.expectNone(() => true); }); - it('monta el contrato solo por inyección de prueba y no lo conserva en la siguiente ficha', () => { + // Fails if a row that only has id_seudonimo asks the risk route (which takes a pac_id) or leaves no «no disponible» state. + it('una ficha de un renglón con solo id_seudonimo no consulta el riesgo y lo declara no disponible', () => { const provider = TestBed.inject(PACIENTE_RIESGO_PROVIDER); - const obtener = vi.spyOn(provider, 'obtener').mockReturnValueOnce(of(riesgoCacuEjemplo())); + const obtener = vi.spyOn(provider, 'obtener'); try { - const detail = abrir(); - const tarjeta = detail.querySelector('app-paciente-riesgo-tabla')!; - expect(tarjeta.textContent).toContain('Información simulada'); - expect(tarjeta.querySelectorAll('tbody tr')).toHaveLength(3); - expect(tarjeta.textContent).not.toContain(pacientes[0].id_seudonimo); - expect(obtener).toHaveBeenCalledExactlyOnceWith(pacientes[0].id_seudonimo); - volver(); - const otra = abrir(1); - expect(otra.textContent).toContain('Riesgo individual no disponible para esta paciente.'); - expect(otra.querySelector('app-paciente-riesgo-tabla table')).toBeNull(); + const tarjeta = abrir().querySelector('app-paciente-riesgo-tabla')!; + expect(tarjeta.textContent).toContain('Riesgo individual no disponible para esta paciente.'); + expect(tarjeta.querySelector('table')).toBeNull(); + expect(obtener).not.toHaveBeenCalled(); http.expectNone(() => true); } finally { obtener.mockRestore(); } }); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts index e223be2..b323aa1 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.state.ts @@ -2,6 +2,7 @@ import { computed, DestroyRef, Injectable, inject, signal } from '@angular/core' import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { Subject, catchError, defer, map, of, switchMap } from 'rxjs'; import { SeguimientoPaciente } from '../cacu-seguimiento.models'; +import { identidadDe } from '../paciente-identidad'; import { PacienteDetalleEstado, PacienteResumen } from './paciente-detalle.models'; import { PACIENTE_DETALLE_PROVIDER } from './paciente-detalle.provider'; import { AltaRegistroTemporal } from './paciente-registro.models'; @@ -17,14 +18,14 @@ export class PacienteDetalleState { readonly estado = this.actual.asReadonly(); readonly registrosTemporales = computed(() => { const estado = this.actual(); - return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.id_seudonimo); + return estado.tipo === 'cerrado' ? [] : this.sesion.paraPaciente(estado.resumen.identidad.id); }); constructor() { this.seleccion.pipe( - switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.id_seudonimo)).pipe( + switchMap(resumen => resumen ? defer(() => this.provider.obtener(resumen.identidad.id)).pipe( map(detalle => { - if (detalle && (detalle.id_seudonimo !== resumen.id_seudonimo || detalle.origen !== 'sintetico')) { + if (detalle && (detalle.id_seudonimo !== resumen.identidad.id || detalle.origen !== 'sintetico')) { throw new Error('Detalle incompatible con la selección'); } return detalle @@ -38,8 +39,10 @@ export class PacienteDetalleState { } abrir(paciente: SeguimientoPaciente, corte: string) { + const identidad = identidadDe(paciente); + if (!identidad) return; const resumen: PacienteResumen = { - id_seudonimo: paciente.id_seudonimo, + identidad, grupoEdad: paciente.grupo_edad === 'sin_dato' ? null : paciente.grupo_edad, estatus: paciente.estatus.etiqueta, corte, @@ -65,7 +68,7 @@ export class PacienteDetalleState { agregarRegistro(alta: AltaRegistroTemporal) { const estado = this.actual(); - if (estado.tipo === 'cerrado' || estado.resumen.id_seudonimo !== alta.id_seudonimo) return false; - return this.sesion.agregar(alta.id_seudonimo, alta.registro); + if (estado.tipo === 'cerrado' || estado.resumen.identidad.id !== alta.paciente.id) return false; + return this.sesion.agregar(alta.paciente.id, alta.registro); } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts index e3d2a75..d9b38c3 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-detalle.ts @@ -4,6 +4,7 @@ import { MatButtonModule } from '@angular/material/button'; import { MatCardModule } from '@angular/material/card'; import { MatDialog, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { MatIconModule } from '@angular/material/icon'; +import { ETIQUETA_IDENTIDAD, IdentidadPaciente } from '../paciente-identidad'; import { PacienteDetalleEstado } from './paciente-detalle.models'; import { PacienteRegistroDialog } from './paciente-registro-dialog'; import { AltaRegistroTemporal, NuevoRegistroTemporal, RegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; @@ -31,19 +32,22 @@ export class PacienteDetalleComponent implements AfterViewInit, OnDestroy { ngAfterViewInit() { this.titulo?.nativeElement.focus(); } ngOnDestroy() { this.dialogoActivo?.close(); } + get etiquetaIdentidad() { return this.estado.tipo === 'cerrado' ? '' : ETIQUETA_IDENTIDAD[this.estado.resumen.identidad.campo]; } + /** The `pac_id` the risk is read by; a row with only the legacy `id_seudonimo` has none. */ + get pacId() { return this.estado.tipo !== 'cerrado' && this.estado.resumen.identidad.campo === 'pac_id' ? this.estado.resumen.identidad.id : null; } temporales(tipo: TipoRegistroTemporal) { return this.registrosTemporales.filter(item => item.tipo === tipo); } abrirRegistro(tipo: TipoRegistroTemporal) { if (this.estado.tipo === 'cerrado' || this.dialogoActivo) return; - const id_seudonimo = this.estado.resumen.id_seudonimo; - const ref = this.dialog.open(PacienteRegistroDialog, { - data: { tipo, id_seudonimo }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh', + const paciente = this.estado.resumen.identidad; + const ref = this.dialog.open(PacienteRegistroDialog, { + data: { tipo, paciente }, width: '34rem', maxWidth: 'calc(100vw - 2rem)', maxHeight: '90dvh', autoFocus: 'first-tabbable', restoreFocus: true, disableClose: false, }); this.dialogoActivo = ref; ref.afterClosed().pipe(takeUntilDestroyed(this.destroy)).subscribe(registro => { this.dialogoActivo = undefined; - if (registro) this.registroAgregado.emit({ id_seudonimo, registro }); + if (registro) this.registroAgregado.emit({ paciente, registro }); }); } etiquetaCitologia(resultado: string | null, calidad: string | null) { diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html index f4f82cc..3b40c1b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.html @@ -1,7 +1,7 @@

{{ titulo }}

-

Paciente {{ data.id_seudonimo }}

+

Paciente {{ data.paciente.id }}

{{ etiquetaTipo }} diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts index 0e5f813..5c2fa08 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-dialog.ts @@ -1,4 +1,5 @@ import { Component, DestroyRef, inject } from '@angular/core'; +import { IdentidadPaciente } from '../paciente-identidad'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { FormControl, FormGroup, ReactiveFormsModule, ValidatorFn, Validators } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; @@ -10,7 +11,7 @@ import { CONDICIONES_DEMO, PROCEDIMIENTOS_DEMO, ESTUDIOS_DEMO, RESULTADOS_DEMO, import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation'; -export interface RegistroDialogData { tipo: TipoRegistroTemporal; id_seudonimo: string; } +export interface RegistroDialogData { tipo: TipoRegistroTemporal; paciente: IdentidadPaciente; } const opcionValida = (catalogo: Readonly>): ValidatorFn => control => !control.value || esOpcion(catalogo, control.value) ? null : { opcion: true }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts index 853caeb..47fb10b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro-integracion.spec.ts @@ -9,6 +9,7 @@ import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing'; import { MatDialog } from '@angular/material/dialog'; import { firstValueFrom, of } from 'rxjs'; import fixtureData from '../fixtures/cacu_seguimiento.json'; +import { SeguimientoPaciente } from '../cacu-seguimiento.models'; import { seguimientoResponse } from '../cacu-seguimiento.service'; import { IndicadoresTracking } from '../indicadores-tracking'; import { PACIENTES_DETALLE_SINTETICOS } from './paciente-detalle.fixtures'; @@ -16,9 +17,11 @@ import { PacienteDetalleState } from './paciente-detalle.state'; import { PACIENTE_RIESGO_PROVIDER } from './paciente-riesgo.provider'; import { PacienteRegistroDialog } from './paciente-registro-dialog'; import { PacienteRegistrosSesion } from './paciente-registros-sesion'; +import { identidadDe } from '../paciente-identidad'; import { TipoRegistroTemporal } from './paciente-registro.models'; -const pacientes = seguimientoResponse(fixtureData).items; +// The fixture is the legacy contract: every row has id_seudonimo. +const pacientes = seguimientoResponse(fixtureData).items as (SeguimientoPaciente & { id_seudonimo: string })[]; const acciones: { tipo: TipoRegistroTemporal; texto: string; opcion: string; resultado?: string }[] = [ { tipo: 'condicion', texto: 'Agregar condición', opcion: 'Embarazo' }, { tipo: 'procedimiento', texto: 'Agregar procedimiento', opcion: 'Colposcopia' }, @@ -132,7 +135,7 @@ describe('Altas de demostración desde la ficha de Seguimiento', () => { expect(JSON.stringify(PACIENTES_DETALLE_SINTETICOS)).toBe(inicial); expect(JSON.stringify(fixture.componentInstance.data)).toBe(resumen); const almacenado = fixture.componentInstance.pacienteDetalle.registrosTemporales()[0]; - expect(almacenado.id_seudonimo).toBe(pacientes[0].id_seudonimo); + expect(almacenado.paciente).toBe(pacientes[0].id_seudonimo); expect(almacenado.origen).toBe('sesion-demostracion'); expect(almacenado.fecha).toBe('2026-10-26'); http.expectNone(() => true); @@ -276,7 +279,7 @@ describe('Vida de la selección y de la memoria de sesión', () => { const a = primero.get(PacienteDetalleState); const b = segundo.get(PacienteDetalleState); a.abrir(pacientes[0], fixtureData.corte); - expect(a.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true); + expect(a.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(true); a.cerrar(); expect(a.registrosTemporales()).toEqual([]); primero.destroy(); @@ -284,7 +287,7 @@ describe('Vida de la selección y de la memoria de sesión', () => { expect(b.registrosTemporales()).toHaveLength(1); b.abrir(pacientes[1], fixtureData.corte); expect(b.registrosTemporales()).toEqual([]); - expect(b.agregarRegistro({ id_seudonimo: pacientes[0].id_seudonimo, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false); + expect(b.agregarRegistro({ paciente: identidadDe(pacientes[0])!, registro: { tipo: 'condicion', condicion: 'embarazo', fecha: '2026-10-26' } })).toBe(false); } finally { if (!primero.destroyed) primero.destroy(); segundo.destroy(); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts index 0f72c23..8fd7b2b 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.models.ts @@ -1,3 +1,4 @@ +import { IdentidadPaciente } from '../paciente-identidad'; import { RESULTADOS_DEMO, TipoCondicionDemo, TipoEstudioDemo, TipoProcedimientoDemo } from './paciente-registro.catalogos'; type ResultadoDemo = { @@ -14,11 +15,12 @@ export type TipoRegistroTemporal = NuevoRegistroTemporal['tipo']; /** Independiente del resumen recibido y del historial inicial del proveedor. */ export type RegistroTemporal = Readonly; export interface AltaRegistroTemporal { - id_seudonimo: string; + paciente: IdentidadPaciente; registro: NuevoRegistroTemporal; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts index 8fb331b..cc78875 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registro.spec.ts @@ -5,6 +5,7 @@ import { PacienteRegistroDialog } from './paciente-registro-dialog'; import { NuevoRegistroTemporal, TipoRegistroTemporal } from './paciente-registro.models'; import { crearRegistroTemporal, esFechaReal } from './paciente-registro.validation'; import { PacienteRegistrosSesion } from './paciente-registros-sesion'; +import { identidadDe } from '../paciente-identidad'; describe('Fecha de calendario de registros temporales', () => { it('acepta días reales, incluyendo años bisiestos y límites de año', () => { @@ -35,7 +36,7 @@ describe.each(casos)('Formulario de $tipo', caso => { beforeEach(() => { cerrar = vi.fn(); TestBed.configureTestingModule({ providers: [ - { provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, id_seudonimo: '001' } }, + { provide: MAT_DIALOG_DATA, useValue: { tipo: caso.tipo, paciente: identidadDe({ id_seudonimo: '001' })! } }, { provide: MatDialogRef, useValue: { close: cerrar } }, ] }); fixture = TestBed.createComponent(PacienteRegistroDialog); @@ -82,7 +83,7 @@ describe('Resultados dependientes del estudio', () => { beforeEach(() => { cerrar = vi.fn(); TestBed.configureTestingModule({ providers: [ - { provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', id_seudonimo: 'A' } }, + { provide: MAT_DIALOG_DATA, useValue: { tipo: 'resultado', paciente: identidadDe({ id_seudonimo: 'A' })! } }, { provide: MatDialogRef, useValue: { close: cerrar } }, ] }); const fixture = TestBed.createComponent(PacienteRegistroDialog); @@ -132,7 +133,7 @@ describe('Memoria de registros temporales', () => { const sesion = TestBed.inject(PacienteRegistrosSesion); for (const caso of casos) expect(sesion.agregar('001', caso.registro)).toBe(true); expect(sesion.paraPaciente('001').map(r => r.tipo)).toEqual(['condicion', 'procedimiento', 'resultado']); - expect(sesion.paraPaciente('001').every(r => r.id_seudonimo === '001' && r.origen === 'sesion-demostracion')).toBe(true); + expect(sesion.paraPaciente('001').every(r => r.paciente === '001' && r.origen === 'sesion-demostracion')).toBe(true); for (const id of ['1', ' 001', '001 ', 'otro', 'toString']) expect(sesion.paraPaciente(id)).toEqual([]); sesion.agregar('toString', casos[0].registro); expect(sesion.paraPaciente('toString')).toHaveLength(1); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts index 8198377..4708ed6 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-registros-sesion.ts @@ -11,21 +11,21 @@ export class PacienteRegistrosSesion { private readonly registros = signal>(new Map()); private siguienteId = 0; - paraPaciente(idSeudonimo: string): readonly RegistroTemporal[] { - return this.registros().get(idSeudonimo) ?? SIN_REGISTROS; + paraPaciente(id: string): readonly RegistroTemporal[] { + return this.registros().get(id) ?? SIN_REGISTROS; } - agregar(idSeudonimo: string, nuevo: NuevoRegistroTemporal): boolean { - if (!idSeudonimo || !nuevo) return false; + agregar(id: string, nuevo: NuevoRegistroTemporal): boolean { + if (!id || !nuevo) return false; const seleccion = nuevo.tipo === 'condicion' ? nuevo.condicion : nuevo.tipo === 'procedimiento' ? nuevo.procedimiento : nuevo.estudio; const validado = crearRegistroTemporal(nuevo.tipo, seleccion, nuevo.fecha, nuevo.tipo === 'resultado' ? nuevo.resultado : ''); if (!validado) return false; const registro: RegistroTemporal = Object.freeze({ - ...validado, id: ++this.siguienteId, id_seudonimo: idSeudonimo, origen: 'sesion-demostracion', + ...validado, id: ++this.siguienteId, paciente: id, origen: 'sesion-demostracion', }); - this.registros.update(actual => new Map(actual).set(idSeudonimo, Object.freeze([ - ...(actual.get(idSeudonimo) ?? []), registro, + this.registros.update(actual => new Map(actual).set(id, Object.freeze([ + ...(actual.get(id) ?? []), registro, ]))); return true; } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts index 2b69b01..bf02e1a 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo-tabla.ts @@ -11,12 +11,13 @@ import { tieneIntervalo } from './paciente-riesgo.validation'; styleUrl: './paciente-riesgo-tabla.scss', }) export class PacienteRiesgoTabla { - readonly idSeudonimo = input.required(); + /** The patient's `pac_id`, or `null` when the row has none: the risk is then unavailable and nothing is requested. */ + readonly pacId = input.required(); private readonly state = inject(PacienteRiesgoState); readonly estado = this.state.estado; readonly tieneIntervalo = tieneIntervalo; constructor() { - effect(() => this.state.idSeudonimo.set(this.idSeudonimo())); + effect(() => this.state.pacId.set(this.pacId())); } } diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts index 0ff9cec..b7ff381 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.models.ts @@ -42,7 +42,7 @@ export interface RiesgoPacienteCacu { /** `null` when the patient has no risk data. */ export interface PacienteRiesgoProvider { - obtener(idSeudonimo: string): Observable; + obtener(pacId: string): Observable; } export type PacienteRiesgoEstado = diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts index 70a3092..0749c29 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.provider.ts @@ -3,12 +3,12 @@ import { inject, InjectionToken } from '@angular/core'; import { catchError, of, throwError } from 'rxjs'; import { PacienteRiesgoProvider } from './paciente-riesgo.models'; -// The follow-up list identifies each patient by the `pac_id` of the risk batches; a 404 is a patient without risk data. +// The risk batches are keyed by `pac_id`, the identifier a follow-up row carries as `pac_id`; a 404 is a patient without risk data. export const PACIENTE_RIESGO_PROVIDER = new InjectionToken('PacienteRiesgoProvider', { providedIn: 'root', factory: () => { const http = inject(HttpClient); return { - obtener: (idSeudonimo: string) => http.get(`/cacu/pacientes/${encodeURIComponent(idSeudonimo)}/riesgo`).pipe( + obtener: (pacId: string) => http.get(`/cacu/pacientes/${encodeURIComponent(pacId)}/riesgo`).pipe( catchError(error => error instanceof HttpErrorResponse && error.status === 404 ? of(null) : throwError(() => error)), ), }; diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts index 20caa5f..4eea34d 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.spec.ts @@ -12,7 +12,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), ...(provider ? [{ provide: PACIENTE_RIESGO_PROVIDER, useValue: provider }] : [])] }); const fixture = TestBed.createComponent(PacienteRiesgoTabla); - fixture.componentRef.setInput('idSeudonimo', '42'); + fixture.componentRef.setInput('pacId', '42'); fixture.detectChanges(); fixture.detectChanges(); return fixture; @@ -138,7 +138,7 @@ describe('RIESGO-CACU-02: presentación y aislamiento', () => { expect(f.nativeElement.querySelector('.percentage')!.textContent).toBe('8 %'); f.destroy(); const otra = TestBed.createComponent(PacienteRiesgoTabla); - otra.componentRef.setInput('idSeudonimo', 'P-OTRA'); otra.detectChanges(); + otra.componentRef.setInput('pacId', '43'); otra.detectChanges(); expect(otra.nativeElement.textContent).toContain('Cargando riesgo individual'); expect(otra.nativeElement.querySelector('table')).toBeNull(); expect(riesgoCacuEjemplo().riesgo!.horizontes[0].probabilidad).toBe(0.08); diff --git a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts index 9a9e868..b5a08d5 100644 --- a/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts +++ b/src/app/features/indicadores/paciente-detalle/paciente-riesgo.state.ts @@ -10,9 +10,10 @@ const CARGANDO: PacienteRiesgoEstado = { tipo: 'cargando' }; @Injectable() export class PacienteRiesgoState { private readonly provider = inject(PACIENTE_RIESGO_PROVIDER); - readonly idSeudonimo = signal(null); - readonly estado = toSignal(toObservable(this.idSeudonimo).pipe( - switchMap(id => id === null ? of(CARGANDO) : defer(() => this.provider.obtener(id)).pipe( + // `undefined` until the input is set; `null` is a patient without `pac_id`. + readonly pacId = signal(undefined); + readonly estado = toSignal(toObservable(this.pacId).pipe( + switchMap(id => id === undefined ? of(CARGANDO) : id === null ? of({ tipo: 'no-disponible' }) : defer(() => this.provider.obtener(id)).pipe( map((datos): PacienteRiesgoEstado => datos === null ? { tipo: 'no-disponible' } : { tipo: 'disponible', datos: riesgoPacienteResponse(datos) }), catchError(() => of({ tipo: 'error' })), diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts new file mode 100644 index 0000000..a87835e --- /dev/null +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -0,0 +1,215 @@ +// Covers how a follow-up row identifies its patient (`pac_id`, or the legacy `id_seudonimo`): the rule itself, the CaMa +// table and record, the files built from the same rows, and CaCu's risk request. Fixtures: fixtures/cama_seguimiento.json +// (27 synthetic rows) rewritten to carry `pac_id`, and fixtures/cacu_seguimiento.json. +import { TestBed } from '@angular/core/testing'; +import { provideHttpClient } from '@angular/common/http'; +import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing'; +import { lastValueFrom, Observable, of, toArray } from 'rxjs'; +import camaData from './fixtures/cama_seguimiento.json'; +import cacuData from './fixtures/cacu_seguimiento.json'; +import { ExportInconsistent } from './export/tracking-export.models'; +import { fetchAllTracking } from './export/tracking-export-source'; +import { flatTable } from './export/tracking-export-table'; +import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla'; +import { IndicadoresTracking } from './indicadores-tracking'; +import { PACIENTE_RIESGO_PROVIDER } from './paciente-detalle/paciente-riesgo.provider'; +import { columnaEnlace, identidadDe, identidadesDe } from './paciente-identidad'; +import { SeguimientoTablaQuery, SeguimientoTablaResponse, SeguimientoTablaService, seguimientoTablaResponse } from './seguimiento-tabla.service'; + +describe('Identidad de un renglón', () => { + // Fails if `pac_id` stops winning over the legacy field, or stops being kept as the text the server sent. + it('uses pac_id when the row has it, and the legacy id_seudonimo otherwise', () => { + expect(identidadDe({ pac_id: '42', id_seudonimo: 'P-X' })).toEqual({ campo: 'pac_id', id: '42' }); + expect(identidadDe({ id_seudonimo: 'P-X' })).toEqual({ campo: 'id_seudonimo', id: 'P-X' }); + expect(identidadDe({ pac_id: null, id_seudonimo: 'P-X' })?.campo).toBe('id_seudonimo'); + }); + + // Fails if a number, a padded value or a pseudonym in `pac_id` is accepted, or if an invalid pac_id falls back to the pseudonym. + it('refuses a pac_id that is not a plain decimal string, without falling back to id_seudonimo', () => { + for (const malo of [42, '042', '-1', '4 2', '1e3', '', 'P-X', '12345678901234567890', {}]) expect(identidadDe({ pac_id: malo, id_seudonimo: 'P-X' })).toBeNull(); + expect(identidadDe({ pac_id: '0' })?.id).toBe('0'); + }); + + // Fails if a row with no identifier opens a record for nobody. + it('has no identity without an identifier', () => { + expect(identidadDe({})).toBeNull(); + expect(identidadDe({ id_seudonimo: '' })).toBeNull(); + expect(identidadDe({ id_seudonimo: 7 })).toBeNull(); + }); + + // Fails if a page that repeats a patient, or identifies rows by different fields, can be shown. + it('refuses a page with a repeated patient or with mixed identifier fields', () => { + expect(identidadesDe([{ pac_id: '7' }, { pac_id: '8' }])).toHaveLength(2); + expect(identidadesDe([{ pac_id: '7' }, { pac_id: '7' }])).toBeNull(); + expect(identidadesDe([{ pac_id: '7' }, { id_seudonimo: 'P-8' }])).toBeNull(); + expect(identidadesDe([])).toEqual([]); + }); + + // Fails if the link moves to a column that is not the identifier when the answer announces it. + it('puts the link on the identifier column of the row, else on any identifier column, else on the first', () => { + expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }, { clave: 'pac_id' }], 'pac_id')).toBe('pac_id'); + expect(columnaEnlace([{ clave: 'a' }, { clave: 'id_seudonimo' }], 'pac_id')).toBe('id_seudonimo'); + expect(columnaEnlace([{ clave: 'a' }, { clave: 'b' }], 'pac_id')).toBe('a'); + }); +}); + +/** The CaMa fixture with `pac_id` (1..n) instead of the pseudonym. */ +function conPacId(): Record { + const d = structuredClone(camaData) as unknown as Record; + d['columnas'][0] = { clave: 'pac_id', etiqueta: 'Identificador de paciente' }; + d['items'] = (d['items'] as Record[]).map((item, i) => { + const { id_seudonimo: _, ...rest } = item; + return { pac_id: String(i + 1), ...rest }; + }); + return d; +} + +describe('Tabla de seguimiento con pac_id', () => { + let fixture: ReturnType>, http: HttpTestingController; + beforeEach(() => { + TestBed.configureTestingModule({ imports: [IndicadoresSeguimientoTabla], providers: [provideHttpClient(), provideHttpClientTesting()] }); + fixture = TestBed.createComponent(IndicadoresSeguimientoTabla); http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('active', true); fixture.detectChanges(); + }); + afterEach(() => { fixture.destroy(); http.verify(); }); + const root = () => fixture.nativeElement as HTMLElement; + const cargar = (respuesta: Record) => { http.expectOne(r => r.url === '/cama/seguimiento').flush(respuesta); fixture.detectChanges(); }; + const enlaces = () => [...root().querySelectorAll('tbody button.patient-link')]; + + // Fails if the header or the link stop following the column the answer announces for the identifier. + it('shows the announced pac_id column and links each row by it', () => { + cargar(conPacId()); + expect([...root().querySelectorAll('thead th')][0].textContent!.trim()).toBe('Identificador de paciente'); + expect(enlaces().slice(0, 3).map(b => b.textContent!.trim())).toEqual(['1', '2', '3']); + expect(enlaces()[0].getAttribute('aria-label')).toBe('Ver ficha del paciente 1'); + expect(root().querySelector('tbody tr')?.getAttribute('data-paciente')).toBe('1'); + }); + + // Fails if the row that was used opens the record of another row, shows the legacy label, or the focus does not go + // back to the control that was used. + it('opens the record of the row that was used and returns focus to it', async () => { + const datos = conPacId(), items = datos['items'] as Record[]; + cargar(datos); + for (const indice of [2, 0]) { + enlaces()[indice].click(); fixture.detectChanges(); + const ficha = root().querySelector('app-cama-patient-card')!; + expect(ficha.querySelector('h2')!.textContent!.trim()).toBe(`Paciente ${items[indice]['pac_id']}`); + expect(ficha.textContent).toContain(items[indice]['birads']); + expect(ficha.textContent).toContain('Identificador de paciente'); + expect(ficha.textContent).not.toContain('Identificador seudónimo'); + ficha.querySelector('.back-button')!.click(); fixture.detectChanges(); + await fixture.whenStable(); fixture.detectChanges(); + expect(document.activeElement).toBe(enlaces()[indice]); + } + }); + + // Fails if a page that repeats a patient, or mixes pac_id with the legacy field, is drawn: its rows would open the same record. + it('does not draw an answer whose rows cannot be told apart or identify patients by different fields', () => { + const repetida = conPacId(); repetida['items'][1]['pac_id'] = repetida['items'][0]['pac_id']; + cargar(repetida); + expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado'); + expect(enlaces()).toHaveLength(0); + }); + + // Fails if a numeric pac_id is accepted: the contract is a decimal string. + it('does not draw an answer whose pac_id is a number', () => { + const numerica = conPacId(); numerica['items'][0]['pac_id'] = 1; + cargar(numerica); + expect(root().querySelector('[role=alert]')?.textContent).toContain('no tiene el formato esperado'); + }); + + // Fails if the legacy contract stops working while the server still sends only id_seudonimo. + it('still draws and opens a row that only has id_seudonimo', () => { + cargar(structuredClone(camaData) as unknown as Record); + enlaces()[0].click(); fixture.detectChanges(); + expect(root().querySelector('app-cama-patient-card h2')!.textContent).toContain('Paciente ' + (camaData.items[0] as any).id_seudonimo); + expect(root().querySelector('app-cama-patient-card')!.textContent).toContain('Identificador seudónimo'); + }); +}); + +describe('Archivos con pac_id', () => { + // A server over `todas`, `tam` rows a page. + function servidor(todas: Record[], tam: number) { + return { + consultar(_d: string, q: SeguimientoTablaQuery): Observable { + const d = conPacId(); d['items'] = todas.slice((q.page - 1) * tam, q.page * tam); + d['paginacion'] = { page: q.page, page_size: tam, total_items: todas.length, total_pages: Math.ceil(todas.length / tam) }; + return of(seguimientoTablaResponse(d)); + }, + } as unknown as SeguimientoTablaService; + } + const consulta: SeguimientoTablaQuery = { corte: '2026-10-20', meses: 3, page: 1, page_size: 5 }; + + // Fails if the file holds other rows, or the same rows in another order, than the pages of the table. + it('hands the files the same rows in the same order as the pages of the table', async () => { + const todas = conPacId()['items'] as Record[]; + const salida = await lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray())); + const hecho = salida.at(-1)!; + expect(hecho.kind).toBe('done'); + if (hecho.kind !== 'done') return; + expect(hecho.snapshot.items.map(i => i['pac_id'])).toEqual(todas.map(i => i['pac_id'])); + const plana = flatTable(hecho.snapshot); + expect(plana.columns[0]).toMatchObject({ key: 'pac_id', label: 'Identificador de paciente' }); + expect(plana.rows.map(f => f[0])).toEqual(todas.map(i => i['pac_id'])); + }); + + // Fails if a patient that appears on two pages is exported twice as if it were two patients. + it('refuses a list in which the same patient is on two pages', async () => { + const todas = conPacId()['items'] as Record[]; + todas[7] = { ...todas[7], pac_id: todas[0]['pac_id'] }; + await expect(lastValueFrom(fetchAllTracking(servidor(todas, 7), 'cama', consulta, 5000).pipe(toArray()))).rejects.toBeInstanceOf(ExportInconsistent); + }); +}); + +describe('Riesgo de CaCu por pac_id', () => { + let http: HttpTestingController; + const solicitudes: string[] = []; + function montar(items: Record[]) { + solicitudes.length = 0; + TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), + { provide: PACIENTE_RIESGO_PROVIDER, useValue: { obtener: (id: string) => { solicitudes.push(id); return of(null); } } }] }); + const fixture = TestBed.createComponent(IndicadoresTracking); + http = TestBed.inject(HttpTestingController); + fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('domainLabel', 'CaCu'); fixture.componentRef.setInput('active', true); + fixture.detectChanges(); + http.expectOne(r => r.url === '/cacu/seguimiento').flush({ ...structuredClone(cacuData), items }); + http.expectOne('/cacu/indicadores/cacu_eu7/metadatos').flush({ categorias: {} }); + fixture.detectChanges(); + return fixture; + } + const filas = () => (structuredClone(cacuData) as unknown as { items: Record[] }).items; + const primerEncabezado = (f: ReturnType) => [...f.nativeElement.querySelectorAll('thead th')][0].textContent.trim(); + const abrirSegunda = (f: ReturnType) => { (f.nativeElement.querySelectorAll('tbody button.patient-link')[1] as HTMLButtonElement).click(); f.detectChanges(); }; + afterEach(() => http.verify()); + + // Fails if the record asks for the risk with something other than the row's pac_id, or shows the legacy label for it. + it('requests the risk with the pac_id of the row and labels the identifier as the patient identifier', () => { + const items = filas().slice(0, 2).map(({ id_seudonimo: _, ...r }, i) => ({ pac_id: String(40 + i), ...r })); + const fixture = montar(items); + expect(primerEncabezado(fixture)).toBe('Identificador de paciente'); + abrirSegunda(fixture); + expect(solicitudes).toEqual(['41']); + expect(fixture.nativeElement.querySelector('app-paciente-detalle h2').textContent).toContain('Paciente 41'); + fixture.destroy(); + }); + + // Fails if the migration alias wins over pac_id: a hash kept in id_seudonimo must never reach the risk route. + it('prefers pac_id over the legacy alias that rows carry during the migration', () => { + const items = filas().slice(0, 2).map((r, i) => ({ ...r, pac_id: String(40 + i) })); + const fixture = montar(items); + expect(primerEncabezado(fixture)).toBe('Identificador de paciente'); + abrirSegunda(fixture); + expect(solicitudes).toEqual(['41']); + fixture.destroy(); + }); + + // Fails if a legacy value is sent to the risk route, which only accepts a pac_id. + it('does not request the risk of a row that only has id_seudonimo', () => { + const fixture = montar(filas().slice(0, 2)); + expect(primerEncabezado(fixture)).toBe('Identificador seudónimo'); + abrirSegunda(fixture); + expect(solicitudes).toEqual([]); + expect(fixture.nativeElement.querySelector('app-paciente-riesgo-tabla').textContent).toContain('Riesgo individual no disponible'); + fixture.destroy(); + }); +}); diff --git a/src/app/features/indicadores/paciente-identidad.ts b/src/app/features/indicadores/paciente-identidad.ts new file mode 100644 index 0000000..403d153 --- /dev/null +++ b/src/app/features/indicadores/paciente-identidad.ts @@ -0,0 +1,54 @@ +// How a follow-up row says who its patient is: `pac_id`, or the legacy `id_seudonimo` that servers may still send. + +/** The fields that can identify a patient on a row, in order of precedence. */ +export const CAMPOS_IDENTIDAD = ['pac_id', 'id_seudonimo'] as const; +export type CampoIdentidad = typeof CAMPOS_IDENTIDAD[number]; + +export interface IdentidadPaciente { + /** The field the identifier came from: `pac_id` wins over the legacy `id_seudonimo`. */ + campo: CampoIdentidad; + /** The identifier as sent, scoped to the domain it was read in. `pac_id` is a decimal string. */ + id: string; +} + +/** What the row's identifier is called on screen and in the files, by the field it comes from. */ +export const ETIQUETA_IDENTIDAD: Readonly> = { + pac_id: 'Identificador de paciente', + id_seudonimo: 'Identificador seudónimo', +}; + +// No leading zeros and no sign: the value is compared and sent as text, so it has one spelling. +const PAC_ID = /^(0|[1-9][0-9]{0,17})$/; +/** The fields of a row that matter here; a typed row or a plain record both fit. */ +export interface FilaConIdentidad { readonly pac_id?: unknown; readonly id_seudonimo?: unknown } +const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0; + +/** + * The identity of a row, or `null` when it has none that can be trusted: a `pac_id` that is not a decimal string + * (a number is refused, not converted) or no identifier at all. A present `pac_id` is never replaced by + * `id_seudonimo` when it is invalid. + */ +export function identidadDe(fila: FilaConIdentidad): IdentidadPaciente | null { + const pacId = fila.pac_id; + if (pacId !== undefined && pacId !== null) return typeof pacId === 'string' && PAC_ID.test(pacId) ? { campo: 'pac_id', id: pacId } : null; + return texto(fila.id_seudonimo) ? { campo: 'id_seudonimo', id: fila.id_seudonimo } : null; +} + +/** + * The identities of a page of rows, or `null` when the page cannot be shown: a row without identity, rows that do not + * identify their patient by the same field, or two rows of the same patient (they would open the same record). + */ +export function identidadesDe(filas: readonly FilaConIdentidad[]): IdentidadPaciente[] | null { + const identidades = filas.map(identidadDe); + if (identidades.some(i => i === null)) return null; + const validas = identidades as IdentidadPaciente[]; + if (validas.some(i => i.campo !== validas[0].campo)) return null; + return new Set(validas.map(i => i.id)).size === validas.length ? validas : null; +} + +/** The column that holds the link to the record: the one of the row's own field, else any identifier column, else the first. */ +export function columnaEnlace(columnas: readonly { clave: string }[], campo: CampoIdentidad): string | undefined { + return columnas.find(c => c.clave === campo)?.clave + ?? columnas.find(c => (CAMPOS_IDENTIDAD as readonly string[]).includes(c.clave))?.clave + ?? columnas[0]?.clave; +} diff --git a/src/app/features/indicadores/seguimiento-tabla.service.ts b/src/app/features/indicadores/seguimiento-tabla.service.ts index f523b2f..bf53616 100644 --- a/src/app/features/indicadores/seguimiento-tabla.service.ts +++ b/src/app/features/indicadores/seguimiento-tabla.service.ts @@ -2,6 +2,7 @@ import { inject, Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { map } from 'rxjs'; import { isoDate } from './cacu-seguimiento.models'; +import { identidadesDe } from './paciente-identidad'; import { etiquetaDeFiltro } from './etiquetas-cohorte'; import { Dominio, requireDominio } from './indicadores.models'; @@ -30,7 +31,7 @@ export interface SeguimientoTablaResponse extends Partial { filtros_disponibles: SeguimientoFiltro[]; columnas: SeguimientoColumna[]; paginacion: { page: number; page_size: number; total_items: number; total_pages: number }; - // Every item has `id_seudonimo`; the rest are the columns' keys and their details. + // Every item names its patient (`pac_id`, or the legacy `id_seudonimo`); the rest are the columns' keys and their details. items: Record[]; } export class SeguimientoInvalido extends Error {} @@ -92,7 +93,7 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse { || !filtrosOk || !columnasOk || !record(filters) || !Object.entries(filters).every(([k, f]) => (f === null || typeof f === 'string') && (available as Record[]).some(a => a['clave'] === k)) || !Array.isArray(v['items']) || v['items'].length > p['page_size'] - || !v['items'].every(item => record(item) && text(item['id_seudonimo']) && Object.values(item).every(valor))) { + || !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record[])) { throw new SeguimientoInvalido('Respuesta de seguimiento inválida'); } const respuesta = v as unknown as SeguimientoTablaResponse; From 01d6e71f07a4833248cabc4ee18be21da22f37e8 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Fri, 13 Nov 2026 18:23:45 -0600 Subject: [PATCH 36/38] Accept 64-bit patient identifiers --- src/app/features/indicadores/paciente-identidad.spec.ts | 1 + src/app/features/indicadores/paciente-identidad.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/features/indicadores/paciente-identidad.spec.ts b/src/app/features/indicadores/paciente-identidad.spec.ts index a87835e..b1a242b 100644 --- a/src/app/features/indicadores/paciente-identidad.spec.ts +++ b/src/app/features/indicadores/paciente-identidad.spec.ts @@ -28,6 +28,7 @@ describe('Identidad de un renglón', () => { it('refuses a pac_id that is not a plain decimal string, without falling back to id_seudonimo', () => { for (const malo of [42, '042', '-1', '4 2', '1e3', '', 'P-X', '12345678901234567890', {}]) expect(identidadDe({ pac_id: malo, id_seudonimo: 'P-X' })).toBeNull(); expect(identidadDe({ pac_id: '0' })?.id).toBe('0'); + expect(identidadDe({ pac_id: '9223372036854775807' })?.id).toBe('9223372036854775807'); }); // Fails if a row with no identifier opens a record for nobody. diff --git a/src/app/features/indicadores/paciente-identidad.ts b/src/app/features/indicadores/paciente-identidad.ts index 403d153..59a7188 100644 --- a/src/app/features/indicadores/paciente-identidad.ts +++ b/src/app/features/indicadores/paciente-identidad.ts @@ -18,7 +18,7 @@ export const ETIQUETA_IDENTIDAD: Readonly> = { }; // No leading zeros and no sign: the value is compared and sent as text, so it has one spelling. -const PAC_ID = /^(0|[1-9][0-9]{0,17})$/; +const PAC_ID = /^(0|[1-9][0-9]{0,18})$/; /** The fields of a row that matter here; a typed row or a plain record both fit. */ export interface FilaConIdentidad { readonly pac_id?: unknown; readonly id_seudonimo?: unknown } const texto = (v: unknown): v is string => typeof v === 'string' && v.length > 0; From 7a2f0f42a92df1735bb775f9178c845eed5de35b Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sat, 14 Nov 2026 00:14:53 -0600 Subject: [PATCH 37/38] =?UTF-8?q?feat(cama):=20An=C3=A1lisis=20epidemiol?= =?UTF-8?q?=C3=B3gico=20frame=20with=20category=20cards,=20cut-off=20bar?= =?UTF-8?q?=20and=20the=20BI-RADS=20count?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../indicadores/indicadores-analisis.spec.ts | 26 +++++ .../indicadores/indicadores-analisis.ts | 103 +++++++++++------- .../indicadores-recorrido-analisis.spec.ts | 2 +- 3 files changed, 89 insertions(+), 42 deletions(-) diff --git a/src/app/features/indicadores/indicadores-analisis.spec.ts b/src/app/features/indicadores/indicadores-analisis.spec.ts index 9a9629a..6a87b0f 100644 --- a/src/app/features/indicadores/indicadores-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-analisis.spec.ts @@ -114,6 +114,32 @@ describe('Pestaña Análisis epidemiológico', () => { expect(filas.map(f => f.querySelector('th')!.textContent!.trim())).toEqual(['BI-RADS 4', 'BI-RADS 4A', 'BI-RADS 4B', 'BI-RADS 4C', 'BI-RADS 5', 'BI-RADS 6']); expect(filas.map(f => f.children[1].textContent!.trim())).toEqual(['No publicado', 'No publicado', 'No publicado', 'No publicado', '6', 'No publicado']); }); + it('encabeza la vista y deriva las dos tarjetas de los estados de los grupos, sin sumar pacientes', () => { + // Fails if the cards count patients instead of categories, appear before an answer, or the heading and denominator are lost. + abrir(); + expect(root().querySelector('h2')!.textContent).toBe('Análisis epidemiológico'); + expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); + pedido().flush(agregadoJson({ corte: hoyIso() })); fixture.detectChanges(); + const tarjetas = Array.from(root().querySelectorAll('app-indicador-kpi-card')) as HTMLElement[]; + expect(tarjetas.map(t => t.querySelector('h3')!.textContent)).toEqual(['Categorías publicadas', 'Categorías no publicadas']); + expect(tarjetas.map(t => t.querySelector('.value')!.textContent!.trim())).toEqual(['1', '5']); + expect(tarjetas[0].textContent).toContain('de 6 categorías BI-RADS'); + expect(tarjetas[0].textContent).not.toContain('6 pacientes'); + expect(root().querySelector('h3#birads-titulo')!.textContent).toBe('Pacientes por categoría BI-RADS'); + expect(text()).toContain('Denominador: pacientes elegibles con última mastografía reportada BI-RADS 4 a 6.'); + expect(text()).toContain('abrir la lista en Seguimiento'); + }); + it('las tarjetas cuentan 0 publicadas cuando todas se suprimen y desaparecen en carga, pendiente y error', () => { + // Fails if the cards stay on screen without an answer with categories. + abrir(); + const grupos = agregado().grupos.map(g => ({ codigo: g.codigo, n: null, suprimido: true })); + pedido().flush(agregadoJson({ corte: hoyIso(), grupos })); fixture.detectChanges(); + expect(Array.from(root().querySelectorAll('app-indicador-kpi-card .value')).map(v => v.textContent!.trim())).toEqual(['0', '6']); + fixture.componentInstance.consultar(); fixture.detectChanges(); + expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); + pedido().flush({}, { status: 404, statusText: 'Not found' }); fixture.detectChanges(); + expect(root().querySelector('app-indicador-kpi-card')).toBeNull(); + }); it('«Consultar» pide el agregado a la fecha elegida y la respuesta tardía de una consulta anterior no se dibuja', async () => { // Fails if a slow answer replaces the aggregate of a later cut-off. abrir(); diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index d727124..d2e08ca 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -6,6 +6,7 @@ import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { catchError, map, Observable, of, startWith, Subject, switchMap } from 'rxjs'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { IndicadorKpiCard } from './indicador-kpi-card'; import { isoDate } from './cacu-seguimiento.models'; import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras'; import { etiquetaBirads } from './etiquetas-cohorte'; @@ -53,62 +54,80 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement { // a suppressed one says why it does not. Nothing is requested until the tab is first opened. @Component({ selector: 'app-indicadores-analisis', - imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart], + imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard], template: ` -
-

Pacientes por categoría BI-RADS

-

Conteo descriptivo de las pacientes de la cohorte en cada categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.

+
+

Análisis epidemiológico

+

Conteo de pacientes de la cohorte por categoría BI-RADS a la fecha de corte. No estima incidencia, recurrencia ni supervivencia.

+ @if (datos(); as d) { +

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

+
+ + +
+ } - @switch (carga().estado) { - @case ('cargando') { } - @case ('pendiente') {

Funcionalidad pendiente de publicación.

} - @case ('no-disponible') { -

La cohorte no está disponible en este momento.

- +
+

Pacientes por categoría BI-RADS

+ @switch (carga().estado) { + @case ('cargando') { } + @case ('pendiente') {

Funcionalidad pendiente de publicación.

} + @case ('no-disponible') { +

La cohorte no está disponible en este momento.

+ + } + @case ('error') { +

{{ $any(carga()).mensaje }}

+ } } - @case ('error') { -

{{ $any(carga()).mensaje }}

+ @if (datos(); as d) { + @if (todasSuprimidas()) { +

Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.

+ } +

{{ aviso() }}

+ +

Haga clic en una barra o use «Ver pacientes» para abrir la lista en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.

+
+
Resultados disponibles por paciente
Identificador seudónimoGrupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ etiquetaIdentidad(response) }}Grupo de edadEstatus de seguimientoÚltima citologíaÚltimo resultado de VPHEstudio más recienteDías de toma a diagnósticoPrioridad
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }}
{{ item.grupo_edad === 'sin_dato' ? 'Sin dato' : item.grupo_edad }}{{ item.estatus.etiqueta }} @if (item.ultima_citologia; as c) { {{ cytologyLabel(c) }}Fecha: {{ c.fecha }}Calidad: {{ c.calidad ?? '—' }} } @else { No disponible } @if (item.ultimo_vph; as v) { {{ v.resultado }}Fecha: {{ v.fecha }}Genotipo 16/18: {{ v.genotipo_16_18 === null ? 'No disponible' : v.genotipo_16_18 ? 'Presente' : 'No detectado' }} } @else { No disponible } {{ latestStudy(item) ?? 'No disponible' }}{{ item.dias_toma_diagnostico ?? 'No disponible' }}{{ item.prioridad?.etiqueta ?? 'No disponible' }}
+ + + + @for (g of d.grupos; track g.codigo) { + + + + + + } + +
Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}
CategoríaPacientesSeguimiento
{{ etiqueta(g.codigo) }}{{ g.suprimido ? 'No publicado' : miles(g.n!) }}@if (g.suprimido) { {{ motivo }} } + @else { }
+
} - } - @if (datos(); as d) { -

Fecha de corte: {{ d.corte }}. Denominador: {{ d.denominador }}.

- @if (todasSuprimidas()) { -

Ninguna categoría alcanza el mínimo de {{ d.umbral_supresion }} pacientes para publicarse a esta fecha de corte.

- } -

{{ aviso() }}

- -

Haga clic en una barra publicada para ver sus pacientes en Seguimiento. Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica.

-
- - - - - @for (g of d.grupos; track g.codigo) { - - - - - - } - -
Pacientes por categoría BI-RADS a la fecha de corte {{ d.corte }}
CategoríaPacientesSeguimiento
{{ etiqueta(g.codigo) }}{{ g.suprimido ? 'No publicado' : miles(g.n!) }}@if (g.suprimido) { {{ motivo }} } - @else { }
-
- } + `, styles: ` :host { display: block; min-width: 0; } + .analisis { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; } + .analisis > * { margin: 0; } + /* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */ + :host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); } + .tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); } + @media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } } .panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } - h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } + h2, h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1.25rem; line-height: 1.3; overflow-wrap: anywhere; } p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } .nota, .contexto, .sin-lista { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); } - .controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-4); } + .controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); padding: var(--issste-space-3) var(--issste-space-4); background: var(--issste-surface); + border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; } input { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; box-sizing: border-box; font: inherit; max-width: 100%; } input:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; } @@ -150,6 +169,8 @@ export class IndicadoresAnalisis { // Why the last click on a bar opened nothing. readonly aviso = signal(''); readonly datos = computed(() => { const c = this.carga(); return c.estado === 'listo' ? c.datos : undefined; }); + // How many categories the answer publishes; the rest are suppressed. Counts categories only, never patients. + readonly publicadas = computed(() => this.datos()?.grupos.filter(g => !g.suprimido).length ?? 0); // The answer cannot tell an empty cohort from categories that are all under the threshold: it only says none is published. readonly todasSuprimidas = computed(() => !!this.datos()?.grupos.every(g => g.suprimido)); readonly figura = computed(() => { const d = this.datos(); return d ? gruposFigura(d, this.tema()) : { data: [], layout: {} }; }); diff --git a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts index 86e447c..54c1052 100644 --- a/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts +++ b/src/app/features/indicadores/indicadores-recorrido-analisis.spec.ts @@ -67,7 +67,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () = // Fails if any step of the journey drops the selection, repeats a request, loses the focus or the answer already loaded. const e = await entrar(); await abrirAnalisis(e); - const origen = e.root.querySelector('#analisis-titulo ~ .tabla-scroll tr[data-grupo="BIRADS_5"] button.ver')!; + const origen = e.root.querySelector('#birads-titulo ~ .tabla-scroll tr[data-grupo="BIRADS_5"] button.ver')!; origen.focus(); origen.click(); e.harness.detectChanges(); // Seguimiento on the whole cohort of the group, at the analysis' cut-off, quoting its cohort and revision. From 7580319fc84f9ab1ec868f7539b8d39b28ef5733 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sat, 14 Nov 2026 07:56:33 -0600 Subject: [PATCH 38/38] =?UTF-8?q?fix(cama):=20single=20vertical=20scroll?= =?UTF-8?q?=20in=20An=C3=A1lisis=20epidemiol=C3=B3gico?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The visually-hidden labels are absolutely positioned and had no positioned ancestor in the view, so they were laid out against the document and, with the table far down the page, gave the document its own vertical scroll next to the one of the page container. The view is now their containing block. --- src/app/features/indicadores/indicadores-analisis.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/app/features/indicadores/indicadores-analisis.ts b/src/app/features/indicadores/indicadores-analisis.ts index d2e08ca..ed721db 100644 --- a/src/app/features/indicadores/indicadores-analisis.ts +++ b/src/app/features/indicadores/indicadores-analisis.ts @@ -115,7 +115,8 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement { `, styles: ` :host { display: block; min-width: 0; } - .analisis { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; } + /* Positioned so the absolutely placed visually-hidden labels belong to this view: otherwise they are laid out against the document and give it a vertical scroll of its own. */ + .analisis { position: relative; display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; } .analisis > * { margin: 0; } /* The dark theme paints the panel's own surfaces, not the page: the loose heading and notes get the dark background so their light text stays legible. */ :host-context(.dark-theme) .analisis { padding: var(--issste-space-4); background: var(--issste-background); color: var(--issste-text); border-radius: var(--issste-radius); }