From f6603ae76ed14c94a7023a1a394e174e706a9a60 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Thu, 19 Nov 2026 19:04:22 -0600 Subject: [PATCH 1/2] fix(cama): align BI-RADS labels and remove historical detection chart --- .../indicadores/indicador-catalog-card.ts | 13 +--- .../indicador-conteos-pareados.html | 34 +++----- .../indicador-conteos-pareados.scss | 11 +-- .../indicadores/indicador-conteos-pareados.ts | 28 +------ .../indicadores/indicadores-cama-f4c.spec.ts | 35 +++++---- .../indicadores-cama-resumen-clinico.spec.ts | 6 ++ .../indicadores-conteos-pareados.spec.ts | 78 +++++++------------ .../indicadores/indicadores-figure-labels.ts | 2 + .../indicadores-historico-cama.spec.ts | 8 +- .../indicadores/indicadores-historico.ts | 4 +- .../features/indicadores/indicadores-page.ts | 4 +- 11 files changed, 89 insertions(+), 134 deletions(-) diff --git a/src/app/features/indicadores/indicador-catalog-card.ts b/src/app/features/indicadores/indicador-catalog-card.ts index 4f583fc..3a22177 100644 --- a/src/app/features/indicadores/indicador-catalog-card.ts +++ b/src/app/features/indicadores/indicador-catalog-card.ts @@ -33,13 +33,13 @@ import { parConteos } from './indicadores-conteos-pareados'; @if (!conteos) {
-

{{ tituloVisible }}

+

{{ indicador.titulo }}

} @if (!sobrio) { @@ -64,7 +64,7 @@ import { parConteos } from './indicadores-conteos-pareados'; } @else if (conteos; as par) {
- +
} @else if (selectedFigure) {
@@ -128,7 +128,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { private metadataSubscription?: Subscription; private metadataKey = ''; metadata?: IndicadorMetadatos; - metadataAttempt = 0; private activatedKey = ''; constructor() { effect(() => { @@ -138,11 +137,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { } // CaMa's cards carry no pin, representation selector or figure count, as in the mockup. get sobrio() { return this.dominio === 'cama'; } - // The published title keeps «individual»; the card does not. The paired BI-RADS card has no card title: - // each donut carries its own («Mastografías por categoría, », «Pacientes por categoría, »). - get tituloVisible() { - return this.indicador.id === 'cama_birads_456_mastografia' ? this.indicador.titulo.replace(' individual', '') : this.indicador.titulo; - } 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; } @@ -228,7 +222,6 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy { if (this.metadataKey !== key) return; if (!value) this.metadataKey = ''; this.metadata = value; - this.metadataAttempt++; this.changeDetector.markForCheck(); }); } diff --git a/src/app/features/indicadores/indicador-conteos-pareados.html b/src/app/features/indicadores/indicador-conteos-pareados.html index 06d7829..b16e730 100644 --- a/src/app/features/indicadores/indicador-conteos-pareados.html +++ b/src/app/features/indicadores/indicador-conteos-pareados.html @@ -7,6 +7,8 @@ @case ('incompatible') {

Respuesta incompatible: {{ message }}

} } @if (status() === 'ready' && model; as m) { + @let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo; + @let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo; @if (pages.length > 1) {
@switch (status()) { @case ('deferred') {

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

} - @case ('loading') {

Cargando el mismo periodo para tasas y dona…

} - @case ('error') {

{{ message }}

} - @case ('incompatible') {

Respuesta incompatible: {{ message }}

} + @case ('incompatible') {

{{ message }}

} } - @if (status() === 'ready' || status() === 'empty') { + @if (status() === 'empty') { +

No hay resultados de biopsia para el periodo seleccionado.

+ } + @if (status() === 'ready') { @if (periods.length > 1) { } @if (model; as m) { - @if (status() === 'empty') {

No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.

} - @else {
@@ -50,7 +41,7 @@
@for (g of m.grupos; track g.id) {
- @for (c of m.categorias; track c.id; let ci = $index) { + @for (c of categoriasExteriores(m); track c.id; let ci = $index) { @if (c.grupo === g.id) { } @@ -71,9 +62,8 @@ } @else {

{{ m.conResultado === null ? 'Dona no disponible: hay celdas suprimidas o datos incompletos. No se calcula un total parcial.' : 'Sin pacientes con resultado de biopsia en el periodo.' }}

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

{{ note }}

} -
Valores publicados +
Ver valores
@for (c of m.categorias; track c.id) { }@for (a of m.aparte; track a.id) { } diff --git a/src/app/features/indicadores/indicador-histopatologia-cama.ts b/src/app/features/indicadores/indicador-histopatologia-cama.ts index d6cd68c..e52dba6 100644 --- a/src/app/features/indicadores/indicador-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicador-histopatologia-cama.ts @@ -1,28 +1,15 @@ -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 { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, signal, SimpleChanges } from '@angular/core'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; +import { Dominio, Indicador, PlotlyFigure, Tema } from './indicadores.models'; import { filterCompatibility, GlobalApplied } from './indicadores-memory'; -import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; -import { httpMessage } from './indicadores-http'; +import { snapshotKey } from './indicadores-snapshots'; 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`. - */ +import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA, + ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama'; +import { modelosHistopatologiaDemo } from './histopatologia-cama-demo'; @Component({ selector: 'app-indicador-histopatologia-cama', - imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], + imports: [PlotlyChart], templateUrl: './indicador-histopatologia-cama.html', styleUrl: './indicador-confirmacion-citologia.scss', }) @@ -32,9 +19,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { @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'); + readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred'); message = ''; selection?: SeleccionHistopatologia; periods: string[] = []; @@ -43,10 +28,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { donutFigure?: PlotlyFigure; ratesFigure?: PlotlyFigure; helpOpen = false; + readonly categoriasExteriores = categoriasExteriores; private helpPinned = false; - private readonly snapshots = inject(IndicadoresSnapshots); private readonly changeDetector = inject(ChangeDetectorRef); - private subscription?: Subscription; private key = ''; private loaded = false; private pages: ModeloHistopatologia[] = []; @@ -61,21 +45,8 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { ?? (this.applied?.selection.mode === 'explicit' && this.applied.selection.periodos.length === 1 ? this.applied.selection.periodos[0] : ''); } 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() { if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; } this.helpPinned = true; @@ -84,7 +55,6 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { showHelp() { if (this.helpOpen) return; this.helpOpen = true; - this.metadataRequested.emit(); } hideHelp() { if (!this.helpPinned) this.helpOpen = false; } onHelpFocusOut(event: FocusEvent) { @@ -95,53 +65,32 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { } 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]); + const key = snapshotKey(this.dominio, this.indicador, this.applied) + + JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]); if (key !== this.key) { - this.subscription?.unsubscribe(); this.key = key; this.loaded = false; + 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(); + const { tipo, selection } = this.applied; + this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined); + this.periods = this.pages.map(modelo => modelo.periodo); + this.periodIndex = Math.max(0, this.periods.length - 1); + this.activatePeriod(); } private activatePeriod() { this.model = this.pages[this.periodIndex]; @@ -166,5 +115,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy { this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches); this.changeDetector.markForCheck(); } - ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); } + ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); } } diff --git a/src/app/features/indicadores/indicador-histopatologia-pendiente.ts b/src/app/features/indicadores/indicador-histopatologia-pendiente.ts deleted file mode 100644 index d7b7d9f..0000000 --- a/src/app/features/indicadores/indicador-histopatologia-pendiente.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Component, signal } from '@angular/core'; -import { MatButtonModule } from '@angular/material/button'; -import { MatCardModule } from '@angular/material/card'; - -/** - * CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator - * (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number. - */ -@Component({ - selector: 'app-indicador-histopatologia-pendiente', - host: { class: 'dual-card' }, - imports: [MatButtonModule, MatCardModule], - template: ` - -

Resultado histopatológico por categoría BI-RADS

- - @if (ayuda()) { -
-

Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.

-
- } -

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

-
-

Por categoría BI-RADS

Sin datos publicados
-

Resultado de la biopsia

Sin datos publicados
-
-
- `, - styles: ` - :host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; } - mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text); - border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; } - h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; } - h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; } - p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; } - .estado { color: var(--issste-text-secondary); } - .methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); } - .methodology p { margin: 0; } - .figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); } - @media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } } - .vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary); - border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); } - button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; } - `, -}) -export class IndicadorHistopatologiaPendiente { - readonly ayuda = signal(false); -} diff --git a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts index 2c3baa5..4929cb2 100644 --- a/src/app/features/indicadores/indicadores-cama-f4c.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-f4c.spec.ts @@ -217,7 +217,6 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { }); 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(); @@ -231,13 +230,10 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => { 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(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente'); + it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => { + const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]); + expect(kpis()).toHaveLength(5); + expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); + expect(pedidos).not.toContain('cama_histopatologia_birads'); }); }); 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 46cc2ba..84fa065 100644 --- a/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts +++ b/src/app/features/indicadores/indicadores-cama-resumen-clinico.spec.ts @@ -53,8 +53,8 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { 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'); - // The paired card has no card title; each donut names itself. The other three indicators are in Histórico. - expect(titles()).toEqual([]); + // The paired card has no card title; each donut names itself. + expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']); expect(root().querySelector('app-indicador-conteos-pareados')).not.toBeNull(); expect(section().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6'); expect(root().textContent).not.toContain('indicador publicado'); @@ -73,26 +73,21 @@ describe('Resumen clínico de CaMa y los demás dominios', () => { expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6'); expect(nombres).not.toContain(CAMA[1].titulo); }); - it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => { + it('CaMa: la tarjeta de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => { open('cama', CAMA); - const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement; - expect(tarjeta).not.toBeNull(); - expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS'); - expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente'); - expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']); - expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull(); - expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false); - // It comes first, as in the reference, and is not counted as a published indicator. - expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta); + const primera = root().querySelector('.catalog-grid')!.firstElementChild!; + expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull(); + expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS'); + expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads'); }); - it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => { + it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => { open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]); - expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); + expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1); expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS'); }); - it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => { + it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => { open(domain, OTRO(domain)); - expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull(); + expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull(); }); 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. diff --git a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts index c55f145..1f51bad 100644 --- a/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts +++ b/src/app/features/indicadores/indicadores-conteos-pareados.spec.ts @@ -204,7 +204,7 @@ describe('Tarjeta pareada de CaMa en la página', () => { const titulos = [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim()); // Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary. // The pair has no card title; each donut has its own heading. - expect(titulos).toEqual([]); + expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']); expect(root().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6'); expect(root().textContent).not.toContain('indicador publicado'); }); diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts index 2073295..6b9988c 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.spec.ts @@ -1,5 +1,5 @@ // 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 +// rates and figures, and the catalog wiring of the local view. 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'; @@ -235,124 +235,32 @@ describe('Histopatología por BI-RADS: componente', () => { 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('.legend 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('.tabs button')].map((b: Element) => b.textContent!.trim())) - .toEqual(['No maligno', 'Maligno']); - expect(f.nativeElement.querySelector('.tabs button[aria-selected=true]')!.textContent!.trim()).toBe('Maligno'); - expect([...f.nativeElement.querySelectorAll('.tab-panel button')].map((b: Element) => b.textContent!.trim())) - .toEqual(['Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor']); - const grafica = f.nativeElement.querySelector('.figures') as HTMLElement; - const leyenda = f.nativeElement.querySelector('.legend') as HTMLElement; - const contexto = f.nativeElement.querySelector('.view-context') as HTMLElement; - expect(leyenda.compareDocumentPosition(grafica) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(Node.DOCUMENT_POSITION_FOLLOWING); - expect(f.nativeElement.textContent).not.toContain('Filtro general aplicado'); - expect(f.nativeElement.querySelector('.selection-status')).toBeNull(); - expect(f.nativeElement.querySelector('.rate-states')).toBeNull(); - expect(f.nativeElement.textContent).not.toContain('Sin pacientes con resultado de biopsia'); - expect(contexto.textContent).toContain('Intervalo semestral'); - expect(contexto.textContent).toContain('Periodo 2025-S1'); - expect(f.componentInstance.selectionLabel).toBe('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;'); - }); - 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); - expect(f.nativeElement.textContent).not.toContain('Volver'); - boton('No maligno').click(); f.detectChanges(); - 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(f.componentInstance.reading).toContain('Proporción con resultado lesión de riesgo (B3)'); - b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' }); - boton('Maligno').click(); f.detectChanges(); - boton('Carcinoma invasor').click(); f.detectChanges(); - expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' }); - boton('Maligno').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' }); + it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => { + f.componentRef.setInput('visible', false); + f.detectChanges(); + expect(f.componentInstance.status()).toBe('deferred'); + f.componentRef.setInput('visible', true); + f.detectChanges(); + expect(f.componentInstance.status()).toBe('ready'); + expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2); + expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma'); + f.componentRef.setInput('tema', 'oscuro'); + f.detectChanges(); + expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); 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); + + it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => { + f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 }); + f.detectChanges(); + expect(f.componentInstance.contextPeriod).toBe('2025-02'); 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('.rates').textContent).not.toContain('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('.rates').textContent).not.toContain('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); + f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 }); + f.detectChanges(); 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.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.'); 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); + http.expectNone(() => true); }); it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => { diff --git a/src/app/features/indicadores/indicadores-histopatologia-cama.ts b/src/app/features/indicadores/indicadores-histopatologia-cama.ts index 35d1e92..83bc7eb 100644 --- a/src/app/features/indicadores/indicadores-histopatologia-cama.ts +++ b/src/app/features/indicadores/indicadores-histopatologia-cama.ts @@ -15,7 +15,7 @@ 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> = { +export 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 @@ -41,19 +41,21 @@ export interface Categoria { id: string; etiqueta: string; color: string; grupo: export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; } export interface FilaBirads { id: string; etiqueta: string; - // The four categories with a result. + // Categories with a biopsy 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. + // Patients with a biopsy result: the denominator. Null while any result cell 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[]; + // When set, the outer ring shows the subtype distribution within this group. + grupoAnilloExterior?: 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; } @@ -66,7 +68,7 @@ const escapar = (v: string) => v.replace(/&/g, '&').replace(/ 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 enFrase = (v: string) => v === v.toUpperCase() ? v : 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. @@ -183,6 +185,9 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo } export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; } +export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] { + return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias; +} export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] { return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? []; } @@ -194,12 +199,15 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop 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]; + const c = categoriasExteriores(m)[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 (m.grupoAnilloExterior) { + return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia'; + } 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 ' + enFrase(seleccionEtiqueta(m, sel)); @@ -229,16 +237,19 @@ export function rangoTasas(valores: Tasa[]): [number, number] { // `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 barras = !!m.grupoAnilloExterior; 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 tono = tonoDe(sel.categoria ?? sel.grupo); const familia = tono === 'frio' ? C2_PALETTE.frios : tono === 'calido' ? C2_PALETTE.calidos : [color]; const y = valores.map(t => t.fila.etiqueta); - const colores = sel.categoria ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); + const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]); + const rango = rangoTasas(valores); return { data: [{ - type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), - marker: { size: 12, color: colores }, cliponaxis: false, - error_x: { type: 'data', symmetric: false, color: colores, thickness: 2, width: 6, + ...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }), + uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor), + marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false, + error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, 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]} %', @@ -248,8 +259,8 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi 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 } }, + xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true, + title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : '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: estrecho ? 11 : 12, color: p.text }, text: t.k === null ? estadoTasa(t) : `${shareText(t.k, t.fila.den!)}
${t.k}/${t.fila.den}` })), @@ -262,17 +273,27 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop 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 categorias = categoriasExteriores(m); + const exterior = categorias.map(c => m.totales[c.id]!); + const centro = m.grupoAnilloExterior + ? `${miles(k)}
de ${miles(total)}
con resultado` + : `${miles(k)}
de ${miles(total)} con resultado`; 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)]); + const custom = (values: number[]) => { + const subtotal = values.reduce((s, n) => s + n, 0); + return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]); + }; + const hoverExterior = m.grupoAnilloExterior + ? { hovertemplate: '%{label}
%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)' } + : hover; const zoomGrupo = (id: string, hijos: readonly string[]) => sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1; const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1; const zoomDe = (values: number[]) => Math.max(1, ...values); const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)'); const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias)); - const categoriasZoom = m.categorias.map(c => zoomCategoria(c.id)); + const categoriasZoom = categorias.map(c => zoomCategoria(c.id)); const anillo = (name: string, values: number[], labels: string[], hole: number, base: readonly [number, number, number, number], zoom: number[], colores: string[]) => ({ ...comun, ...hover, name, values, labels, hole, customdata: custom(values), domain: caja(base, zoomDe(zoom)), @@ -280,16 +301,16 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop }); return { data: [ { ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside', - text: [`${miles(k)}
de ${miles(total)} con resultado`], textfont: { size: 16, color: p.text }, + text: [centro], 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: caja(CAJA_GRUPO, 1), labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior), marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } }, - { ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1), - labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), - marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 2 } } }, + { ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1), + labels: categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior), + marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } }, anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)), - anillo('categorias', exterior, m.categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, m.categorias.map(c => c.color)), + { ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior }, ], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } }, config: { displayModeBar: false } }; } diff --git a/src/app/features/indicadores/indicadores-initial-integration.spec.ts b/src/app/features/indicadores/indicadores-initial-integration.spec.ts index 61b0a4c..91a8301 100644 --- a/src/app/features/indicadores/indicadores-initial-integration.spec.ts +++ b/src/app/features/indicadores/indicadores-initial-integration.spec.ts @@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; -import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi'; +import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi'; import { pending } from './indicadores-memory'; import { Indicador } from './indicadores.models'; @@ -64,7 +64,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos')); } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); } - function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + // CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards. + function cards() { + return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) + .filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA); + } function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; } // The shared request queue runs four at a time: flushing a batch starts the next. function flushPanels(period: string, expected = definitions.length - 1) { diff --git a/src/app/features/indicadores/indicadores-navigation.spec.ts b/src/app/features/indicadores/indicadores-navigation.spec.ts index 49eec65..7efe6df 100644 --- a/src/app/features/indicadores/indicadores-navigation.spec.ts +++ b/src/app/features/indicadores/indicadores-navigation.spec.ts @@ -15,6 +15,7 @@ import { IndicadoresPage } from './indicadores-page'; import { IndicadorFigureCard } from './indicador-figure-card'; import { IndicadorPeriodFilters } from './indicador-period-filters'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { PlotlyFigure } from './indicadores.models'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; @@ -36,7 +37,9 @@ describe('UX-04 navegación Angular', () => { harness.detectChanges(); const page = harness.routeDebugElement!.componentInstance as IndicadoresPage; vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {}); - const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard; + // CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one. + const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) + .find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!; if (!card.visible) { card.setVisible(true); harness.detectChanges(); } const req = http.expectOne(r => r.url.includes('/figuras/')); req.flush({ data: [{ y: [0, null] }], layout: {} }); diff --git a/src/app/features/indicadores/indicadores-page.html b/src/app/features/indicadores/indicadores-page.html index a7c3ed6..59905a6 100644 --- a/src/app/features/indicadores/indicadores-page.html +++ b/src/app/features/indicadores/indicadores-page.html @@ -117,7 +117,6 @@ }
- @if (histopatologiaPendiente) { } @for (item of searchResults().items; track cardIdentity(item)) { diff --git a/src/app/features/indicadores/indicadores-page.spec.ts b/src/app/features/indicadores/indicadores-page.spec.ts index eac148d..d737559 100644 --- a/src/app/features/indicadores/indicadores-page.spec.ts +++ b/src/app/features/indicadores/indicadores-page.spec.ts @@ -15,6 +15,7 @@ import { MatSelect } from '@angular/material/select'; import { NgModel } from '@angular/forms'; import { IndicadoresMemory } from './indicadores-memory'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; +import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { Indicador, PlotlyFigure } from './indicadores.models'; import { syntheticCatalogs } from './indicadores.synthetic-fixtures'; @@ -37,7 +38,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => { function load(items: Indicador[] = [item, second], domain = 'tea') { http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges(); } - function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); } + // CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards. + function cards() { + return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard) + .filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA); + } function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); } function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); } function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); } diff --git a/src/app/features/indicadores/indicadores-page.ts b/src/app/features/indicadores/indicadores-page.ts index 0f4327c..f26d910 100644 --- a/src/app/features/indicadores/indicadores-page.ts +++ b/src/app/features/indicadores/indicadores-page.ts @@ -31,7 +31,6 @@ 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 { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels'; type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos'; @@ -52,7 +51,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [ @Component({ selector: 'app-indicadores-page', - imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo], + imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo], templateUrl: './indicadores-page.html', styleUrl: './indicadores-page.scss', }) @@ -315,14 +314,15 @@ export class IndicadoresPage { private cardsDeCama(catalog: Indicador[]) { const ids = catalog.map(item => item.id); 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. + if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) { + cards.unshift({ + id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS', + contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'], + }); + } + // The histopathology card comes first, including when only the local source is available. 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() { - return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0 - && !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA); - } // How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them. get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); } // TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period. @@ -365,8 +365,8 @@ export class IndicadoresPage { return selected.length + ' indicadores'; }); readonly searchResults = computed(() => { - const selected = new Set(this.selectedIndicators()); - const items = this.catalogOrder().filter(item => selected.has(item.id)); + const selected = this.indicatorSelection(); + const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id)); return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] }; }); readonly catalogLoading = signal(true); diff --git a/src/app/features/indicadores/indicadores-pinning.spec.ts b/src/app/features/indicadores/indicadores-pinning.spec.ts index 8bf182a..f9fc8ca 100644 --- a/src/app/features/indicadores/indicadores-pinning.spec.ts +++ b/src/app/features/indicadores/indicadores-pinning.spec.ts @@ -8,6 +8,7 @@ import { IndicadoresPage } from './indicadores-page'; import { IndicadorCatalogCard } from './indicador-catalog-card'; import { IndicadorFigurePanel } from './indicador-figure-panel'; import { IndicadoresMemory } from './indicadores-memory'; +import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi'; import { Indicador } from './indicadores.models'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime'; @@ -83,7 +84,8 @@ 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)); + // Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned. + await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]); 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);
Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}
Categoría BI-RADS{{ c.etiqueta }}Con resultado{{ a.etiqueta }}Total de pacientes