Compare commits

...

35 Commits

Author SHA1 Message Date
Angel Capetillo Zavala 3385df4ba3 Merge current WebApp dev into the CaMa selective rollback 2026-11-20 09:57:32 -06:00
Manuel Aurrecoechea Castillo 96b1cabb5a feat(cama): space the opportunity strip, share its period and unify history lines
The section sat flush against its cards, each card repeated the period, the history selector was taller than the summary, and each CaMa line used a different color.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 09:49:32 -06:00
Angel Capetillo Zavala 366591f247 fix(cama): restore published histopathology and mammography counts 2026-11-20 09:07:38 -06:00
angel 241631b884 Merge pull request 'Finalize CaMa wording, demo mammography counts and histologic classification' (#13) from feature/cama-clasificacion-histologica into dev 2026-11-20 00:52:29 -06:00
Angel Capetillo Zavala 6c063344a3 feat(cama): adjust summary wording, double mastography counts and classify histologic types
Reword the histopathologic confirmation note, the BI-RADS 4, 5 or 6 titles and the
radiologic interpretation time title. Show twice the BI-RADS 4, 5 or 6 mastography
counts in the FHIR and base data services. Add the histologic type classification
and a follow-up table column that appears only when a row carries tipo_histologico.
2026-11-20 00:32:27 -06:00
angel 2f5b1ce1f2 Merge pull request 'Feature/cama audit histopathology demo' (#12) from feature/cama-audit-histopathology-demo into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/12
2026-11-19 19:45:53 -06:00
Angel Capetillo Zavala 56b3ac6b0c feat(cama): add synthetic histopathology breakdown for demo 2026-11-19 19:36:18 -06:00
Angel Capetillo Zavala f6603ae76e fix(cama): align BI-RADS labels and remove historical detection chart 2026-11-19 19:04:22 -06:00
Manuel Aurrecoechea Castillo 21ae95b5ed 20261119 CaMa: ayuda en cada dona de BI-RADS
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:11:20 -06:00
Manuel Aurrecoechea Castillo ce2e86c045 20261119 CaMa: cada dona de BI-RADS lleva su título y la categoría más alta
El resumen ya no repite el porcentaje publicado; pacientes y mastografías se leen en su propia gráfica.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:05:40 -06:00
angel 0f8eb0ec94 Merge pull request 'Add unavailable CaMa diagnosis-to-treatment card' (#11) from feature/cama-diagnosis-to-treatment-card into dev 2026-11-19 17:51:43 -06:00
Angel Capetillo Zavala 2f6d419453 Add unavailable CaMa diagnosis-to-treatment card 2026-11-19 17:48:13 -06:00
Manuel Aurrecoechea Castillo f34f9e1607 20261119 favico 2026-11-19 17:17:45 -06:00
Manuel Aurrecoechea Castillo c7dd134fce 20261119 CaMa titulos ayuda filtros
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 17:13:07 -06:00
Manuel Aurrecoechea Castillo 03cc9c9800 20261119 CaMa: donas de BI-RADS y etiquetas del resumen
La oportunidad dice confirmación histopatológica, la tarjeta de mastografías muestra dos donas y Cómo leer puede reintentar los metadatos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:50:01 -06:00
Manuel Aurrecoechea Castillo de3d247d0d 20261119 Favicon colores textos 2026-11-19 15:10:59 -06:00
Angel Capetillo Zavala ee87bcb8d0 test(webapp): seed the visual login session in indicadores specs
The indicadores navigation, sections and cancer-journey specs routed through
the real routes without a session, so authGuard redirected to LoginPage.
Add auth.testing helpers that seed and clear the sessionStorage session, use
them in those specs, and add a spec that /indicadores/<dominio> without a
session presents LoginPage with returnUrl.
2026-11-19 11:33:26 -06:00
Erick ivan aaeea7a7b0 refactor(auth): keep the session in the browser
The WebApi no longer authenticates, so the login validates against the accounts in auth.service.ts and the session lives in sessionStorage. The guard, the domain guard and the filtering of the import workspace and governance stay as they were; the interceptor and the /auth proxy entries go away because nothing answers 401.
2026-11-19 10:32:25 -06:00
Erick ivan 7f17681409 feat(auth): login screen and domain-scoped navigation
Session login against /auth/*, with a guard on every route and an interceptor that returns to the login on 401. The header, the import workspace and both governance panels only offer the account's own domains (auth/dominios.ts), and a batch opens on the account's database.

The sign-in screen follows the app's palette: logo above the title, the action button in the shared tokens, and no register or password-recovery rows.
2026-11-19 09:36:54 -06:00
angel d72c18756f Merge pull request 'test(indicadores): follow the published CAM-03 title and the Análisis tab' (#10) from fix/ci-spec-contracts into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/10
2026-11-19 00:09:54 -06:00
Angel Capetillo Zavala baf5edca42 test(indicadores): follow the published CAM-03 title and the Análisis tab
The history names CAM-03 «Resultado histopatológico»; the CAM-03 expectation in the F4C spec
now uses that title.

The CaMa page does not offer the Análisis tab while CAMA_ANALYSIS_ENABLED is off. The journey
specs that open it run only while the flag is on and are reported as skipped otherwise. The
domain-change spec selects patients through the page instead of through that tab, so it keeps
checking that the selection is cleared and that CaCu and TEA keep their sections.
2026-11-18 23:41:41 -06:00
Manuel Aurrecoechea Castillo fefa28ae7a 20261118 Pastilla Fix 2026-11-18 16:53:56 -06:00
Manuel Aurrecoechea Castillo a217ddae38 20261118 Color Fix 2026-11-18 16:10:11 -06:00
Manuel Aurrecoechea Castillo 97fcb37761 20261118 Sharts Colors 2026-11-18 15:43:23 -06:00
Manuel Aurrecoechea Castillo 58ff3870be 20261118 colorfix front
Cambio de los colores de las graficas para tener una mejor armonía de colores y evitar el uso de la unión de colores que interpreten ideas falsas
2026-11-18 15:16:13 -06:00
Angel Capetillo Zavala 439a039ff4 fix(cama): recuperar el tamaño responsivo de la dona BI-RADS 2026-11-18 14:58:54 -06:00
Angel Capetillo Zavala 049a9ca43c fix(cama): ocultar temporalmente la pestaña Análisis 2026-11-18 14:15:49 -06:00
Angel Capetillo Zavala f128f2e13a fix(cama): mostrar solo el conteo al pasar sobre la dona 2026-11-18 13:15:54 -06:00
Angel Capetillo Zavala 20b8c80aaf fix(cama): equilibrar centro y anillo de la dona 2026-11-18 12:56:27 -06:00
Angel Capetillo Zavala 8e85c91f15 fix(cama): completar ajustes visuales de indicadores 2026-11-18 12:23:17 -06:00
Angel Capetillo Zavala 1ac8d5c258 fix(cama): ajustar resumen y ocultar análisis 2026-11-18 09:25:38 -06:00
Angel Capetillo Zavala 23cd89e882 Adjust CaMa indicator labels 2026-11-17 12:44:25 -06:00
Angel Capetillo Zavala 47a0ab5f1b Connect CaMa dashboard to follow-up, analysis and L3 FHIR measures
Preserve dev governance and risk-batch UI. Validate cohort navigation, API contracts and shared summary/history measures. Production build passes; 1785 tests pass with the six known Node 26 localStorage failures.
2026-11-17 10:44:08 -06:00
Roberto Treviño Cervantes dc37c54938 wording fixes 2026-11-17 02:17:24 -06:00
roberto 2834fac85c Merge pull request 'Kit exit: TEA over FHIR, dashboard-test presentation merged in' (#9) from feature/kit-exit-integration into dev
Reviewed-on: http://10.0.10.41:3000/ISSSTELEON/WebApp/pulls/9
2026-11-16 21:09:07 -06:00
136 changed files with 19179 additions and 585 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 717 B

+2 -1
View File
@@ -37,7 +37,8 @@ describe('Encabezado del marco', () => {
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);
// The application's routes live under the guarded parent ('login' is its sibling).
const paths = routes.flatMap((ruta) => [ruta.path, ...(ruta.children ?? []).map((hijo) => hijo.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) => {
+2
View File
@@ -12,6 +12,8 @@ export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes),
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
// porque la WebApi no responde 401.
provideHttpClient(),
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
+42 -23
View File
@@ -1,33 +1,52 @@
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
@if (!sinCromo()) {
<header class="site-header">
<div class="site-header__content">
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
</a>
@if (activeDomain(); as domain) {
<span class="platform-title">{{ title }}</span>
@if (otherDomains().length) {
@defer (on immediate) {
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
} @placeholder {
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
}
} @else {
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
}
</nav>
}
</div>
</header>
} @else {
<nav class="site-header__nav" aria-label="Secciones">
<a class="site-header__section" routerLink="/">Análisis de información</a>
@if (breadcrumb(); as crumb) {
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
}
</nav>
}
@if (usuario(); as sesion) {
<button
class="site-header__salir"
type="button"
(click)="salir()"
[attr.title]="'Cerrar sesión de ' + sesion.nombre"
[attr.aria-label]="'Cerrar sesión de ' + sesion.nombre"
>
<mat-icon aria-hidden="true">logout</mat-icon>
<span class="site-header__salir-nombre">{{ sesion.nombre }}</span>
</button>
}
</div>
</header>
}
<main class="app-main">
<router-outlet />
</main>
@if (!workspace()) {
@if (!workspace() && !sinCromo()) {
<footer class="site-footer">
<div class="site-footer__content">
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
+57 -37
View File
@@ -1,49 +1,69 @@
import { Routes } from '@angular/router';
import { Home } from './home';
import { authGuard } from './auth/auth.guard';
import { dominioGuard } from './auth/dominio.guard';
import { DOMINIOS } from './features/indicadores/indicadores.models';
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
export const routes: Routes = [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
data: { workspace: true, breadcrumb: 'Casos por estatus' },
path: 'login',
title: 'Inicio de sesión | ISSSTELEON',
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
data: { sinCromo: true },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
// Lazy: the workspace (and the ~15 Material modules it uses) only
// downloads when someone actually opens it.
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
data: { workspace: true, breadcrumb: 'Conectar datos' },
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
path: '',
canActivateChild: [authGuard],
children: [
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
{
path: 'indicadores/tea-estatus',
title: 'Casos por estatus | ISSSTELEON',
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Casos por estatus', dominio: 'tea' },
},
{
path: 'conectar',
title: 'Conectar datos | ISSSTELEON',
// Lazy: the workspace (and the ~15 Material modules it uses) only
// downloads when someone actually opens it.
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
data: { workspace: true, breadcrumb: 'Conectar datos' },
},
{
path: 'gobernanza',
title: 'Gobernanza de modelos | ISSSTELEON',
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
},
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
// The page reads CaCu's measures: an account of another domain goes to its own.
canActivate: [dominioGuard],
data: { workspace: true, breadcrumb: 'Indicadores', dominio: 'cacu' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
title: 'Indicadores | ISSSTELEON',
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
canActivate: [dominioGuard],
loadComponent: loadIndicadores,
})),
{ path: '**', redirectTo: '' },
],
},
{
path: 'gobernanza',
title: 'Gobernanza de modelos | ISSSTELEON',
loadComponent: () => import('./governance/components/governance-page/governance-page').then((m) => m.GovernancePage),
data: { workspace: true, breadcrumb: 'Gobernanza de modelos' },
},
{
path: 'bitacora',
title: 'Bitácora de cargas | ISSSTELEON',
loadComponent: () => import('./reportes/reportes-page').then((m) => m.ReportsPage),
data: { workspace: true, breadcrumb: 'Bitácora de cargas' },
},
{
path: 'kpis',
title: 'Indicadores | ISSSTELEON',
loadComponent: () => import('./features/indicadores/kpis-page').then(m => m.KpisPage),
data: { workspace: true, breadcrumb: 'Indicadores' },
},
{ path: 'indicadores', pathMatch: 'full', redirectTo: 'indicadores/tea' },
...DOMINIOS.map(dominio => ({
path: `indicadores/${dominio}`,
title: 'Indicadores | ISSSTELEON',
data: { workspace: true, breadcrumb: 'Indicadores', dominio },
loadComponent: loadIndicadores,
})),
{ path: '**', redirectTo: '' },
];
+40
View File
@@ -120,6 +120,46 @@
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
}
/* Session exit: the same action look as the home buttons, in header size. */
.site-header__salir {
align-items: center;
background: transparent;
border: 1px solid var(--color-action);
border-radius: 8px;
color: var(--color-text);
cursor: pointer;
display: inline-flex;
flex: none;
font: inherit;
font-size: 13px;
font-weight: 600;
gap: 6px;
margin-inline-start: var(--space-4);
min-height: 34px;
padding: 0 var(--space-3);
transition:
background-color 0.2s ease,
border-color 0.2s ease,
color 0.2s ease;
}
.site-header__salir:hover {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.site-header__salir:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.site-header__salir mat-icon {
color: var(--color-action);
font-size: 18px;
height: 18px;
width: 18px;
}
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
@media (max-width: 599px) {
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
+96 -25
View File
@@ -1,46 +1,117 @@
import { signal } from '@angular/core';
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 { provideRouter, Router } from '@angular/router';
import { of } from 'rxjs';
import { App } from './app';
import { routes } from './app.routes';
import { AuthService, Usuario } from './auth/auth.service';
const TODOS: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] };
/**
* Doble de la sesión: `App` lee la señal y los guards preguntan si hay sesión y
* qué dominios alcanza. Las pruebas de este archivo cubren el marco, no el
* inicio de sesión en sí (`auth/auth.service.spec.ts`).
*/
function authFalso(sesion: Usuario | null) {
return {
usuario: signal(sesion),
autenticado: signal(sesion !== null),
sesion: () => of(sesion),
puedeVer: (dominio: string) => sesion?.dominios.includes(dominio) ?? false,
logout: () => of(undefined),
limpiar: () => undefined,
};
}
async function montar(sesion: Usuario | null): Promise<Router> {
await TestBed.configureTestingModule({
imports: [App],
providers: [
provideRouter(routes),
provideHttpClient(),
provideHttpClientTesting(),
{ provide: AuthService, useValue: authFalso(sesion) },
],
}).compileComponents();
return TestBed.inject(Router);
}
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
}).compileComponents();
});
async function render(url: string) {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
await TestBed.inject(Router).navigateByUrl(url);
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
await fixture.whenStable();
fixture.detectChanges();
return fixture.nativeElement as HTMLElement;
}
it('renders the ISSSTELEON shell and home page with its footer', async () => {
const page = await render('/');
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
expect(page.querySelector('.site-footer')).not.toBeNull();
describe('con sesión de administrador', () => {
beforeEach(() => montar(TODOS));
it('renders the ISSSTELEON shell and home page with its footer', async () => {
const page = await render('/');
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
expect(page.querySelector('.site-footer')).not.toBeNull();
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
expect(page.querySelector('.site-footer')).toBeNull();
}, 15000);
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
const page = await render('/gobernanza');
expect(page.querySelector('app-governance-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
expect(page.querySelector('.site-footer')).toBeNull();
});
it('el encabezado nombra al usuario de la sesión y ofrece cerrarla', async () => {
// Fails if the shell forgets the session: the user would have no way out.
const page = await render('/');
expect(page.querySelector('.site-header__salir')?.textContent).toContain('Administrador');
});
});
it('/conectar opens the full-height workspace (breadcrumb, no footer)', async () => {
const page = await render('/conectar');
expect(page.querySelector('app-connect-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
expect(page.querySelector('.site-footer')).toBeNull();
describe('con una cuenta de un solo dominio', () => {
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
// Fails if the domain scope exists only on the server: the interface would show an empty page.
await render('/indicadores/cama');
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
}, 15000);
it('el encabezado no ofrece los otros dominios', async () => {
const page = await render('/indicadores/cacu');
expect(page.querySelector('app-domain-selector')).toBeNull();
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('CaCu');
});
});
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
const page = await render('/gobernanza');
expect(page.querySelector('app-governance-page')).not.toBeNull();
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
expect(page.querySelector('.site-footer')).toBeNull();
describe('sin sesión', () => {
beforeEach(() => montar(null));
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
const page = await render('/conectar');
expect(TestBed.inject(Router).url).toContain('/login');
expect(page.querySelector('.login')).not.toBeNull();
expect(page.querySelector('.site-header')).toBeNull();
expect(page.querySelector('.site-footer')).toBeNull();
expect(page.querySelector('app-connect-page')).toBeNull();
});
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
await render('/gobernanza');
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
});
});
});
+22 -2
View File
@@ -1,12 +1,14 @@
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
import { AuthService } from './auth/auth.service';
import { DomainSelector } from './domain-selector';
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
@Component({
imports: [RouterLink, RouterOutlet, DomainSelector],
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
selector: 'app-root',
styleUrl: './app.scss',
templateUrl: './app.html',
@@ -14,6 +16,7 @@ import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
export class App {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly auth = inject(AuthService);
private readonly leafRouteData = toSignal(
this.router.events.pipe(
@@ -30,7 +33,10 @@ 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);
/** The login screen (`data.sinCromo`) owns the whole window: no header, no footer. */
readonly sinCromo = computed(() => !!this.leafRouteData()['sinCromo']);
protected readonly usuario = this.auth.usuario;
protected readonly title = 'Plataforma de Indicadores';
protected readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
private readonly url = toSignal(this.router.events.pipe(
@@ -38,5 +44,19 @@ export class App {
/** 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()));
/** Only the domains the account may see: the header never offers a forbidden one. */
private readonly permitidos = computed<readonly Dominio[]>(() => {
const sesion = this.auth.usuario();
return sesion ? DOMINIOS.filter(dominio => sesion.dominios.includes(dominio)) : DOMINIOS;
});
protected readonly otherDomains = computed(() =>
this.permitidos().filter(domain => domain !== this.activeDomain()));
protected salir(): void {
// Whether the server session was already gone, the browser ends up at the login screen.
this.auth.logout().subscribe({
next: () => void this.router.navigate(['/login']),
error: () => void this.router.navigate(['/login']),
});
}
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Sin sesión no hay ruta protegida: se manda al inicio de sesión y se recuerda
* `returnUrl` para volver a donde iba el usuario.
*/
export const authGuard: CanActivateFn = (_ruta, estado) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth
.sesion()
.pipe(
map(
(usuario) =>
usuario !== null ||
router.createUrlTree(['/login'], { queryParams: { returnUrl: estado.url } }),
),
);
};
+60
View File
@@ -0,0 +1,60 @@
// La sesión vive en el navegador (la WebApi no autentica): estas pruebas fijan
// el contrato del servicio —quién entra, qué dominios ve y qué queda guardado—
// porque de él dependen el guard de rutas y el recorte de los selectores.
import { TestBed } from '@angular/core/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let auth: AuthService;
beforeEach(() => {
sessionStorage.clear();
TestBed.configureTestingModule({});
auth = TestBed.inject(AuthService);
});
it('entra con la contraseña correcta y deja al usuario en la señal', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.usuario()).toEqual({ usuario: 'cama', nombre: 'Equipo CaMa', dominios: ['cama'] });
expect(auth.autenticado()).toBe(true);
});
it('rechaza una contraseña incorrecta sin abrir sesión', () => {
let error: Error | undefined;
auth.login('cama', 'otra').subscribe({ error: (e: Error) => (error = e) });
expect(error?.message).toContain('incorrectos');
expect(auth.autenticado()).toBe(false);
});
it('dice qué dominios puede ver la cuenta', () => {
auth.login('cama', 'cama2026').subscribe();
expect(auth.puedeVer('cama')).toBe(true);
expect(auth.puedeVer('cacu')).toBe(false);
expect(auth.puedeVer('tea')).toBe(false);
});
it('el administrador ve los tres dominios', () => {
auth.login('admin', 'admin2026').subscribe();
expect(['cacu', 'cama', 'tea'].every((dominio) => auth.puedeVer(dominio))).toBe(true);
});
it('cerrar sesión borra al usuario y lo guardado', () => {
auth.login('tea', 'tea2026').subscribe();
auth.logout().subscribe();
expect(auth.autenticado()).toBe(false);
expect(sessionStorage.getItem('isssteleon.sesion')).toBeNull();
});
it('la sesión sobrevive a una recarga de la pestaña', () => {
// Fails if the login is kept only in memory: a refresh would log the team out mid-task.
auth.login('cacu', 'cacu2026').subscribe();
TestBed.resetTestingModule();
TestBed.configureTestingModule({});
expect(TestBed.inject(AuthService).usuario()?.usuario).toBe('cacu');
});
});
+91
View File
@@ -0,0 +1,91 @@
import { Injectable, computed, signal } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
/** El usuario de la sesión, con los dominios que la interfaz le deja ver. */
export interface Usuario {
readonly usuario: string;
readonly nombre: string;
readonly dominios: readonly string[];
}
/**
* Cuentas de la interfaz. La WebApi no tiene autenticación: el inicio de sesión
* y el recorte por dominio viven aquí, en el navegador, para ordenar el trabajo
* de cada equipo. No son seguridad: cualquiera puede leer esta lista en el
* paquete de la aplicación y la API responde a quien la llame.
*/
const CUENTAS: readonly (Usuario & { contrasena: string })[] = [
{ usuario: 'admin', contrasena: 'admin2026', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] },
{ usuario: 'cacu', contrasena: 'cacu2026', nombre: 'Equipo CaCu', dominios: ['cacu'] },
{ usuario: 'cama', contrasena: 'cama2026', nombre: 'Equipo CaMa', dominios: ['cama'] },
{ usuario: 'tea', contrasena: 'tea2026', nombre: 'Equipo TEA', dominios: ['tea'] },
];
/** La sesión se guarda por pestaña: cerrar el navegador pide entrar de nuevo. */
const CLAVE = 'isssteleon.sesion';
/**
* Sesión local de la aplicación. Es la única fuente de verdad del usuario: el
* guard pregunta aquí, los paneles filtran dominios con `puedeVer` y salir solo
* borra el registro del navegador.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly usuarioActual = signal<Usuario | null>(this.leer());
readonly usuario = this.usuarioActual.asReadonly();
readonly autenticado = computed(() => this.usuarioActual() !== null);
/** Si la cuenta puede ver ese dominio. Sin sesión no se opina (los guards deciden). */
puedeVer(dominio: string): boolean {
const sesion = this.usuarioActual();
return sesion ? sesion.dominios.includes(dominio) : true;
}
/** La sesión guardada en esta pestaña; se resuelve al instante, sin servidor. */
sesion(): Observable<Usuario | null> {
return of(this.usuarioActual());
}
/** Valida contra la lista local; un error marca las credenciales como incorrectas. */
login(usuario: string, contrasena: string): Observable<Usuario> {
const cuenta = CUENTAS.find((c) => c.usuario === usuario.trim() && c.contrasena === contrasena);
if (!cuenta) return throwError(() => new Error('usuario o contraseña incorrectos'));
const sesion: Usuario = { usuario: cuenta.usuario, nombre: cuenta.nombre, dominios: [...cuenta.dominios] };
this.establecer(sesion);
return of(sesion);
}
logout(): Observable<void> {
this.limpiar();
return of(undefined);
}
limpiar(): void {
this.usuarioActual.set(null);
try {
sessionStorage.removeItem(CLAVE);
} catch {
// Almacenamiento deshabilitado: la sesión dura lo que la pestaña en memoria.
}
}
private establecer(sesion: Usuario): void {
this.usuarioActual.set(sesion);
try {
sessionStorage.setItem(CLAVE, JSON.stringify(sesion));
} catch {
// Idem: sin almacenamiento, la sesión no sobrevive a una recarga.
}
}
private leer(): Usuario | null {
try {
const crudo = sessionStorage.getItem(CLAVE);
if (!crudo) return null;
const sesion = JSON.parse(crudo) as Usuario;
return typeof sesion?.usuario === 'string' && Array.isArray(sesion.dominios) ? sesion : null;
} catch {
return null;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Usuario } from './auth.service';
/** Same key AuthService persists the visual session under. */
const CLAVE_SESION = 'isssteleon.sesion';
/**
* Seeds the browser-only visual session before the router and AuthService are created,
* so routes behind authGuard render instead of redirecting to /login. Pair every call
* with `limpiarSesionVisual()` in afterEach so the session never leaks between tests.
*/
export function iniciarSesionVisual(sesion: Usuario = { usuario: 'admin', nombre: 'Administrador', dominios: ['cacu', 'cama', 'tea'] }): void {
sessionStorage.setItem(CLAVE_SESION, JSON.stringify(sesion));
}
export function limpiarSesionVisual(): void {
sessionStorage.removeItem(CLAVE_SESION);
}
+22
View File
@@ -0,0 +1,22 @@
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { map } from 'rxjs';
import { AuthService } from './auth.service';
/**
* Cada cuenta ve solo sus dominios: una ruta con `data.dominio` ajeno manda a la
* cuenta a su primer dominio. Sin sesión no decide nada (`authGuard` ya la
* mandó al inicio de sesión).
*/
export const dominioGuard: CanActivateFn = (ruta) => {
const auth = inject(AuthService);
const router = inject(Router);
const pedido = ruta.data?.['dominio'] as string | undefined;
return auth.sesion().pipe(
map((usuario) => {
if (!usuario || !pedido || usuario.dominios.includes(pedido)) return true;
const propio = usuario.dominios[0];
return propio ? router.createUrlTree(['/indicadores', propio]) : router.createUrlTree(['/']);
}),
);
};
+27
View File
@@ -0,0 +1,27 @@
import { AuthService } from './auth.service';
/**
* Helpers for the screens that list domains (cargar información, gobernanza):
* an account only ever sees its own, and «Todos» only belongs to one that
* reaches every domain — the administrator.
*/
/** De la lista dada, las entradas cuyo dominio alcanza la cuenta. */
export function dominiosPermitidos<T extends { id: string }>(auth: AuthService, dominios: readonly T[]): T[] {
return dominios.filter((dominio) => auth.puedeVer(dominio.id));
}
/** Si la cuenta alcanza todos: solo entonces tiene sentido ofrecer «Todos». */
export function alcanzaTodos(auth: AuthService, dominios: readonly { id: string }[]): boolean {
return dominios.every((dominio) => auth.puedeVer(dominio.id));
}
/**
* El dominio con el que abre una pantalla: el único que alcanza la cuenta, o
* `null` («Todos») cuando alcanza varios. Sin sesión resuelta devuelve `null`,
* que es el comportamiento de siempre.
*/
export function dominioInicial<T extends string>(auth: AuthService, dominios: readonly { id: T }[]): T | null {
const propios = dominiosPermitidos(auth, dominios);
return propios.length === 1 ? propios[0].id : null;
}
+59
View File
@@ -0,0 +1,59 @@
<section class="login" aria-labelledby="login-titulo">
<div class="login__caja">
<img class="login__logo" src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
<h1 class="login__titulo" id="login-titulo">Inicio de sesión</h1>
<form class="login__formulario" (ngSubmit)="ingresar()" novalidate>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="usuario"
[(ngModel)]="usuario"
placeholder="Usuario"
aria-label="Usuario"
autocomplete="username"
autocapitalize="none"
spellcheck="false"
/>
</mat-form-field>
<mat-form-field appearance="outline" class="login__campo" subscriptSizing="dynamic">
<input
matInput
name="contrasena"
[(ngModel)]="contrasena"
[type]="verContrasena() ? 'text' : 'password'"
placeholder="Contraseña"
aria-label="Contraseña"
autocomplete="current-password"
/>
<button
mat-icon-button
matSuffix
type="button"
class="login__ojo"
(click)="mostrarContrasena()"
[attr.aria-label]="verContrasena() ? 'Ocultar contraseña' : 'Mostrar contraseña'"
[attr.aria-pressed]="verContrasena()"
>
<mat-icon>{{ verContrasena() ? 'visibility_off' : 'visibility' }}</mat-icon>
</button>
</mat-form-field>
@if (error(); as mensaje) {
<p class="login__error" role="alert">{{ mensaje }}</p>
}
<button
type="submit"
class="login__ingresar"
[disabled]="!usuario.trim() || !contrasena || enviando()"
>
{{ enviando() ? 'Ingresando…' : 'Ingresar' }}
</button>
</form>
<p class="login__legal">©{{ anio }} Todos los derechos reservados.</p>
</div>
</section>
+170
View File
@@ -0,0 +1,170 @@
:host {
display: flex;
flex: 1;
min-width: 0;
/* The button borrows the home actions' palette: white with a thin gray border
until the form is complete, then `--color-action` (see styles.scss). */
--login-fondo: #f8f9fa;
--login-borde: #e9ecef;
}
.login {
align-items: center;
display: flex;
flex: 1;
justify-content: center;
/* The whole block sits a little below the middle: the logo above it gives the screen its weight. */
padding: var(--space-9) var(--space-5) var(--space-8);
}
.login__caja {
display: flex;
flex-direction: column;
gap: var(--space-4);
max-width: 340px;
width: 100%;
}
/* The brand opens the screen and is the biggest thing on it: it is what fills the empty space. */
.login__logo {
align-self: center;
display: block;
margin-bottom: 0;
width: 260px;
animation: login-logo-entrada 600ms ease-out both;
}
@keyframes login-logo-entrada {
from {
opacity: 0;
transform: translateY(-8px);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
.login__logo {
animation: none;
}
}
.login__titulo {
align-items: center;
color: var(--color-text);
display: flex;
font-family: var(--font-heading);
font-size: 1.375rem;
font-weight: 600;
gap: var(--space-4);
margin: 0 0 var(--space-2);
white-space: nowrap;
}
/* The two rules that flank the title, as in the reference screen. */
.login__titulo::before,
.login__titulo::after {
background: var(--color-border);
content: '';
flex: 1;
height: 1px;
}
.login__formulario {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.login__campo {
width: 100%;
--mat-form-field-container-height: 44px;
--mat-form-field-container-vertical-padding: 12px;
}
.login__ojo {
color: var(--color-text-secondary);
}
/* Edge paints its own reveal control over the password field; the eye in the field is ours. */
.login__campo input::-ms-reveal,
.login__campo input::-ms-clear {
display: none;
}
.login__error {
color: var(--mat-sys-error);
font-size: 0.875rem;
margin: calc(-1 * var(--space-1)) 0 0;
}
/* The button shares the fields' width: one column, one border, no icon and no underline.
Its border turns teal when the form is complete, and it fades in instead of switching. */
.login__ingresar {
align-items: center;
background: var(--login-fondo);
border: 1px solid var(--login-borde);
border-radius: 10px;
color: var(--color-text-secondary);
cursor: default;
display: flex;
font: inherit;
font-size: 0.9375rem;
font-weight: 500;
justify-content: center;
margin-top: var(--space-2);
min-height: 46px;
padding: 0 var(--space-5);
text-decoration: none;
transition:
background-color 260ms ease,
border-color 260ms ease,
color 260ms ease;
width: 100%;
}
.login__ingresar:not(:disabled) {
border-color: var(--color-action);
color: var(--color-text);
cursor: pointer;
}
.login__ingresar:hover:not(:disabled) {
background: var(--color-action-hover);
border-color: var(--color-action);
}
.login__ingresar:focus-visible {
outline: 2px solid var(--color-action);
outline-offset: 2px;
}
.login__ingresar:disabled {
background: var(--login-fondo);
border-color: var(--login-borde);
}
.login__legal {
color: var(--color-text-secondary);
font-size: 0.8125rem;
margin: var(--space-4) 0 0;
text-align: center;
}
@media (max-width: 600px) {
.login {
padding: var(--space-7) var(--space-4);
}
.login__caja {
max-width: 100%;
}
.login__logo {
width: 208px;
}
}
+61
View File
@@ -0,0 +1,61 @@
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from './auth.service';
/**
* Inicio de sesión: valida contra las cuentas locales de `AuthService` y, si el
* usuario ya tiene sesión, salta al destino. `returnUrl` lo pone el guard cuando
* una ruta protegida lo trajo aquí.
*/
@Component({
selector: 'app-login-page',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatIconModule, MatInputModule],
styleUrl: './login-page.scss',
templateUrl: './login-page.html',
})
export class LoginPage implements OnInit {
private readonly auth = inject(AuthService);
private readonly router = inject(Router);
private readonly ruta = inject(ActivatedRoute);
protected usuario = '';
protected contrasena = '';
protected readonly verContrasena = signal(false);
protected readonly enviando = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly anio = new Date().getFullYear();
ngOnInit(): void {
// Quien ya inició sesión y abre /login vuelve derecho a la aplicación.
this.auth.sesion().subscribe((usuario) => {
if (usuario) void this.router.navigateByUrl(this.destino());
});
}
protected ingresar(): void {
if (!this.usuario.trim() || !this.contrasena || this.enviando()) return;
this.enviando.set(true);
this.error.set(null);
this.auth.login(this.usuario.trim(), this.contrasena).subscribe({
next: () => void this.router.navigateByUrl(this.destino()),
error: () => {
this.enviando.set(false);
this.error.set('Usuario o contraseña incorrectos.');
},
});
}
protected mostrarContrasena(): void {
this.verContrasena.update((visible) => !visible);
}
private destino(): string {
const pedido = this.ruta.snapshot.queryParamMap.get('returnUrl');
return pedido?.startsWith('/') && !pedido.startsWith('/login') ? pedido : '/';
}
}
@@ -17,7 +17,7 @@
aria-label="Base de datos destino"
[matTooltip]="store.domainLocked() ? 'Una carga va a una sola base; quita los flujos para cambiarla' : 'Base de datos destino'"
>
@for (domain of domains; track domain.id) {
@for (domain of domains(); track domain.id) {
<mat-button-toggle [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
}
</mat-button-toggle-group>
@@ -1,6 +1,6 @@
import { DragDropModule } from '@angular/cdk/drag-drop';
import { DecimalPipe } from '@angular/common';
import { Component, Injector, inject, signal } from '@angular/core';
import { Component, Injector, computed, inject, signal } from '@angular/core';
import { MatBadgeModule } from '@angular/material/badge';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
@@ -12,6 +12,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { Domain, TargetMeta } from '../../api/api.types';
import { AuthService } from '../../../auth/auth.service';
import { dominiosPermitidos } from '../../../auth/dominios';
import { DataConnection, SourceTable } from '../../domain/data-source';
import { PdfConnection } from '../../domain/pdf-source';
import { SqlConnection } from '../../domain/sql-source';
@@ -59,11 +61,13 @@ import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-di
})
export class ConnectPage {
readonly store = inject(ConnectWorkspaceStore);
private readonly auth = inject(AuthService);
private readonly dialog = inject(MatDialog);
private readonly snackBar = inject(MatSnackBar);
private readonly injector = inject(Injector);
readonly domains = DOMAINS;
/** Only the account's own databases: the picker never offers a domain the server will reject. */
readonly domains = computed(() => dominiosPermitidos(this.auth, DOMAINS));
readonly paneOpen = signal(true);
readonly validatingAll = signal(false);
@@ -100,8 +100,8 @@
type="button"
class="saved-connection__forget"
(click)="forgetSaved(saved, $event)"
aria-label="Olvidar esta conexión guardada"
matTooltip="Olvidar"
aria-label="Eliminar esta conexión guardada"
matTooltip="Eliminar"
>
<mat-icon aria-hidden="true">close</mat-icon>
</button>
@@ -134,7 +134,7 @@
</mat-form-field>
</form>
<mat-checkbox [checked]="remember()" (change)="remember.set($event.checked)">
Recordar servidor, usuario y base de datos (nunca la contraseña)
Guardar servidor, usuario y base de datos para conexiones futuras (la contraseña no se guarda)
</mat-checkbox>
}
@@ -1,5 +1,6 @@
import { TestBed } from '@angular/core/testing';
import { Observable, firstValueFrom, of } from 'rxjs';
import { AuthService } from '../../auth/auth.service';
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
import { ImportsApi } from '../api/imports.api';
import { SourceGateway } from '../api/source-gateway';
@@ -32,6 +33,8 @@ describe('ConnectWorkspaceStore', () => {
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
{ provide: ImportsApi, useValue: imports },
{ provide: SourceGateway, useValue: {} },
// Sin sesión resuelta el alcance es todo; el caso restringido se arma en su propia prueba.
{ provide: AuthService, useValue: { puedeVer: () => true } },
],
});
store = TestBed.inject(ConnectWorkspaceStore);
@@ -52,6 +55,25 @@ describe('ConnectWorkspaceStore', () => {
expect(store.domain()).toBe('cacu');
});
it('opens on the account\'s own domain and refuses the others', () => {
// Fails if the destination database ignores the session: a CaMa team could load into CaCu's database.
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
ConnectWorkspaceStore,
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
{ provide: ImportsApi, useValue: imports },
{ provide: SourceGateway, useValue: {} },
{ provide: AuthService, useValue: { puedeVer: (dominio: string) => dominio === 'cama' } },
],
});
const restringido = TestBed.inject(ConnectWorkspaceStore);
expect(restringido.domain()).toBe('cama');
restringido.setDomain('cacu');
expect(restringido.domain()).toBe('cama');
});
it('removing a connection removes the flows built on its tables', () => {
const { connection } = flowFrom('a.csv', PACIENTE);
flowFrom('b.csv', PACIENTE);
@@ -2,6 +2,8 @@ import { Injectable, computed, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
import { AuthService } from '../../auth/auth.service';
import { dominiosPermitidos } from '../../auth/dominios';
import { ConnectorsApi } from '../api/connectors.api';
import { ImportsApi } from '../api/imports.api';
import { SourceGateway } from '../api/source-gateway';
@@ -29,6 +31,7 @@ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
export class ConnectWorkspaceStore {
private readonly gateway = inject(SourceGateway);
private readonly importsApi = inject(ImportsApi);
private readonly auth = inject(AuthService);
private readonly targetsError = signal<string | null>(null);
readonly allTargets = toSignal(
@@ -50,7 +53,8 @@ export class ConnectWorkspaceStore {
});
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
private readonly _domain = signal<Domain>('cacu');
/** The destination database: the account's own when it only reaches one. */
private readonly _domain = signal<Domain>(this.dominioInicial());
private readonly _connections = signal<DataConnection[]>([]);
private readonly _flows = signal<ImportFlow[]>([]);
private readonly _selectedFlowId = signal<string | null>(null);
@@ -128,7 +132,12 @@ export class ConnectWorkspaceStore {
});
setDomain(domain: Domain): void {
if (!this.domainLocked()) this._domain.set(domain);
if (!this.domainLocked() && this.auth.puedeVer(domain)) this._domain.set(domain);
}
/** The first domain the account may see; every account has at least one (`WebApi` gives none other). */
private dominioInicial(): Domain {
return dominiosPermitidos(this.auth, DOMAINS)[0]?.id ?? 'cacu';
}
setOnConflict(strategy: ConflictStrategy): void {
@@ -1,6 +1,6 @@
// Display only codes confirmed by the cohort and CaMa catalog; preserve unknown values as received.
const EDADES: Readonly<Record<string, string>> = {
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',
MENOR_40: 'Menores de 40 años', '<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<Record<string, string>> = {
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "dimensiones": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "medidas": [{"clave": "maligno", "etiqueta": "Carcinoma in situ o invasor"}, {"clave": "invasor", "etiqueta": "Carcinoma invasor"}], "horizontes_dias": [30, 90, 180, 365], "tipos_periodo": ["mes", "semestre"], "secciones": [{"clave": "resumen", "titulo": "Indicadores de la cohorte", "estado": "disponible", "motivo": null}, {"clave": "distribucion", "titulo": "Distribución de pacientes", "estado": "disponible", "motivo": null}, {"clave": "comparacion", "titulo": "Comparación entre grupos", "estado": "disponible", "motivo": null}, {"clave": "mapa", "titulo": "Mapa entre variables", "estado": "disponible", "motivo": null}, {"clave": "tendencia", "titulo": "Tendencia en el tiempo", "estado": "disponible", "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "medida": "maligno", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "seleccion": {"birads": "BIRADS_4"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "seleccion": {"birads": "BIRADS_4A"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "seleccion": {"birads": "BIRADS_4B"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "seleccion": {"birads": "BIRADS_4C"}}, {"estado": "suprimido", "casos": null, "total": null, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "seleccion": {"birads": "BIRADS_5"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "seleccion": {"birads": "BIRADS_6"}}], "prueba": {"valida": false, "motivo": "Hacen falta al menos dos grupos con datos publicados.", "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "medida": "invasor", "denominador": "pacientes con resultado de biopsia conocido", "grupos": [{"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "<40", "etiqueta": "<40", "seleccion": {"grupo_edad": "<40"}}, {"estado": "disponible", "casos": 5, "total": 12, "valor": 41.67, "ic_bajo": 19.33, "ic_alto": 68.05, "codigo": "40-49", "etiqueta": "40-49", "seleccion": {"grupo_edad": "40-49"}}, {"estado": "disponible", "casos": 6, "total": 13, "valor": 46.15, "ic_bajo": 23.21, "ic_alto": 70.86, "codigo": "50-59", "etiqueta": "50-59", "seleccion": {"grupo_edad": "50-59"}}, {"estado": "disponible", "casos": 8, "total": 17, "valor": 47.06, "ic_bajo": 26.17, "ic_alto": 69.04, "codigo": "60-69", "etiqueta": "60-69", "seleccion": {"grupo_edad": "60-69"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "70+", "etiqueta": "70+", "seleccion": {"grupo_edad": "70+"}}, {"estado": "sin_datos", "casos": null, "total": 0, "valor": null, "ic_bajo": null, "ic_alto": null, "codigo": "SIN_DATO", "etiqueta": "Sin dato", "seleccion": {"grupo_edad": "SIN_DATO"}}], "prueba": {"valida": true, "estadistico": 0.0889, "gl": 2, "p": 0.9565070599102384, "nombre": "Chi cuadrada de homogeneidad"}}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "biopsia", "total": 61, "items": [{"codigo": "BENIGNO", "etiqueta": "Benigno", "suprimido": false, "n": 21, "porcentaje": 34.43, "ic_bajo": 23.75, "ic_alto": 46.95, "seleccion": {"biopsia": "BENIGNO"}}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_IN_SITU"}}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"biopsia": "CARCINOMA_INVASOR"}}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"biopsia": "SIN_DATO"}}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"biopsia": "SIN_BIOPSIA"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "birads", "total": 61, "items": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4", "suprimido": false, "n": 33, "porcentaje": 54.1, "ic_bajo": 41.72, "ic_alto": 65.99, "seleccion": {"birads": "BIRADS_4"}}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4A"}}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4B"}}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"birads": "BIRADS_4C"}}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_5"}}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6", "suprimido": true, "n": null, "porcentaje": null, "ic_bajo": null, "ic_alto": null, "seleccion": {"birads": "BIRADS_6"}}]}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "por": "grupo_edad", "total": 61, "items": [{"codigo": "<40", "etiqueta": "<40", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "<40"}}, {"codigo": "40-49", "etiqueta": "40-49", "suprimido": false, "n": 16, "porcentaje": 26.23, "ic_bajo": 16.84, "ic_alto": 38.44, "seleccion": {"grupo_edad": "40-49"}}, {"codigo": "50-59", "etiqueta": "50-59", "suprimido": false, "n": 19, "porcentaje": 31.15, "ic_bajo": 20.94, "ic_alto": 43.59, "seleccion": {"grupo_edad": "50-59"}}, {"codigo": "60-69", "etiqueta": "60-69", "suprimido": false, "n": 26, "porcentaje": 42.62, "ic_bajo": 31.02, "ic_alto": 55.1, "seleccion": {"grupo_edad": "60-69"}}, {"codigo": "70+", "etiqueta": "70+", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "70+"}}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato", "suprimido": false, "n": 0, "porcentaje": 0.0, "ic_bajo": 0.0, "ic_alto": 5.92, "seleccion": {"grupo_edad": "SIN_DATO"}}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "escenario": "diagnostico", "corte": "2026-11-16", "umbral_supresion": 5, "unidad": "paciente", "denominador": "pacientes elegibles con última mastografía reportada BI-RADS 4 a 6", "grupos": [{"codigo": "BIRADS_4", "n": 33, "suprimido": false}, {"codigo": "BIRADS_4A", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4B", "n": 0, "suprimido": false}, {"codigo": "BIRADS_4C", "n": 0, "suprimido": false}, {"codigo": "BIRADS_5", "n": null, "suprimido": true}, {"codigo": "BIRADS_6", "n": null, "suprimido": true}], "horizonte_dias": 0, "indicadores": []}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "e8fd850e31064f098b34540003d38b6b39b124f21d9ed40f3e52dce8ffc672d0", "corte": "2026-11-16", "ventana": {"meses": 0, "desde": "2025-01-30", "hasta": "2026-11-16"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "umbral_supresion": 5, "horizonte_dias": 90, "indicadores": [{"clave": "cohorte", "titulo": "Pacientes en la cohorte BI-RADS 4 a 6", "descripcion": "Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6.", "unidad": "pacientes", "estado": "disponible", "valor": 61, "ic_bajo": null, "ic_alto": null, "n": 61, "denominador": null, "q1": null, "q3": null, "motivo": null}, {"clave": "con_biopsia", "titulo": "Con biopsia reportada", "descripcion": "Pacientes de la cohorte con al menos un reporte de biopsia de esa mastografía, entre las de la cohorte.", "unidad": "%", "estado": "disponible", "valor": 68.85, "ic_bajo": 56.41, "ic_alto": 79.06, "n": 42, "denominador": 61, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_conocido", "titulo": "Resultado maligno entre las biopsias con resultado", "descripcion": "Carcinoma in situ o invasor entre las pacientes de la cohorte con resultado de biopsia conocido. No es incidencia: el denominador son pacientes ya biopsiadas.", "unidad": "%", "estado": "disponible", "valor": 50.0, "ic_bajo": 35.53, "ic_alto": 64.47, "n": 21, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "invasor_conocido", "titulo": "Carcinoma invasor entre las biopsias con resultado", "descripcion": "Carcinoma invasor entre las pacientes de la cohorte con resultado de biopsia conocido.", "unidad": "%", "estado": "disponible", "valor": 45.24, "ic_bajo": 31.22, "ic_alto": 60.05, "n": 19, "denominador": 42, "q1": null, "q3": null, "motivo": null}, {"clave": "biopsia_90d", "titulo": "Biopsia reportada en 90 días", "descripcion": "Pacientes cuya biopsia se reportó dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte.", "unidad": "%", "estado": "disponible", "valor": 75.56, "ic_bajo": 61.33, "ic_alto": 85.76, "n": 34, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "maligno_90d", "titulo": "Cáncer confirmado en 90 días", "descripcion": "Pacientes con un reporte de biopsia maligna dentro de 90 días de la mastografía, entre las que ya cumplieron 90 días al corte. No es incidencia acumulada: no hay seguimiento de quien no tuvo biopsia.", "unidad": "%", "estado": "disponible", "valor": 40.0, "ic_bajo": 27.02, "ic_alto": 54.55, "n": 18, "denominador": 45, "q1": null, "q3": null, "motivo": null}, {"clave": "dias_a_biopsia", "titulo": "Días de la mastografía al reporte de biopsia", "descripcion": "Mediana y cuartiles entre las pacientes con biopsia reportada.", "unidad": "días", "estado": "disponible", "valor": 27.5, "ic_bajo": null, "ic_alto": null, "n": 42, "denominador": null, "q1": 19.25, "q3": 30.75, "motivo": null}], "no_disponibles": [{"clave": "supervivencia", "titulo": "Supervivencia", "motivo": "No hay estado vital ni fecha de defunción en las fuentes."}, {"clave": "recaida", "titulo": "Recaída", "motivo": "No hay registro de recurrencia ni de tratamiento en las fuentes."}, {"clave": "adherencia_tratamiento", "titulo": "Adherencia al tratamiento", "motivo": "No hay tabla de tratamientos ni de visitas de seguimiento."}, {"clave": "curvas_tiempo_a_evento", "titulo": "Curvas de incidencia acumulada y de supervivencia", "motivo": "El seguimiento de quien no tuvo el evento no está registrado: no hay censura verificable ni tiempo cero común, y la muerte como riesgo competitivo no existe."}, {"clave": "riesgos_proporcionales", "titulo": "Razones de riesgo (Cox), log-rank y tiempo medio restringido", "motivo": "Dependen de las curvas anteriores."}, {"clave": "brca_estadio_tamano", "titulo": "BRCA, estadio clínico y tamaño tumoral", "motivo": "No hay registros de estas variables en las fuentes."}]}
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"corte": "2026-11-16", "umbral_supresion": 5, "tipo_periodo": "semestre", "unidad": "reportes", "poblacion": "Reportes de mastografía con BI-RADS reportado y reportes de biopsia vinculados a una de esas mastografías, de todas las pacientes; no la cohorte de Seguimiento", "alcance_biopsias": "Solo biopsias que se pueden ligar a una mastografía con BI-RADS reportado (mastografía, orden, reporte); una biopsia sin mastografía ligada no se cuenta", "denominador": "reportes de biopsia con resultado conocido en el periodo", "periodos": [{"periodo": "2025-S1", "inicio": "2025-01-01", "fin": "2025-06-30", "incompleto": false, "reportes_mastografia": {"total": 96, "por_categoria": {"4_a_6": {"n": 31, "suprimido": false}, "otras": {"n": 65, "suprimido": false}}}, "reportes_biopsia": {"total": 24, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 15, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 16, "total": 24, "valor": 66.67, "ic_bajo": 46.71, "ic_alto": 82.03}}, {"periodo": "2025-S2", "inicio": "2025-07-01", "fin": "2025-12-31", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 37, "suprimido": false}, "otras": {"n": 60, "suprimido": false}}}, "reportes_biopsia": {"total": 25, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 13, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 14, "total": 25, "valor": 56.0, "ic_bajo": 37.07, "ic_alto": 73.33}}, {"periodo": "2026-S1", "inicio": "2026-01-01", "fin": "2026-06-30", "incompleto": false, "reportes_mastografia": {"total": 97, "por_categoria": {"4_a_6": {"n": 25, "suprimido": false}, "otras": {"n": 72, "suprimido": false}}}, "reportes_biopsia": {"total": 18, "por_grado": {"BENIGNO": {"n": null, "suprimido": true}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": 11, "suprimido": false}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 13, "total": 18, "valor": 72.22, "ic_bajo": 49.13, "ic_alto": 87.5}}, {"periodo": "2026-S2", "inicio": "2026-07-01", "fin": "2026-12-31", "incompleto": true, "reportes_mastografia": {"total": 72, "por_categoria": {"4_a_6": {"n": 27, "suprimido": false}, "otras": {"n": 45, "suprimido": false}}}, "reportes_biopsia": {"total": 19, "por_grado": {"BENIGNO": {"n": 9, "suprimido": false}, "CARCINOMA_IN_SITU": {"n": null, "suprimido": true}, "CARCINOMA_INVASOR": {"n": null, "suprimido": true}, "SIN_DATO": {"n": 0, "suprimido": false}}}, "maligno": {"estado": "disponible", "casos": 10, "total": 19, "valor": 52.63, "ic_bajo": 31.71, "ic_alto": 72.67}}]}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,842 @@
{
"resourceType": "Bundle",
"type": "searchset",
"total": 8,
"link": [
{
"relation": "self",
"url": "http://127.0.0.1:28091/cama/fhir/Measure?_count=50&_offset=0"
}
],
"entry": [
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIOPSIAS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIOPSIAS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIOPSIAS",
"version": "0.2.0",
"name": "cama_biopsias",
"title": "Distribución de resultados de biopsia",
"status": "active",
"description": "Cuántas biopsias reportadas en el semestre caen en cada grado histológico. Se cuenta cada biopsia, no cada paciente. «Sin dato»: el reporte no trae grado.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_biopsias"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grado"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS",
"version": "0.2.0",
"name": "cama_birads",
"title": "Distribución de BI-RADS",
"status": "active",
"description": "Cuántas pacientes caen en cada categoría de BI-RADS en el semestre, cada una en la más grave de sus mastografías. «Sin dato»: ninguna de sus mastografías tiene reporte con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS-CANCER-INVASOR",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS-CANCER-INVASOR",
"version": "0.1.0",
"name": "cama_birads_cancer_invasor",
"title": "BI-RADS de los cánceres invasores",
"status": "active",
"description": "De las pacientes con una biopsia reportada en el periodo con carcinoma invasor, cuántas tenían cada BI-RADS en la mastografía que originó su biopsia más reciente, por edad y por las características del tumor: estadio clínico, etapa, subtipo molecular y tamaño. Las características vienen de los reportes leídos por texto y son provisionales. «Sin dato»: la biopsia no se ligó a una mastografía con BI-RADS.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_cancer_invasor"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "grupo_edad"
}
],
"text": "grupo_edad"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "estadio"
}
],
"text": "Estadio clínico"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "etapa"
}
],
"text": "Etapa"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "clasificacion"
}
],
"text": "Subtipo molecular"
}
},
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "tamano"
}
],
"text": "Tamaño tumoral (T)"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-MASTOGRAFIA",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-MASTOGRAFIA",
"version": "0.2.0",
"name": "cama_birads_456_mastografia",
"title": "Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas mastografías tomadas en el periodo tienen BI-RADS 4, 5 o 6, cada una con su categoría.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_mastografia"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"resource": {
"resourceType": "Measure",
"id": "CAMA-BIRADS456-PACIENTE",
"url": "https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE",
"version": "0.2.0",
"name": "cama_birads_456_paciente",
"title": "Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6",
"status": "active",
"description": "Cuántas pacientes tienen como BI-RADS más grave del periodo un 4, 5 o 6, cada una en la más grave de sus mastografías.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C2"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "cohort"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_birads_456_paciente"
}
}
],
"stratifier": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/estratificador",
"code": "birads"
}
]
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "paciente"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"resource": {
"resourceType": "Measure",
"id": "CAMA-CONFIRMACION-BIRADS45",
"url": "https://isssteleon.org/fhir/Measure/CAMA-CONFIRMACION-BIRADS45",
"version": "0.2.0",
"name": "cama_confirmacion_birads45",
"title": "Tasa de confirmación histopatológica",
"status": "active",
"description": "De las mastografías del semestre con BI-RADS de sospecha, las que tienen una biopsia reportada originada por esa mastografía. A la fecha de corte: sin un plazo máximo, el valor puede subir mientras lleguen reportes. No dice si la biopsia confirmó cáncer.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C1"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "proportion"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "principal"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "denominator"
}
]
},
"description": "Denominador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_denominador"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "numerator"
}
]
},
"description": "Numerador",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_confirmacion_birads45_numerador"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "episodio"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "increase"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"resource": {
"resourceType": "Measure",
"id": "CAMA-DIAS-TOMA-DIAGNOSTICO",
"url": "https://isssteleon.org/fhir/Measure/CAMA-DIAS-TOMA-DIAGNOSTICO",
"version": "0.2.2",
"name": "cama_dias_toma_diagnostico",
"title": "Tiempo de tamizaje a diagnóstico",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a la primera nota médica posterior que la resuelve: un diagnóstico CIE-10 de la lista (normal, benigno, lesión o cáncer), escrito por una de las especialidades que diagnostican, dentro del horizonte y a la fecha de corte. Entran todas las mastografías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_dias_toma_diagnostico"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
},
{
"fullUrl": "http://127.0.0.1:28091/cama/fhir/Measure/CAMA-EU38A",
"resource": {
"resourceType": "Measure",
"id": "CAMA-EU38A",
"url": "https://isssteleon.org/fhir/Measure/CAMA-EU38A",
"version": "0.2.1",
"name": "cama_eu38a",
"title": "Días de la toma de la mastografía a su resultado",
"status": "active",
"description": "Días naturales de la toma de cada mastografía del semestre a su resultado, a la fecha de corte. Las que aún no tienen resultado y siguen dentro del horizonte no se miden; las que lo pasaron sin resultado cuentan en los excluidos.",
"extension": [
{
"url": "https://isssteleon.org/fhir/StructureDefinition/contrato",
"valueCode": "C3r"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "semestre"
},
{
"url": "https://isssteleon.org/fhir/StructureDefinition/tipos-periodo",
"valueCode": "mes"
}
],
"scoring": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-scoring",
"code": "continuous-variable"
}
]
},
"group": [
{
"code": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/grupo-medida",
"code": "TOTAL"
}
]
},
"population": [
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "initial-population"
}
]
},
"description": "Unidades del periodo",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-observation"
}
]
},
"description": "Unidades con valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
},
{
"code": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-population",
"code": "measure-population-exclusion"
}
]
},
"description": "Unidades sin valor",
"criteria": {
"language": "text/x-dbt-metric",
"expression": "cama_eu38a"
}
}
]
}
],
"subjectCodeableConcept": {
"coding": [
{
"system": "https://isssteleon.org/fhir/CodeSystem/unidad",
"code": "examen"
}
]
},
"improvementNotation": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/measure-improvement-notation",
"code": "decrease"
}
]
}
},
"search": {
"mode": "match"
}
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
{"error": "la selección tiene menos de 5 pacientes: su lista no se publica.", "motivo": "supresion"}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 6, "desde": "2026-05-18", "hasta": "2026-11-17"}, "filtros": {"birads": "BIRADS_5", "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"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": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "254", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-11", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-09-16"}, {"pac_id": "129", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-22", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-20"}, {"pac_id": "117", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-08-09"}, {"pac_id": "101", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-03", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-31"}, {"pac_id": "225", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-07-02", "biopsia": "CARCINOMA_IN_SITU", "biopsia_fecha": "2026-07-31"}, {"pac_id": "287", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-14", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-07-13"}, {"pac_id": "55", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-09", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-30"}, {"pac_id": "7", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-06-02", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "260", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-05-21", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-06-07"}]}
@@ -0,0 +1 @@
{"simulado": true, "cohorte": "cama_birads_v1", "escenario": "diagnostico", "revision": "a2c95b755ba3ccab288c148153e14be1e958aadff1f5a320a4d54e84b3cae745", "corte": "2026-11-17", "ventana": {"meses": 3, "desde": "2026-08-18", "hasta": "2026-11-17"}, "filtros": {"birads": null, "grupo_edad": null, "biopsia": null}, "filtros_disponibles": [{"clave": "birads", "etiqueta": "Categoría BI-RADS", "opciones": [{"codigo": "BIRADS_4", "etiqueta": "BI-RADS 4"}, {"codigo": "BIRADS_4A", "etiqueta": "BI-RADS 4A"}, {"codigo": "BIRADS_4B", "etiqueta": "BI-RADS 4B"}, {"codigo": "BIRADS_4C", "etiqueta": "BI-RADS 4C"}, {"codigo": "BIRADS_5", "etiqueta": "BI-RADS 5"}, {"codigo": "BIRADS_6", "etiqueta": "BI-RADS 6"}]}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad", "opciones": [{"codigo": "<40", "etiqueta": "<40"}, {"codigo": "40-49", "etiqueta": "40-49"}, {"codigo": "50-59", "etiqueta": "50-59"}, {"codigo": "60-69", "etiqueta": "60-69"}, {"codigo": "70+", "etiqueta": "70+"}, {"codigo": "SIN_DATO", "etiqueta": "Sin dato"}]}, {"clave": "biopsia", "etiqueta": "Resultado de la biopsia", "opciones": [{"codigo": "BENIGNO", "etiqueta": "Benigno"}, {"codigo": "CARCINOMA_IN_SITU", "etiqueta": "Carcinoma in situ"}, {"codigo": "CARCINOMA_INVASOR", "etiqueta": "Carcinoma invasor"}, {"codigo": "SIN_DATO", "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": "SIN_BIOPSIA", "etiqueta": "Sin biopsia reportada"}]}], "columnas": [{"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"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": 1, "page_size": 50, "total_items": 16, "total_pages": 1}, "items": [{"pac_id": "251", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-11-05", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "54", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "185", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-24", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "255", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-21", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "95", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-15", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-11-14"}, {"pac_id": "4", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-10", "biopsia": "BENIGNO", "biopsia_fecha": "2026-11-06"}, {"pac_id": "256", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-10-08", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "188", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-10-04", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-20"}, {"pac_id": "239", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-14", "biopsia": "BENIGNO", "biopsia_fecha": "2026-10-06"}, {"pac_id": "245", "grupo_edad": "40-49", "birads": "BIRADS_4", "mastografia_fecha": "2026-09-09", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "186", "grupo_edad": "60-69", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-31", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}, {"pac_id": "282", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-29", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-10"}, {"pac_id": "126", "grupo_edad": "60-69", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-27", "biopsia": "CARCINOMA_INVASOR", "biopsia_fecha": "2026-10-04"}, {"pac_id": "31", "grupo_edad": "50-59", "birads": "BIRADS_4", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "52", "grupo_edad": "40-49", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-20", "biopsia": null, "biopsia_fecha": null}, {"pac_id": "220", "grupo_edad": "50-59", "birads": "BIRADS_5", "mastografia_fecha": "2026-08-19", "biopsia": "BENIGNO", "biopsia_fecha": "2026-09-23"}]}
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -30,11 +30,13 @@ import { parConteos } from './indicadores-conteos-pareados';
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
template: `
<mat-card>
<header>
<div class="card-identity">
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div>
</header>
@if (!conteos) {
<header>
<div class="card-identity">
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
</div>
</header>
}
@if (!sobrio) {
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
@@ -42,7 +44,7 @@ import { parConteos } from './indicadores-conteos-pareados';
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
</button>
}
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="titleId">
<div class="catalog-content" [id]="contentId" [attr.aria-labelledby]="conteos ? null : titleId">
@if (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
@if (isEu7) {
<div #visibilityRegion class="eu7-region">
@@ -62,7 +64,7 @@ import { parConteos } from './indicadores-conteos-pareados';
</div>
} @else if (conteos; as par) {
<div #visibilityRegion class="conteos-region">
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
<app-indicador-conteos-pareados [dominio]="dominio" [par]="par" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
</div>
} @else if (selectedFigure) {
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
@@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; }
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
.selection-status { font-weight: 600; }
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
.families { display: flex; flex-wrap: wrap; gap: .75rem; }
.family { flex: 1 1 16rem; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--issste-border); border-radius: 1rem; background: var(--issste-surface); }
.family button { display: inline-flex; align-items: center; gap: .55rem; }
.family .parent { width: 100%; justify-content: flex-start; border: 0; border-radius: 0; border-bottom: 1px solid var(--issste-border); font-weight: 650; background: color-mix(in srgb, var(--swatch) 14%, var(--issste-surface)); }
.family .children { display: flex; flex-wrap: wrap; gap: .4rem; padding: .55rem; }
.family .child { flex: 1 1 8rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
.family .parent[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 24%, var(--issste-surface)); box-shadow: inset 0 -3px 0 var(--swatch); }
.family .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); transform: scale(1.03); }
.family .swatch { width: .35rem; height: 1.15rem; border: 0; border-radius: .2rem; background: var(--swatch); }
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
.legend > button { justify-self: start; }
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
@@ -26,6 +35,23 @@ summary { cursor: pointer; padding-block: .75rem; }
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; }
.histo-meta { display: flex; justify-content: flex-end; align-items: flex-start; gap: .75rem; margin: -.85rem -.65rem 0 0; }
.view-context { display: flex; flex-direction: column; align-items: flex-end; gap: .1rem; margin: .2rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; }
.histo .figure { border-top: 0; }
.histo .figure + .figure { border-top: 1px solid var(--issste-border); padding-top: .25rem; }
.histo .help { position: relative; display: flex; justify-content: flex-end; padding-bottom: 0; }
.histo .help .methodology-toggle { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; font-weight: 800; font-size: 1rem; line-height: 1; background: var(--issste-accent); color: var(--issste-on-accent); }
.histo .help .methodology { position: absolute; z-index: 8; top: 100%; right: 0; width: min(34rem, calc(100vw - 2rem)); max-height: 18rem; overflow: auto; background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
.histo .legend { display: flex; flex-direction: column; gap: 0; margin-block: .15rem 1rem; }
.histo .tab-bar { display: flex; align-items: flex-end; gap: .5rem; border-bottom: 1px solid var(--issste-border); }
.histo .tabs { display: flex; flex-wrap: wrap; gap: .2rem; min-width: 0; }
.histo .tabs .tab { display: inline-flex; align-items: center; gap: .45rem; border: 1px solid transparent; border-bottom: 0; border-radius: .75rem .75rem 0 0; background: transparent; box-shadow: none; }
.histo .tabs .tab[aria-selected=true] { background: color-mix(in srgb, var(--swatch) 18%, var(--issste-surface)); border-color: var(--issste-border); box-shadow: inset 0 -3px 0 var(--swatch); font-weight: 700; }
.histo .child-groups { display: flex; flex-wrap: wrap; align-items: center; column-gap: 2rem; row-gap: .45rem; padding: .65rem .1rem .1rem; }
.histo .tab-panel { display: flex; flex-wrap: wrap; gap: .45rem; }
.histo .tab-panel .child { display: inline-flex; align-items: center; gap: .45rem; border-radius: .75rem; border-color: color-mix(in srgb, var(--swatch) 55%, var(--issste-border)); background: var(--issste-surface); }
.histo .tab-panel .child[aria-pressed=true] { background: color-mix(in srgb, var(--swatch) 16%, var(--issste-surface)); border-color: var(--swatch); }
.histo .tab .swatch, .histo .tab-panel .swatch { display: block; width: .35rem; height: 1em; margin: 0; border: 0; border-radius: .2rem; background: var(--swatch); align-self: center; }
.reading-guide h3 { margin: 0 0 .25rem; }
.reading-guide + .reading-guide { margin-top: 1rem; }
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
@@ -34,4 +60,7 @@ app-plotly-chart { --plot-height: 360px; }
.rate-states { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
.rate-states:empty { display: none; }
/* Rates on the left, donut on the right (the reverse of EU7). */
@media (min-width: 1100px) { .figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); } }
@media (min-width: 1100px) {
.figures { grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); }
.histo .figure + .figure { border-top: 0; border-inline-start: 1px solid var(--issste-border); padding-top: 0; padding-inline-start: 1rem; }
}
@@ -1,21 +1,4 @@
<section class="conteos" [attr.aria-label]="indicador.titulo + ', por ' + par.unidades.pacientes.slice(0, -1) + ' y por ' + par.unidades.examenes.slice(0, -1)">
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<section class="reading-guide" aria-label="Cómo leer: dona por categoría">
<h3>Dona por categoría</h3>
@if (donutGuide; as guide) {
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
} @else if (!metadata) { <p>Metadatos publicados pendientes. Vuelve a abrir «Cómo leer» para reintentar su consulta.</p> }
@else { <p>El servicio no publica instrucciones de lectura para esta figura.</p> }
</section>
<section class="reading-guide" aria-label="Cómo leer: pacientes y mastografías">
<h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}</h3>
<p>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.</p>
</section>
</div>
}
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" [attr.aria-label]="'Cargando ' + indicador.titulo" /><p role="status">Cargando {{ par.unidades.examenes }} y {{ par.unidades.pacientes }} del mismo periodo…</p> }
@@ -24,6 +7,8 @@
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
}
@if (status() === 'ready' && model; as m) {
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, ' + m.periodo;
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
@if (pages.length > 1) {
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
@@ -32,22 +17,43 @@
</nav>
}
<div class="figures">
<section class="figure"><h3>{{ par.unidades.examenes | titlecase }} por categoría, {{ m.periodo }}</h3>
<section class="figure">
<div class="figure-head">
<h3>{{ tituloMastografias }}</h3>
<div class="help" (mouseenter)="openHelp('examenes')" (mouseleave)="hideHelp('examenes')" (focusin)="openHelp('examenes')" (focusout)="onHelpFocusOut('examenes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, mastografías por categoría" [attr.aria-expanded]="helpWhich === 'examenes'"
[attr.aria-describedby]="helpWhich === 'examenes' ? 'cama-birads-ayuda-mastografias' : null" (click)="toggleHelp('examenes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'examenes') {
<div class="methodology" id="cama-birads-ayuda-mastografias" role="tooltip">Cada mastografía cuenta en su propia categoría.</div>
}
</div>
</div>
@if (total) {
<app-plotly-chart [figure]="donutFigure!" [showNotes]="false" [label]="indicador.titulo + ', dona, ' + m.periodo" />
<app-plotly-chart [figure]="donutFigure!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [showNotes]="false" [label]="tituloMastografias" />
} @else { <p role="status">{{ total === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.examenes + ' en el periodo.' }}</p> }
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
</section>
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
<section class="figure">
<div class="figure-head">
<h3>{{ tituloPacientes }}</h3>
<div class="help" (mouseenter)="openHelp('pacientes')" (mouseleave)="hideHelp('pacientes')" (focusin)="openHelp('pacientes')" (focusout)="onHelpFocusOut('pacientes', $event)">
<button type="button" class="help-icon" aria-label="Cómo leer, pacientes por categoría" [attr.aria-expanded]="helpWhich === 'pacientes'"
[attr.aria-describedby]="helpWhich === 'pacientes' ? 'cama-birads-ayuda-pacientes' : null" (click)="toggleHelp('pacientes')"><span aria-hidden="true">!</span></button>
@if (helpWhich === 'pacientes') {
<div class="methodology" id="cama-birads-ayuda-pacientes" role="tooltip">La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.</div>
}
</div>
</div>
@if (totalPacientes) {
<app-plotly-chart [figure]="patientsFigure!" class="donut-chart" (widthChanged)="ajustarAnchoPacientes($event)" [showNotes]="false" [label]="tituloPacientes" />
} @else { <p role="status">{{ !m.pacientesVerificados ? 'Dona de pacientes no disponible hasta verificar la definición publicada.' : totalPacientes === null ? 'Dona no disponible: hay celdas suprimidas o sin dato.' : 'Sin ' + par.unidades.pacientes + ' en el periodo.' }}</p> }
@if (!m.pacientesVerificados) { <p class="note" role="status">Pacientes pendientes: la versión publicada del indicador de pacientes no es una cuya definición se haya verificado para sumar sus categorías.</p> }
</section>
</div>
<p class="note">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.</p>
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
<details class="published-values"><summary>Valores publicados</summary>
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más grave) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<table><caption>{{ par.unidades.pacientes | titlecase }} (su categoría más alta) y {{ par.unidades.examenes }}, {{ m.periodo }}</caption>
<thead><tr><th scope="col">Familia de BI-RADS</th><th scope="col">{{ par.unidades.pacientes | titlecase }}</th><th scope="col">{{ par.unidades.examenes | titlecase }}</th></tr></thead>
<tbody>@for (f of m.filas; track f.id) { <tr><th scope="row">{{ f.etiqueta }}</th><td>{{ textoPacientes(f.pacientes) }}</td><td>{{ texto(f.examenes) }}</td></tr> }</tbody>
</table>
@@ -3,17 +3,28 @@
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; }
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
.figure-head h3 { margin: 0; }
.help { display: flex; flex: none; justify-content: flex-end; }
.help .methodology { position: absolute; z-index: 8; inset-block-start: calc(100% + .35rem); inset-inline-end: 0;
box-sizing: border-box; inline-size: min(34rem, 100%); background: var(--issste-surface); box-shadow: 0 10px 28px rgb(0 0 0 / .14); }
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)); } }
.help-icon { display: inline-flex; align-items: center; justify-content: center; width: 1.75rem; height: 1.75rem; min-width: 1.75rem; min-height: 1.75rem; padding: 0; border: 0; border-radius: 50%; background: var(--issste-accent); color: var(--issste-on-accent); font: inherit; font-weight: 800; line-height: 1; cursor: pointer; }
.help-icon:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; }
.figure + .figure { border-top: 1px solid var(--issste-border); margin-top: var(--issste-space-4); padding-top: var(--issste-space-4); }
@media (min-width: 1100px) {
.figures { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.figure + .figure { border-top: 0; margin-top: 0; padding-top: 0; border-inline-start: 1px solid var(--issste-border); padding-inline-start: var(--issste-space-6); }
}
app-plotly-chart { --plot-height: 400px; }
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
.donut-chart { --plot-min-width: 230px; }
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; }
@@ -1,15 +1,15 @@
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core';
import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, 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 { 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 { barrasConteos, ConteosIncompatibles, donaConteos, ModeloConteos, modelosConteos, ParConteos, totalExamenes } from './indicadores-conteos-pareados';
import { ConteosIncompatibles, donaConteos, donaPacientes, ModeloConteos, modelosConteos, ParConteos, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
@Component({
selector: 'app-indicador-conteos-pareados',
@@ -25,38 +25,45 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
@Input({ required: true }) tema!: Tema;
@Input({ required: true }) applied!: GlobalApplied;
@Input() visible = true;
@Input() metadata?: IndicadorMetadatos;
readonly metadataRequested = output<void>();
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
message = '';
periodIndex = 0;
pages: ModeloConteos[] = [];
donutFigure?: PlotlyFigure;
barsFigure?: PlotlyFigure;
patientsFigure?: PlotlyFigure;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
private key = '';
private loaded = false;
// On a narrow screen the donut's long label gives way to a legend under it.
private readonly estrecha = typeof matchMedia === 'function' ? matchMedia('(max-width: 520px)') : undefined;
private readonly alCambiarAncho = () => { if (this.model) this.draw(); };
constructor() { this.estrecha?.addEventListener('change', this.alCambiarAncho); }
private anchoDona = 390;
private anchoPacientes = 390;
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
get total() { return this.model ? totalExamenes(this.model) : null; }
get totalPacientes() { return this.model ? totalPacientes(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;
helpWhich: 'examenes' | 'pacientes' | null = null;
private helpPinned: 'examenes' | 'pacientes' | null = null;
toggleHelp(which: 'examenes' | 'pacientes') {
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
this.helpPinned = which;
this.openHelp(which);
}
openHelp(which: 'examenes' | 'pacientes') {
this.helpWhich = which;
}
hideHelp(which: 'examenes' | 'pacientes') {
if (this.helpPinned === which) return;
if (this.helpWhich === which) this.helpWhich = null;
}
onHelpFocusOut(which: 'examenes' | 'pacientes', event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
if (this.helpPinned === which) this.helpPinned = null;
if (this.helpWhich === which) this.helpWhich = null;
}
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]);
@@ -68,7 +75,7 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
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 clear() { this.pages = []; this.periodIndex = 0; this.donutFigure = undefined; this.patientsFigure = undefined; }
private load() {
this.subscription?.unsubscribe();
this.loaded = true; this.clear();
@@ -108,12 +115,24 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return;
this.periodIndex += step; this.draw();
}
ajustarAnchoDona(ancho: number) {
if (ancho === this.anchoDona) return;
this.anchoDona = ancho;
const m = this.model;
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
}
ajustarAnchoPacientes(ancho: number) {
if (ancho === this.anchoPacientes) return;
this.anchoPacientes = ancho;
const m = this.model;
if (m) this.patientsFigure = donaPacientes(m, this.par, this.tema, ancho);
}
private draw() {
const m = this.model;
if (!m) return;
this.donutFigure = donaConteos(m, this.par, this.tema, this.estrecha?.matches ?? false);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecha?.removeEventListener('change', this.alCambiarAncho); }
ngOnDestroy() { this.subscription?.unsubscribe(); }
}
@@ -37,7 +37,7 @@
:host(.methodology-expanded) .figure-card { grid-row: auto; }
.figure-title { display: block; padding: 1rem 1rem 0; margin: 0; font: var(--mat-sys-title-medium); font-family: var(--issste-font-heading); overflow-wrap: anywhere; }
.state { padding: 1.25rem; margin: 0; overflow-wrap: anywhere; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b1c9ff; --mat-sys-outline: #a1aabd; }
.dark { background: #151b28; color: #eef1f7; color-scheme: dark; --mat-sys-primary: #b7d251; --mat-sys-outline: #a1aabd; }
.figure-id { padding: .25rem 1rem 0; margin: 0; font: var(--mat-sys-body-small); opacity: .8; overflow-wrap: anywhere; }
@media (max-width: 550px) { .methodology-detail { padding: var(--issste-space-3); } }
@@ -13,6 +13,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
import { recolorFigure } from './indicadores-c2-palette';
// The panel owns requests; the card receives the original and its presentation copy.
export interface FigureState {
@@ -62,7 +63,8 @@ export class IndicadorFigureCard implements OnChanges {
}
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
legendColor(label: string, parent: boolean): string {
const trace = this.chartFigure?.data[parent && this.activeParent ? 1 : 0];
const painted = this.chartFigure ? recolorFigure(this.chartFigure) : undefined;
const trace = painted?.data[parent && this.activeParent ? 1 : 0];
const labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : undefined;
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
@@ -1,20 +1,27 @@
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
@if (helpOpen) {
<div class="methodology">
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
<section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
<div class="histo-meta">
<p class="view-context">
<span>{{ intervalLabel }}</span>
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
</p>
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
<button type="button" class="methodology-toggle" aria-label="Cómo leer" [attr.aria-expanded]="helpOpen" [attr.aria-describedby]="helpOpen ? 'histo-como-leer' : null" (click)="toggleHelp()"><span aria-hidden="true">!</span></button>
@if (helpOpen) {
<div class="methodology" id="histo-como-leer" role="tooltip">
<p>Cada punto es el porcentaje de pacientes de esa categoría BI-RADS cuyo resultado de biopsia pertenece a la selección, entre las que tienen resultado; la línea es su intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» no entran en el denominador y se muestran aparte, en la tabla de valores publicados.</p>
@if (metadata) {
@for (guide of readingGuide; track guide.figura) {
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
<h3>{{ guide.nombre }}</h3>
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
</section>
}
}
}
</div>
}
</div>
}
</div>
</div>
@switch (status()) {
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
@case ('loading') { <mat-progress-bar mode="indeterminate" aria-label="Cargando la histopatología por BI-RADS" /><p role="status">Cargando el mismo periodo para tasas y dona…</p> }
@@ -30,19 +37,25 @@
</nav>
}
@if (model; as m) {
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</p>
@if (status() === 'empty') { <p role="status">No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.</p> }
@else {
<div class="legend" role="group" aria-label="Seleccionar resultado de biopsia">
<button type="button" (click)="select('centro')" [disabled]="isBase" aria-label="Volver a la vista general de la histopatología">Volver</button>
<div class="keys" role="group" aria-label="Grupos del anillo interior">
@for (g of m.grupos; track g.id; let i = $index) {
<button type="button" [attr.aria-pressed]="!selection?.categoria && selection?.grupo === g.id" (click)="select('grupos', i)"><span class="swatch" [style.background]="g.color" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
<div class="legend">
<div class="tab-bar">
<div class="tabs" role="tablist" aria-label="Seleccionar resultado de biopsia">
@for (g of m.grupos; track g.id; let gi = $index) {
<button type="button" role="tab" class="tab" [id]="'histo-tab-' + g.id" [style.--swatch]="g.color" [attr.aria-selected]="selection?.grupo === g.id" [attr.aria-controls]="'histo-panel-' + g.id" (click)="select('grupos', gi)"><span class="swatch" aria-hidden="true"></span>{{ g.etiqueta }}</button>
}
</div>
</div>
<div class="keys" role="group" aria-label="Categorías del anillo exterior">
@for (c of m.categorias; track c.id; let i = $index) {
<button type="button" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', i)"><span class="swatch" [style.background]="c.color" aria-hidden="true"></span>{{ c.etiqueta }}</button>
<div class="child-groups">
@for (g of m.grupos; track g.id) {
<div class="tab-panel" role="group" [id]="'histo-panel-' + g.id" [attr.aria-labelledby]="'histo-tab-' + g.id">
@for (c of m.categorias; track c.id; let ci = $index) {
@if (c.grupo === g.id) {
<button type="button" class="child" [style.--swatch]="c.color" [attr.aria-pressed]="selection?.categoria === c.id" (click)="select('categorias', ci)"><span class="swatch" aria-hidden="true"></span>{{ c.etiqueta }}</button>
}
}
</div>
}
</div>
</div>
@@ -51,13 +64,10 @@
@if (ratesFigure) {
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
}
<ul class="rate-states">
@for (t of rates; track t.fila.id) { @if (t.k === null) { <li>{{ t.fila.etiqueta }}: {{ estadoTasa(t) }}</li> } }
</ul>
</section>
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
<app-plotly-chart [figure]="donutFigure" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
<app-plotly-chart [figure]="donutFigure" [animated]="true" [showNotes]="false" [label]="'Histopatología, dona de resultados de la biopsia, ' + m.periodo + ', ' + selectionLabel" (plotClick)="plotClicked($event)" />
} @else { <p role="status">{{ 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.' }}</p> }
</section>
</div>
@@ -5,7 +5,7 @@ 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 { filterCompatibility, GlobalApplied } from './indicadores-memory';
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { Celda } from './indicadores-confirmacion-citologia';
@@ -43,6 +43,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
donutFigure?: PlotlyFigure;
ratesFigure?: PlotlyFigure;
helpOpen = false;
private helpPinned = false;
private readonly snapshots = inject(IndicadoresSnapshots);
private readonly changeDetector = inject(ChangeDetectorRef);
private subscription?: Subscription;
@@ -54,7 +55,11 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
private readonly alCambiarAncho = () => this.draw();
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); }
get intervalLabel() { return this.applied?.tipo === 'mes' ? 'Intervalo mensual' : 'Intervalo semestral'; }
get contextPeriod() {
return this.model?.periodo ?? this.periods[this.periodIndex]
?? (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; }
@@ -71,7 +76,23 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
});
}
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
toggleHelp() {
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
this.helpPinned = true;
this.showHelp();
}
showHelp() {
if (this.helpOpen) return;
this.helpOpen = true;
this.metadataRequested.emit();
}
hideHelp() { if (!this.helpPinned) this.helpOpen = false; }
onHelpFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && (event.currentTarget as Node).contains(next)) return;
this.helpPinned = false;
this.helpOpen = false;
}
ngOnChanges(changes: SimpleChanges) {
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
@@ -27,6 +27,10 @@ import { IndicadorKpiCard } from './indicador-kpi-card';
expect(fixture.nativeElement.querySelector('.value').textContent).toContain('Valor de prueba');
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
expect(fixture.nativeElement.textContent).toContain('Referencia de prueba');
expect(fixture.nativeElement.querySelector('.period-label')).toBeNull();
fixture.componentRef.setInput('temporalReference', '2025-S2'); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.period-label').textContent).toBe('Periodo:');
expect(fixture.nativeElement.querySelector('.kpi-foot').textContent).toContain('2025-S2');
expect(fixture.nativeElement.querySelector('.kpi-state').textContent).toBe('Estado de prueba');
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
@if (value !== null && value !== undefined) {
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
}
@if (temporalReference) { <p>{{ temporalReference }}</p> }
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
<div class="kpi-foot">
@if (showPeriod && temporalReference) {
<p class="period">@if (labeledPeriod) { <span class="period-label">Periodo:</span> }<span>{{ temporalReference }}</span></p>
}
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
</div>
</mat-card>
`,
styles: `
:host { display: block; min-width: 0; }
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
:host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
mat-card { box-sizing: border-box; display: flex; flex-direction: column; flex: 1 1 auto; height: auto; min-height: 100%; padding: var(--issste-space-6);
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); box-shadow: none; }
.kpi-foot { margin-top: auto; }
.period { display: flex; flex-wrap: wrap; align-items: baseline; gap: .35rem; }
.period-label { font-weight: 600; }
h3 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
h3, p { overflow-wrap: anywhere; }
p { margin: var(--issste-space-3) 0 0; }
@@ -33,6 +40,7 @@ import { MatCardModule } from '@angular/material/card';
// 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; }
:host-context(.kpi-section[data-domain='cama']) .value { font-size: 1.65rem; }
`,
})
export class IndicadorKpiCard {
@@ -40,12 +48,18 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null;
@Input() unit?: string;
@Input() temporalReference?: string;
// CaMa's opportunity strip shares one period, shown by the parent instead of on every card.
@Input() showPeriod = true;
@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 labeledPeriod(): boolean {
const text = this.temporalReference?.trim();
return !!text && text.split(',').every(part => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(part.trim()));
}
get informationLine(): string | undefined {
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
return [...new Set(lines)].join(' ');
@@ -183,14 +183,21 @@ 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 : 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).toHaveLength(5);
expect(cards.map(card => card.querySelector('.value')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, undefined]);
expect(cards.map(card => card.querySelector('.value span')?.textContent.trim())).toEqual(['pacientes', undefined, 'días (mediana)', 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', 'Indicador no 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.'),
]));
if (domain === 'cama') {
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
} else {
expect(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([expect.stringContaining('2025-S1')]));
}
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
// CaCu and CaMa cards say only their own line, as in the reference; the kit notes are the figure footer and the definitions.
expect(fixture.nativeElement.textContent.includes('Nota del pie de la figura.')).toBe(false);
@@ -19,7 +19,8 @@ interface KpiDisplay extends KpiResult { period?: string; earlier?: boolean; ver
imports: [IndicadorKpiCard, MatButtonModule],
template: `<app-indicador-kpi-card [title]="definition.title" [value]="result().value" [unit]="definition.unit"
[state]="result().state" [additionalInfo]="result().info" [temporalReference]="temporalReference"
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'" />
[loading]="result().loading ?? false" [notes]="dominio === 'tea' ? result().notes ?? [] : []" [quietWhenAvailable]="dominio === 'cama'"
[showPeriod]="dominio !== 'cama'" />
@if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
@@ -2,11 +2,13 @@
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields compact">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<div class="interval">
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -51,11 +53,13 @@
<section aria-label="Editor de filtros generales del proyecto">
@if (!types.includes(state.tipo)) { <p role="status">El intervalo de análisis del borrador ya no está publicado para este proyecto. Elige un intervalo de análisis disponible.</p> }
<div class="fields">
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
</mat-select>
</mat-form-field>
<div class="interval">
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (types.includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
@@ -2,13 +2,30 @@
:host { display: block; min-width: 0; margin: var(--issste-space-4) 0; }
// CaMa's compact row: tighter fields and buttons, one line of text under it.
:host(.compacto) { margin: 0; @include mat.theme((density: -4)); }
:host(.compacto) {
margin: 0;
@include mat.theme((density: -4));
// That theme also rewrites the corner scale, which turns this switch into a pill.
// The history switch keeps the slight rounding of the indicators pages.
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
:host(.compacto) .interval mat-button-toggle-group {
--mat-button-toggle-height: 40px;
--mat-button-toggle-shape: 6px;
}
:host(.compacto) p { line-height: 1.4; margin: var(--issste-space-2) 0 0; font: var(--mat-sys-body-small); }
:host(.compacto) .pending { color: var(--issste-text); border-left-color: var(--issste-accent); padding-left: var(--issste-space-2); }
:host(.compacto) .apply-button { min-height: 40px; }
:host(.compacto) .period-builder button { min-height: 40px; }
section { min-width: 0; }
.fields { display: flex; flex-wrap: wrap; align-items: start; gap: var(--issste-space-3); }
.fields { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
.period-builder mat-form-field { flex: 0 1 10rem; }
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
@@ -21,7 +38,7 @@ 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 { align-items: end; }
.fields.compact mat-form-field { flex: 0 1 14rem; }
.fields.compact .apply-button { margin-top: 0; }
@media (max-width: 550px) {
@@ -138,16 +138,11 @@ describe('UX-04 control asistido', () => {
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
expect(apply).toHaveBeenCalledTimes(1);
});
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', async () => {
it('ofrece el intervalo de análisis mensual o semestral, sin Modalidad', () => {
const labels = Array.from(fixture.nativeElement.querySelectorAll('mat-label') as NodeListOf<HTMLElement>).map(l => l.textContent);
expect(labels).toContain('Intervalo de análisis');
expect(fixture.nativeElement.querySelector('.field-label').textContent).toBe('Intervalo de análisis');
expect(labels).not.toContain('Modalidad');
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
.find(f => f.nativeElement.textContent.includes('Intervalo de análisis'))!.query(By.directive(MatSelect));
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
const options = Array.from(document.querySelectorAll('mat-option')).map(o => o.textContent?.trim());
expect(options).toEqual(['Semestral', 'Mensual']);
select.componentInstance.close();
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
});
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
@@ -1,6 +1,7 @@
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
@@ -10,7 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
@Component({
selector: 'app-indicador-period-filters',
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
imports: [FormsModule, MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatInputModule, MatSelectModule],
host: { '[class.compacto]': 'compact' },
templateUrl: './indicador-period-filters.html',
styleUrl: './indicador-period-filters.scss',
@@ -0,0 +1,109 @@
import { PlotlyFigure, Tema } from './indicadores.models';
import { C2_PALETTE, c2Theme } from './indicadores-c2-palette';
import { CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis, TendenciaAnalisis } from './indicadores-analisis.service';
// The figures of the descriptive analysis. They draw what the answer publishes and nothing else: a suppressed or missing
// value is left out of the drawing (a gap, never a zero) and named in the table beside it.
const miles = (v: number) => v.toLocaleString('es-MX');
const pct = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) + ' %';
const base = (tema: Tema, alto: number, margen: Record<string, number>) => {
const t = c2Theme(tema);
return { autosize: true, height: alto, paper_bgcolor: t.background, plot_bgcolor: t.background, font: { color: t.text }, margin: margen, showlegend: false };
};
const config = { displayModeBar: false };
/** Share of the selection by category, with the Wilson interval of each published share as a horizontal bar. */
export function distribucionFigura(d: DistribucionAnalisis, tema: Tema): PlotlyFigure {
const t = c2Theme(tema);
const items = d.items.filter(i => !i.suprimido && (i.n ?? 0) > 0 && i.porcentaje !== null);
return {
data: [{
type: 'bar', orientation: 'h', y: items.map(i => i.etiqueta), x: items.map(i => i.porcentaje), customdata: items.map(i => i.codigo),
marker: { color: C2_PALETTE.series[0] },
error_x: { type: 'data', symmetric: false, array: items.map(i => i.ic_alto! - i.porcentaje!), arrayminus: items.map(i => i.porcentaje! - i.ic_bajo!), color: t.text },
text: items.map(i => `${miles(i.n!)} (${pct(i.porcentaje!)})`), textposition: 'inside', insidetextanchor: 'start', textfont: { color: '#081839' }, cliponaxis: false,
hovertemplate: items.map(i => `<b>${i.etiqueta}</b><br>${miles(i.n!)} pacientes<br>${pct(i.porcentaje!)} (IC 95 %: ${pct(i.ic_bajo!)} a ${pct(i.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 60 + 44 * items.length), { t: 24, l: 150, r: 90, b: 52 }),
xaxis: { title: { text: 'Porcentaje de la selección' }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', automargin: true, fixedrange: true } },
config,
};
}
/** The share of cases per group as a point with its interval: groups that aren't published have no point. */
export function comparacionFigura(c: ComparacionAnalisis, tema: Tema, medida: string): PlotlyFigure {
const t = c2Theme(tema);
const grupos = c.grupos.filter(g => g.estado === 'disponible');
return {
data: [{
type: 'scatter', mode: 'markers', y: grupos.map(g => g.etiqueta), x: grupos.map(g => g.valor), customdata: grupos.map(g => g.codigo),
marker: { color: C2_PALETTE.series[1], size: 11 },
error_x: { type: 'data', symmetric: false, array: grupos.map(g => g.ic_alto! - g.valor!), arrayminus: grupos.map(g => g.valor! - g.ic_bajo!), color: t.text, thickness: 2, width: 6 },
hovertemplate: grupos.map(g => `<b>${g.etiqueta}</b><br>${g.casos} de ${g.total} pacientes con resultado<br>${pct(g.valor!)} (IC 95 %: ${pct(g.ic_bajo!)} a ${pct(g.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, Math.max(220, 80 + 46 * grupos.length), { t: 24, l: 150, r: 28, b: 56 }),
xaxis: { title: { text: `${medida} entre pacientes con resultado de biopsia` }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true },
yaxis: { autorange: 'reversed', type: 'category', automargin: true, fixedrange: true } },
config,
};
}
const textoCelda = (c: CeldaMapa, medida: string) => c.suprimido ? 'No publicado'
: medida === 'pacientes' ? `${miles(c.n!)} pacientes` : c.resultado.estado === 'disponible' ? `${pct(c.resultado.valor!)}<br>${c.resultado.casos} de ${c.resultado.total}` : c.resultado.estado === 'suprimido' ? 'No publicado' : 'Sin pacientes con resultado';
/** BI-RADS by age group: the number of patients or the share of cases in each cell; hidden cells are blank. */
export function mapaFigura(m: MapaAnalisis, tema: Tema, medida: 'pacientes' | 'resultado'): PlotlyFigure {
const t = c2Theme(tema);
const celdas = new Map(m.celdas.map(c => [c.fila + '\u0000' + c.columna, c]));
const valor = (c: CeldaMapa | undefined) => !c || c.suprimido ? null : medida === 'pacientes' ? c.n : c.resultado.estado === 'disponible' ? c.resultado.valor : null;
const z = m.filas.categorias.map(f => m.columnas.categorias.map(c => valor(celdas.get(f.codigo + '\u0000' + c.codigo))));
return {
data: [{
type: 'heatmap', x: m.columnas.categorias.map(c => c.etiqueta), y: m.filas.categorias.map(f => f.etiqueta), z,
customdata: m.filas.categorias.map(f => m.columnas.categorias.map(c => [f.codigo, c.codigo])),
text: m.filas.categorias.map(f => m.columnas.categorias.map(c => textoCelda(celdas.get(f.codigo + '\u0000' + c.codigo)!, medida === 'pacientes' ? 'pacientes' : 'resultado'))),
hovertemplate: '%{y}, %{x}<br>%{text}<extra></extra>', hoverongaps: false, xgap: 2, ygap: 2,
colorscale: [[0, '#E4EEC0'], [1, '#6A8000']], zmin: 0, zmax: medida === 'resultado' ? 100 : undefined,
colorbar: { title: { text: medida === 'resultado' ? '% de casos' : 'Pacientes' } },
}],
layout: { ...base(tema, Math.max(280, 90 + 40 * m.filas.categorias.length), { t: 24, l: 130, r: 28, b: 60 }),
xaxis: { automargin: true, fixedrange: true, type: 'category' }, yaxis: { autorange: 'reversed', automargin: true, fixedrange: true, type: 'category' },
plot_bgcolor: t.grid },
config,
};
}
export interface FigurasTendencia { actividad: PlotlyFigure; proporcion: PlotlyFigure; }
/** Reports per period (bars; a hidden total is a gap) and the share of malignant results with its interval. */
export function tendenciaFiguras(r: TendenciaAnalisis, tema: Tema, medida: string): FigurasTendencia {
const t = c2Theme(tema);
const x = r.periodos.map(p => p.periodo + (p.incompleto ? ' (en curso)' : ''));
const disponibles = r.periodos.map((p, i) => ({ p, x: x[i] })).filter(({ p }) => p.maligno.estado === 'disponible');
return {
actividad: {
data: [
{ type: 'bar', name: 'Reportes de mastografía', x, y: r.periodos.map(p => p.reportes_mastografia.total), marker: { color: C2_PALETTE.series[2] },
hovertemplate: '%{x}<br>%{y} reportes de mastografía<extra></extra>' },
{ type: 'bar', name: 'Reportes de biopsia', x, y: r.periodos.map(p => p.reportes_biopsia.total), marker: { color: C2_PALETTE.series[3] },
hovertemplate: '%{x}<br>%{y} reportes de biopsia<extra></extra>' },
],
layout: { ...base(tema, 340, { t: 24, l: 56, r: 16, b: 80 }), showlegend: true, legend: { orientation: 'h', y: -0.28 }, barmode: 'group',
xaxis: { type: 'category', automargin: true, fixedrange: true }, yaxis: { title: { text: 'Reportes' }, gridcolor: t.grid, rangemode: 'tozero', fixedrange: true } },
config,
},
proporcion: {
data: [{
type: 'scatter', mode: 'lines+markers', x: disponibles.map(d => d.x), y: disponibles.map(d => d.p.maligno.valor), connectgaps: false,
line: { color: C2_PALETTE.series[1] }, marker: { color: C2_PALETTE.series[1], size: 9 },
error_y: { type: 'data', symmetric: false, array: disponibles.map(d => d.p.maligno.ic_alto! - d.p.maligno.valor!), arrayminus: disponibles.map(d => d.p.maligno.valor! - d.p.maligno.ic_bajo!), color: t.text },
hovertemplate: disponibles.map(d => `${d.x}<br>${d.p.maligno.casos} de ${d.p.maligno.total} reportes de biopsia con resultado<br>${pct(d.p.maligno.valor!)} (IC 95 %: ${pct(d.p.maligno.ic_bajo!)} a ${pct(d.p.maligno.ic_alto!)})<extra></extra>`),
}],
layout: { ...base(tema, 340, { t: 24, l: 64, r: 16, b: 64 }),
xaxis: { type: 'category', categoryorder: 'array', categoryarray: x, automargin: true, fixedrange: true },
yaxis: { title: { text: medida }, range: [0, 100], ticksuffix: ' %', gridcolor: t.grid, fixedrange: true } },
config,
},
};
}
@@ -0,0 +1,298 @@
// What this module covers: CaMa's descriptive analysis in the Analysis tab: the answers' validation, the cards, the
// figures built from them, the sections the component draws, the way from a figure to Seguimiento and the states
// without data, suppressed or not published.
// Fixtures (`fixtures/cama_analisis_real_*.json`): answers of the WebApi's `/cama/analisis` endpoints over the local
// installation's synthetic CaMa data at 2026-11-16, whole cohort: catalog, indicators (90 days), distribution by BI-RADS, by
// age group and by biopsy result, comparison by age group, map, trend by semester and by month, and the 403 body.
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { IndicadoresAnalisisDescriptivo, detalleTarjeta, valorTarjeta } from './indicadores-analisis-descriptivo';
import {
catalogoDescriptivo, comparacionDescriptiva, distribucionDescriptiva, mapaDescriptivo, resumenDescriptivo, tendenciaDescriptiva,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import catalogoData from './fixtures/cama_analisis_real_catalogo.json';
import resumenData from './fixtures/cama_analisis_real_resumen90.json';
import distBirads from './fixtures/cama_analisis_real_dist_birads.json';
import distEdad from './fixtures/cama_analisis_real_dist_edad.json';
import distBiopsia from './fixtures/cama_analisis_real_dist_biopsia.json';
import compBirads from './fixtures/cama_analisis_real_comp_birads.json';
import compEdad from './fixtures/cama_analisis_real_comp_edad.json';
import mapaData from './fixtures/cama_analisis_real_mapa.json';
import tendSem from './fixtures/cama_analisis_real_tend_sem.json';
import tendMes from './fixtures/cama_analisis_real_tend_mes.json';
import pequenoData from './fixtures/cama_analisis_real_pequeno.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
const CORTE = '2026-11-16';
describe('Respuestas del análisis descriptivo', () => {
it('las respuestas reales cumplen su contrato y nombran la cohorte que describen', () => {
// Pins down: every answer is accepted as the server sends it, names the cohort, scenario, revision and cut-off, and
// carries no `simulado` field. Fails if the contract drifts from what the client validates.
const todas = [catalogoDescriptivo(copia(catalogoData)), resumenDescriptivo(copia(resumenData)), distribucionDescriptiva(copia(distBirads)),
comparacionDescriptiva(copia(compEdad)), mapaDescriptivo(copia(mapaData))];
for (const r of todas) { expect(r.cohorte).toBe('cama_birads_v1'); expect(r.revision).toMatch(/^[0-9a-f]{64}$/); expect(r.corte).toBe(CORTE); expect('simulado' in r).toBe(false); }
expect(new Set(todas.map(r => r.revision)).size).toBe(1);
// The trend is activity, not the cohort: it names its cut-off, unit, population and biopsy scope, and no cohort, filters or test.
for (const t of [tendenciaDescriptiva(copia(tendSem)), tendenciaDescriptiva(copia(tendMes))]) {
expect(t.corte).toBe(CORTE); expect(t.unidad).toBe('reportes'); expect(t.poblacion).toBeTruthy(); expect(t.alcance_biopsias).toBeTruthy();
expect(Object.keys(t)).not.toEqual(expect.arrayContaining(['cohorte']));
for (const k of ['cohorte', 'revision', 'ventana', 'filtros', 'prueba', 'simulado']) expect(k in t).toBe(false);
}
});
it('una respuesta con un conteo publicado y suprimido a la vez, o sin cohorte, se rechaza', () => {
// Pins down: a suppressed item can't carry a count and a published one must; an answer without cohort context isn't read.
// Fails if the client draws figures from an answer that contradicts itself.
const d = copia(distBirads); d['items'][0].suprimido = true;
expect(() => distribucionDescriptiva(d)).toThrow();
const sin = copia(distBirads); delete sin['revision'];
expect(() => distribucionDescriptiva(sin)).toThrow();
const r = copia(resumenData); r['indicadores'][1].estado = 'suprimido';
expect(() => resumenDescriptivo(r)).toThrow();
});
it('las tarjetas escriben el valor, su intervalo y su denominador, o dicen por qué no hay cifra', () => {
// Pins down: a proportion reads «68.9»-style with its Wilson interval and `k de n pacientes`; a median reads its quartiles;
// a suppressed card has no value and says why. Fails if a card shows a number the answer doesn't publish.
const r = resumenDescriptivo(copia(resumenData));
const t = Object.fromEntries(r.indicadores.map(i => [i.clave, i]));
expect(valorTarjeta(t['cohorte'])).toBe('61');
expect(valorTarjeta(t['con_biopsia'])).toBe('68.9');
expect(detalleTarjeta(t['con_biopsia'])).toContain('IC 95 %: 56.4 a 79.1 %. 42 de 61 pacientes.');
expect(detalleTarjeta(t['dias_a_biopsia'])).toContain('Q1 a Q3: 19.3 a 30.8 días. 42 pacientes.');
const oculta = { ...t['con_biopsia'], estado: 'suprimido' as const, valor: null, ic_bajo: null, ic_alto: null };
expect(valorTarjeta(oculta)).toBeNull();
expect(detalleTarjeta(oculta)).toContain('Muy pocos pacientes');
});
});
describe('Figuras del análisis descriptivo', () => {
it('la distribución dibuja solo las categorías publicadas, con su intervalo, y deja las suprimidas fuera', () => {
// Pins down: BI-RADS 5 and 6 are suppressed in the real answer, so only BI-RADS 4 is drawn, at its share with its Wilson
// interval as asymmetric error bars; a hidden category is a gap, not a zero bar. Fails if a suppressed group is drawn.
const d = distribucionDescriptiva(copia(distBirads));
const [traza] = distribucionFigura(d, 'claro').data as Record<string, any>[];
expect(traza['y']).toEqual(['BI-RADS 4']);
expect(traza['x']).toEqual([54.1]);
expect(traza['error_x']['array'][0] + traza['x'][0]).toBeCloseTo(d.items[0].ic_alto!, 5);
});
it('la comparación dibuja un punto por grupo publicado con su intervalo', () => {
// Pins down: by age group three groups have enough patients with a result; each point is its share and the interval is
// asymmetric. Fails if a group without data or a hidden one gets a point.
const c = comparacionDescriptiva(copia(compEdad));
const [traza] = comparacionFigura(c, 'claro', 'Carcinoma invasor').data as Record<string, any>[];
expect(traza['y']).toEqual(['40 a 49 años', '50 a 59 años', '60 a 69 años'].map(e => expect.stringContaining(e.split(' ')[0])));
expect(traza['x']).toHaveLength(3);
expect(c.grupos.filter(g => g.estado === 'disponible').map(g => g.casos)).toEqual([5, 6, 8]);
});
it('el mapa deja en blanco las celdas que no se publican y conserva la posición de cada celda publicada', () => {
// Pins down: a hidden cell is `null` in the matrix (blank), never zero; published cells keep their row and column and carry
// the key that opens their patients. Fails if suppression turns into a zero or shifts a cell.
const m = mapaDescriptivo(copia(mapaData));
const [traza] = mapaFigura(m, 'claro', 'pacientes').data as Record<string, any>[];
const iFila = m.filas.categorias.findIndex(f => f.codigo === 'BIRADS_4'), iCol = m.columnas.categorias.findIndex(c => c.codigo === '50-59');
expect(traza['z'][iFila][iCol]).toBeNull();
const publicada = m.celdas.find(c => !c.suprimido && (c.n ?? 0) > 0)!;
const f = m.filas.categorias.findIndex(x => x.codigo === publicada.fila), c = m.columnas.categorias.findIndex(x => x.codigo === publicada.columna);
expect(traza['z'][f][c]).toBe(publicada.n);
expect(traza['customdata'][f][c]).toEqual([publicada.fila, publicada.columna]);
});
it('la tendencia dibuja los periodos y el porcentaje solo donde se publica, y marca el periodo en curso', () => {
// Pins down: by semester four periods carry a share with an interval; by month the months with fewer than five biopsies
// have no point; the period the cut-off cuts is labelled. Fails if an unpublished period gets a point.
const sem = tendenciaFiguras(tendenciaDescriptiva(copia(tendSem)), 'claro', 'x');
expect((sem.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(4);
const mes = tendenciaDescriptiva(copia(tendMes));
const figuras = tendenciaFiguras(mes, 'claro', 'x');
const publicados = mes.periodos.filter(p => p.maligno.estado === 'disponible').length;
expect((figuras.proporcion.data[0] as Record<string, any>)['x']).toHaveLength(publicados);
expect((figuras.actividad.data[0] as Record<string, any>)['x'].at(-1)).toContain('(en curso)');
});
});
describe('Análisis descriptivo de CaMa (componente)', () => {
let fixture: ComponentFixture<IndicadoresAnalisisDescriptivo>, http: HttpTestingController;
let emitidas: { seleccion: any; origen: HTMLElement | null }[];
beforeEach(() => {
TestBed.configureTestingModule({ imports: [IndicadoresAnalisisDescriptivo], providers: [provideHttpClient(), provideHttpClientTesting()] });
fixture = TestBed.createComponent(IndicadoresAnalisisDescriptivo); http = TestBed.inject(HttpTestingController);
emitidas = []; fixture.componentInstance.verPacientes.subscribe(e => emitidas.push(e));
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('corte', CORTE);
});
afterEach(() => { fixture.destroy(); http.verify(); });
const root = () => fixture.nativeElement as HTMLElement;
const pide = (ruta: string) => http.expectOne(r => r.url === `/cama/analisis${ruta}`);
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
async function abrir() {
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData); pide('/resumen').flush(resumenData); pide('/distribucion').flush(distBirads);
pide('/comparacion').flush(compBirads); pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
}
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
it('no pide nada hasta que la pestaña se abre y entonces pide sus seis respuestas con el corte y la selección', async () => {
// Pins down: nothing before the tab is open; then the catalog, indicators (90-day horizon), distribution by BI-RADS,
// comparison by age group, map and semester trend, all at the cut-off and the whole cohort. Fails if a section is
// asked early or without the selection.
http.expectNone(() => true);
fixture.componentRef.setInput('active', true); fixture.detectChanges();
const parametros = (ruta: string) => { const r = pide(ruta); const p = Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)])); r.flush({}, { status: 404, statusText: 'x' }); return p; };
expect(parametros('')).toEqual({ corte: CORTE, meses: '0' });
expect(parametros('/resumen')).toEqual({ corte: CORTE, meses: '0', horizonte: '90' });
expect(parametros('/distribucion')).toEqual({ corte: CORTE, meses: '0', por: 'birads' });
expect(parametros('/comparacion')).toEqual({ corte: CORTE, meses: '0', por: 'grupo_edad', medida: 'maligno' });
expect(parametros('/mapa')).toEqual({ corte: CORTE, meses: '0', filas: 'birads', columnas: 'grupo_edad', medida: 'maligno' });
expect(parametros('/tendencia')).toEqual({ corte: CORTE, tipo: 'semestre', periodos: '6' });
});
it('dibuja las tarjetas, las tablas y la lista de lo que no se puede calcular, con las mismas 61 pacientes en todas partes', async () => {
// Pins down: the cohort card, the distribution's total and its caption agree on 61 patients; the unavailable analyses
// are listed with their reasons; nothing says the data is simulated, provisional or a test. Fails if two parts of the tab
// count different patients or a banner of that kind appears.
await abrir();
const texto = root().textContent!;
expect(root().querySelectorAll('app-indicador-kpi-card')).toHaveLength(7);
expect(root().querySelector('app-indicador-kpi-card .value')?.textContent).toContain('61');
expect(root().querySelector('#desc-dist ~ div table caption, section[aria-labelledby="desc-dist"] caption')?.textContent).toContain('61 pacientes');
expect(texto).toContain('No disponible con las fuentes actuales');
for (const titulo of ['Supervivencia', 'Recaída', 'Adherencia al tratamiento']) expect(texto).toContain(titulo);
expect(texto).toContain('No hay estado vital');
expect(texto).not.toMatch(/simulad|demostraci|provisional|prueba de concepto|modo de desarrollo|datos de prueba/i);
});
it('una categoría suprimida dice «No publicado» sin botón y una publicada abre sus pacientes con la selección completa', async () => {
// Pins down: BI-RADS 5 (suppressed) has no «Ver pacientes» button; BI-RADS 4 has one and its click emits the filter, the
// label, the cut-off, the patients counted and the cohort context to quote back. Fails if a hidden group can be opened or
// the list would open another selection.
await abrir();
const fila = (codigo: string) => root().querySelector<HTMLElement>(`tr[data-codigo="${codigo}"]`)!;
expect(fila('BIRADS_5').textContent).toContain('No publicado'); expect(fila('BIRADS_5').querySelector('button')).toBeNull();
fila('BIRADS_4').querySelector<HTMLButtonElement>('button.ver')!.click();
expect(emitidas).toHaveLength(1);
expect(emitidas[0].seleccion).toMatchObject({ filtros: { birads: 'BIRADS_4' }, etiqueta: 'BI-RADS 4', corte: CORTE, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('cambiar la dimensión de la distribución vuelve a pedir solo esa sección', async () => {
// Pins down: choosing «Grupo de edad» asks `distribucion?por=grupo_edad` and nothing else, and its answer replaces the
// table. Fails if a choice in one section reloads the rest.
await abrir();
boton('Grupo de edad').click(); fixture.detectChanges();
const r = pide('/distribucion'); expect(r.request.params.get('por')).toBe('grupo_edad'); r.flush(distEdad); await asentar();
expect([...root().querySelectorAll('tr[data-codigo]')].map(tr => tr.getAttribute('data-codigo'))).toEqual(['<40', '40-49', '50-59', '60-69', '70+', 'SIN_DATO']);
http.expectNone(() => true);
boton('Resultado de la biopsia').click(); fixture.detectChanges(); pide('/distribucion').flush(distBiopsia); await asentar();
expect(root().querySelector('tr[data-codigo="SIN_BIOPSIA"]')?.textContent).toContain('19');
});
it('un grupo sin suficientes pacientes dice por qué, un 503 lo dice y un 404 queda pendiente, sin pantalla vacía', async () => {
// Pins down: a 403 on the distribution shows the fixed message; the indicators' 503 says the cohort isn't available and
// offers a retry; a 404 is «pendiente», not an error. Fails if a failure leaves the section empty or shows the body.
fixture.componentRef.setInput('active', true); fixture.detectChanges();
pide('').flush(catalogoData);
pide('/resumen').flush({}, { status: 503, statusText: 'x' });
pide('/distribucion').flush(pequenoData, { status: 403, statusText: 'x' });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' });
pide('/mapa').flush(mapaData); pide('/tendencia').flush(tendSem);
await asentar();
expect(root().textContent).toContain('La cohorte no está disponible en este momento.');
expect(root().querySelector('#desc-dist')!.parentElement!.querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(root().querySelector('#desc-dist')!.parentElement!.textContent).not.toContain('menos de 5 pacientes: su lista');
expect(root().querySelector('[aria-labelledby="desc-comp"] table')).toBeNull();
});
it('la comparación sin prueba válida lo dice; con prueba válida da el estadístico y su p', async () => {
// Pins down: by BI-RADS no table supports the test and the page says «No disponible» with the reason; by age group it
// gives chi-square, degrees of freedom and p. Fails if a p-value appears on a table the server called invalid.
await abrir();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toContain('No disponible. Hacen falta al menos dos grupos');
const c = fixture.componentInstance;
c.cambiarComparacion('grupo_edad', 'invasor'); fixture.detectChanges();
pide('/comparacion').flush(compEdad); await asentar();
expect(root().querySelector('[aria-labelledby="desc-comp"] .nota[role=status]')?.textContent).toMatch(/χ² 0.089, 2 gl, p 0.957/);
});
it('la tendencia marca el periodo en curso y deja sin cifra el porcentaje que no se publica', async () => {
// Pins down: by month the table says «No publicado» where a month has too few biopsies and labels the current month.
// Fails if a hidden share is written as a number or the partial period looks whole.
await abrir();
fixture.componentInstance.cambiarTendencia('mes', 12); fixture.detectChanges(); pide('/tendencia').flush(tendMes); await asentar();
const tabla = root().querySelector('[aria-labelledby="desc-tend"] table')!;
expect(tabla.textContent).toContain('(en curso)');
expect(tabla.textContent).toContain('No publicado');
expect(new Set([...tabla.querySelectorAll('tbody tr')].map(tr => tr.children[3].textContent!.trim())).has('No publicado')).toBe(true);
});
it('la actividad de reportes conserva su definición: solo cambia con el corte, nunca con la ventana ni los filtros', async () => {
// Pins down: «Aplicar» with another window and filters reloads the cohort sections with them but not the trend, and a new
// cut-off reloads the trend with only that cut-off, the period type and the count. Fails if the trend takes a filter or
// window it doesn't apply, or isn't refreshed when the cut-off changes.
await abrir();
const c = fixture.componentInstance;
c.meses = 3; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
const d = pide('/distribucion'); expect(d.request.params.get('meses')).toBe('3'); expect(d.request.params.get('grupo_edad')).toBe('50-59');
d.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
http.expectNone(r => r.url.endsWith('/tendencia'));
fixture.componentRef.setInput('corte', '2026-10-31'); await asentar();
const t = http.expectOne(r => r.url === '/cama/analisis/tendencia');
expect(Object.fromEntries(t.request.params.keys().map(k => [k, t.request.params.get(k)]))).toEqual({ corte: '2026-10-31', tipo: 'semestre', periodos: '6' });
t.flush({}, { status: 404, statusText: 'x' });
for (const ruta of ['', '/resumen', '/distribucion', '/comparacion', '/mapa']) pide(ruta).flush({}, { status: 404, statusText: 'x' });
});
it('la actividad de reportes se presenta con su población, la unidad y el alcance de las biopsias, y sin prueba estadística', async () => {
// Pins down: the section names what it counts (reports, not patients), over whom, the scope of the biopsies and that the
// cohort selection doesn't apply; it has no chi-square paragraph. Fails if the text attributes the filters or implies a test.
await abrir();
const seccion = root().querySelector('[aria-labelledby="desc-tend"]')!.textContent!;
expect(seccion).toContain('Actividad de reportes en el tiempo');
expect(seccion).toContain('no depende de la cohorte, la ventana ni los filtros');
expect(seccion).toContain('Cuenta reportes, no pacientes');
expect(seccion).toContain((tendSem as any).alcance_biopsias);
expect(seccion).toContain('Reportes de biopsia');
expect(seccion).not.toMatch(/χ²|p-valor|prueba de homogeneidad/i);
});
it.each([0, 1, 3, 6, 12])('una barra de la distribución con la ventana de %i meses y filtros abre la lista con esa misma ventana', async (m) => {
// Pins down: the selection a published bar emits carries the window the analysis was computed over, the filters applied,
// the cut-off and the cohort context. Fails if a window turns into the whole cohort when the patients are opened.
await abrir();
const c = fixture.componentInstance;
c.meses = m; c.filtros = { grupo_edad: '50-59' }; c.aplicar(); fixture.detectChanges();
pide('').flush({}, { status: 404, statusText: 'x' }); pide('/resumen').flush({}, { status: 404, statusText: 'x' });
pide('/distribucion').flush({ ...(distBirads as any), ventana: { ...(distBirads as any).ventana, meses: m }, filtros: { birads: null, grupo_edad: '50-59', biopsia: null } });
pide('/comparacion').flush({}, { status: 404, statusText: 'x' }); pide('/mapa').flush({}, { status: 404, statusText: 'x' });
await asentar();
root().querySelector<HTMLButtonElement>('tr[data-codigo="BIRADS_4"] button.ver')!.click();
expect(emitidas.at(-1)!.seleccion).toMatchObject({ filtros: { grupo_edad: '50-59', birads: 'BIRADS_4' }, corte: CORTE, meses: m, esperados: 33,
contexto: { cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: (distBirads as any).revision } });
});
it('«No disponible con las fuentes actuales» es una sección plegable, cerrada al inicio, con todo su contenido al abrirla', async () => {
// Pins down: the unavailable analyses sit in a native disclosure (keyboard and screen reader for free), closed at first,
// with its heading as the summary and every title and reason in the list inside it; opening it shows the same text as
// before. Fails if it starts open, loses an entry or stops being reachable from the keyboard.
await abrir();
const plegable = root().querySelector<HTMLDetailsElement>('details[data-plegable="no-disponibles"]')!;
const resumen = plegable.querySelector('summary')!;
expect(plegable.open).toBe(false);
expect(resumen.querySelector('h2')!.textContent).toBe('No disponible con las fuentes actuales');
expect(root().querySelector('section[aria-labelledby="desc-no"] h2')!.id).toBe('desc-no');
expect(resumen.tabIndex).toBeGreaterThanOrEqual(0);
const entradas = [...plegable.querySelectorAll('li')].map(li => li.textContent);
expect(entradas.length).toBe((resumenData as any).no_disponibles.length);
for (const n of (resumenData as any).no_disponibles) expect(entradas.some(t => t!.includes(n.titulo) && t!.includes('No disponible. ' + n.motivo))).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(true);
resumen.dispatchEvent(new MouseEvent('click', { bubbles: true })); fixture.detectChanges();
expect(plegable.open).toBe(false);
});
});
@@ -0,0 +1,368 @@
import { Component, DestroyRef, effect, inject, input, output, signal, untracked, WritableSignal } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { Observable, Subscription } from 'rxjs';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadorKpiCard } from './indicador-kpi-card';
import {
AnalisisCatalogoDescriptivo, AnalisisDescriptivoService, AnalisisSeleccion, CeldaMapa, ComparacionAnalisis, DistribucionAnalisis, MapaAnalisis,
PedidoDescriptivo, ResumenAnalisis, TarjetaAnalisis, TendenciaAnalisis,
} from './indicadores-analisis.service';
import { comparacionFigura, distribucionFigura, FigurasTendencia, mapaFigura, tendenciaFiguras } from './indicadores-analisis-descriptivo-figuras';
import { Dominio, PlotlyFigure, Tema } from './indicadores.models';
import type { SeleccionPacientes } from './indicadores-analisis';
type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estado: 'error'; mensaje: string } | { estado: 'pendiente' } | { estado: 'no-disponible' };
const VACIA = { data: [], layout: {} } as PlotlyFigure;
const miles = (v: number) => v.toLocaleString('es-MX');
const decimal = (v: number) => v.toLocaleString('es-MX', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** The card's value as the page writes it: a share with its interval, a median with its quartiles, or a count. */
export function valorTarjeta(t: TarjetaAnalisis): string | null {
if (t.estado !== 'disponible' || t.valor === null) return null;
return t.unidad === '%' ? decimal(t.valor) : t.unidad === 'días' ? decimal(t.valor) : miles(t.valor);
}
export function detalleTarjeta(t: TarjetaAnalisis): string {
if (t.estado === 'suprimido') return 'Muy pocos pacientes para publicar esta cifra. ' + t.descripcion;
if (t.estado === 'sin_datos') return 'No hay pacientes en esta base para calcularla. ' + t.descripcion;
const partes: string[] = [];
if (t.unidad === '%' && t.ic_bajo !== null && t.ic_alto !== null) partes.push(`IC 95 %: ${decimal(t.ic_bajo)} a ${decimal(t.ic_alto)} %. ${miles(t.n ?? 0)} de ${miles(t.denominador ?? 0)} pacientes.`);
if (t.unidad === 'días' && t.q1 !== null && t.q3 !== null) partes.push(`Q1 a Q3: ${decimal(t.q1)} a ${decimal(t.q3)} días. ${miles(t.n ?? 0)} pacientes.`);
partes.push(t.descripcion);
return partes.join(' ');
}
// Descriptive analysis of the BI-RADS cohort: its indicators, its distribution, a comparison between groups, the map
// between two variables and the trend over time. Every figure is drawn from the endpoint's answer; what the data cannot
// hold is listed as not available, with its reason. Nothing is requested until the tab is first opened.
@Component({
selector: 'app-indicadores-analisis-descriptivo',
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard],
template: `
<section class="bloque" aria-labelledby="desc-resumen">
<h2 id="desc-resumen">Indicadores de la cohorte</h2>
<p class="nota">Pacientes cuya última mastografía reportada al corte es BI-RADS 4, 5 o 6. Descriptivos: describen a estas pacientes, no la incidencia en una población.</p>
<form class="controles" (ngSubmit)="aplicar()">
<label>Ventana
<select name="meses" [(ngModel)]="meses">
<option [ngValue]="0">Toda la cohorte</option><option [ngValue]="1">Último mes</option><option [ngValue]="3">Últimos 3 meses</option>
<option [ngValue]="6">Últimos 6 meses</option><option [ngValue]="12">Últimos 12 meses</option>
</select></label>
<label>Categoría BI-RADS
<select name="birads" [(ngModel)]="filtros['birads']"><option [ngValue]="undefined">Todas</option>
@for (o of opciones('birads'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Grupo de edad
<select name="grupo_edad" [(ngModel)]="filtros['grupo_edad']"><option [ngValue]="undefined">Todos</option>
@for (o of opciones('grupo_edad'); track o.codigo) { <option [ngValue]="o.codigo">{{ o.etiqueta }}</option> }</select></label>
<label>Horizonte del seguimiento diagnóstico
<select name="horizonte" [(ngModel)]="horizonte">
@for (h of horizontes(); track h) { <option [ngValue]="h">{{ h }} días</option> }</select></label>
<button type="submit" mat-stroked-button [disabled]="cargando()">Aplicar</button>
</form>
@switch (resumen().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando los indicadores" /> }
@case ('pendiente') { <p role="status">Funcionalidad pendiente de publicación.</p> }
@case ('no-disponible') { <p role="status">La cohorte no está disponible en este momento.</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button> }
@case ('error') { <div role="alert"><p>{{ $any(resumen()).mensaje }}</p><button type="button" mat-stroked-button (click)="aplicar()">Reintentar consulta</button></div> }
}
@if (r(); as res) {
<p class="contexto">Fecha de corte: {{ res.corte }}. Ventana: {{ res.ventana.meses === 0 ? 'toda la cohorte' : res.ventana.desde + ' al ' + res.ventana.hasta }}.</p>
<div class="tarjetas">
@for (t of res.indicadores; track t.clave) {
<app-indicador-kpi-card [title]="t.titulo" [value]="valor(t)" [unit]="t.unidad === 'pacientes' ? '' : t.unidad === 'días' ? 'días (mediana)' : '%'"
[state]="t.estado === 'disponible' ? 'Disponible' : t.estado === 'suprimido' ? 'Dato oculto por tamaño' : 'Sin valor disponible'"
[quietWhenAvailable]="true" [additionalInfo]="detalle(t)" />
}
</div>
}
</section>
<section class="bloque" aria-labelledby="desc-dist">
<h2 id="desc-dist">Distribución de pacientes</h2>
<div class="selector" role="group" aria-label="Distribuir por">
@for (d of dimensionesDist; track d.clave) {
<button type="button" mat-stroked-button [class.activo]="por() === d.clave" [attr.aria-pressed]="por() === d.clave" (click)="cambiarPor(d.clave)">{{ d.etiqueta }}</button>
}
</div>
@switch (distribucion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la distribución" /> }
@case ('error') { <div role="alert"><p>{{ $any(distribucion()).mensaje }}</p></div> }
}
@if (dist(); as d) {
@if (d.total === 0) { <p role="status">No hay pacientes en esta cohorte para el corte seleccionado.</p> }
@else {
<app-plotly-chart [style.--plot-height]="'auto'" [showNotes]="false" [figure]="figuraDist()" label="Distribución de pacientes" (plotClick)="clicDist($event)" />
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Distribución de pacientes, tabla">
<table><caption>{{ miles(d.total) }} pacientes en la selección</caption>
<thead><tr><th scope="col">Categoría</th><th scope="col">Pacientes</th><th scope="col">Porcentaje (IC 95 %)</th><th scope="col"><span class="visually-hidden">Seguimiento</span></th></tr></thead>
<tbody>@for (i of d.items; track i.codigo) {
<tr [attr.data-codigo]="i.codigo"><th scope="row">{{ i.etiqueta }}</th>
<td>{{ i.suprimido ? 'No publicado' : miles(i.n!) }}</td>
<td>{{ i.suprimido || i.porcentaje === null ? 'No disponible' : decimal(i.porcentaje) + ' % (' + decimal(i.ic_bajo!) + ' a ' + decimal(i.ic_alto!) + ')' }}</td>
<td>@if (!i.suprimido && i.n) { <button type="button" class="ver" (click)="abrir(i.seleccion, i.etiqueta, i.n, d, $event.currentTarget)"
[attr.aria-label]="'Ver pacientes de ' + i.etiqueta + ' en Seguimiento'">Ver pacientes</button> }</td></tr>
}</tbody></table>
</div>
@if (d.items.some(i => i.suprimido)) { <p class="nota">Una categoría con menos de {{ d.umbral_supresion }} pacientes no se publica; para que su cifra no se pueda deducir, otra categoría puede quedar sin publicar.</p> }
}
}
</section>
<section class="bloque" aria-labelledby="desc-comp">
<h2 id="desc-comp">Comparación entre grupos</h2>
<p class="nota">Porcentaje de pacientes con el resultado elegido entre las que tienen resultado de biopsia conocido, por grupo. Es una comparación descriptiva dentro de la cohorte.</p>
<div class="controles">
<label>Comparar por
<select name="comp-por" [ngModel]="compPor()" (ngModelChange)="cambiarComparacion($event, compMedida())">
<option value="birads">Categoría BI-RADS</option><option value="grupo_edad">Grupo de edad</option></select></label>
<label>Resultado
<select name="comp-medida" [ngModel]="compMedida()" (ngModelChange)="cambiarComparacion(compPor(), $event)">
<option value="maligno">Carcinoma in situ o invasor</option><option value="invasor">Carcinoma invasor</option></select></label>
</div>
@switch (comparacion().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la comparación" /> }
@case ('error') { <div role="alert"><p>{{ $any(comparacion()).mensaje }}</p></div> }
}
@if (comp(); as c) {
@if (hayComparables()) { <app-plotly-chart [showNotes]="false" [figure]="figuraComp()" label="Comparación entre grupos" /> }
@else { <p role="status">Ningún grupo tiene suficientes pacientes con resultado de biopsia para publicar su porcentaje.</p> }
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Comparación entre grupos, tabla">
<table><caption>{{ c.denominador }}</caption>
<thead><tr><th scope="col">Grupo</th><th scope="col">Con el resultado</th><th scope="col">Con resultado conocido</th><th scope="col">Porcentaje (IC 95 %)</th></tr></thead>
<tbody>@for (g of c.grupos; track g.codigo) {
<tr><th scope="row">{{ g.etiqueta }}</th>
<td>{{ g.estado === 'disponible' ? miles(g.casos!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? miles(g.total!) : g.estado === 'suprimido' ? 'No publicado' : '0' }}</td>
<td>{{ g.estado === 'disponible' ? decimal(g.valor!) + ' % (' + decimal(g.ic_bajo!) + ' a ' + decimal(g.ic_alto!) + ')' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ textoPrueba(c.prueba) }}</p>
}
</section>
<section class="bloque" aria-labelledby="desc-mapa">
<h2 id="desc-mapa">Mapa entre variables: categoría BI-RADS y grupo de edad</h2>
<div class="selector" role="group" aria-label="Medida del mapa">
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'pacientes'" [attr.aria-pressed]="mapaMedida() === 'pacientes'" (click)="cambiarMapa('pacientes')">Pacientes</button>
<button type="button" mat-stroked-button [class.activo]="mapaMedida() === 'resultado'" [attr.aria-pressed]="mapaMedida() === 'resultado'" (click)="cambiarMapa('resultado')">Porcentaje con carcinoma</button>
</div>
@switch (mapa().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando el mapa" /> }
@case ('error') { <div role="alert"><p>{{ $any(mapa()).mensaje }}</p></div> }
}
@if (m(); as mm) {
<app-plotly-chart [showNotes]="false" [figure]="figuraMapa()" label="Mapa entre variables" (plotClick)="clicMapa($event)" />
<p class="nota">Las celdas en blanco no se publican (menos de {{ mm.umbral_supresion }} pacientes, o se ocultan para que otra no se pueda deducir). Una celda publicada abre sus pacientes en Seguimiento.</p>
<details><summary>Valores publicados</summary>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Mapa entre variables, tabla">
<table><thead><tr><th scope="col">BI-RADS</th><th scope="col">Grupo de edad</th><th scope="col">Pacientes</th><th scope="col">Con carcinoma entre los de resultado conocido</th></tr></thead>
<tbody>@for (c of celdasPublicadas(mm); track c.fila + c.columna) {
<tr><th scope="row">{{ etiqueta(mm.filas.categorias, c.fila) }}</th><td>{{ etiqueta(mm.columnas.categorias, c.columna) }}</td><td>{{ miles(c.n!) }}</td>
<td>{{ c.resultado.estado === 'disponible' ? c.resultado.casos + ' de ' + c.resultado.total + ' (' + decimal(c.resultado.valor!) + ' %)' : 'No disponible' }}</td></tr>
}</tbody></table>
</div>
</details>
}
</section>
<section class="bloque" aria-labelledby="desc-tend">
<h2 id="desc-tend">Actividad de reportes en el tiempo</h2>
<p class="nota">Reportes de mastografía con BI-RADS y de biopsia ligada a esas mastografías en cada periodo, de todas las pacientes, y el porcentaje de resultados con carcinoma entre los reportes de biopsia con resultado. Es la actividad general: no depende de la cohorte, la ventana ni los filtros de arriba. Cuenta reportes, no pacientes; una paciente con varios reportes se cuenta varias veces.</p>
<div class="controles">
<label>Periodo
<select name="tend-tipo" [ngModel]="tendTipo()" (ngModelChange)="cambiarTendencia($event, tendPeriodos())"><option value="semestre">Semestral</option><option value="mes">Mensual</option></select></label>
<label>Periodos a mostrar
<select name="tend-n" [ngModel]="tendPeriodos()" (ngModelChange)="cambiarTendencia(tendTipo(), $event)"><option [ngValue]="4">4</option><option [ngValue]="6">6</option><option [ngValue]="12">12</option><option [ngValue]="24">24</option></select></label>
</div>
@switch (tendencia().estado) {
@case ('cargando') { <mat-progress-bar mode="indeterminate" aria-label="Calculando la tendencia" /> }
@case ('error') { <div role="alert"><p>{{ $any(tendencia()).mensaje }}</p></div> }
}
@if (t(); as tt) {
<div class="par">
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().actividad" label="Reportes de mastografía y de biopsia por periodo" />
<app-plotly-chart [showNotes]="false" [figure]="figurasTend().proporcion" label="Porcentaje de resultados con carcinoma por periodo" />
</div>
<div class="tabla-scroll" role="region" tabindex="0" aria-label="Tendencia, tabla">
<table><thead><tr><th scope="col">Periodo</th><th scope="col">Reportes de mastografía</th><th scope="col">Reportes de biopsia</th><th scope="col">Con carcinoma (IC 95 %)</th></tr></thead>
<tbody>@for (p of tt.periodos; track p.periodo) {
<tr><th scope="row">{{ p.periodo }}@if (p.incompleto) { <span class="nota"> (en curso)</span> }</th>
<td>{{ p.reportes_mastografia.total === null ? 'No publicado' : miles(p.reportes_mastografia.total) }}</td>
<td>{{ p.reportes_biopsia.total === null ? 'No publicado' : miles(p.reportes_biopsia.total) }}</td>
<td>{{ p.maligno.estado === 'disponible' ? p.maligno.casos + ' de ' + p.maligno.total + ' (' + decimal(p.maligno.valor!) + ' %; ' + decimal(p.maligno.ic_bajo!) + ' a ' + decimal(p.maligno.ic_alto!) + ')' : p.maligno.estado === 'suprimido' ? 'No publicado' : 'Sin reportes de biopsia con resultado' }}</td></tr>
}</tbody></table>
</div>
<p class="nota" role="status">{{ tt.alcance_biopsias }}. Los periodos en curso están incompletos y se marcan.</p>
}
</section>
@if (r(); as res) {
<section class="bloque" aria-labelledby="desc-no">
<!-- Closed at first; the native disclosure gives the keyboard (Enter and Space) and the screen reader its state. -->
<details class="plegable" data-plegable="no-disponibles">
<summary><h2 id="desc-no">No disponible con las fuentes actuales</h2></summary>
<ul class="no-disponibles">
@for (n of res.no_disponibles; track n.clave) { <li><strong>{{ n.titulo }}</strong>: No disponible. {{ n.motivo }}</li> }
</ul>
</details>
</section>
}
`,
styles: `
:host { display: flex; flex-direction: column; gap: var(--issste-space-4); min-width: 0; }
.bloque { 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, ul { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
.nota, .contexto { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.tarjetas { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-4); }
@media (min-width: 700px) { .tarjetas { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (min-width: 1100px) { .tarjetas { grid-template-columns: repeat(4, minmax(0, 1fr)); } .par { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.par { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
.controles { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); margin-top: var(--issste-space-3); }
.selector { display: flex; flex-wrap: wrap; gap: var(--issste-space-2); margin-top: var(--issste-space-3); }
.selector .activo { background: var(--issste-accent, #A8C243); color: #081839; }
label { display: flex; flex-direction: column; gap: .5rem; max-width: 100%; }
select { color: inherit; background: var(--issste-surface); border: 1px solid var(--issste-border); border-radius: 4px; padding: .6rem; min-height: 44px; font: inherit; }
select:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
app-plotly-chart { margin-top: var(--issste-space-3); }
.tabla-scroll { overflow-x: auto; margin-top: var(--issste-space-4); }
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 { font-variant-numeric: tabular-nums; }
.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 currentColor; outline-offset: 2px; }
details { margin-top: var(--issste-space-3); } summary { cursor: pointer; }
.no-disponibles { padding-left: 1.2rem; color: var(--issste-text-secondary); }
.plegable > summary { display: list-item; list-style-position: inside; cursor: pointer; border-radius: var(--issste-radius); }
.plegable > summary h2 { display: inline; }
.plegable > summary:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
.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; }
`,
})
export class IndicadoresAnalisisDescriptivo {
readonly dominio = input.required<Dominio>();
readonly tema = input.required<Tema>();
readonly corte = input.required<string>();
readonly active = input(false);
readonly verPacientes = output<{ seleccion: SeleccionPacientes; origen: HTMLElement | null }>();
readonly miles = miles; readonly decimal = decimal;
readonly valor = valorTarjeta; readonly detalle = detalleTarjeta;
readonly dimensionesDist = [{ clave: 'birads', etiqueta: 'Categoría BI-RADS' }, { clave: 'grupo_edad', etiqueta: 'Grupo de edad' }, { clave: 'biopsia', etiqueta: 'Resultado de la biopsia' }];
meses = 0; horizonte = 90; filtros: Record<string, string | undefined> = {};
readonly por = signal('birads');
readonly compPor = signal('grupo_edad'); readonly compMedida = signal('maligno');
readonly mapaMedida = signal<'pacientes' | 'resultado'>('pacientes');
readonly tendTipo = signal('semestre'); readonly tendPeriodos = signal(6);
readonly catalogo = signal<Carga<AnalisisCatalogoDescriptivo>>({ estado: 'cargando' });
readonly resumen = signal<Carga<ResumenAnalisis>>({ estado: 'cargando' });
readonly distribucion = signal<Carga<DistribucionAnalisis>>({ estado: 'cargando' });
readonly comparacion = signal<Carga<ComparacionAnalisis>>({ estado: 'cargando' });
readonly mapa = signal<Carga<MapaAnalisis>>({ estado: 'cargando' });
readonly tendencia = signal<Carga<TendenciaAnalisis>>({ estado: 'cargando' });
readonly figuraDist = signal<PlotlyFigure>(VACIA); readonly figuraComp = signal<PlotlyFigure>(VACIA);
readonly figuraMapa = signal<PlotlyFigure>(VACIA);
readonly figurasTend = signal<FigurasTendencia>({ actividad: VACIA, proporcion: VACIA });
private readonly service = inject(AnalisisDescriptivoService);
private readonly destroy = inject(DestroyRef);
private readonly suscripciones = new Map<string, Subscription>();
private abierto = false; private corteCargado = ''; private tendCorte = '';
// The filters and window the sections were last asked with: one selection for all of them.
private pedidoVigente: PedidoDescriptivo = { corte: '', meses: 0, filtros: {} };
constructor() {
effect(() => {
const activa = this.active(), corte = this.corte();
if (!activa) return;
untracked(() => { if (!this.abierto || corte !== this.corteCargado) { this.abierto = true; this.corteCargado = corte; this.aplicar(); } });
});
}
// Each accessor gives the loaded data or nothing: the template draws only what the endpoint answered.
r() { const c = this.resumen(); return c.estado === 'listo' ? c.datos : undefined; }
dist() { const c = this.distribucion(); return c.estado === 'listo' ? c.datos : undefined; }
comp() { const c = this.comparacion(); return c.estado === 'listo' ? c.datos : undefined; }
m() { const c = this.mapa(); return c.estado === 'listo' ? c.datos : undefined; }
t() { const c = this.tendencia(); return c.estado === 'listo' ? c.datos : undefined; }
cargando() { return [this.resumen(), this.distribucion(), this.comparacion(), this.mapa(), this.tendencia()].some(c => c.estado === 'cargando'); }
opciones(clave: string) { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.dimensiones.find(d => d.clave === clave)?.opciones ?? [] : []; }
horizontes() { const c = this.catalogo(); return c.estado === 'listo' ? c.datos.horizontes_dias : [90]; }
hayComparables() { return !!this.comp()?.grupos.some(g => g.estado === 'disponible'); }
celdasPublicadas(m: MapaAnalisis): CeldaMapa[] { return m.celdas.filter(c => !c.suprimido && (c.n ?? 0) > 0); }
etiqueta(categorias: { codigo: string; etiqueta: string }[], codigo: string) { return categorias.find(c => c.codigo === codigo)?.etiqueta ?? codigo; }
textoPrueba(p: { valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; nombre: string }) {
if (!p.valida) return `${p.nombre}: No disponible. ${p.motivo ?? ''}`.trim();
const valor = p.p! < 0.001 ? '< 0.001' : p.p!.toLocaleString('es-MX', { minimumFractionDigits: 3, maximumFractionDigits: 3 });
return `${p.nombre}: χ² ${p.estadistico!.toLocaleString('es-MX')}, ${p.gl} gl, p ${valor}. Describe diferencias en estas pacientes; no es una estimación causal.`;
}
private pedido(): PedidoDescriptivo {
return { corte: this.corte(), meses: this.meses, filtros: { ...this.filtros } };
}
/** Asks every section for the selection in the form: the first time, on a new cut-off and on «Aplicar». */
aplicar() {
this.pedidoVigente = this.pedido();
const p = this.pedidoVigente;
this.cargar('catalogo', this.catalogo, this.service.catalogo(this.dominio(), p));
this.cargar('resumen', this.resumen, this.service.resumen(this.dominio(), p, this.horizonte));
this.recargarDist(); this.recargarComp(); this.recargarMapa();
// The trend depends only on the cut-off: «Aplicar» with other filters or window leaves it as it is.
if (this.corte() !== this.tendCorte) { this.tendCorte = this.corte(); this.recargarTend(); }
}
private recargarDist() { this.cargar('dist', this.distribucion, this.service.distribucion(this.dominio(), this.pedidoVigente, this.por()), d => this.figuraDist.set(distribucionFigura(d, this.tema()))); }
private recargarComp() { this.cargar('comp', this.comparacion, this.service.comparacion(this.dominio(), this.pedidoVigente, this.compPor(), this.compMedida()), c => this.figuraComp.set(comparacionFigura(c, this.tema(), this.compMedida() === 'invasor' ? 'Carcinoma invasor' : 'Carcinoma in situ o invasor'))); }
private recargarMapa() { this.cargar('mapa', this.mapa, this.service.mapa(this.dominio(), this.pedidoVigente, 'birads', 'grupo_edad', 'maligno'), m => this.figuraMapa.set(mapaFigura(m, this.tema(), this.mapaMedida()))); }
private recargarTend() { this.cargar('tend', this.tendencia, this.service.tendencia(this.dominio(), this.corte(), this.tendTipo(), this.tendPeriodos()), t => this.figurasTend.set(tendenciaFiguras(t, this.tema(), 'Con carcinoma entre biopsias con resultado'))); }
cambiarPor(clave: string) { this.por.set(clave); this.recargarDist(); }
cambiarComparacion(por: string, medida: string) { this.compPor.set(por); this.compMedida.set(medida); this.recargarComp(); }
cambiarMapa(medida: 'pacientes' | 'resultado') { this.mapaMedida.set(medida); const m = this.m(); if (m) this.figuraMapa.set(mapaFigura(m, this.tema(), medida)); }
cambiarTendencia(tipo: string, periodos: number) { this.tendTipo.set(tipo); this.tendPeriodos.set(periodos); this.recargarTend(); }
private cargar<T>(clave: string, destino: WritableSignal<Carga<T>>, fuente: Observable<T>, alListo?: (d: T) => void) {
this.suscripciones.get(clave)?.unsubscribe();
destino.set({ estado: 'cargando' });
this.suscripciones.set(clave, fuente.pipe(takeUntilDestroyed(this.destroy)).subscribe({
next: datos => { destino.set({ estado: 'listo', datos }); alListo?.(datos); },
error: error => destino.set(this.fallo(error)),
}));
}
private fallo(error: unknown): Carga<never> {
if (error instanceof HttpErrorResponse) {
if (error.status === 404) return { estado: 'pendiente' };
if (error.status === 503) return { estado: 'no-disponible' };
if (error.status === 403) return { estado: 'error', mensaje: 'La selección tiene muy pocos pacientes para publicar sus resultados.' };
if (error.status === 409) return { estado: 'error', mensaje: 'La cohorte cambió. Consulta de nuevo.' };
if (error.status === 400) return { estado: 'error', mensaje: 'El servicio rechazó la selección. Revisa la ventana y los filtros.' };
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 >= 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.' };
}
/** The patients of a published group or cell, for the page to open them in Seguimiento. */
abrir(seleccion: Record<string, string>, etiqueta: string, n: number | null, base: AnalisisSeleccion, origen?: EventTarget | null) {
if (!n) return;
const activos = Object.fromEntries(Object.entries(base.filtros).filter(([, v]) => v !== null)) as Record<string, string>;
this.verPacientes.emit({
origen: origen instanceof HTMLElement ? origen : null,
seleccion: { filtros: { ...activos, ...seleccion }, etiqueta, corte: base.corte, meses: base.ventana.meses, esperados: n, contexto: { cohorte: base.cohorte, escenario: base.escenario, revision: base.revision } },
});
}
clicDist(evento: unknown) {
const codigo = (evento as { points?: { customdata?: unknown }[] } | undefined)?.points?.[0]?.customdata;
const d = this.dist(), item = d?.items.find(i => i.codigo === codigo && !i.suprimido);
if (d && item) this.abrir(item.seleccion, item.etiqueta, item.n, d);
}
clicMapa(evento: unknown) {
const c = (evento as { points?: { customdata?: unknown; z?: unknown }[] } | undefined)?.points?.[0];
const [fila, columna] = Array.isArray(c?.customdata) ? c.customdata as string[] : [];
const mm = this.m(), celda = mm?.celdas.find(x => x.fila === fila && x.columna === columna && !x.suprimido);
if (mm && celda) this.abrir(celda.seleccion, `${this.etiqueta(mm.filas.categorias, celda.fila)}, ${this.etiqueta(mm.columnas.categorias, celda.columna)}`, celda.n, mm);
}
}
@@ -55,3 +55,119 @@ export class AnalisisService {
return this.http.get<unknown>(`/${requireDominio(dominio)}/analisis/indicadores`, { params: new HttpParams().set('corte', corte) }).pipe(map(analisisAgregado));
}
}
// The descriptive analysis (`/<dominio>/analisis/...`): counts and proportions of the cohort at a cut-off, with the
// window and filters of the follow-up list. Every answer names the cohort it describes, so a figure can open its patients.
export interface AnalisisSeleccion {
cohorte: string; escenario: string; revision: string; corte: string; umbral_supresion: number;
ventana: { meses: number; desde: string; hasta: string };
filtros: Record<string, string | null>;
}
export type EstadoDato = 'disponible' | 'suprimido' | 'sin_datos';
export interface Proporcion { estado: EstadoDato; casos: number | null; total: number | null; valor: number | null; ic_bajo: number | null; ic_alto: number | null; }
export interface DimensionAnalisis { clave: string; etiqueta: string; opciones: { codigo: string; etiqueta: string }[]; }
export interface NoDisponible { clave: string; titulo: string; motivo: string; }
export interface AnalisisCatalogoDescriptivo extends AnalisisSeleccion {
dimensiones: DimensionAnalisis[]; medidas: { clave: string; etiqueta: string }[]; horizontes_dias: number[]; tipos_periodo: string[];
secciones: { clave: string; titulo: string; estado: string; motivo: string | null }[]; no_disponibles: NoDisponible[];
}
export interface TarjetaAnalisis {
clave: string; titulo: string; descripcion: string; unidad: string; estado: EstadoDato; valor: number | null; ic_bajo: number | null; ic_alto: number | null;
n: number | null; denominador: number | null; q1: number | null; q3: number | null; motivo: string | null;
}
export interface ResumenAnalisis extends AnalisisSeleccion { horizonte_dias: number; indicadores: TarjetaAnalisis[]; no_disponibles: NoDisponible[]; }
export interface ItemDistribucion { codigo: string; etiqueta: string; suprimido: boolean; n: number | null; porcentaje: number | null; ic_bajo: number | null; ic_alto: number | null; seleccion: Record<string, string>; }
export interface DistribucionAnalisis extends AnalisisSeleccion { por: string; total: number; items: ItemDistribucion[]; }
export interface Prueba { nombre: string; valida: boolean; motivo?: string; estadistico?: number; gl?: number; p?: number; }
export interface GrupoComparacion extends Proporcion { codigo: string; etiqueta: string; seleccion: Record<string, string>; }
export interface ComparacionAnalisis extends AnalisisSeleccion { por: string; medida: string; denominador: string; grupos: GrupoComparacion[]; prueba: Prueba; }
export interface CeldaMapa { fila: string; columna: string; suprimido: boolean; n: number | null; seleccion: Record<string, string>; resultado: Proporcion; }
export interface EjeMapa { por: string; categorias: { codigo: string; etiqueta: string }[]; }
export interface MapaAnalisis extends AnalisisSeleccion { filas: EjeMapa; columnas: EjeMapa; medida: string; celdas: CeldaMapa[]; }
export interface ConteoPeriodo { n: number | null; suprimido: boolean; }
export interface PeriodoTendencia {
periodo: string; inicio: string; fin: string; incompleto: boolean;
reportes_mastografia: { total: number | null; por_categoria: Record<string, ConteoPeriodo> };
reportes_biopsia: { total: number | null; por_grado: Record<string, ConteoPeriodo> };
maligno: Proporcion;
}
// The trend is general activity, not the cohort: it carries no cohort, window or filters, only what it counts and over whom.
export interface TendenciaAnalisis {
corte: string; umbral_supresion: number; tipo_periodo: string; unidad: string; poblacion: string; alcance_biopsias: string;
denominador: string; periodos: PeriodoTendencia[];
}
export interface PedidoDescriptivo { corte: string; meses: number; filtros: Record<string, string | undefined>; contexto?: { cohorte: string; escenario: string; revision: string }; }
const numOnulo = (v: unknown) => v === null || (typeof v === 'number' && Number.isFinite(v));
const estadoOk = (v: unknown) => v === 'disponible' || v === 'suprimido' || v === 'sin_datos';
const proporcionOk = (v: unknown) => record(v) && estadoOk(v['estado']) && numOnulo(v['valor']) && numOnulo(v['ic_bajo']) && numOnulo(v['ic_alto'])
&& numOnulo(v['casos']) && numOnulo(v['total']) && (v['estado'] === 'disponible' ? v['valor'] !== null && v['casos'] !== null : v['valor'] === null);
const seleccionOk = (v: unknown): v is Record<string, unknown> => record(v) && text(v['cohorte']) && text(v['escenario']) && text(v['revision']) && text(v['corte'])
&& typeof v['umbral_supresion'] === 'number' && record(v['ventana']) && record(v['filtros']);
const invalidoDescriptivo = (): never => { throw new Error('Respuesta de análisis inválida'); };
export function catalogoDescriptivo(v: unknown): AnalisisCatalogoDescriptivo {
if (!seleccionOk(v) || !Array.isArray(v['dimensiones']) || !v['dimensiones'].every(d => record(d) && text(d['clave']) && Array.isArray(d['opciones']))
|| !Array.isArray(v['no_disponibles']) || !Array.isArray(v['horizontes_dias']) || !Array.isArray(v['tipos_periodo'])) invalidoDescriptivo();
return v as unknown as AnalisisCatalogoDescriptivo;
}
export function resumenDescriptivo(v: unknown): ResumenAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['indicadores']) || !v['indicadores'].every(t => record(t) && text(t['clave']) && text(t['titulo']) && estadoOk(t['estado'])
&& numOnulo(t['valor']) && (t['estado'] === 'disponible' ? t['valor'] !== null : t['valor'] === null))) invalidoDescriptivo();
return v as unknown as ResumenAnalisis;
}
export function distribucionDescriptiva(v: unknown): DistribucionAnalisis {
if (!seleccionOk(v) || typeof v['total'] !== 'number' || !Array.isArray(v['items'])
|| !v['items'].every(i => record(i) && text(i['codigo']) && typeof i['suprimido'] === 'boolean' && numOnulo(i['n']) && (i['suprimido'] ? i['n'] === null : i['n'] !== null)
&& record(i['seleccion']))) invalidoDescriptivo();
return v as unknown as DistribucionAnalisis;
}
export function comparacionDescriptiva(v: unknown): ComparacionAnalisis {
if (!seleccionOk(v) || !Array.isArray(v['grupos']) || !v['grupos'].every(g => record(g) && text(g['codigo']) && proporcionOk(g))
|| !record(v['prueba']) || typeof v['prueba']['valida'] !== 'boolean') invalidoDescriptivo();
return v as unknown as ComparacionAnalisis;
}
export function mapaDescriptivo(v: unknown): MapaAnalisis {
if (!seleccionOk(v) || !record(v['filas']) || !record(v['columnas']) || !Array.isArray(v['celdas'])
|| !v['celdas'].every(c => record(c) && text(c['fila']) && text(c['columna']) && typeof c['suprimido'] === 'boolean' && numOnulo(c['n'])
&& (c['suprimido'] ? c['n'] === null : c['n'] !== null) && record(c['resultado']) && estadoOk(c['resultado']['estado']))) invalidoDescriptivo();
return v as unknown as MapaAnalisis;
}
export function tendenciaDescriptiva(v: unknown): TendenciaAnalisis {
if (!record(v) || !text(v['corte']) || v['unidad'] !== 'reportes' || !text(v['poblacion']) || !text(v['alcance_biopsias']) || !text(v['tipo_periodo'])
|| !Array.isArray(v['periodos']) || !v['periodos'].every(p => record(p) && text(p['periodo']) && typeof p['incompleto'] === 'boolean'
&& record(p['reportes_mastografia']) && record(p['reportes_biopsia']) && proporcionOk(p['maligno']))) invalidoDescriptivo();
return v as unknown as TendenciaAnalisis;
}
function paramsDe(pedido: PedidoDescriptivo, extra: Record<string, string | number | undefined> = {}) {
let params = new HttpParams().set('corte', pedido.corte).set('meses', pedido.meses);
for (const [k, v] of Object.entries(pedido.filtros)) if (v) params = params.set(k, v);
if (pedido.contexto) for (const [k, v] of Object.entries(pedido.contexto)) params = params.set(k, v);
for (const [k, v] of Object.entries(extra)) if (v !== undefined) params = params.set(k, v);
return params;
}
@Injectable({ providedIn: 'root' })
export class AnalisisDescriptivoService {
private readonly http = inject(HttpClient);
private url(dominio: Dominio, ruta: string) { return `/${requireDominio(dominio)}/analisis${ruta}`; }
catalogo(d: Dominio, p: PedidoDescriptivo) { return this.http.get<unknown>(this.url(d, ''), { params: paramsDe(p) }).pipe(map(catalogoDescriptivo)); }
resumen(d: Dominio, p: PedidoDescriptivo, horizonte: number) {
return this.http.get<unknown>(this.url(d, '/resumen'), { params: paramsDe(p, { horizonte }) }).pipe(map(resumenDescriptivo));
}
distribucion(d: Dominio, p: PedidoDescriptivo, por: string) {
return this.http.get<unknown>(this.url(d, '/distribucion'), { params: paramsDe(p, { por }) }).pipe(map(distribucionDescriptiva));
}
comparacion(d: Dominio, p: PedidoDescriptivo, por: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/comparacion'), { params: paramsDe(p, { por, medida }) }).pipe(map(comparacionDescriptiva));
}
mapa(d: Dominio, p: PedidoDescriptivo, filas: string, columnas: string, medida: string) {
return this.http.get<unknown>(this.url(d, '/mapa'), { params: paramsDe(p, { filas, columnas, medida }) }).pipe(map(mapaDescriptivo));
}
/** The trend takes only the cut-off, the period type and the number of periods: never the window, filters or context. */
tendencia(d: Dominio, corte: string, tipo: string, periodos: number) {
const params = new HttpParams().set('corte', corte).set('tipo', tipo).set('periodos', periodos);
return this.http.get<unknown>(this.url(d, '/tendencia'), { params }).pipe(map(tendenciaDescriptiva));
}
}
@@ -1,12 +1,12 @@
import { Component, output } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { IndicadoresAnalisis, MOTIVO_GRUPO_SUPRIMIDO, SeleccionPacientes, hoyIso, motivoSinLista, seleccionDeGrupo } from './indicadores-analisis';
import { etiquetaBirads, grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { analisisAgregado } from './indicadores-analisis.service';
import { agregado, agregadoJson, CONTEXTO, CORTE } from './indicadores-analisis.testing';
import { agregado, agregadoJson, CONTEXTO, CORTE, sinAnalisisDescriptivo } from './indicadores-analisis.testing';
// Covers the «Análisis epidemiológico» tab of breast cancer as the cohort API publishes it today: the guard of its answer
// (an aggregate, never patient rows, nothing published under the threshold), the figure, the selection a published group
@@ -80,7 +80,7 @@ class ChartStub { readonly plotClick = output<unknown>(); }
describe('Pestaña Análisis epidemiológico', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresAnalisis>>, http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
TestBed.configureTestingModule({ providers: [provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting()] });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresAnalisis); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cama'); fixture.componentRef.setInput('tema', 'claro');
@@ -1,5 +1,7 @@
// Fixtures of the analysis tab and of its journey to Seguimiento, shaped like the answers of the cohort API
// (`GET /cama/analisis/indicadores?corte=` and the list `GET /cama/seguimiento` of a cohort).
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { throwError } from 'rxjs';
import { AnalisisAgregado } from './indicadores-analisis.service';
export const REVISION = 'dae23030398f86a24e8ad910471d27ce02502ac6b174063c98e5163dea0ce7a7';
@@ -45,3 +47,12 @@ export function listaCohorte(o: { corte?: string; filtros?: Record<string, strin
/** What the API sends on the wire: the aggregate plus the fields of the prototype it leaves empty. */
export const agregadoJson = (extra: Record<string, unknown> = {}) => ({ ...agregado(), horizonte_dias: 0, indicadores: [], ...extra });
/**
* For specs of the analysis tab that are about its BI-RADS aggregate and its way to Seguimiento: the descriptive sections
* below it (catalog, indicators, distribution, comparison, map, trend) answer «not published» and never reach the test
* backend, so those specs keep counting only the requests they are about.
*/
export const sinAnalisisDescriptivo: HttpInterceptorFn = (req, next) =>
/^\/[a-z]+\/analisis(\/(resumen|distribucion|comparacion|mapa|tendencia))?$/.test(req.url)
? throwError(() => new HttpErrorResponse({ status: 404, url: req.url })) : next(req);
@@ -7,6 +7,7 @@ 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 { IndicadoresAnalisisDescriptivo } from './indicadores-analisis-descriptivo';
import { isoDate } from './cacu-seguimiento.models';
import { grupoDelClic, gruposFigura } from './indicadores-analisis-figuras';
import { etiquetaBirads } from './etiquetas-cohorte';
@@ -20,7 +21,7 @@ type Carga<T> = { estado: 'cargando' } | { estado: 'listo'; datos: T } | { estad
* name the selection, the cut-off and the cohort the group was counted in (the list quotes it back), and how many
* patients the analysis counts there.
*/
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; esperados: number | null; contexto: ContextoCohorte; }
export interface SeleccionPacientes { filtros: Record<string, string>; etiqueta: string; corte: string; meses?: number; esperados: number | null; contexto: ContextoCohorte; }
export const MOTIVO_GRUPO_SUPRIMIDO = 'El grupo tiene muy pocos pacientes: su lista no se publica.';
@@ -54,7 +55,7 @@ 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, IndicadorKpiCard],
imports: [FormsModule, MatButtonModule, MatProgressBarModule, PlotlyChart, IndicadorKpiCard, IndicadoresAnalisisDescriptivo],
template: `
<section class="analisis" aria-labelledby="analisis-titulo">
<h2 id="analisis-titulo">Análisis epidemiológico</h2>
@@ -112,6 +113,7 @@ function contenedorDeScroll(el: HTMLElement): HTMLElement {
}
</article>
</section>
<app-indicadores-analisis-descriptivo [dominio]="dominio()" [tema]="tema()" [corte]="corteConsultado()" [active]="active()" (verPacientes)="abrirDescriptivo($event)" />
`,
styles: `
:host { display: block; min-width: 0; }
@@ -166,6 +168,8 @@ export class IndicadoresAnalisis {
private ultimo?: string;
private retorno?: { origen: HTMLElement | null; area: HTMLElement; arriba: number };
corte = this.hoy;
// The cut-off of the last query: the descriptive sections follow it.
readonly corteConsultado = signal(this.hoy);
readonly carga = signal<Carga<AnalisisAgregado>>({ estado: 'cargando' });
// Why the last click on a bar opened nothing.
readonly aviso = signal('');
@@ -206,6 +210,7 @@ export class IndicadoresAnalisis {
consultar() {
if (!isoDate(this.corte)) { this.carga.set({ estado: 'error', mensaje: 'Revisa la fecha de corte.' }); return; }
this.ultimo = this.corte;
this.corteConsultado.set(this.corte);
this.pedidos.next(this.corte);
}
reintentar() { this.pedidos.next(this.ultimo ?? this.corte); }
@@ -229,6 +234,12 @@ export class IndicadoresAnalisis {
this.retorno = { origen: el, area, arriba: area.scrollTop };
this.verPacientes.emit(seleccion);
}
// The patients of a figure of the descriptive sections: the same way back as a bar of the BI-RADS table.
abrirDescriptivo(evento: { seleccion: SeleccionPacientes; origen: HTMLElement | null }) {
const area = contenedorDeScroll(this.host.nativeElement);
this.retorno = { origen: evento.origen, area, arriba: area.scrollTop };
this.verPacientes.emit(evento.seleccion);
}
/** Back from Seguimiento: the scroll where it was and the focus on the control that opened the list. */
restaurar() {
const r = this.retorno;
@@ -18,7 +18,7 @@ export function c1AlterationCapability(contract: string, representation: string)
const count = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The any-alteration bar keeps the red of the event; each alteration takes its own colour.
// The any-alteration bar uses the second series colour; each alteration takes its own colour.
const COLORS = [C2_PALETTE.series[1], ...C2_PALETTE.edades, C2_PALETTE.series[2], C2_PALETTE.series[3], C2_PALETTE.series[0]];
const color = (i: number) => COLORS[i % COLORS.length];
@@ -21,7 +21,7 @@ const EVENT_LABELS: Readonly<Record<string, readonly [string, string]>> = {
M22_diagnosticados_sin_eeg: ['Sin EEG', 'Con EEG'],
M24_confirmacion_diagnostico: ['Diagnóstico confirmado', 'En proceso'],
};
// Green for the event, red for its complement; age groups get lighter shades.
// Olive for the event, the next series colour for its complement; age groups keep their own colours.
const RING_COLORS = [C2_PALETTE.series[0], C2_PALETTE.series[1]] as const;
// One colour per age group, the same in the donut (M21) and the bars (M22).
const ageColor = (i: number) => C2_PALETTE.edades[i % C2_PALETTE.edades.length];
@@ -1,5 +1,5 @@
import { c2Capability, c2Descendants, c2Figure } from './indicadores-c2-adapter';
import { c2Color, C2_PALETTE } from './indicadores-c2-palette';
import { c2Color, C2_PALETTE, seriesColors } from './indicadores-c2-palette';
import { c2Fixture } from './indicadores-c2-adapter.testing';
import { FigureSelection } from './indicadores.models';
import { donutFixture } from './indicadores-donut-drilldown.testing';
@@ -43,7 +43,7 @@ describe('C2: datos publicados a Plotly', () => {
const final = figurePresentation(result.figure, selection).figure, before = structuredClone(final);
const legend = donutLegend(final), view = donutSimpleView(final);
expect(legend).toEqual([
{ label: 'A', color: '#A8C243' }, { label: 'B', color: '#B8433A' }, { label: 'C', color: '#7184A2' },
{ label: 'A', color: C2_PALETTE.series[0] }, { label: 'B', color: C2_PALETTE.series[1] }, { label: 'C', color: C2_PALETTE.series[2] },
]);
expect(view.layout).toMatchObject({ showlegend: false, height: 440, margin: { l: 16, r: 16, t: 16, b: 16, pad: 0 } });
expect(view.data[0]['domain']).toEqual({ x: [0, 1], y: [0, 1] });
@@ -158,15 +158,20 @@ describe('C2: datos publicados a Plotly', () => {
});
describe('paleta C2 institucional y semántica', () => {
it.each(['claro','oscuro'] as const)('conserva colores publicados en %s y separa interfaz, series y estados', tema => {
it.each(['claro','oscuro'] as const)('sustituye tonos ajenos al logo en %s y separa interfaz, series y estados', tema => {
const data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
const figure = supported(data, { ...selection, tema }).figure;
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual(['#D98E4A', '#B8433A', '#7184A2']);
expect((figure.data[0]['marker'] as Record<string, unknown>)['colors']).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual([C2_PALETTE.series[0], C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(figure.layout['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
expect(c2Color(undefined, 0)).toBe('#A8C243'); expect(c2Color(undefined, 1)).toBe('#B8433A');
expect(c2Color(undefined, 2)).toBe('#7184A2'); expect(c2Color(undefined, 3)).toBe('#D0B778');
expect(c2Color(undefined, 0)).toBe(C2_PALETTE.series[0]); expect(c2Color(undefined, 1)).toBe(C2_PALETTE.series[1]);
expect(c2Color(undefined, 2)).toBe(C2_PALETTE.series[2]); expect(c2Color(undefined, 3)).toBe(C2_PALETTE.series[3]);
expect(c2Color('#D98E4A', 0)).toBe(C2_PALETTE.series[0]);
expect(c2Color('#B55A1F', 2)).toBe(C2_PALETTE.series[2]);
expect(c2Color('#9DBFE3', 1)).toBe('#9DBFE3');
expect(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
});
it('mantiene contraste de texto legible y separadores suaves en ambos temas', () => {
@@ -1,6 +1,6 @@
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
import { DonutHierarchy } from './indicadores-donut-drilldown';
import { c2Color, c2Theme } from './indicadores-c2-palette';
import { basesPorGrupo, C2_PALETTE, c2Theme, seriesColors } from './indicadores-c2-palette';
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
// Normalized presentation nodes and a selection path are independent of Plotly.
@@ -81,7 +81,8 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
const nodes: C2Node[] = [...parents, ...categories.map(c => ({ id: 'category:' + c.id, label: c.label, parentId: c.parentId ? 'group:' + c.parentId : undefined }))];
const model: C2Distribution = { period, unit: data['unidad'], title: data['titulo'], categories, parents, nodes, total, notes: [...data.notas] };
const theme = c2Theme(selection.tema), values = categories.map(c => c.value), labels = categories.map(c => c.label);
const colors = categories.map((c, i) => c2Color(c.color, i));
const colors = seriesColors(categories.map(c => c.color), categories.map(c => c.parentId ?? c.id));
const bases = basesPorGrupo(parentIds);
const emptyMessage = !rows.length ? 'No hay filas publicadas para este periodo.' : total === 0 ? 'Los conteos publicados son cero; no hay una composición porcentual que representar.' : undefined;
const layout: Record<string, unknown> = { title: { text: model.title + ', ' + period }, autosize: true,
paper_bgcolor: theme.background, plot_bgcolor: theme.background, font: { color: theme.text, family: 'Roboto, sans-serif', size: 14 },
@@ -109,7 +110,7 @@ export function c2Figure(data: IndicadorDatos, selection: FigureSelection): C2Re
hovertemplate: '%{label}<br>%{value} ' + model.unit + '<br>%{percent} de los ' + total + ' ' + model.unit + ' publicados<extra></extra>' }];
if (parents.length) figure.data.push({ type: 'pie', labels: parents.map(p => p.label),
values: parentIds.map(p => categories.filter(c => c.parentId === p).reduce((sum, c) => sum + c.value, 0)),
marker: { colors: parents.map((_, i) => c2Color(undefined, i)), line: { color: theme.outline, width: 0.7 } },
marker: { colors: parents.map(p => bases.get(p.id.replace(/^group:/, '')) ?? C2_PALETTE.series[0]), line: { color: theme.outline, width: 0.7 } },
hole: 0.55, sort: false, name: period + ', grupos', textinfo: 'none', domain: { x: [0.14, 0.58], y: [0.29, 0.71] } });
}
const hierarchy = selection.figura === 'fig_c2_donas' && parents.length && total > 0
@@ -19,7 +19,9 @@ describe('selección local segura de barras generales C2', () => {
it('grupo conserva hijos, etiquetas, orden, colores y unidad sin cambiar el denominador', () => {
const data = c2Fixture(), source = bars(data), before = structuredClone({ data, source });
const view = c2GeneralSelection(source, data, selection, local)!;
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'], marker: { color: ['#B8433A', '#7184A2'] } });
const marker = source.data[0]['marker'] as { color: string[] }, labels = source.data[0]['y'] as string[];
expect(view.figure.data[0]).toMatchObject({ x: [3, 1], y: ['B', 'C'],
marker: { color: ['B', 'C'].map(label => marker.color[labels.indexOf(label)]) } });
expect(view.figure.layout['yaxis']).toMatchObject({ categoryarray: ['C', 'B'] });
expect(view.figure.layout['meta']).toMatchObject({ denominator: 10, period: local.period, unit: 'paciente' });
expect(view.context).toContain('G2, 2025-S2');
@@ -0,0 +1,51 @@
import { C2_PALETTE, groupBase, institutionalize, isHarmoniousColor, paintByGroup, recolorFigure } from './indicadores-c2-palette';
describe('paleta del logo ISSSTELEON', () => {
it('combina varios matices del logo y del verde azulado, sin repetir el mismo color', () => {
expect(new Set(C2_PALETTE.series).size).toBe(C2_PALETTE.series.length);
for (const color of C2_PALETTE.series) expect(isHarmoniousColor(color)).toBe(true);
expect(institutionalize(['#a8c243'])).toEqual(['#a8c243']);
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
});
it('cambia el café y el anaranjado por la serie, y deja azul, rojo, gris y edad', () => {
const [cafe, otroCafe, rojo, azul, sinDato, edad] = institutionalize([
'#B55A1F', '#D9822B', '#C41E3A', '#0044CC', '#C9CDD2', '#2F6DB3',
]);
expect([cafe, otroCafe]).toEqual(C2_PALETTE.series.slice(0, 2));
expect(rojo).toBe('#C41E3A');
expect(azul).toBe('#0044CC');
expect(sinDato).toBe('#C9CDD2');
expect(edad).toBe('#2F6DB3');
});
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
expect(new Set(colors.slice(0, 3)).size).toBe(3);
expect(colors[3]).toBe(C2_PALETTE.calidos[0]);
expect(colors[0]).not.toBe(C2_PALETTE.calidos[0]);
expect(colors[0]).not.toBe(colors[3]);
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
});
it('pinta la tinta categórica, deja una escala continua y no toca texto ni fondo', () => {
const figure = recolorFigure({
data: [{
type: 'scatter', marker: { color: '#B55A1F' }, error_x: { color: 'rgba(0,68,204,0.4)' }, line: { color: '#C9CDD2' },
colorscale: [[0, '#0d0887'], [0.5, '#ed7953'], [1, '#f0f921']],
}],
layout: { font: { color: '#081839' }, paper_bgcolor: '#FFFFFF', colorway: ['#EF553B', '#636efa'] },
});
expect((figure.data[0]['marker'] as { color: string }).color).toBe(C2_PALETTE.series[0]);
expect((figure.data[0]['error_x'] as { color: string }).color).toBe('rgba(0,68,204,0.4)');
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
const scale = figure.data[0]['colorscale'] as [number, string][];
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
expect(scale[0][1]).not.toBe('#0d0887');
expect(scale[0][1]).not.toBe(scale[1][1]);
expect(figure.layout['font']).toEqual({ color: '#081839' });
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
expect(figure.layout['colorway']).toEqual([C2_PALETTE.series[1], '#636efa']);
expect(recolorFigure(figure)).toBe(figure);
});
});
@@ -1,11 +1,19 @@
import { Tema } from './indicadores.models';
import { PlotlyFigure, Tema } from './indicadores.models';
// Matches src/styles.scss: interface tokens are the source of these candidates,
// not a certified brand guide. Published semantic colours always take priority.
// Logo lime plus the analogous and complementary hues chosen for the charts.
// Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side.
// Neutrals stay neutral. Sequential fills run from pale lime to deep teal.
const OWNED = new Set<string>();
function own(hex: string): string { OWNED.add(hex.toLowerCase()); return hex; }
export const C2_PALETTE = Object.freeze({
// ISSSTELEON green and a brick red dark enough to stay apart from it with red-green colour blindness.
series: Object.freeze(['#A8C243', '#B8433A', '#7184A2', '#D0B778']),
// Age groups of the EEG indicators (M21, M22), which avoid the green and red of the rest.
frios: Object.freeze([own('#A8C243'), own('#69C242'), own('#42C25C'), own('#42C29C'), own('#4269C2')]),
calidos: Object.freeze([own('#C24269'), own('#9C42C2'), own('#5C42C2'), own('#C2429C'), own('#8E2F62'), own('#7A3496')]),
series: Object.freeze([
'#A8C243', '#42C29C', '#C24269', '#9C42C2',
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
]),
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
edades: Object.freeze(['#2F6DB3', '#E0A526', '#A23E8C']),
states: Object.freeze({ null: '#8A9199', noData: '#C9CDD2', suppressed: '#4B4949' }),
// line: the green for thin marks; the brand green itself is too light to read as a line on white.
@@ -13,6 +21,253 @@ export const C2_PALETTE = Object.freeze({
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 {
return published ?? C2_PALETTE.series[index % C2_PALETTE.series.length];
const ageKeys = new Set(C2_PALETTE.edades.map(color => parseColor(color)?.key).filter((key): key is string => !!key));
export function isAgeColor(color: string): boolean {
const key = parseColor(color)?.key;
return !!key && ageKeys.has(key);
}
/** Orange, tan and coffee. Age gold and the palette's own stone are not included. */
function isCoffeeParsed(item: Parsed | undefined): boolean {
if (!item || item.kind === 'neutral' || ageKeys.has(item.key)) return false;
return item.hue >= 8 && item.hue <= 46 && item.sat >= 0.28;
}
export function isCoffeeColor(color: string): boolean {
return isCoffeeParsed(parseColor(color));
}
export type Tono = 'frio' | 'calido' | 'neutro';
/** Metadata id: cool for normal groups, warm for abnormal ones. Unknown ids stay neutral. */
export function tonoDe(clave: string | undefined | null): Tono {
if (!clave) return 'neutro';
const id = clave.normalize('NFD').replace(/\p{M}/gu, '').toUpperCase().replace(/[^A-Z0-9]+/g, '_');
if (id.includes('SIN_DATO') || id.includes('SIN_BIOPSIA')) return 'neutro';
if (id.includes('NO_METAST') || id.includes('SIN_METAST') || id.includes('NO_ANORMAL') || id.includes('NO_MALIG') || id.includes('BENIGN') || id.includes('NO_ALTER')) return 'frio';
if (id.includes('METAST') || id.includes('CARCINOMA') || id.includes('ANORMAL') || id.includes('MALIG') || id.includes('INVAS') || id.includes('IN_SITU') || id.includes('LIEAG') || id.includes('ALTER')) return 'calido';
if (/^(B4|B4A|B4B|B4C|B5|B6)$/.test(id) || /^BIRADS_[456]/.test(id)) return 'calido';
return 'neutro';
}
function poolDe(tono: Tono): readonly string[] {
if (tono === 'calido') return C2_PALETTE.calidos;
if (tono === 'frio') return C2_PALETTE.frios;
return C2_PALETTE.series;
}
export function c2Color(published: string | undefined, index: number, tono: Tono = 'neutro'): string {
// Coffee takes the cool or warm pool when the category metadata says which. Other published colours stay.
if (published && isAgeColor(published)) return published;
if (published && isNeutralColor(published)) return published;
const pool = poolDe(tono);
if (published && isCoffeeColor(published)) return pool[index % pool.length];
if (published && /^#[0-9a-f]{6}$/i.test(published)) return published;
return pool[index % pool.length];
}
/** One base per group: cool if the id is normal, warm if it is abnormal, then steps so siblings differ. */
export function basesPorGrupo(groups: readonly string[]): ReadonlyMap<string, string> {
const seen = { frio: 0, calido: 0, neutro: 0 };
const base = new Map<string, string>();
for (const id of [...new Set(groups)]) {
const tono = tonoDe(id);
const pool = poolDe(tono);
base.set(id, pool[seen[tono] % pool.length]);
seen[tono] += 1;
}
return base;
}
export function paintByGroup(groups: readonly string[]): string[] {
const bases = basesPorGrupo(groups);
const counts = new Map([...bases.keys()].map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map([...bases].map(([id, color]) => [id, steps(color, counts.get(id)!)]));
const cursor = new Map<string, number>();
return groups.map(id => {
const index = cursor.get(id) ?? 0;
cursor.set(id, index + 1);
return stairs.get(id)![index];
});
}
export function groupBase(index: number): string {
return C2_PALETTE.series[index % C2_PALETTE.series.length];
}
/** Replace inharmonious hues. Same source colour keeps the same slot; grays and palette hues stay. */
export function institutionalize(colors: readonly string[]): string[] {
const parsed = colors.map(parseColor);
const foreign: string[] = [];
const seen = new Set<string>();
for (const item of parsed) {
if (!item || !isCoffeeParsed(item) || seen.has(item.key)) continue;
seen.add(item.key);
foreign.push(item.key);
}
const assigned = new Map(foreign.map((key, i) => [key, C2_PALETTE.series[i % C2_PALETTE.series.length]]));
return colors.map((color, i) => {
const item = parsed[i];
const next = item && assigned.get(item.key);
return item && next ? formatAs(item, next) : color;
});
}
/** Coffee published colours take the cool or warm pool of their metadata id. */
export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] {
const seen = { frio: 0, calido: 0, neutro: 0 };
return published.map((color, index) => {
const tono = tonoDe(claves?.[index]);
const slot = tono === 'neutro' ? index : seen[tono]++;
return c2Color(color, slot, tono);
});
}
const NAMED: Record<string, [number, number, number]> = {
black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
red: [255, 0, 0], blue: [0, 0, 255], green: [0, 128, 0], orange: [255, 165, 0], yellow: [255, 255, 0],
purple: [128, 0, 128], brown: [165, 42, 42], pink: [255, 192, 203], cyan: [0, 255, 255], magenta: [255, 0, 255],
gold: [255, 215, 0], navy: [0, 0, 128], teal: [0, 128, 128], maroon: [128, 0, 0], lime: [0, 255, 0], olive: [128, 128, 0],
};
interface Parsed { r: number; g: number; b: number; a: number; key: string; hue: number; sat: number; lum: number; kind: 'neutral' | 'harmonious' | 'foreign'; explicitAlpha: boolean; }
function parseColor(input: string): Parsed | undefined {
const text = input.trim();
let r = 0, g = 0, b = 0, a = 1, explicitAlpha = false;
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text);
const rgb = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
if (hex) {
const raw = hex[1].length === 3 ? hex[1].split('').map(c => c + c).join('') : hex[1];
r = parseInt(raw.slice(0, 2), 16); g = parseInt(raw.slice(2, 4), 16); b = parseInt(raw.slice(4, 6), 16);
} else if (rgb) {
r = Number(rgb[1]); g = Number(rgb[2]); b = Number(rgb[3]);
if (rgb[4] !== undefined) { a = Number(rgb[4]); explicitAlpha = true; }
if ([r, g, b].some(v => v > 255) || !Number.isFinite(a)) return undefined;
} else if (NAMED[text.toLowerCase()]) {
[r, g, b] = NAMED[text.toLowerCase()];
} else return undefined;
const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min;
const sat = max === 0 ? 0 : d / max;
let hue = 0;
if (d !== 0) {
if (max === r) hue = ((g - b) / d) % 6;
else if (max === g) hue = (b - r) / d + 2;
else hue = (r - g) / d + 4;
hue *= 60; if (hue < 0) hue += 360;
}
const lum = luminance({ r, g, b });
const neutral = sat < 0.18;
const swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
const harmonious = OWNED.has(swatch) || (!neutral && (
(hue >= 64 && hue <= 175 && sat >= 0.22)
|| (hue >= 200 && hue <= 320 && sat >= 0.22)
|| (hue >= 320 && hue < 356 && sat >= 0.28 && sat <= 0.78)
|| (hue > 188 && hue <= 230 && sat <= 0.5)
|| (hue >= 40 && hue < 64 && sat <= 0.42)));
return { r, g, b, a, key: `${r},${g},${b}`, hue, sat, lum, explicitAlpha, kind: neutral ? 'neutral' : harmonious ? 'harmonious' : 'foreign' };
}
function steps(base: string, count: number): string[] {
if (count <= 1) return [base];
return Array.from({ length: count }, (_, i) => {
const t = i / (count - 1);
if (t < 0.5) return mixHex(base, [0, 0, 0], (0.5 - t) * 0.5);
return mixHex(base, [255, 255, 255], (t - 0.5) * 0.22);
});
}
function mixHex(base: string, toward: [number, number, number], amount: number): string {
const item = parseColor(base)!;
const channel = (from: number, to: number) => Math.round(from + (to - from) * amount);
return '#' + [channel(item.r, toward[0]), channel(item.g, toward[1]), channel(item.b, toward[2])]
.map(v => v.toString(16).padStart(2, '0')).join('');
}
function sampleScale(t: number): string {
const stops = C2_PALETTE.scale;
const scaled = Math.min(1, Math.max(0, t)) * (stops.length - 1);
const index = Math.min(stops.length - 2, Math.floor(scaled));
const item = parseColor(stops[index])!, next = parseColor(stops[index + 1])!;
return mixHex(stops[index], [next.r, next.g, next.b], scaled - index);
}
function luminance(input: { r: number; g: number; b: number } | Parsed): number {
const c = [input.r, input.g, input.b].map(v => v / 255).map(v => v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
return c[0] * 0.2126 + c[1] * 0.7152 + c[2] * 0.0722;
}
function formatAs(original: Parsed, hex: string): string {
if (!original.explicitAlpha) return hex;
const item = parseColor(hex)!;
const alpha = Number(original.a.toFixed(3));
return `rgba(${item.r},${item.g},${item.b},${alpha})`;
}
export function isNeutralColor(color: string): boolean { return parseColor(color)?.kind === 'neutral'; }
export function isHarmoniousColor(color: string): boolean { return parseColor(color)?.kind === 'harmonious'; }
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function collectStrings(value: unknown, into: string[]) {
if (typeof value === 'string') into.push(value);
else if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') into.push(value[1]);
else value.forEach(item => collectStrings(item, into));
}
}
function mapColors(value: unknown, lookup: Map<string, string>): unknown {
if (typeof value === 'string') return lookup.get(value) ?? value;
if (Array.isArray(value)) {
if (value.length === 2 && typeof value[0] === 'number' && typeof value[1] === 'string') return [value[0], lookup.get(value[1]) ?? value[1]];
return value.map(item => mapColors(item, lookup));
}
return value;
}
function paintTrace(trace: Record<string, unknown>, lookup: Map<string, string>) {
if (record(trace['marker'])) {
const marker = { ...trace['marker'] };
if ('color' in marker) marker['color'] = mapColors(marker['color'], lookup);
if ('colors' in marker) marker['colors'] = mapColors(marker['colors'], lookup);
if (record(marker['line']) && 'color' in marker['line']) marker['line'] = { ...marker['line'], color: mapColors(marker['line']['color'], lookup) };
trace['marker'] = marker;
}
if (record(trace['line']) && 'color' in trace['line']) trace['line'] = { ...trace['line'], color: mapColors(trace['line']['color'], lookup) };
if (typeof trace['fillcolor'] === 'string') trace['fillcolor'] = lookup.get(trace['fillcolor']) ?? trace['fillcolor'];
for (const key of ['error_x', 'error_y']) {
if (record(trace[key]) && 'color' in (trace[key] as Record<string, unknown>)) {
trace[key] = { ...(trace[key] as Record<string, unknown>), color: mapColors((trace[key] as Record<string, unknown>)['color'], lookup) };
}
}
if (Array.isArray(trace['colorscale'])) trace['colorscale'] = sequentialScale(trace['colorscale']);
}
function sequentialScale(stops: unknown[]): unknown[] {
return stops.map(stop => {
if (!Array.isArray(stop) || typeof stop[0] !== 'number' || typeof stop[1] !== 'string') return stop;
return [stop[0], sampleScale(stop[0])];
});
}
function scalePending(figure: PlotlyFigure): boolean {
return traceList(figure).some(trace => Array.isArray(trace['colorscale'])
&& JSON.stringify(sequentialScale(trace['colorscale'] as unknown[])) !== JSON.stringify(trace['colorscale']));
}
function traceList(host: { data?: unknown; frames?: unknown }): Record<string, unknown>[] {
const traces = Array.isArray(host.data) ? host.data.filter(record) : [];
if (Array.isArray(host.frames)) {
for (const frame of host.frames) {
if (record(frame) && Array.isArray(frame['data'])) traces.push(...frame['data'].filter(record));
}
}
return traces;
}
function gather(figure: PlotlyFigure): string[] {
const found: string[] = [];
for (const trace of traceList(figure)) {
const marker = record(trace['marker']) ? trace['marker'] : undefined;
collectStrings(marker?.['color'], found); collectStrings(marker?.['colors'], found);
collectStrings(record(marker?.['line']) ? marker['line']['color'] : undefined, found);
collectStrings(record(trace['line']) ? trace['line']['color'] : undefined, found);
collectStrings(trace['fillcolor'], found);
collectStrings(record(trace['error_x']) ? trace['error_x']['color'] : undefined, found);
collectStrings(record(trace['error_y']) ? trace['error_y']['color'] : undefined, found);
}
if (Array.isArray(figure.layout['colorway'])) collectStrings(figure.layout['colorway'], found);
return found;
}
/** Data ink of a published figure, without touching text, grid or background. */
export function recolorFigure<T extends PlotlyFigure>(figure: T): T {
const collected = gather(figure);
const painted = institutionalize(collected);
if (painted.every((color, i) => color === collected[i]) && !scalePending(figure)) return figure;
const lookup = new Map(collected.map((color, i) => [color, painted[i]]));
const copy = structuredClone(figure);
for (const trace of traceList(copy)) paintTrace(trace, lookup);
if (Array.isArray(copy.layout['colorway'])) copy.layout['colorway'] = mapColors(copy.layout['colorway'], lookup);
return copy;
}
@@ -10,6 +10,7 @@ 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 { C2_PALETTE } from './indicadores-c2-palette';
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';
@@ -31,7 +32,7 @@ describe('CAM-01 y CAM-02: tarjetas con las respuestas reales de WebApi', () =>
it('CAM-01 con el umbral de prueba: un 0 de 1 es un cero válido, con su detalle', () => {
// Fails if a published 0/1 becomes "sin valor" or loses its numerator and denominator.
expect(kpiResult(dato(tasaVisible), CAMA_TASA_DETECCION_KPI, 'cama', applied))
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con resultado maligno.' });
.toEqual({ state: 'Disponible', value: '0.0', info: '0 de 1 biopsias con riesgo a carcinoma.' });
});
it('CAM-01 con el umbral normal: el dato está suprimido y no muestra cifra', () => {
const r = kpiResult(dato(tasaSuprimida), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -86,7 +87,7 @@ describe('CAM-01, CAM-02 y CAM-03: histórico con las respuestas reales', () =>
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.data.map(t => (t['marker'] as { color: string }).color)).toEqual(['#9DBFE3', '#2F6DB3', C2_PALETTE.calidos[0], C2_PALETTE.calidos[1], '#C9CDD2', '#C9CDD2']);
expect(f.figure.layout['barmode']).toBe('stack');
expect(f.comoLeer).toContain('pacientes');
});
@@ -112,9 +113,10 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
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<string, unknown> = 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 respuestas: Record<string, unknown> = {
cama_dias_resultado_diagnostico: visibles ? diasVisible : 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) {
@@ -131,28 +133,29 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
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', () => {
it('omite el panel y las consultas de detección aunque la medida figure en el catálogo', () => {
const pedidos = montar(true);
expect(REALES.map(i => i.id)).toContain('cama_tasa_deteccion_histopatologica');
expect(pedidos.some(p => p.includes('cama_tasa_deteccion_histopatologica'))).toBe(false);
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)));
'/cama/indicadores/cama_dias_resultado_diagnostico/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]);
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
expect(titulos.filter(([, estado]) => estado === 'dibujado'))
.toEqual([['Resultado histopatológico', 'dibujado'], ['Días del resultado de la mastografía al diagnóstico', 'dibujado']]);
expect(graficas().map(g => g.figure!.data.length)).toEqual([6, 2]);
});
it('con el umbral normal los dos paneles C1 y C3r avisan el periodo suprimido, y la matriz CAM-03 sigue visible', () => {
it('el panel C3r avisa 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);
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(1);
expect(graficas()).toHaveLength(2);
});
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
montar(false);
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
expect(notas).toHaveLength(2);
expect(notas).toHaveLength(1);
for (const nota of notas) {
expect(nota.open).toBe(false);
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
@@ -160,7 +163,6 @@ describe('CAM-01, CAM-02 y CAM-03 en el panel histórico', () => {
}
notas[0].open = true;
expect(notas[0].open).toBe(true);
expect(notas[1].open).toBe(false);
});
});
@@ -201,12 +203,17 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
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);
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
// Fails if the unavailable slot displays a value or displaces the published measures.
const pedidos = cargar(completo());
expect(kpis()).toHaveLength(5);
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con riesgo a carcinoma.');
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
expect(kpis()[4].querySelector('.kpi-state')?.textContent).toBe('Indicador no disponible');
expect(kpis()[4].querySelector('.value')).toBeNull();
});
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());
@@ -231,6 +238,6 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
});
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');
expect(kpis()).toHaveLength(5); expect(root().querySelector('app-indicador-histopatologia-pendiente')!.textContent).toContain('Integración pendiente');
});
});
@@ -0,0 +1,340 @@
// What this module covers: CaMa's eight FHIR measures as the page reads them: their ids, catalog entries, category
// metadata, the rows of each contract (C1, C2, C3r) and what the summary's cards and figures make of them, for periods
// with data and for periods that legitimately have none.
// Fixtures (`fixtures/cama_fhir_*.json`): `reportes` are real `GET /cama/fhir/MeasureReport` answers of the local
// installation, cut to three semesters (2021-S1 without units, 2024-S2 and 2025-S2 with them) and two months;
// `measures` is the Measure bundle the WebApi serves from the current dbt definitions; `measures_instalada` is the one
// the installation served before the category metadata existed.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { firstValueFrom } from 'rxjs';
import { Bundle, resources } from './fhir';
import { cajaDeDatos, categorias, datosDeReportes, FhirIndicadoresService, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { modelosConteos, parConteos, totalExamenes } from './indicadores-conteos-pareados';
import { CAMA_CONFIRMACION_KPI, CAMA_TAMIZAJE_RESULTADO_KPI, CAMA_TOMA_DIAGNOSTICO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import measuresData from './fixtures/cama_fhir_measures.json';
import installedData from './fixtures/cama_fhir_measures_instalada.json';
import reportsData from './fixtures/cama_fhir_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const installed = resources(installedData as unknown as Bundle, 'Measure') as Measure[];
const answers = reportsData.reports as unknown as Record<string, { semestre: Bundle; mes?: Bundle }>;
const measure = (fhirId: string, from = measures) => from.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start: string) =>
(resources(answers[fhirId][tipo]!, 'MeasureReport') as Report[]).filter(r => r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', from = measures): IndicadorDatos {
return datosValidos(datosDeReportes(measure(fhirId, from), reportsOf(fhirId, tipo, start), tipo), indicadorId(fhirId), tipo, [periodo]);
}
const SEMESTRE_VACIO = ['2021-01-01', '2021-S1'] as const;
const SEMESTRE_CON_DATOS = ['2025-07-01', '2025-S2'] as const;
describe('Identificadores de CaMa entre FHIR y la página', () => {
it('cada Measure publicada tiene un id de la página y ninguno se repite', () => {
// Pins down: the explicit table covers the eight measures the WebApi publishes and the page ids stay unique
// (`BIRADS456` is `birads_456`, which no rule derives). Fails if a measure is published without a
// correspondence, or two measures collapse into one page id.
const ids = measures.map(m => indicadorId(m.id!));
expect(ids.sort()).toEqual(['cama_biopsias', 'cama_birads', 'cama_birads_456_mastografia', 'cama_birads_456_paciente',
'cama_birads_cancer_invasor', 'cama_confirmacion_birads45', 'cama_dias_resultado_diagnostico', 'cama_dias_toma_diagnostico',
'cama_eu38a', 'cama_histopatologia_birads', 'cama_tasa_deteccion_histopatologica']);
expect(new Set(ids).size).toBe(measures.length);
expect(measures.every(m => Object.hasOwn(CAMA_MEASURE_IDS, m.id!))).toBe(true);
});
it('el id de una medida de otro dominio sigue la regla general', () => {
// Pins down: only CaMa's measures use the table; TEA's and CaCu's keep `-` to `_`. Fails if the table captures
// ids of other domains or the generic rule changes.
expect(indicadorId('M21-diagnosticados-con-eeg')).toBe('M21_diagnosticados_con_eeg');
expect(indicadorId('CACU-EU7')).toBe('CACU_EU7');
});
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
// Pins down: the contract, the figures and the period types each CaMa measure publishes: a distribution offers
// the donut and the bars, a duration its box plot, a proportion none (its history is drawn from the data rows).
// Fails if the dbt definitions stop declaring them or the mapper drops them.
const catalog = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalog['cama_birads_456_paciente']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'], tipos_periodo: ['semestre', 'mes'], estratos: [] });
expect(catalog['cama_biopsias']).toMatchObject({ contrato: 'C2', figuras: ['fig_c2_donas', 'fig_c2_barras'] });
expect(catalog['cama_confirmacion_birads45']).toMatchObject({ contrato: 'C1', figuras: [], sentido: 'mayor_mejor' });
expect(catalog['cama_eu38a']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalog['cama_dias_toma_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'] });
expect(catalog['cama_birads_cancer_invasor']).toMatchObject({ contrato: 'C2', estratos: ['grupo_edad', 'estadio', 'etapa', 'clasificacion', 'tamano'] });
});
});
describe('Ficha técnica de CaMa', () => {
it('cada medida tiene su propio código y sus poblaciones con la métrica que las cuenta', () => {
// Pins down: the sheet's code is the measure's name without the domain (not `CAMA` for all eight) and each
// population names the dbt metric that counts it. Fails if the sheets of different measures read alike.
const codes = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codes).size).toBe(measures.length);
expect(metadatosDeMeasure(measure('CAMA-EU38A')).ficha!.codigo).toBe('EU38A');
expect(metadatosDeMeasure(measure('CAMA-BIRADS456-PACIENTE')).ficha!.codigo).toBe('BIRADS456-PACIENTE');
expect(metadatosDeMeasure(measure('CAMA-CONFIRMACION-BIRADS45')).poblaciones!.map(p => p.grupo)).toEqual(['poblacion', 'denominador', 'numerador']);
});
});
describe('Categorías de las composiciones de CaMa', () => {
it('BI-RADS 4 a 6 declara solo sus subcategorías y BI-RADS completo añade «Sin dato»', () => {
// Pins down: the labels and colours come from the Measure's extensions, in the order of the catalog, and the
// exams' and patients' measures declare the same categories. Fails if the dbt labels drift or one measure loses them.
expect(Object.keys(categorias(measure('CAMA-BIRADS456-PACIENTE')))).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6']);
expect(categorias(measure('CAMA-BIRADS456-MASTOGRAFIA'))).toEqual(categorias(measure('CAMA-BIRADS456-PACIENTE')));
expect(Object.keys(categorias(measure('CAMA-BIRADS')))).toEqual(['B0', 'B1', 'B2', 'B3', 'B4A', 'B4B', 'B4C', 'B5', 'B6', 'SIN_DATO']);
expect(categorias(measure('CAMA-BIRADS'))['B5']).toEqual({ etiqueta: 'BI-RADS 5', color: '#B55A1F', grupo: null });
expect(Object.keys(categorias(measure('CAMA-BIOPSIAS')))).toEqual(['BENIGNO', 'CARCINOMA_IN_SITU', 'CARCINOMA_INVASOR', 'SIN_DATO']);
});
it('un BI-RADS 4 sin subcategoría se muestra después de las categorías declaradas y no se pierde', () => {
// Pins down: the real 2025-S2 report counts patients in `B4`, which no Measure declares. The rows add it after the
// declared categories under the Core catalog's caption, and the total is still the report's units. Fails if
// undeclared categories are dropped (the card would show fewer patients than the report counts).
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4A', 'B4B', 'B4C', 'B5', 'B6', 'B4']);
expect((periodo['categorias'] as Record<string, { etiqueta: string }>)['B4'].etiqueta).toBe('BI-RADS 4 (sin subcategoría)');
const total = periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total).toBe(36);
expect(periodo.filas.map(row => [row['categoria'], row['orden']])).toEqual([['B4A', 0], ['B4B', 1], ['B4C', 2], ['B5', 3], ['B6', 4], ['B4', 5]]);
});
it('una Measure sin metadatos de categoría deja ver las categorías con su código, sin perder unidades', () => {
// Pins down: against the Measure the installation served before the labels existed (no category extensions),
// every counted category is still listed (by its code) and the figure still draws the whole partition. Fails if a
// Measure without metadata makes the distribution empty or undercounts it.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS, 'semestre', installed);
expect(Object.keys(periodo['categorias'] as object)).toEqual(['B4', 'B5', 'B6']);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(36);
});
});
describe('Composiciones (C2): BI-RADS y biopsias', () => {
it.each(['CAMA-BIRADS456-PACIENTE', 'CAMA-BIRADS456-MASTOGRAFIA', 'CAMA-BIRADS', 'CAMA-BIOPSIAS'])('%s se dibuja como dona y como barras con el total de sus unidades', fhirId => {
// Pins down: for a period with units, both published figures are supported and the total equals the report's
// `initial-population`. Fails if a category, a label or the unit total is lost between the report and the figure.
const periodo = datos(fhirId, ...SEMESTRE_CON_DATOS);
const units = reportsOf(fhirId, 'semestre', SEMESTRE_CON_DATOS[0])[0].group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const result = c2Figure(periodo, { dominio: 'cama', indicador: indicadorId(fhirId), figura, tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2025-S2'] });
if (result.status !== 'supported') throw new Error(`${fhirId} ${figura}: ${result.reason}`);
expect(result.model.total).toBe(units);
expect(result.model.total).toBeGreaterThan(0);
}
});
it('todas las composiciones de CaMa de los reportes reales suman las unidades de su periodo', () => {
// Pins down: for every C2 measure and every real period in the fixtures (semesters and months), the categories the
// mapper lists add up to the report's units, so none is dropped. Fails if a report counts a category the rows lose.
// The three measures of L3 have their own fixture (`indicadores-cama-l3.spec.ts`).
for (const m of measures.filter(item => indicadorDeMeasure(item).contrato === 'C2' && Object.hasOwn(answers, item.id!))) {
for (const tipo of ['semestre', 'mes'] as const) {
const bundle = answers[m.id!][tipo];
if (!bundle) continue;
const reports = resources(bundle, 'MeasureReport') as Report[];
const rows = datosDeReportes(m, reports, tipo).filas;
for (const report of reports) {
const units = report.group![0].population!.find(p => p.code?.coding?.[0].code === 'initial-population')!.count!;
const label = report.period!.start;
const total = rows.filter(row => row['periodo'] === (tipo === 'mes' ? label.slice(0, 7) : label.slice(0, 4) + (label.slice(5, 7) < '07' ? '-S1' : '-S2'))).reduce((sum, row) => sum + (row['n'] as number), 0);
expect(total, `${m.id} ${label}`).toBe(units);
}
}
}
});
it('un periodo sin unidades da una distribución vacía, no un error', () => {
// Pins down: a semester without mammograms (legitimate absence of data) is a supported figure with the
// «conteos en cero» message and every category at zero. Fails if an empty period turns into an unsupported figure.
const periodo = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_VACIO);
const result = c2Figure(periodo, { dominio: 'cama', indicador: 'cama_birads_456_paciente', figura: 'fig_c2_barras', tema: 'claro', tipoPeriodo: 'semestre', periodos: ['2021-S1'] });
if (result.status !== 'supported') throw new Error(result.reason);
expect(result.model.total).toBe(0);
expect(result.emptyMessage).toContain('cero');
expect(periodo.filas.every(row => row['n'] === 0)).toBe(true);
});
it('la tarjeta de pacientes BI-RADS 4, 5 y 6 suma las categorías del periodo', () => {
// Pins down: the opportunity card reads the patients' distribution: its value is the sum of the categories
// (including the undeclared B4) and the card says «Disponible». Fails if the card still sees the catalog without B4.
const result = kpiResult(datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS), KPI_BY_DOMAIN.cama[0], 'cama', apply('2025-S2'));
expect(result).toMatchObject({ state: 'Disponible', value: 36 });
expect(Object.values(result.categorias!).reduce((a, b) => a + b, 0)).toBe(36);
});
it('un mes con datos se lee igual que un semestre', () => {
// Pins down: the monthly search answers by `periodo` labels like `2025-12`, and the rows carry that label. Fails
// if the month's period is read as a semester or the categories are lost.
const periodo = datos('CAMA-BIRADS456-PACIENTE', '2025-12-01', '2025-12', 'mes');
expect(periodo.tipo_periodo).toBe('mes');
expect(periodo.periodos).toEqual(['2025-12']);
expect(periodo.filas.reduce((sum, row) => sum + (row['n'] as number), 0)).toBeGreaterThan(0);
});
it('las biopsias suman por grado histológico con los rótulos del catálogo', () => {
// Pins down: the grades arrive as `BENIGNO`, `CARCINOMA_IN_SITU` and `CARCINOMA_INVASOR` and are drawn with the
// catalog's captions. Fails if a grade loses its caption or is merged into another.
const periodo = datos('CAMA-BIOPSIAS', ...SEMESTRE_CON_DATOS);
const labels = Object.fromEntries(Object.entries(periodo['categorias'] as Record<string, { etiqueta: string }>).map(([k, v]) => [k, v.etiqueta]));
expect(labels).toEqual({ BENIGNO: 'Benigno', CARCINOMA_IN_SITU: 'Carcinoma in situ', CARCINOMA_INVASOR: 'Carcinoma invasor', SIN_DATO: 'Sin dato' });
expect(Object.fromEntries(periodo.filas.map(row => [row['categoria'], row['n']]))).toEqual({ BENIGNO: 11, CARCINOMA_IN_SITU: 1, CARCINOMA_INVASOR: 13, SIN_DATO: 0 });
});
});
describe('Proporción (C1): confirmación histopatológica', () => {
it('el grupo principal llega a la página como `total` con numerador, denominador y porcentaje', () => {
// Pins down: the WebApi's `principal` group is the page's `total`, and the score becomes a percentage next to
// its numerator and denominator. Fails if the group keeps its FHIR name (the card would find no rows).
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_CON_DATOS);
expect(periodo['grupos']).toEqual({ total: 'Total' });
expect(periodo.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador: 28, denominador: 37, valor: 75.7, suprimido: 0 })]);
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: '75.7',
info: '28 de 37 mastografías BI-RADS 4 y 5 con reporte de biopsia.' });
});
it('un periodo sin mastografías de sospecha no muestra un porcentaje', () => {
// Pins down: denominator zero and no score is «Sin valor disponible», never 0 %. Fails if an empty period is
// drawn as a measured zero.
const periodo = datos('CAMA-CONFIRMACION-BIRADS45', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ grupo: 'total', numerador: 0, denominador: 0, valor: null });
expect(kpiResult(periodo, CAMA_CONFIRMACION_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
});
describe('Duraciones (C3r): tiempos de CaMa', () => {
it('toma a resultado da mediana, cuartiles y número de mastografías', () => {
// Pins down: median 8 days with Q1 4 and Q3 12 over 101 mammograms for 2025-S2, and the card shows them. Fails if the
// quartiles or the observation count stop coming from the report's extensions and populations.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ grupo: 'TOTAL', n: 101, mediana: 8, q1: 4, q3: 12, n_sin_evento: 0, unidad: 'dias' });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 8,
info: '101 mastografías; Q1 a Q3: 4 a 12 días.' });
});
it('tamizaje a diagnóstico separa las mastografías medidas de las que no tienen diagnóstico', () => {
// Pins down: 55 measured and 43 without a diagnosis by the cut-off (FHIR's population exclusion), median 60 days.
// Fails if the unmeasured units are counted as observations or lost.
const periodo = datos('CAMA-DIAS-TOMA-DIAGNOSTICO', ...SEMESTRE_CON_DATOS);
expect(periodo.filas[0]).toMatchObject({ n: 55, n_sin_evento: 43, mediana: 60, q1: 41.5, q3: 131.5 });
expect(kpiResult(periodo, CAMA_TOMA_DIAGNOSTICO_KPI, 'cama', apply('2025-S2'))).toMatchObject({ state: 'Disponible', value: 60 });
});
it('un periodo sin mastografías no tiene mediana', () => {
// Pins down: zero observations and no score is «Sin valor disponible», not a median of 0 days. Fails if an empty
// period is shown as an instant result.
const periodo = datos('CAMA-EU38A', ...SEMESTRE_VACIO);
expect(periodo.filas[0]).toMatchObject({ n: 0, mediana: null });
expect(kpiResult(periodo, CAMA_TAMIZAJE_RESULTADO_KPI, 'cama', apply('2021-S1')).state).toBe('Sin valor disponible');
});
it('la caja de cuartiles se dibuja con los semestres que tienen mediana', () => {
// Pins down: the box plot keeps the periods with a median and leaves out the empty one. Fails if an empty
// period becomes a box at zero.
const reports = ['2021-01-01', '2024-07-01', '2025-07-01'].flatMap(start => reportsOf('CAMA-EU38A', 'semestre', start));
const figure = cajaDeDatos(datosValidos(datosDeReportes(measure('CAMA-EU38A'), reports, 'semestre'), 'cama_eu38a', 'semestre'));
expect((figure.data[0] as Record<string, unknown>)['x']).toEqual(['2024-S2', '2025-S2']);
expect((figure.data[0] as Record<string, unknown>)['median']).toEqual([7.5, 8]);
});
});
describe('Servicio FHIR sobre CaMa', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('pide por el id de la página y consulta la medida por su canónico', async () => {
// Pins down: the page asks for `cama_birads_456_paciente` and the WebApi receives the canonical of
// `CAMA-BIRADS456-PACIENTE` with the periods asked for. Fails if the page id is sent as the measure or the table is bypassed.
const service = TestBed.inject(FhirIndicadoresService);
const answer = firstValueFrom(service.datos('cama', 'cama_birads_456_paciente', 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
const request = http.expectOne(r => r.url === '/cama/fhir/MeasureReport');
expect(request.request.params.get('measure')).toBe('https://isssteleon.org/fhir/Measure/CAMA-BIRADS456-PACIENTE');
expect(request.request.params.get('periodo')).toBe('2025-S2');
request.flush({ ...answers['CAMA-BIRADS456-PACIENTE'].semestre, entry: reportsOf('CAMA-BIRADS456-PACIENTE', 'semestre', '2025-07-01').map(resource => ({ resource })) });
expect((await answer).id).toBe('cama_birads_456_paciente');
});
it('el catálogo de CaMa publica los ocho ids de la página', async () => {
// Pins down: the catalog the page receives lists the correspondence ids, so its filters and cards find them.
// Fails if a measure reaches the page under its FHIR id.
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).catalogo('cama'));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
expect((await answer).map(item => item.id).sort()).toEqual(Object.values(CAMA_MEASURE_IDS).sort());
});
});
describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () => {
const models = (examenes: IndicadorDatos, pacientes: IndicadorDatos) => modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, examenes, pacientes, 'semestre');
it('con datos reales del semestre da los conteos por categoría de ambas medidas', () => {
// Pins down: the page's pair reads the two real C2 answers (units `examen` and `paciente`, version 0.2.0 of the
// patients' measure) and gives the exams by category and the patients by BI-RADS family. Fails if an id, a unit or
// a category of either measure stops matching what the pair checks.
const [model] = models(datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS), datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS));
expect(model.pacientesVerificados).toBe(true);
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
});
it('un periodo sin BI-RADS 4 sin subcategoría cuenta cero en esa categoría y no rompe la tarjeta', () => {
// Pins down: `B4` is published only when some report counts it; a period set without it leaves the card
// working, with zero exams in that category. The reports are the real 2025-S2 ones with the `B4` stratum removed
// and the units reduced by its count. Fails if the card turns «categorías no coinciden» whenever no 4 arrives unqualified.
const without = (fhirId: string) => {
const [report] = reportsOf(fhirId, 'semestre', '2025-07-01');
const group = report.group![0];
const removed = group.stratifier![0].stratum!.find(s => s.value?.coding?.[0].code === 'B4')!.population![0].count!;
const units = group.population!.map(p => p.code?.coding?.[0].code === 'initial-population' ? { ...p, count: p.count! - removed } : p);
const stratifier = [{ ...group.stratifier![0], stratum: group.stratifier![0].stratum!.filter(s => s.value?.coding?.[0].code !== 'B4') }];
const copy = { ...report, group: [{ ...group, population: units, stratifier }] } as Report;
return datosValidos(datosDeReportes(measure(fhirId), [copy], 'semestre'), indicadorId(fhirId), 'semestre', ['2025-S2']);
};
const [model] = models(without('CAMA-BIRADS456-MASTOGRAFIA'), without('CAMA-BIRADS456-PACIENTE'));
expect(model.examenes.find(c => c.id === 'B4')!.n).toBe(0);
expect(model.filas.map(f => f.examenes)).toEqual([0, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
describe('Conteos publicados de CaMa en la ruta FHIR', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting(), FhirIndicadoresService] });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
function pedir(id: string, fhirId: string) {
const answer = firstValueFrom(TestBed.inject(FhirIndicadoresService).datos('cama', id, 'semestre', ['2025-S2']));
http.expectOne('/cama/fhir/Measure').flush(measuresData);
http.expectOne(r => r.url === '/cama/fhir/MeasureReport').flush({ ...answers[fhirId].semestre, entry: reportsOf(fhirId, 'semestre', '2025-07-01').map(resource => ({ resource })) });
return answer;
}
it('las mastografías llegan a la tarjeta con los conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-MASTOGRAFIA', ...SEMESTRE_CON_DATOS);
const mostrado = await pedir('cama_birads_456_mastografia', 'CAMA-BIRADS456-MASTOGRAFIA');
expect(mostrado.filas).toEqual(publicado.filas);
const pacientes = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const [model] = modelosConteos(parConteos('cama', 'cama_birads_456_mastografia')!, mostrado, pacientes, 'semestre');
expect(totalExamenes(model)).toBe(39);
expect(model.filas.map(f => f.examenes)).toEqual([16, 21, 2]);
expect(model.filas.map(f => f.pacientes)).toEqual([14, 20, 2]);
});
it('los pacientes conservan sus conteos publicados', async () => {
const publicado = datos('CAMA-BIRADS456-PACIENTE', ...SEMESTRE_CON_DATOS);
const pacientes = await pedir('cama_birads_456_paciente', 'CAMA-BIRADS456-PACIENTE');
expect(pacientes.filas).toEqual(publicado.filas);
});
});
@@ -0,0 +1,47 @@
// How CaMa's FHIR measures map onto what the indicator page reads: the page's id of each measure, the name of a
// proportion's primary group and the categories a composition publishes beyond its declared ones.
//
// The WebApi names a measure `CAMA-BIRADS456-PACIENTE`; the page, its history and its cards use
// `cama_birads_456_paciente`. A rule can't derive one from the other (`BIRADS456` splits into `birads_456`), so the
// correspondence is explicit and a measure outside it keeps the generic rule.
export const CAMA_MEASURE_IDS: Readonly<Record<string, string>> = {
'CAMA-BIOPSIAS': 'cama_biopsias',
'CAMA-BIRADS': 'cama_birads',
'CAMA-BIRADS-CANCER-INVASOR': 'cama_birads_cancer_invasor',
'CAMA-BIRADS456-MASTOGRAFIA': 'cama_birads_456_mastografia',
'CAMA-BIRADS456-PACIENTE': 'cama_birads_456_paciente',
'CAMA-CONFIRMACION-BIRADS45': 'cama_confirmacion_birads45',
'CAMA-DIAS-RESULTADO-DIAGNOSTICO': 'cama_dias_resultado_diagnostico',
'CAMA-DIAS-TOMA-DIAGNOSTICO': 'cama_dias_toma_diagnostico',
'CAMA-EU38A': 'cama_eu38a',
'CAMA-HISTOPATOLOGIA-BIRADS': 'cama_histopatologia_birads',
'CAMA-TASA-DETECCION-HISTOPATOLOGICA': 'cama_tasa_deteccion_histopatologica',
};
export const esMedidaCama = (measureId: string | undefined): boolean =>
measureId !== undefined && Object.hasOwn(CAMA_MEASURE_IDS, measureId);
// A proportion's primary group is `principal` in the WebApi; CaMa's page names it `total`.
export const GRUPO_PRINCIPAL_PAGINA = 'total';
export const GRUPO_PRINCIPAL_FHIR = 'principal';
// A category a report counts that its Measure doesn't declare (a BI-RADS 4 without subcategory arrives as `B4`) is
// shown after the declared ones under the caption the Core catalog gives it.
export const ETIQUETA_CATEGORIA_NO_DECLARADA: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The histopathological result by BI-RADS (`CAMA-HISTOPATOLOGIA-BIRADS`) publishes the cross of two stratifiers, the
// BI-RADS of the mammogram and the grade of its biopsy, as FHIR codes (`B4A`, `CARCINOMA_IN_SITU`); the view that
// draws it reads the page's codes. The correspondence is explicit, one table per axis, so a code outside it is an error
// and never a silent zero. A grade is benign or malignant as the parameter `cama.biopsia_cancer` says; no biopsy and
// no grade belong to no group.
export const ESTRATO_BIRADS_PAGINA: Readonly<Record<string, string>> = {
B4: 'BIRADS_4', B4A: 'BIRADS_4A', B4B: 'BIRADS_4B', B4C: 'BIRADS_4C', B5: 'BIRADS_5', B6: 'BIRADS_6',
};
export const CATEGORIA_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, { id: string; grupo: string | null; gravedad: number | null }>> = {
BENIGNO: { id: 'BENIGNO', grupo: 'NO_MALIGNO', gravedad: 1 },
CARCINOMA_IN_SITU: { id: 'IN_SITU', grupo: 'MALIGNO', gravedad: 3 },
CARCINOMA_INVASOR: { id: 'INVASOR', grupo: 'MALIGNO', gravedad: 4 },
SIN_BIOPSIA: { id: 'SIN_BIOPSIA', grupo: null, gravedad: null },
SIN_DATO: { id: 'SIN_DATO', grupo: 'SIN_DATO', gravedad: null },
};
export const GRUPOS_HISTOPATOLOGIA_PAGINA: Readonly<Record<string, string>> = { NO_MALIGNO: 'No maligno', MALIGNO: 'Maligno', SIN_DATO: 'Sin dato' };
@@ -0,0 +1,242 @@
// What this module covers: the three CaMa measures of L3 as the page reads them from FHIR: the detection rate (C1), the
// time from the mammogram's result to the diagnosis (C3r) and the histopathological result by BI-RADS (C2 stratified by
// BI-RADS): their ids, catalog entries, numerators and denominators, medians, the BI-RADS by result matrix, the periods
// with no data and the reports that don't add up.
// Fixtures: `fixtures/cama_fhir_measures.json` (the Measure bundle the WebApi serves from the current dbt definitions) and
// `fixtures/cama_fhir_l3_reportes.json` (real `GET /cama/fhir/MeasureReport` answers over a read-only copy of the data of
// the 18092 installation, with L3's views applied on the copy), cut to six semesters and three months. The semesters:
// 2021-S1 (no data), 2024-S2, 2025-S1, 2025-S2, 2026-S1 and 2026-S2 (the one the cut-off cuts).
import { Bundle, resources } from './fhir';
import { datosDeReportes, indicadorDeMeasure, indicadorId, Measure, metadatosDeMeasure, Report } from './indicadores-fhir';
import { CAMA_MEASURE_IDS } from './indicadores-cama-fhir';
import { CAMA_RESULTADO_DIAGNOSTICO_KPI, CAMA_TASA_DETECCION_KPI, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { IndicadorDatos, TipoPeriodo } from './indicadores.models';
import { datosValidos } from './indicadores.service';
import { etiquetaPeriodo, historicoFigura } from './indicadores-historico-figures';
import { ESTRATOS_BIRADS, modeloHistopatologia, periodosHistopatologia, seleccionBase, tasas } from './indicadores-histopatologia-cama';
import measuresData from './fixtures/cama_fhir_measures.json';
import l3Data from './fixtures/cama_fhir_l3_reportes.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const answers = l3Data.reports as unknown as Record<string, { semestre: Bundle; mes: Bundle }>;
const TASA = 'CAMA-TASA-DETECCION-HISTOPATOLOGICA', DIAS = 'CAMA-DIAS-RESULTADO-DIAGNOSTICO', HISTO = 'CAMA-HISTOPATOLOGIA-BIRADS';
const measure = (fhirId: string) => measures.find(m => m.id === fhirId)!;
const reportsOf = (fhirId: string, tipo: TipoPeriodo, start?: string) =>
(resources(answers[fhirId][tipo], 'MeasureReport') as Report[]).filter(r => !start || r.period?.start === start);
const apply = (periodo: string, tipo: TipoPeriodo = 'semestre'): GlobalApplied =>
({ tipo, selection: { mode: 'explicit', periodos: [periodo] }, revision: 0 });
function datos(fhirId: string, start: string, periodo: string, tipo: TipoPeriodo = 'semestre', scope = {}): IndicadorDatos {
return datosDeReportes(measure(fhirId), reportsOf(fhirId, tipo, start), tipo, scope);
}
const SEMESTRES = [['2025-01-01', '2025-S1'], ['2025-07-01', '2025-S2'], ['2026-01-01', '2026-S1'], ['2026-07-01', '2026-S2']] as const;
const BIRADS_PACIENTES_2025_S2 = 36;
describe('Las tres medidas de L3 en el catálogo', () => {
it('cada una tiene su id de página, su contrato y su sentido', () => {
// Pins down: the explicit table names the three, none collides with another, and the catalog gives each its contract
// (a proportion, a duration with its box plot, a composition stratified by BI-RADS). Fails if a measure is published
// without a correspondence or its contract drifts.
expect(indicadorId(TASA)).toBe('cama_tasa_deteccion_histopatologica');
expect(indicadorId(DIAS)).toBe('cama_dias_resultado_diagnostico');
expect(indicadorId(HISTO)).toBe('cama_histopatologia_birads');
expect([TASA, DIAS, HISTO].every(id => Object.hasOwn(CAMA_MEASURE_IDS, id))).toBe(true);
const catalogo = Object.fromEntries(measures.map(m => [indicadorId(m.id!), indicadorDeMeasure(m)]));
expect(catalogo['cama_tasa_deteccion_histopatologica']).toMatchObject({ contrato: 'C1', figuras: [], unidad: 'examen', tipos_periodo: ['semestre', 'mes'] });
expect(catalogo['cama_dias_resultado_diagnostico']).toMatchObject({ contrato: 'C3r', figuras: ['fig_c3r_caja'], sentido: 'menor_mejor' });
expect(catalogo['cama_histopatologia_birads']).toMatchObject({ contrato: 'C2', estratos: ['birads'], unidad: 'paciente' });
expect(new Set(measures.map(m => indicadorId(m.id!))).size).toBe(measures.length);
});
it('la ficha de cada una dice qué cuenta y qué no es', () => {
// Pins down: the description is the measure's definition: the detection rate is of biopsy reports and says it is not a
// rate over screened women nor the confirmation proportion; the time says its note isn't linked to the mammogram nor is
// the biopsy's date. Fails if the sheet is lost or reads like another indicator.
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/reporte de biopsia, no la\s+paciente/);
expect(metadatosDeMeasure(measure(TASA)).descripcion).toMatch(/no es una tasa\s+sobre las mujeres tamizadas/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no está ligada a la mastografía/);
expect(metadatosDeMeasure(measure(DIAS)).descripcion).toMatch(/no es la fecha de la biopsia/);
expect(metadatosDeMeasure(measure(HISTO)).descripcion).toMatch(/la misma regla de CAMA_BIRADS456_PACIENTE/);
const codigos = measures.map(m => metadatosDeMeasure(m).ficha!.codigo);
expect(new Set(codigos).size).toBe(measures.length);
expect(metadatosDeMeasure(measure(TASA)).ficha!.codigo).toBe('TASA-DETECCION-HISTOPATOLOGICA');
});
});
describe('Tasa de detección histopatológica (C1)', () => {
it.each([['2025-01-01', '2025-S1', 16, 24, 66.7], ['2025-07-01', '2025-S2', 14, 25, 56], ['2026-01-01', '2026-S1', 13, 18, 72.2], ['2026-07-01', '2026-S2', 10, 19, 52.6]] as const)(
'en %s el numerador y el denominador son los reportes de biopsia malignos y con resultado conocido', (inicio, periodo, numerador, denominador, valor) => {
// Pins down: each semester's rows carry the report counts (malignant over known result) and the percentage the card
// shows, in the page's group `total`, and the card reads «Disponible» with its sentence. Fails if a count is lost or
// the numerator leaves its denominator.
const d = datosValidos(datos(TASA, inicio, periodo), 'cama_tasa_deteccion_histopatologica', 'semestre', [periodo]);
expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
});
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
// Pins down: over the real periods, malignant ≤ known result, and the four semesters add up to 56 + ... = the reports
// (16+14+13+10 malignant of 24+25+18+19 with known result). Fails if a report is counted in two periods or one is dropped.
const filas = SEMESTRES.flatMap(([inicio, periodo]) => datos(TASA, inicio, periodo).filas);
expect(filas.every(f => (f['numerador'] as number) <= (f['denominador'] as number))).toBe(true);
expect(filas.reduce((s, f) => s + (f['numerador'] as number), 0)).toBe(53);
expect(filas.reduce((s, f) => s + (f['denominador'] as number), 0)).toBe(86);
});
it('un semestre sin reportes de biopsia no da una tasa: 0 de 0 es sin datos, no 0 %', () => {
// Pins down: 2021-S1 has no biopsy reports; the rows say 0 of 0 with no value and the card doesn't claim a rate.
// Fails if an empty period is shown as 0 % or as an error.
const d = datos(TASA, '2021-01-01', '2021-S1');
expect(d.filas).toEqual([expect.objectContaining({ numerador: 0, denominador: 0, valor: null })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Tiempo de resultado a diagnóstico (C3r)', () => {
it.each([['2025-01-01', '2025-S1', 56, 41, 65], ['2025-07-01', '2025-S2', 59, 41, 49], ['2026-01-01', '2026-S1', 61, 21, 58], ['2026-07-01', '2026-S2', 18, 0, 40]] as const)(
'en %s mide las mastografías con nota diagnóstica y deja fuera, contadas, las que no la tienen', (inicio, periodo, n, sinEvento, mediana) => {
// Pins down: the observations (mammograms with a diagnosing note in the horizon), those without one and the median in
// days, as the report publishes them, with the card reading the median. Fails if an unmeasured mammogram is dropped
// without being counted or a median is read as zero.
const d = datosValidos(datos(DIAS, inicio, periodo), 'cama_dias_resultado_diagnostico', 'semestre', [periodo]);
expect(d.filas).toEqual([expect.objectContaining({ n, mediana, n_sin_evento: sinEvento, unidad: 'dias' })]);
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(periodo))).toMatchObject({ state: 'Disponible', value: mediana });
});
it('las mastografías del periodo son las observadas más las que no tienen nota', () => {
// Pins down: initial population = observations + exclusions in every real semester, so no mammogram is lost between
// the population and the box plot. Fails if the report's counts don't close.
for (const [inicio] of SEMESTRES) {
const grupo = reportsOf(DIAS, 'semestre', inicio)[0].group![0];
const n = (c: string) => grupo.population!.find(p => p.code?.coding?.[0].code === c)!.count!;
expect(n('measure-observation') + n('measure-population-exclusion'), inicio).toBe(n('initial-population'));
}
});
it('un semestre sin mastografías no da una mediana', () => {
// Pins down: with no observations the card has no value (a median over zero observations is no value, not zero days).
// Fails if an empty period reads as 0 days.
const d = datos(DIAS, '2021-01-01', '2021-S1');
expect(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply('2021-S1')).state).not.toBe('Disponible');
});
});
describe('Resultado histopatológico por categoría BI-RADS (C2 por BI-RADS)', () => {
const matriz = (inicio: string, periodo: string, tipo: TipoPeriodo = 'semestre') =>
modeloHistopatologia(datosValidos(datos(HISTO, inicio, periodo, tipo, { estrato: 'birads' }), 'cama_histopatologia_birads', tipo, [periodo], { estrato: 'birads' }), periodo);
const celdas = (m: ReturnType<typeof matriz>) => Object.fromEntries(m.filas.map(f => [f.id,
{ ...Object.fromEntries(Object.entries(f.celdas).map(([k, c]) => [k, c.n])), ...Object.fromEntries(Object.entries(f.aparte).map(([k, c]) => [k, c.n])), total: f.total.n }]));
it('2025-S1: la matriz BI-RADS por resultado es la del reporte, con ceros publicados en las categorías sin pacientes', () => {
// Pins down: the cells of the real report (BI-RADS 4: 8 benign, 6 invasive, 6 without biopsy; BI-RADS 5: 6 invasive, 1 in
// situ, 3 without biopsy), every other stratum a published zero (never «No disponible»), each stratum's total the sum of
// its cells and the matrix the 30 patients of the period. Fails if a cell moves, a zero turns unavailable or a total drifts.
const m = matriz('2025-01-01', '2025-S1');
expect(m.filas.map(f => f.id)).toEqual([...ESTRATOS_BIRADS]);
expect(celdas(m)).toEqual({
BIRADS_4: { BENIGNO: 8, IN_SITU: 0, INVASOR: 6, SIN_BIOPSIA: 6, SIN_DATO: 0, total: 20 },
BIRADS_4A: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4B: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_4C: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
BIRADS_5: { BENIGNO: 0, IN_SITU: 1, INVASOR: 6, SIN_BIOPSIA: 3, SIN_DATO: 0, total: 10 },
BIRADS_6: { BENIGNO: 0, IN_SITU: 0, INVASOR: 0, SIN_BIOPSIA: 0, SIN_DATO: 0, total: 0 },
});
expect(m.filas.every(f => Object.values(f.celdas).every(c => c.estado === 'Publicado'))).toBe(true);
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(30);
expect(m.conResultado).toBe(21);
});
it('la lesión de riesgo (B3) no se inventa: no hay esa categoría en las fuentes y la matriz no la dibuja', () => {
// Pins down: the source grades are benign, in situ and invasive; the page's optional «Lesión de riesgo (B3)» isn't
// published, so the model lists three categories and two groups (non malignant, malignant). Fails if a category the
// source lacks appears, or the model needs it.
const m = matriz('2025-01-01', '2025-S1');
expect(m.categorias.map(c => c.id)).toEqual(['BENIGNO', 'IN_SITU', 'INVASOR']);
expect(m.categorias.map(c => c.etiqueta)).toEqual(['Benigno', 'Carcinoma in situ', 'Carcinoma invasor']);
expect(m.grupos.map(g => [g.id, g.categorias])).toEqual([['NO_MALIGNO', ['BENIGNO']], ['MALIGNO', ['IN_SITU', 'INVASOR']]]);
expect(m.aparte.map(a => a.id)).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
});
it('las tasas por categoría usan solo a las pacientes con resultado de biopsia y llevan su intervalo', () => {
// Pins down: for the malignant group the rate of BI-RADS 4 is 6 of 14 and BI-RADS 5 is 7 of 7 (no biopsy and no data
// never enter the denominator), and a stratum with no patients has no rate. Fails if «sin biopsia» enters a denominator.
const m = matriz('2025-01-01', '2025-S1');
const t = Object.fromEntries(tasas(m, seleccionBase(m)).map(x => [x.fila.id, x]));
expect([t['BIRADS_4'].k, t['BIRADS_4'].fila.den]).toEqual([6, 14]);
expect([t['BIRADS_5'].k, t['BIRADS_5'].fila.den]).toEqual([7, 7]);
expect(t['BIRADS_5'].valor).toBe(100);
expect(t['BIRADS_4'].bajo).toBeLessThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_4'].alto).toBeGreaterThan(t['BIRADS_4'].valor!);
expect(t['BIRADS_6'].valor).toBeNull();
});
it('el total de la matriz de cada semestre es el de pacientes BI-RADS 4, 5 y 6 del periodo', () => {
// Pins down: the matrix counts the same patients as CAMA_BIRADS456_PACIENTE (36 in 2025-S2, the report of the earlier
// fixture), and in every real semester the units of the report are the matrix's cells. Fails if the two measures count
// different patients.
const total = (inicio: string, periodo: string) => matriz(inicio, periodo).filas.reduce((s, f) => s + f.total.n!, 0);
expect(total('2025-07-01', '2025-S2')).toBe(BIRADS_PACIENTES_2025_S2);
for (const [inicio, periodo] of SEMESTRES) {
expect(total(inicio, periodo), periodo).toBe(reportsOf(HISTO, 'semestre', inicio)[0].group![0].population![0].count);
}
});
it('un semestre sin pacientes es una matriz de ceros publicados, no un error', () => {
// Pins down: 2021-S1 has no mammograms: the matrix is complete with zeros and the denominators are zero (no rate).
// Fails if an empty period breaks the view or turns into «No disponible».
const m = matriz('2021-01-01', '2021-S1');
expect(m.filas.every(f => f.total.n === 0 && f.den === 0)).toBe(true);
expect(m.conResultado).toBe(0);
});
it('un mes con pacientes se lee igual que un semestre', () => {
// Pins down: the monthly answer carries the month label and the same matrix shape. Fails if the month is read as a semester.
const m = matriz('2025-12-01', '2025-12', 'mes');
expect(m.periodo).toBe('2025-12');
expect(m.filas.reduce((s, f) => s + f.total.n!, 0)).toBe(8);
});
it('el catálogo de categorías sale de la Measure y los códigos desconocidos son un error, no ceros', () => {
// Pins down: an unknown BI-RADS or grade code in a report, or cells that don't add up to the units, throw instead of
// being read as zero. Fails if the adapter hides an inconsistent report.
const clon = (): Report[] => structuredClone(reportsOf(HISTO, 'semestre', '2025-01-01'));
const conCodigo = clon();
conCodigo[0].group![0].stratifier![1]['stratum']![0].component![0].value!.coding![0].code = 'B9';
expect(() => datosDeReportes(measure(HISTO), conCodigo, 'semestre', { estrato: 'birads' })).toThrow(/no reconocido/);
const desajustado = clon();
desajustado[0].group![0].stratifier![1]['stratum']![0].population![0].count! += 1;
expect(() => datosDeReportes(measure(HISTO), desajustado, 'semestre', { estrato: 'birads' })).toThrow(/no suman/);
const sinCruce = clon();
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
expect(() => datosDeReportes(measure(HISTO), sinCruce, 'semestre', { estrato: 'birads' })).toThrow(/no admitida/);
});
it('sin pedir el estrato, la medida se lee como una distribución por resultado y suma las mismas pacientes', () => {
// Pins down: asked without the stratum the measure is a plain C2 (categories of the biopsy result); its categories add
// to the report's units. Fails if the stratified reading changes the plain one.
const d = datos(HISTO, '2025-01-01', '2025-S1');
expect(d.filas.reduce((s, f) => s + (f['n'] as number), 0)).toBe(30);
expect(periodosHistopatologia(datos(HISTO, '2025-01-01', '2025-S1', 'semestre', { estrato: 'birads' }), 'semestre')).toEqual(['2025-S1']);
});
});
describe('Resumen e Histórico leen lo mismo', () => {
type Traza = { name?: string; x: (string | null)[]; y: (number | null)[] };
const serie = (d: IndicadorDatos, nombre: string): Traza =>
((historicoFigura(d, 'claro').figure as unknown as { data: Traza[] }).data).find(t => t.name === nombre)!;
it.each([[TASA, 'Porcentaje', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(p)).value)],
[DIAS, 'Mediana', (d: IndicadorDatos, p: string) => Number(kpiResult(d, CAMA_RESULTADO_DIAGNOSTICO_KPI, 'cama', apply(p)).value)]] as const)(
'%s: el valor de la tarjeta de cada semestre es el punto del Histórico en ese semestre', (fhirId, nombre, tarjeta) => {
// Pins down: the card of one semester and the history of all of them are built from the same reports, so the number on the
// card is the point of the series for that period. Fails if the two screens compute the figure differently.
const historico = datosDeReportes(measure(fhirId), SEMESTRES.map(([inicio]) => reportsOf(fhirId, 'semestre', inicio)[0]), 'semestre');
const traza = serie(historico, nombre);
for (const [inicio, periodo] of SEMESTRES) {
const i = traza.x.indexOf(etiquetaPeriodo(periodo));
expect(i, periodo).toBeGreaterThanOrEqual(0);
expect(traza.y[i], periodo).toBe(tarjeta(datos(fhirId, inicio, periodo), periodo));
}
});
});
@@ -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 mastografía a resultado', 'Tiempo de resultado a diagnóstico']);
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
});
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
@@ -53,7 +53,7 @@ describe('Tarjetas de oportunidad de CaMa: valores', () => {
it('la tasa de detección muestra el porcentaje del C1 sin recalcularlo, con su propia línea de detalle', () => {
// Fails if the card recomputes the rate or reuses the confirmation wording ("con reporte de biopsia").
const result = kpiResult(c1({ valor: 12.34, numerador: 3, denominador: 20 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con resultado maligno.' });
expect(result).toEqual({ state: 'Disponible', value: '12.3', info: '3 de 20 biopsias con riesgo a carcinoma.' });
});
it('una tasa de cero con denominador es un cero real, no una ausencia', () => {
const result = kpiResult(c1({ valor: 0, numerador: 0, denominador: 8 }), CAMA_TASA_DETECCION_KPI, 'cama', applied);
@@ -208,28 +208,35 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
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.
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
// Fails if any card without a published measure makes a request or displays a value.
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([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards().every(card => !card.textContent?.includes('Periodo'))).toBe(true);
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 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']);
'Pacientes evaluadas con BI-RADS 4, 5 o 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía a interpretación radiológica',
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined, undefined]);
expect(cards().map(card => text(card, '.kpi-state'))).toEqual([
'Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente', 'Indicador no disponible']);
expect(cards()[1].textContent).toContain('aún no está publicado');
expect(cards()[1].textContent).not.toMatch(/\d/);
expect(cards()[4].textContent).toContain('aún no está publicado');
expect(cards()[4].textContent).not.toMatch(/\d|días|mediana/);
});
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.
it('dibuja los cuatro indicadores publicados y mantiene diagnóstico a tratamiento sin valor', () => {
// Fails if a published measure is skipped or the placeholder borrows data from another measure.
const urls = load([...KPI_BY_DOMAIN.cama, CAMA_TASA_DETECCION_KPI, CAMA_RESULTADO_DIAGNOSTICO_KPI]);
expect(cards()).toHaveLength(4);
expect(cards()).toHaveLength(5);
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'))).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title));
expect(cards().slice(0, 4).map(card => text(card, 'h3'))).toEqual(CAMA_OPORTUNIDAD_KPIS.map(d => d.title));
expect(text(cards()[4], '.kpi-state')).toBe('Indicador no disponible');
expect(text(cards()[4], '.value')).toBeUndefined();
expect(cards().some(card => card.textContent?.includes('Integración pendiente'))).toBe(false);
expect(cards()[1].textContent).toContain('2 de 5 biopsias con resultado maligno.');
expect(cards()[1].textContent).toContain('2 de 5 biopsias con riesgo a carcinoma.');
});
it('sin catálogo de CaMa no se dibuja la sección de indicadores destacados', () => {
fixture.componentInstance.changeDominio('cama'); fixture.detectChanges();
@@ -249,7 +256,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 mastografía a resultado"]')).not.toBeNull();
expect(fixture.nativeElement.querySelector('button[aria-label="Reintentar Tiempo de toma de mastografía a interpretación radiológica"]')).not.toBeNull();
});
it('la tarjeta de distribución de biopsias no se dibuja en el resumen de CaMa y el resto de las figuras sigue', () => {
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
@@ -266,7 +273,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
expect(text).not.toContain('Cáncer de mama, investigación');
expect(text).toContain('Explora los indicadores de cáncer de mama.');
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros generales');
expect(fixture.nativeElement.querySelector('#global-filters-title').textContent.trim()).toBe('Filtros');
expect(fixture.nativeElement.querySelector('.global-filters .section-description')).toBeNull();
expect(text).not.toContain('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
expect(text).not.toContain('Filtro general aplicado');
@@ -312,7 +319,8 @@ describe('Filtros generales de CaMa: periodo único', () => {
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('.field-label').textContent!.trim()).toBe('Intervalo de análisis');
expect(labels()).toEqual(['Periodo seleccionado']);
expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull();
const text = fixture.nativeElement.textContent as string;
expect(text).not.toContain('Modalidad');
@@ -13,7 +13,7 @@ const item = (id: string, titulo: string, contrato: string, figuras: string[]) =
// 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_mastografia', 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6', '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']),
@@ -46,16 +46,18 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
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.
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
// Fails if the heading goes back to the whole catalog 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');
// 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');
// Only the paired card is a published indicator the summary draws; the other three are in Histórico.
expect(titles()).toEqual(['Porcentaje individual de mastografías']);
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
// The paired card has no card title; each donut names itself. The other three indicators are in Histórico.
expect(titles()).toEqual([]);
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');
});
it('CaMa: las tarjetas que el mockup no tiene en el Resumen se retiran sin quitarlas del catálogo', () => {
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
@@ -65,6 +67,12 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
}
});
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
open('cama', CAMA);
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
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', () => {
open('cama', CAMA);
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
@@ -111,7 +119,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
expect(root().querySelector('.catalog-search')).not.toBeNull();
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
expect(section().textContent).toContain('2 figuras publicadas');
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
expect(root().textContent).not.toContain('indicadores publicados');
});
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
open('cacu', OTRO('cacu'));
@@ -0,0 +1,151 @@
// What this module covers: CaMa's follow-up as the WebApi's cohort endpoint answers it (`GET /cama/seguimiento`):
// the answer's validation and labels, the table the page draws from it, its states, the record of one patient and the
// rows of a file. Nothing here is a status, a priority or a figure the data doesn't hold.
// Fixtures (`fixtures/cama_seguimiento_cohorte_real*.json`): answers of the endpoint over the local installation's
// synthetic CaMa data: `_inicial` (default: today, three months), `_consulta` (six months, BI-RADS 5), the whole cohort
// at 2026-11-16 and the 403 body of a group of fewer than five patients.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ComponentFixture } from '@angular/core/testing';
import { IndicadoresSeguimientoTabla } from './indicadores-seguimiento-tabla';
import { consultaAplicada, contextoDe, seguimientoTablaResponse, SeguimientoTablaQuery } from './seguimiento-tabla.service';
import { identidadesDe } from './paciente-identidad';
import { toCamaPatientSummary } from './paciente-detalle/cama/cama-patient.models';
import { flatTable } from './export/tracking-export-table';
import inicialData from './fixtures/cama_seguimiento_cohorte_real_inicial.json';
import consultaData from './fixtures/cama_seguimiento_cohorte_real_consulta.json';
import cohorteData from './fixtures/cama_seguimiento_cohorte_real.json';
import pequenoData from './fixtures/cama_seguimiento_cohorte_real_403.json';
const copia = (v: unknown) => structuredClone(v) as unknown as Record<string, any>;
describe('Seguimiento de CaMa sobre la cohorte del servidor', () => {
it('la respuesta cumple el contrato, nombra la cohorte y rotula los códigos sin cambiar los valores enviados', () => {
// Pins down: the answer is accepted as is (every row names its patient by `pac_id`, a decimal text), the cohort
// context is read from it, and codes read as the clinic writes them while the code stays in `<clave>_codigo`.
// Fails if the endpoint's shape stops passing the client's validation, or a label replaces a code the requests send.
const respuesta = seguimientoTablaResponse(copia(cohorteData));
expect(respuesta.items).toHaveLength(61);
expect(identidadesDe(respuesta.items)!.every(i => i.campo === 'pac_id' && /^[1-9][0-9]*$/.test(i.id))).toBe(true);
expect(contextoDe(respuesta)).toEqual({ cohorte: 'cama_birads_v1', escenario: 'diagnostico', revision: expect.stringMatching(/^[0-9a-f]{64}$/) });
const fila = respuesta.items.find(i => i['birads_codigo'] === 'BIRADS_4')!;
expect(fila['birads']).toBe('BI-RADS 4');
expect(respuesta.filtros_disponibles.find(f => f.clave === 'birads')!.opciones.map(o => [o.codigo, o.etiqueta]))
.toContainEqual(['BIRADS_4A', 'BI-RADS 4A']);
expect(respuesta.filtros_disponibles.find(f => f.clave === 'grupo_edad')!.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(respuesta.columnas.map(c => c.clave)).toEqual(['pac_id', 'grupo_edad', 'birads', 'biopsia']);
});
it('una página o un archivo solo se acepta si es de la consulta, la cohorte y la revisión que se pidieron', () => {
// Pins down: the answer must repeat the window, filters and context asked for. Fails if rows of another revision
// or another selection could be shown under the title of this one.
const respuesta = seguimientoTablaResponse(copia(consultaData));
const contexto = contextoDe(respuesta)!;
const pedido: SeguimientoTablaQuery = { corte: respuesta.corte, meses: 6, page: 1, page_size: 50, filtros: { birads: 'BIRADS_5' }, contexto };
expect(consultaAplicada(pedido, respuesta)).toBe(true);
expect(consultaAplicada({ ...pedido, contexto: { ...contexto, revision: 'otra' } }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, filtros: {} }, respuesta)).toBe(false);
expect(consultaAplicada({ ...pedido, meses: 3 }, respuesta)).toBe(false);
});
it('la ficha de una paciente muestra lo que trae la fila y deja sin dato estatus, prioridad y días', () => {
// Pins down: the record reads BI-RADS, its date, the age group and the biopsy from the row, and what the list
// doesn't carry stays `null` (shown as «No disponible»), never a value made up. Fails if the summary fills
// status, priority or the days to diagnosis from anywhere.
const r = seguimientoTablaResponse(copia(cohorteData));
const conBiopsia = r.items.find(i => i['biopsia'] !== null)!, sinBiopsia = r.items.find(i => i['biopsia'] === null)!;
const resumen = toCamaPatientSummary(conBiopsia, r.corte, r.columnas)!;
expect(resumen).toMatchObject({ patientId: String(conBiopsia['pac_id']), idField: 'pac_id', cutoff: r.corte, status: null, priority: null,
daysMammographyToDiagnosis: null, birads: conBiopsia['birads'], biopsyDate: conBiopsia['biopsia_fecha'] });
expect(resumen.biopsyDateLabel).toBe('Fecha de reporte');
expect(toCamaPatientSummary(sinBiopsia, r.corte, r.columnas)).toMatchObject({ histopathology: null, biopsyDate: null });
});
it('el archivo lleva las columnas del servidor, sin estatus, prioridad ni días de diagnóstico', () => {
// Pins down: the file's columns are the announced ones (with their date details) and no other, and a missing biopsy
// is `null`. Fails if the files add a column the cohort doesn't have.
const r = seguimientoTablaResponse(copia(cohorteData));
const tabla = flatTable({ corte: r.corte, ventana: r.ventana, filtros: r.filtros, filtros_disponibles: r.filtros_disponibles, columnas: r.columnas, items: r.items });
expect(tabla.columns.map(c => c.label)).toEqual(['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Última mastografía: Fecha',
'Resultado histopatológico', 'Resultado histopatológico: Fecha de reporte']);
expect(tabla.rows).toHaveLength(61);
expect(tabla.rows.some(fila => fila[4] === null && fila[5] === null)).toBe(true);
});
});
describe('Seguimiento de CaMa (tabla) con las respuestas del servidor', () => {
let fixture: ComponentFixture<IndicadoresSeguimientoTabla>, 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 solicitud = () => http.expectOne(r => r.url === '/cama/seguimiento');
async function asentar() { fixture.detectChanges(); await fixture.whenStable(); fixture.detectChanges(); }
const boton = (texto: string) => [...root().querySelectorAll('button')].find(b => b.textContent!.trim() === texto) as HTMLButtonElement;
const campo = (etiqueta: string) => [...root().querySelectorAll('label')].find(l => l.textContent!.trim().startsWith(etiqueta))!;
const filas = () => [...root().querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => [...td.childNodes]
.filter(n => n.nodeType !== Node.COMMENT_NODE).map(n => (n.textContent ?? '').trim()).filter(Boolean).join(' ')));
const elegir = (etiqueta: string, valor: string) => {
const s = campo(etiqueta).querySelector('select')!;
s.value = [...s.options].find(o => o.value.endsWith(valor))!.value; s.dispatchEvent(new Event('change'));
};
it('la primera consulta pide la ventana de 3 meses y dibuja las cuatro columnas de la cohorte con los datos que hay', async () => {
// Pins down: the table has the cohort's four columns and no status, priority or days; the first request is three
// months, page one of 50, with no cut-off (the server's today); a patient without biopsy reads «No disponible».
// Fails if the table asks for or draws a column the endpoint doesn't announce.
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({ meses: '3', page: '1', page_size: '50' });
r.flush(inicialData); await asentar();
expect([...root().querySelectorAll('thead th')].map(th => th.textContent!.trim())).toEqual(
['Identificador de paciente', 'Grupo de edad', 'Última mastografía', 'Resultado histopatológico']);
expect(filas()).toHaveLength(16);
const sin = filas().find(f => f[3] === 'No disponible');
expect(sin).toBeDefined();
expect(sin![2]).toMatch(/^BI-RADS (4|4A|4B|4C|5|6) Fecha: 20\d\d-\d\d-\d\d$/);
expect(root().textContent).toContain(`Ventana consultada: ${(inicialData as any).ventana.desde} al ${(inicialData as any).ventana.hasta}.`);
});
it('el formulario ofrece los filtros que anuncia el servidor y Consultar envía el filtro elegido, el corte y la revisión que devolvió', async () => {
// Pins down: the filters are BI-RADS, age group and biopsy result as announced, and a second query sends the cut-off
// the first answer gave, with its cohort, scenario and revision, plus the chosen window and filter. Fails if the revision isn't quoted back or a filter the server doesn't announce appears
// (BRCA, stage, size, priority...).
solicitud().flush(inicialData); await asentar();
expect([...root().querySelectorAll('form label')].map(l => l.firstChild!.textContent!.trim()))
.toEqual(['Fecha de corte', 'Ventana de meses', 'Categoría BI-RADS', 'Grupo de edad', 'Resultado de la biopsia', 'Registros por página']);
expect([...campo('Resultado de la biopsia').querySelectorAll('option')].map(o => o.text.trim())).toEqual(
['Todos', 'Benigno', 'Carcinoma in situ', 'Carcinoma invasor', 'Biopsia reportada sin resultado', 'Sin biopsia reportada']);
elegir('Ventana de meses', '6'); elegir('Categoría BI-RADS', 'BIRADS_5'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
const r = solicitud();
expect(Object.fromEntries(r.request.params.keys().map(k => [k, r.request.params.get(k)]))).toEqual({
meses: '6', page: '1', page_size: '50', corte: (inicialData as any).corte, birads: 'BIRADS_5',
cohorte: (inicialData as any).cohorte, escenario: (inicialData as any).escenario, revision: (inicialData as any).revision });
r.flush(consultaData); await asentar();
expect(root().textContent).toContain(`Ventana consultada: ${(consultaData as any).ventana.desde} al ${(consultaData as any).ventana.hasta}.`);
expect(filas().every(f => f[2].startsWith('BI-RADS 5'))).toBe(true);
});
it('un grupo de menos de cinco pacientes se dice con su motivo y no se dibuja ninguna fila', async () => {
// Pins down: the server's 403 for a small selection is shown as a message and clears the table. Fails if rows of a
// previous selection stay on screen or the page says nothing.
solicitud().flush(inicialData); await asentar();
elegir('Categoría BI-RADS', 'BIRADS_6'); await asentar();
boton('Consultar').click(); fixture.detectChanges();
solicitud().flush(pequenoData, { status: 403, statusText: 'Forbidden' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('muy pocos pacientes');
expect(filas()).toHaveLength(0);
});
it('si el servidor responde 404 en CaMa dice que la cohorte no está disponible, sin pantalla vacía', async () => {
// Pins down: an endpoint that isn't there leaves an informative state. Fails if the tab shows an empty table or an
// unhandled error.
solicitud().flush({}, { status: 404, statusText: 'Not Found' }); await asentar();
expect(root().querySelector('[role=alert]')?.textContent).toContain('cohorte no está disponible');
});
});
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
@@ -69,10 +69,6 @@ function suma(celdas: Celda[]): number | null {
function estado(celdas: Celda[]): Celda['estado'] {
return 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})`;
@@ -101,15 +97,20 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
const c = cats[a.id];
return { id: a.id, etiqueta: registro(c) && texto(c['etiqueta']) ? c['etiqueta'] : a.etiqueta };
});
const grados: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
const gradosCrudos: Grado[] = Object.entries(cats).filter(([id]) => !APARTE_IDS.includes(id)).map(([id, c]) => {
if (!registro(c) || !texto(c['etiqueta']) || (c['color'] !== null && (typeof c['color'] !== 'string' || !/^#[0-9a-f]{6}$/i.test(c['color'])))
|| typeof c['grupo'] !== 'string' || !etiquetaGrupo(nombres[c['grupo']])) return fail('Grados de biopsia incompatibles.');
return { id, etiqueta: c['etiqueta'], color: (c['color'] as string | null) ?? COLOR_RESPALDO, grupo: c['grupo'] };
});
const conColor = gradosCrudos.filter(g => g.color !== COLOR_RESPALDO);
const colores = paintByGroup(conColor.map(g => g.grupo));
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
const grados = gradosCrudos.map(g => ({ ...g, color: colorDe.get(g.id) ?? g.color }));
const bases = basesPorGrupo(conColor.map(g => g.grupo));
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
// Off-catalogue grades share the group but not its colour.
const propios = grados.filter(g => g.grupo === id), publicados = propios.filter(g => g.color !== COLOR_RESPALDO);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: promedio((publicados.length ? publicados : propios).map(g => g.color)),
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
const propios = grados.filter(g => g.grupo === id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
grados: propios.map(g => g.id) };
});
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
@@ -14,7 +14,7 @@ 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';
import { barrasConteos, ConteosIncompatibles, donaConteos, donaPacientes, esSocioConteos, modelosConteos, parConteos, PARES_CONTEOS, totalExamenes, totalPacientes } from './indicadores-conteos-pareados';
const PAR = parConteos('cama', 'cama_birads_456_mastografia')!;
const CATEGORIAS = {
@@ -87,50 +87,34 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
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('<b>35</b><br>mastografías');
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>35</b>', 'mastografías']);
});
it('la dona de pacientes usa la categoría más grave de cada paciente, con ceros y sin razón', () => {
const m = modelo(examenes({ ...LAB_E, B4A: 2 }), pacientes(LAB_P));
expect(totalPacientes(m)).toBe(31);
const dona = donaPacientes(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([13, 0, 0, 0, 18, 0]);
expect(dona.layout.annotations.slice(0, 2).map(a => a.text)).toEqual(['<b>31</b>', 'pacientes']);
expect(JSON.stringify(dona)).not.toMatch(/≈|por paciente|razón/i);
expect(donaPacientes(modelo(examenes(LAB_E), pacientes(LAB_P, { version: '0.3.0' })), PAR, 'claro').data).toEqual([]);
});
});
describe('Conteos pareados de CaMa: etiquetas de la dona', () => {
type Figura = { data: Record<string, any>[]; layout: { annotations: Record<string, any>[]; margin: Record<string, number>; showlegend: boolean } };
const dona = (compacta = false) => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro', compacta) as unknown as Figura;
const dona = () => donaConteos(modelo(examenes(LAB_E), pacientes(LAB_P)), PAR, 'claro') as unknown as Figura;
// Fails if the long label of the 4 without subcategory goes back inside the ring (where it is cut), loses its
// percentage or its guide line, or if the short labels or the centre total change.
it('2025-S2: la etiqueta larga sale del anillo, horizontal y con línea guía; las cortas y el total se conservan', () => {
const f = dona(), t = f.data[0], llamada = f.layout.annotations[1];
expect(t['text'][0]).toBe('');
expect(t['text'][1]).toBe('');
expect(t['text'][4]).toMatch(/^BI-RADS 5<br>54[.,]5 %$/);
it('mantiene las etiquetas con porcentaje fuera del sector', () => {
const f = dona(), t = f.data[0];
expect(t['textinfo']).toBe('none');
expect(t['hovertemplate']).toBe('%{value}<extra></extra>');
expect(f.layout.annotations.slice(2).map(a => a['text']).sort()).toEqual([
'BI-RADS 4<br>(sin<br>subcategoría)<br>45.5 %', 'BI-RADS 5<br>54.5 %',
]);
expect(t['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations[0]['text']).toBe('<b>33</b><br>mastografías');
expect(f.layout.annotations).toHaveLength(2);
expect(llamada['text']).toBe('BI-RADS 4<br>(sin subcategoría)<br>45.5 %');
// A guide line: an arrow without head from the label to a point inside the slice, and no text rotation.
expect(llamada['showarrow']).toBe(true);
expect(llamada['arrowhead']).toBe(0);
expect(llamada['textangle']).toBeUndefined();
});
// Fails if the label can reach the neighbouring chart: its side must keep a margin, and it sits on the side of its slice.
it('reserva espacio del lado de la etiqueta y la coloca del lado de su segmento', () => {
const f = dona(), llamada = f.layout.annotations[1];
// The slice is 45 % of a clockwise ring: its middle points right, so label and margin are on the right.
expect(llamada['xanchor']).toBe('left');
expect(llamada['ax']).toBeGreaterThan(0);
expect(f.layout.margin['r']).toBeGreaterThanOrEqual(110);
expect(f.layout.margin['l']).toBeLessThan(20);
expect(f.layout.showlegend).toBe(false);
});
// Fails if a narrow screen keeps a label that needs side room instead of moving to a legend under the donut.
it('en pantalla estrecha no hay llamada: la dona usa una leyenda debajo', () => {
const f = dona(true);
expect(f.layout.annotations).toHaveLength(1);
expect(f.layout.showlegend).toBe(true);
expect((f.layout as Record<string, any>)['legend']['orientation']).toBe('h');
expect(f.layout.margin['r']).toBeLessThan(20);
expect(f.data[0]['values']).toEqual([15, 0, 0, 0, 18, 0]);
expect(f.layout.annotations.slice(0, 2).map(a => a['text'])).toEqual(['<b>33</b>', 'mastografías']);
});
});
@@ -142,6 +126,7 @@ describe('Conteos pareados de CaMa: lo que no se calcula', () => {
const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record<string, unknown> };
expect(barras.layout['annotations']).toBeUndefined();
expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i);
expect(JSON.stringify(barras)).toContain('pacientes (su categoría más alta)');
expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']);
});
it.each([
@@ -171,7 +156,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, 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_mastografia', 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6', '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']),
];
@@ -218,28 +203,60 @@ describe('Tarjeta pareada de CaMa en la página', () => {
// 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());
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
expect(titulos).toEqual(['Porcentaje individual de mastografías']);
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
// The pair has no card title; each donut has its own heading.
expect(titulos).toEqual([]);
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');
});
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']);
expect(h3).toEqual([
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, 2025-S2',
'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, 2025-S2',
]);
expect(root().querySelector('.conteos')?.getAttribute('aria-label')).toBe(
'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6, por paciente y por mastografía');
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]);
expect(graficas.map(g => g.label)).toEqual(h3);
expect(graficas.map(g => g.figure!.data.length)).toEqual([1, 1]);
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
expect(filas).toEqual([['BI-RADS 4', '13', '15'], ['BI-RADS 5', '18', '18'], ['BI-RADS 6', '0', '0']]);
expect(texto('app-indicador-conteos-pareados')).toContain('no se calcula la razón de mastografías por paciente');
expect(root().querySelector('.published-values caption')?.textContent).toContain('su categoría más alta');
expect(texto('app-indicador-conteos-pareados')).not.toContain('no se calcula la razón de mastografías por paciente');
expect([...root().querySelectorAll('.help-icon')].map(b => b.getAttribute('aria-label'))).toEqual(['Cómo leer, mastografías por categoría', 'Cómo leer, pacientes por categoría']);
expect(texto('app-indicador-conteos-pareados')).not.toContain('Sin dato');
});
it('cada ayuda muestra su explicación exacta sin depender de metadatos de FHIR', () => {
abrir();
const [mastografias, pacientes] = [...root().querySelectorAll<HTMLButtonElement>('.help-icon')];
const ayuda = () => root().querySelector('[role=tooltip]');
mastografias.dispatchEvent(new FocusEvent('focusin', { bubbles: true }));
fixture.detectChanges();
expect(ayuda()?.textContent?.trim()).toBe('Cada mastografía cuenta en su propia categoría.');
expect(mastografias.getAttribute('aria-describedby')).toBe(ayuda()?.id);
pacientes.click();
fixture.detectChanges();
expect(ayuda()?.textContent?.trim()).toBe('La paciente se cuenta una vez con la categoría más alta de sus mastografías en el periodo.');
expect(pacientes.getAttribute('aria-describedby')).toBe(ayuda()?.id);
expect(mastografias.getAttribute('aria-expanded')).toBe('false');
expect(root().querySelectorAll('[role=tooltip]')).toHaveLength(1);
pacientes.click();
fixture.detectChanges();
expect(ayuda()).toBeNull();
http.expectNone(r => r.url.endsWith('/metadatos'));
});
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);
expect(root().textContent).toContain('Dona de pacientes no disponible');
expect(fixture.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(1);
});
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.
@@ -1,5 +1,5 @@
import { Dominio, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { c2Color, c2Theme, tonoDe } 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.
@@ -42,15 +42,15 @@ export const esSocioConteos = (dominio: Dominio, id: string, ids: readonly strin
// The kit publishes a 4 without subcategory as «B4», with no colour.
const ETIQUETA_RESPALDO: Readonly<Record<string, string>> = { B4: 'BI-RADS 4 (sin subcategoría)' };
// The categories a response lists only when some unit falls in them: a period set without any has none, not an unknown.
const OPCIONALES: ReadonlySet<string> = new Set(Object.keys(ETIQUETA_RESPALDO));
const COLOR_RESPALDO: Readonly<Record<string, string>> = { B4: '#E9C08C' };
const COLOR_NEUTRO = '#8A9199';
// Labels longer than «BI-RADS 4A» do not fit inside the ring.
const LARGO_ETIQUETA_INTERIOR = 12;
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[];
periodo: string; examenes: CategoriaConteo[]; pacientes: 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[];
}
@@ -80,79 +80,110 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
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 color = (id: string, index: number) => {
const publicado = registro(catExamenes[id]) && typeof catExamenes[id]['color'] === 'string' ? catExamenes[id]['color'] as string : COLOR_RESPALDO[id] ?? COLOR_NEUTRO;
return c2Color(publicado, index, tonoDe(id));
};
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))) {
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|| todas.some(id => !OPCIONALES.has(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<string, unknown>[], filasP = pacientes.filas as Record<string, unknown>[];
const de = (filas: Record<string, unknown>[], cat: Record<string, unknown>, periodo: string, id: string) =>
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
return periodos.map(periodo => ({
periodo,
examenes: par.categoriasExamen.map(id => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id), n: cuenta(filasE, periodo, id) })),
examenes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catExamenes, id), color: color(id, index), n: de(filasE, catExamenes, periodo, id) })),
// The same published cells the family rows add up, kept by category for the patients' donut.
pacientes: par.categoriasExamen.map((id, index) => ({ id, etiqueta: etiqueta(catPacientes, id), color: color(id, index), n: verificados ? de(filasP, catPacientes, periodo, id) : null })),
// 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))),
pacientes: verificados ? sumar(g.categorias.map(id => de(filasP, catPacientes, periodo, id))) : null,
examenes: sumar(g.categorias.map(id => de(filasE, catExamenes, periodo, id))),
})),
pacientesVerificados: verificados,
notas: [...new Set([...(examenes.notas ?? []), ...(pacientes.notas ?? [])])],
}));
}
export const totalExamenes = (m: ModeloConteos) => sumar(m.examenes.map(c => c.n));
export const totalPacientes = (m: ModeloConteos) => m.pacientesVerificados ? sumar(m.pacientes.map(c => c.n)) : null;
// Geometry the callouts rely on. The ring is height-bound (a 400 px figure with a 10 px margin above and below and
// the pie over 90 % of that height), so its radius does not depend on the width of the card.
const ALTO_DONA = 400, MARGEN_VERTICAL = 10, RADIO_DONA = Math.round((ALTO_DONA - 2 * MARGEN_VERTICAL) * .9 / 2);
const MARGEN_ROTULO = 120, SALIDA_ROTULO = 28;
const ALTO_DONA = 400, MARGEN_DONA = 8;
const DIAMETRO_MAXIMO_DONA = 270;
/**
* Exams by category around their total; nothing is drawn when a cell is unknown. A long label does not fit in the
* ring: it is drawn outside, horizontal and on two lines, joined to its slice by a guide line, on the side of the
* slice with room reserved for it so it never reaches the neighbouring chart. On a narrow card (`compacta`) the
* callouts give way to a legend under the donut.
*/
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, compacta = false): PlotlyFigure {
const total = totalExamenes(m);
function donaDe(categorias: CategoriaConteo[], unidad: string, tema: Tema, ancho: number): PlotlyFigure {
const total = sumar(categorias.map(c => c.n));
if (!total) return { data: [], layout: {} };
const p = c2Theme(tema), n = m.examenes.map(c => c.n!);
const larga = (i: number) => m.examenes[i].etiqueta.length > LARGO_ETIQUETA_INTERIOR && n[i] > 0;
const porcentaje = (i: number) => percentNumber(100 * n[i] / total) + ' %';
const dibujadas = (i: number) => !larga(i) && n[i] / total >= .05;
// Each long label is a callout whose guide line ends inside its slice.
let antes = 0;
const llamadas = n.flatMap((v, i) => {
const angulo = 2 * Math.PI * (antes + v / 2) / total;
antes += v;
if (compacta || !larga(i)) return [];
const seno = Math.sin(angulo), coseno = Math.cos(angulo), dentro = Math.round(RADIO_DONA * .8), fuera = RADIO_DONA + SALIDA_ROTULO - dentro;
const etiqueta = escapar(m.examenes[i].etiqueta), corte = etiqueta.indexOf(' (');
return [{ x: .5, y: .5, xref: 'paper', yref: 'paper', xshift: Math.round(dentro * seno), yshift: Math.round(dentro * coseno),
ax: Math.round(fuera * seno), ay: Math.round(-fuera * coseno), axref: 'pixel', ayref: 'pixel', showarrow: true, arrowhead: 0, arrowwidth: 1, arrowcolor: p.text,
text: (corte > 0 ? etiqueta.slice(0, corte) + '<br>' + etiqueta.slice(corte + 1) : etiqueta) + '<br>' + porcentaje(i),
align: seno >= 0 ? 'left' : 'right', xanchor: seno >= 0 ? 'left' : 'right', yanchor: 'middle', font: { size: 12, color: p.text }, lado: seno >= 0 ? 'r' : 'l' }];
const p = c2Theme(tema), n = categorias.map(c => c.n!);
// Fit both label columns before sizing the ring. Use the same radius for Plotly and the guide lines.
const margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
const radio = diametro / 2;
const fraccionVertical = radio / (ALTO_DONA - 2 * MARGEN_DONA);
const fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
const etiquetas = categorias.map(c => escapar(c.etiqueta));
const porcentajes = n.map(v => percentNumber(100 * v / total));
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
// The pie starts at noon. Keep each callout on its slice's side and order the rows vertically,
// so even several adjacent slivers get separate labels and their guide lines keep the same order.
let acumulado = 0;
const puntos = n.flatMap((valor, i) => {
const angulo = 2 * Math.PI * (acumulado + valor / 2) / total;
acumulado += valor;
if (!valor) return [];
const x = radio * Math.sin(angulo), y = radio * Math.cos(angulo);
return [{ i, x, y }];
});
const lado = (l: string) => llamadas.some(a => a.lado === l) ? MARGEN_ROTULO : 10;
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((_, i) => dibujadas(i) ? escapar(m.examenes[i].etiqueta) + '<br>' + porcentaje(i) : ''),
domain: { x: [0, 1], y: [.05, .95] },
customdata: n.map(v => [miles(v), percentNumber(100 * v / total)]),
hovertemplate: `%{label}<br>%{customdata[0]} ${par.unidades.examenes}, %{customdata[1]} %<extra></extra>` }],
layout: { autosize: true, height: compacta ? ALTO_DONA + 40 : ALTO_DONA, showlegend: compacta, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_VERTICAL, b: compacta ? 70 : MARGEN_VERTICAL, l: lado('l'), r: lado('r') },
...(compacta ? { legend: { orientation: 'h', x: .5, xanchor: 'center', y: -.02, yanchor: 'top', font: { size: 12 } } } : {}),
annotations: [{ x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false, font: { size: 18, color: p.text },
text: `<b>${miles(total)}</b><br>${par.unidades.examenes}` }, ...llamadas.map(({ lado: _lado, ...a }) => a)] }, config: { displayModeBar: false } };
const llamadas = [-1, 1].flatMap(lado => {
const columna = puntos.filter(punto => (punto.x < 0 ? -1 : 1) === lado).sort((a, b) => b.y - a.y);
return columna.map(({ i, x, y }, fila) => {
const altura = (columna.length - 1 - 2 * fila) * 24;
const texto = etiquetas[i].replace(' (sin subcategoría)', '<br>(sin<br>subcategoría)');
return {
annotation: { ...centro, xshift: lado * (radio + 10), yshift: altura,
xanchor: lado < 0 ? 'right' : 'left', align: lado < 0 ? 'right' : 'left',
font: { size: fuenteEtiqueta, color: p.text }, text: texto + '<br>' + porcentajes[i] + ' %' },
shape: { type: 'path', xref: 'paper', yref: 'paper', xsizemode: 'pixel', ysizemode: 'pixel',
xanchor: .5, yanchor: .5, line: { color: p.text, width: 1 },
path: 'M ' + Math.round(x) + ',' + Math.round(y) + ' L ' + lado * (radio + 3) + ',' + y + ' L ' + lado * (radio + 8) + ',' + altura },
};
});
});
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
hovertemplate: '%{value}<extra></extra>' }],
layout: { autosize: true, height: ALTO_DONA, showlegend: false, paper_bgcolor: p.background, font: { color: p.text },
margin: { t: MARGEN_DONA, b: MARGEN_DONA, l: MARGEN_DONA, r: MARGEN_DONA },
shapes: llamadas.map(({ shape }) => shape),
annotations: [
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
{ ...centro, yshift: -separacionCentro, font: { size: fuenteUnidad, color: p.text }, text: unidad },
...llamadas.map(({ annotation }) => annotation),
] }, config: { displayModeBar: false } };
}
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
return donaDe(m.examenes, par.unidades.examenes, tema, ancho);
}
/** Patients in the most severe BI-RADS category of the period. Same slices as the exams' donut; no ratio. */
export function donaPacientes(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
return donaDe(m.pacientes, par.unidades.pacientes, tema, ancho);
}
/** 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 nombres = { pacientes: `${par.unidades.pacientes} (su categoría más alta)`, 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) => ({
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { basesPorGrupo, c2Theme, paintByGroup } from './indicadores-c2-palette';
import { percentNumber, shareText } from './indicadores-format';
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
@@ -39,10 +39,6 @@ function estado(celdas: Celda[]): Escenario['estado'] {
return 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})`;
@@ -128,9 +124,12 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
if (new Set(orden.values()).size !== orden.size) return fail('Orden de categorías EU7 duplicado.');
// Missing rows remain unavailable. Catalog order is used only for the accessible
// list of missing categories; a partial distribution is never drawn as a donut.
const categorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id],
color: promedio(categorias.filter(c => c.grupo === id).map(c => c.color)) }));
const baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const claves = baseCategorias.map(c => c.grupo);
const bases = basesPorGrupo(claves);
const colores = paintByGroup(claves);
const categorias = baseCategorias.map((c, i) => ({ ...c, color: colores[i] }));
const grupos = [...new Set(categorias.map(c => c.grupo))].map(id => ({ id, etiqueta: nombres[id], color: bases.get(id)! }));
const celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
const totals = porEscenario['totales_estrato'];
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
@@ -9,6 +9,10 @@ import {
import { catalogoValido, datosParams, datosValidos, figuraPeriodos, figuraValida, IndicadoresService, metadatosValidos } from './indicadores.service';
import { AvailablePeriod, IndicadoresPeriodos, periodOrder } from './indicadores-periodos';
import { IndicadoresRequests } from './indicadores-requests';
import {
CAMA_MEASURE_IDS, CATEGORIA_HISTOPATOLOGIA_PAGINA, esMedidaCama, ESTRATO_BIRADS_PAGINA, ETIQUETA_CATEGORIA_NO_DECLARADA, GRUPO_PRINCIPAL_FHIR,
GRUPO_PRINCIPAL_PAGINA, GRUPOS_HISTOPATOLOGIA_PAGINA,
} from './indicadores-cama-fhir';
// The indicator page over the WebApi's FHIR endpoint (`/<domain>/fhir/`): `Measure` for the catalog and the technical
// sheet, `MeasureReport` for the data rows. Everything is mapped into the shapes the page already reads, and checked
@@ -27,7 +31,7 @@ export interface Measure extends Resource {
export interface Report extends Resource {
measure?: string; date?: string; period?: { start: string; end: string }; group?: Group[];
}
interface Categoria { etiqueta: string; color: string | null; grupo: null }
interface Categoria { etiqueta: string; color: string | null; grupo: string | null; gravedad?: number | null }
const MAX_COUNT = 200;
const POPULATION_GROUP: Record<string, string> = {
@@ -35,8 +39,9 @@ const POPULATION_GROUP: Record<string, string> = {
'denominator-exclusion': 'exclusion', 'measure-population-exclusion': 'exclusion', 'measure-observation': 'observacion',
};
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use.
export const indicadorId = (measureId: string) => measureId.replace(/-/g, '_');
// `M21-diagnosticados-con-eeg` <-> `M21_diagnosticados_con_eeg`, the ids the page and its TEA texts use; CaMa's measures
// have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`).
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? measureId.replace(/-/g, '_');
const stratifierCode = (s: Stratifier) => code(Array.isArray(s.code) ? s.code[0] : s.code);
// Age groups travel as `16_23`; the page names them `16-23`.
export const estratoValor = (value: string) => /^\d+_\d+$/.test(value) ? value.replace('_', '-') : value;
@@ -84,13 +89,16 @@ export function indicadorDeMeasure(measure: Measure): Indicador & Record<string,
};
}
// TEA's measures are named by their first segment (`M21`); CaMa's share the domain's, so theirs is the rest (`BIRADS456-PACIENTE`).
const codigoDeFicha = (measureId: string) => esMedidaCama(measureId) ? measureId.slice(measureId.indexOf('-') + 1) : measureId.split('-')[0];
export function metadatosDeMeasure(measure: Measure): IndicadorMetadatos {
const unidad = code(measure.subjectCodeableConcept) ?? null;
return {
id: indicadorId(measure.id ?? ''),
version: measure.version,
descripcion: measure.description ?? null,
ficha: { codigo: (measure.id ?? '').split('-')[0], unidad, definicion: measure.description ?? null },
ficha: { codigo: codigoDeFicha(measure.id ?? ''), unidad, definicion: measure.description ?? null },
unidad,
referencias: [],
poblaciones: (measure.group?.[0]?.population ?? []).map(p => ({
@@ -148,12 +156,67 @@ function stratumValue(stratum: Stratum): string | undefined {
return value === undefined ? undefined : estratoValor(value);
}
// The categories a composition's reports count that its Measure doesn't declare, in order of appearance, with their
// captions. Only CaMa's: its BI-RADS 4 without subcategory is published this way.
function categoriasNoDeclaradas(reports: Report[], declaradas: Record<string, Categoria>): Map<string, string> {
const found = new Map<string, string>();
for (const report of reports) {
for (const stratum of report.group?.flatMap(g => g.stratifier?.[0]?.stratum ?? []) ?? []) {
const categoria = code(stratum.value);
if (!categoria || Object.hasOwn(declaradas, categoria) || found.has(categoria) || !(stratum.population?.[0]?.count)) continue;
found.set(categoria, ETIQUETA_CATEGORIA_NO_DECLARADA[categoria] ?? display(stratum.value) ?? categoria);
}
}
return found;
}
// The cross of the two stratifiers of CaMa's histopathological result (BI-RADS by biopsy grade) in one report, in the
// page's codes. FHIR publishes only the cells that have patients; the report is complete, so a cell it doesn't list is
// zero. A code the correspondence tables don't know, or cells that don't add up to the report's units, is an error.
function cruceDeHistopatologia(group: Group, estrato: string): Map<string, number> {
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
const unidades = count(group.population, 'initial-population');
// A report with no units has no cell to cross: it is a published matrix of zeros, not a missing stratifier.
if (!stratifier && unidades === 0) return new Map();
if (!stratifier) throw new Error('Dimensión no admitida');
const celdas = new Map<string, number>();
for (const stratum of stratifier.stratum ?? []) {
const bi = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
const e = ESTRATO_BIRADS_PAGINA[code(bi?.value) ?? ''], c = CATEGORIA_HISTOPATOLOGIA_PAGINA[code(cat?.value) ?? ''];
if (!e || !c) throw new Error('Código de histopatología no reconocido');
const clave = `${e}|${c.id}`;
celdas.set(clave, (celdas.get(clave) ?? 0) + (stratum.population?.[0]?.count ?? 0));
}
if (unidades !== null && [...celdas.values()].reduce((sum, n) => sum + n, 0) !== unidades) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
return celdas;
}
// The `/datos` answer for `measure`, from one report per period.
export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoPeriodo, scope: DatosScope = {}): IndicadorDatos {
const kind = contrato(measure), cats = categorias(measure), estrato = scope.estrato;
const kind = contrato(measure), estrato = scope.estrato, cama = esMedidaCama(measure.id);
const declaradas = categorias(measure);
const extras = kind === 'C2' && cama ? categoriasNoDeclaradas(reports, declaradas) : new Map<string, string>();
// The histopathological result by BI-RADS asked by its stratum is read as a matrix of the page's codes (see above).
const cruzado = kind === 'C2' && estrato !== undefined && CAMA_MEASURE_IDS[measure.id ?? ''] === 'cama_histopatologia_birads';
const cats: Record<string, Categoria> = cruzado
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
if (!m) throw new Error('Categoría de histopatología no reconocida');
return [m.id, { ...c, grupo: m.grupo, gravedad: m.gravedad }];
}))
: { ...declaradas,
...Object.fromEntries([...extras].map(([categoria, etiqueta]) => [categoria, { etiqueta, color: null, grupo: null }])) };
const totales: Record<string, unknown>[] = [];
// CaMa's page names the primary group of a proportion `total`; the WebApi names it `principal`.
const nombre = (codigo: string | undefined) => {
const grupo = codigo ?? 'TOTAL';
return cama && kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = code(g.code) ?? 'TOTAL';
return [id, id === 'TOTAL' ? 'Total' : display(g.code) ?? id];
const id = nombre(code(g.code));
return [id, id === 'TOTAL' || id === GRUPO_PRINCIPAL_PAGINA ? 'Total' : display(g.code) ?? id];
}));
const valores = new Map<string, string>();
const filas: Record<string, unknown>[] = [];
@@ -163,9 +226,29 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
const periodo = periodLabel(report.period);
periodos.push(periodo);
for (const group of report.group ?? []) {
const grupo = code(group.code) ?? 'TOTAL';
const grupo = nombre(code(group.code));
if (cruzado) {
const celdas = cruceDeHistopatologia(group, estrato!);
Object.values(ESTRATO_BIRADS_PAGINA).forEach(e => {
let total = 0;
Object.keys(cats).forEach((categoria, orden) => {
const n = celdas.get(`${e}|${categoria}`) ?? 0;
total += n;
filas.push({ periodo, grupo, estrato: e, categoria, n, orden, suprimido: 0 });
});
totales.push({ periodo, grupo, estrato: e, n: total, suprimido: 0 });
valores.set(e, e);
});
continue;
}
if (kind === 'C2') {
const counts = new Map((group.stratifier?.[0]?.stratum ?? []).map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
const strata = group.stratifier?.[0]?.stratum ?? [];
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
// A report whose categories don't add up to its units can't be drawn as a partition; say so, don't undercount.
const units = count(group.population, 'initial-population');
if (cama && units !== null && [...counts.values()].reduce((sum, n) => sum + n, 0) !== units) {
throw new Error('Los conteos por categoría no suman las unidades del periodo');
}
Object.keys(cats).forEach((categoria, orden) =>
filas.push({ periodo, grupo, estrato: null, categoria, n: counts.get(categoria) ?? 0, orden, suprimido: 0 }));
continue;
@@ -196,10 +279,11 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
tipo_periodo: tipo,
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: Object.fromEntries(valores) } : { valores_estrato: [] }),
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado ? { totales_estrato: totales } : {}),
grupos,
categorias: cats,
grupos_de_categoria: {},
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
notas: [],
reportes: reports.filter(r => r.period).map(r => reporte(r, periodLabel(r.period!))),
filas,
@@ -1,6 +1,8 @@
// Presentation labels for representations confirmed in the published catalog.
// Exact IDs remain the option values and HTTP identities; never infer a type
// from a prefix. Unknown options keep a neutral label in publication order.
export const TITULO_MASTOGRAFIAS_CAMA = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
const FIGURE_LABELS: Readonly<Record<string, string>> = {
fig_c1_barras_alteracion: 'Barras por alteración',
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
@@ -58,8 +58,7 @@ describe('D.2 integración de autoridad global y consumidores', () => {
load(undefined, domain);
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
expect(sections[0].textContent).toContain(domain === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + page.domainLabels[domain]);
if (domain === 'cama') expect(sections[0].textContent).not.toContain('Filtros generales de ');
expect(sections[0].querySelector('#global-filters-title')!.textContent!.trim()).toBe('Filtros');
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
expect(page.filters!.applied.selection.mode).toBe('todos');
@@ -11,6 +11,7 @@ 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 { C2_PALETTE } from './indicadores-c2-palette';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
@@ -21,7 +22,7 @@ import { clicHistopatologia, donaHistopatologia, estadoTasa, figuraTasas, Histop
periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
@Component({ selector: 'app-plotly-chart', template: '' })
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); plotClick = output<unknown>(); }
class ChartStub { figure = input<unknown>(); label = input<string>(); showNotes = input<boolean>(); animated = input<boolean>(); plotClick = output<unknown>(); }
const estrato = () => structuredClone(estratoFixture) as unknown as IndicadorDatos & { filas: Record<string, any>[]; totales_estrato: Record<string, any>[]; valores_estrato: string[]; categorias: Record<string, any> };
const fila = (d: { filas: Record<string, any>[] }, e: string, c: string) => d.filas.find(f => f['estrato'] === e && f['categoria'] === c)!;
@@ -34,7 +35,10 @@ describe('Histopatología por BI-RADS: modelo', () => {
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.categorias.map(c => c.color)).toEqual([C2_PALETTE.frios[0], C2_PALETTE.frios[4], C2_PALETTE.calidos[1], C2_PALETTE.calidos[2]]);
expect(m.grupos.map(g => g.color)).toEqual([C2_PALETTE.frios[3], C2_PALETTE.calidos[0]]);
const tasas = figuraTasas(m, seleccionBase(m), 'claro');
expect((tasas.data[0]['marker'] as { color: string[] }).color).toEqual([...C2_PALETTE.calidos]);
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');
@@ -192,15 +196,21 @@ describe('Histopatología por BI-RADS: tasas, selección y figuras', () => {
expect((estrecho.layout['xaxis'] as { title: { text: string }; nticks: number })).toMatchObject({ title: { text: 'Porcentaje' }, nticks: 3 });
expect((ancho.layout['yaxis'] as Record<string, unknown>)['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»', () => {
it('dona de dos anillos: grupos dentro, categorías fuera; la selección agranda el trozo sin cambiar el color 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.map(t => t['name'])).toEqual(['centro', 'grupos', 'categorias', 'grupos', 'categorias']);
expect(d.data[1]['values']).toEqual([12, 13]); expect(d.data[2]['values']).toEqual([7, 5, 6, 7]);
expect(d.data[4]['values']).toEqual(d.data[2]['values']);
expect(d.data[0]['text']).toEqual(['<b>13</b><br>de 25 con resultado']);
expect((d.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color));
expect((d.data[4]['marker'] as { colors: string[] }).colors).toEqual(['rgba(0,0,0,0)', 'rgba(0,0,0,0)', m.categorias[2].color, m.categorias[3].color]);
const baseSpan = ((d.data[2]['domain'] as { x: number[] }).x[1] - (d.data[2]['domain'] as { x: number[] }).x[0]);
const zoomSpan = ((d.data[4]['domain'] as { x: number[] }).x[1] - (d.data[4]['domain'] as { x: number[] }).x[0]);
expect(zoomSpan).toBeGreaterThan(baseSpan);
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[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color));
expect((otra.data[4]['marker'] as { colors: string[] }).colors[1]).toBe(m.categorias[1].color);
expect(otra.data[0]['text']).toEqual(['<b>5</b><br>de 25 con resultado']);
});
it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => {
@@ -231,7 +241,7 @@ describe('Histopatología por BI-RADS: componente', () => {
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
r.flush(body as Record<string, unknown>); f.detectChanges();
}
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
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();
@@ -240,9 +250,22 @@ describe('Histopatología por BI-RADS: componente', () => {
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');
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']);
@@ -255,16 +278,17 @@ describe('Histopatología por BI-RADS: componente', () => {
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);
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(volver().disabled).toBe(false);
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de 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' });
volver().click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
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();
@@ -278,7 +302,7 @@ describe('Histopatología por BI-RADS: componente', () => {
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');
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');
});
@@ -288,7 +312,7 @@ describe('Histopatología por BI-RADS: componente', () => {
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');
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 = [];
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme } from './indicadores-c2-palette';
import { C2_PALETTE, c2Color, c2Theme, tonoDe } from './indicadores-c2-palette';
import { Celda, wilson } from './indicadores-confirmacion-citologia';
import { percentNumber, shareText } from './indicadores-format';
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
@@ -21,6 +21,7 @@ const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
// 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;
const OBLIGATORIAS: readonly string[] = ['BENIGNO', 'IN_SITU', 'INVASOR'];
// 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' },
@@ -30,6 +31,11 @@ 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';
// Chosen from the logo scheme: cool for a normal result, warm for an abnormal one, each slice a different hue.
const COLOR_RESULTADO: Readonly<Record<string, string>> = {
BENIGNO: C2_PALETTE.frios[0], RIESGO_B3: C2_PALETTE.frios[4], IN_SITU: C2_PALETTE.calidos[1], INVASOR: C2_PALETTE.calidos[2],
};
const COLOR_GRUPO: Readonly<Record<string, string>> = { NO_MALIGNO: C2_PALETTE.frios[3], MALIGNO: C2_PALETTE.calidos[0] };
export interface Categoria { id: string; etiqueta: string; color: string; grupo: string; }
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
@@ -76,9 +82,16 @@ 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})`;
const ZOOM_GRUPO = 1.12;
const ZOOM_HIJO = 1.08;
const ZOOM_ELEGIDO = 1.16;
const ZOOM_PADRE = 1.06;
const CAJA_GRUPO = [0.2, 0.8, 0.2, 0.8] as const;
const CAJA_CATEGORIA = [0.1, 0.9, 0.1, 0.9] as const;
function caja(base: readonly [number, number, number, number], zoom: number) {
const [x0, x1, y0, y1] = base;
const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, hx = (x1 - x0) / 2 * zoom, hy = (y1 - y0) / 2 * zoom;
return { x: [cx - hx, cx + hx], y: [cy - hy, cy + hy] };
}
/** Validated periods of one stratified response, in request order or sorted. */
@@ -100,18 +113,26 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
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))) {
// The risk lesion (B3) is only published by a source that has it: the others have to be there.
if (Object.keys(cats).some(id => !conocidas.includes(id)) || OBLIGATORIAS.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 curso = { frio: 0, calido: 0, neutro: 0 };
const categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).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 publicado = (c['color'] as string | null | undefined) ?? COLOR_RESPALDO;
const tono = tonoDe(c['grupo']) === 'neutro' ? tonoDe(c['etiqueta']) : tonoDe(c['grupo']);
const asignado = c['color'] == null ? c2Color(publicado, curso[tono]++, tono) : COLOR_RESULTADO[id] ?? c2Color(publicado, curso[tono]++, tono);
return { id, etiqueta: c['etiqueta'], color: asignado, 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) };
const etiqueta = id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : etiquetaGrupo(nombres[id])!;
const tono = tonoDe(id) === 'neutro' ? tonoDe(etiqueta) : tonoDe(id);
const color = COLOR_GRUPO[id] ?? (tono === 'calido' ? '#C24269' : tono === 'frio' ? '#42C29C' : promedio(propias.map(c => c.color)));
return { id, etiqueta, 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;
@@ -210,11 +231,14 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
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 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]);
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,
marker: { size: 12, color: colores }, cliponaxis: false,
error_x: { type: 'data', symmetric: false, color: 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}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
@@ -232,7 +256,7 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
}, config: { displayModeBar: false } };
}
/** Donut on the right: result groups inside, categories outside; selection dims, values stay. Empty over an incomplete matrix. */
/** Donut on the right: groups inside, categories outside. Selection zooms those slices; colours stay. */
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;
@@ -242,16 +266,30 @@ export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes con resultado, %{customdata[1]}<extra></extra>' };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
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 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)),
marker: { colors: tinta(colores, zoom), line: { color: 'rgba(0,0,0,0)', width: 0 } },
});
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.34, .66], y: [.34, .66] }, textinfo: 'text', textposition: 'inside',
text: [`<b>${miles(k)}</b><br>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) + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
{ ...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 => 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] },
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 => 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 } },
marker: { colors: m.categorias.map(c => c.color), line: { color: p.background, width: 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)),
], 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 } };
}
@@ -46,7 +46,7 @@ describe('Histórico de CaMa', () => {
}
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) {
function responder(fallo?: (r: TestRequest) => boolean, sinDatos?: (periodo: string) => boolean) {
const vistos: string[] = [];
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
for (const r of ola) {
@@ -56,7 +56,9 @@ describe('Histórico de CaMa', () => {
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));
const d = datos(id, entrada.contrato, periodos[0].includes('S') ? 'semestre' : 'mes', periodos);
if (sinDatos) d.filas = d.filas.filter(fila => !sinDatos(fila.periodo));
r.flush(d);
}
}
fixture.detectChanges();
@@ -77,14 +79,41 @@ describe('Histórico de CaMa', () => {
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', () => {
it('dibuja siete paneles en orden, cinco con gráfica y dos pendientes', () => {
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(pendientes).toEqual(['Resultado histopatológico', 'Días del resultado de la mastografía al diagnóstico']);
expect(paneles()).toHaveLength(7);
const titulo = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6';
expect(paneles()[2].querySelector('h2')?.textContent).toBe(titulo);
expect(graficas().some(g => g.label?.startsWith('Histórico de ' + titulo))).toBe(true);
expect(graficas()).toHaveLength(5);
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
});
it('los periodos sin dato van en una sección plegable cerrada, con una etiqueta breve, y al abrirla salen completos', () => {
// Pins down: a chart with months without data keeps its figure and its caption and puts the list of those months in a
// closed disclosure labelled «Periodos sin dato (n)»; opening it shows every month, as the note read before. Fails if the
// list is open from the start, is cut short, or the figure changes.
montar(CATALOGO, true); responder(undefined, periodo => !['2025-01', '2025-02'].includes(periodo));
const panel = paneles()[1];
const plegable = panel.querySelector<HTMLDetailsElement>('details[data-plegable="sin-dato"]')!;
expect(plegable).not.toBeNull();
expect(plegable.open).toBe(false);
expect(plegable.querySelector('summary')!.textContent!.trim()).toBe('Periodos sin dato (5)');
expect(plegable.querySelector('p')!.textContent).toMatch(/Sin dato: .*mar 2025.*abr 2025.*may 2025.*jun 2025.*jul 2025./);
expect(panel.querySelector('app-plotly-chart')).not.toBeNull();
expect(panel.querySelector('.nota')).toBeNull();
expect(panel.textContent).not.toContain('Cada barra es el total de pacientes');
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
fixture.detectChanges();
expect(plegable.open).toBe(true);
});
it('un panel sin periodos sin dato no muestra la sección', () => {
// Fails if an empty disclosure appears where every period has data.
montar(CATALOGO, true); responder();
expect(root().querySelector('details[data-plegable="sin-dato"]')).toBeNull();
});
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');
@@ -1,6 +1,7 @@
// 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/<id>/datos.
import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures';
import { C2_PALETTE } from './indicadores-c2-palette';
import { IndicadorDatos } from './indicadores.models';
type Fig = { data: Record<string, unknown>[]; layout: Record<string, unknown> };
@@ -76,7 +77,7 @@ describe('Histórico: C2 (conteos por categoría)', () => {
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]['marker'] as { color: string }).color).toBe(C2_PALETTE.calidos[0]);
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');
@@ -86,6 +87,12 @@ describe('Histórico: C2 (conteos por categoría)', () => {
expect((r.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
expect(r.comoLeer).toContain('mastografías');
});
it('Pacientes evaluadas con BI-RADS 4, 5 o 6 conserva la gráfica y omite la explicación de la barra', () => {
const pacientes = figura(d(completo, { id: 'cama_birads_456_paciente' }));
expect(pacientes.comoLeer).toBe('');
expect((pacientes.figure as unknown as Fig).data.map(t => t['name'])).toEqual(['BI-RADS 5', 'BI-RADS 4 (sin subcategoría)', 'Sin dato']);
expect(figura(d(completo)).comoLeer).toContain('Cada barra es el total de pacientes');
});
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);
@@ -1,5 +1,5 @@
import { filasDelGrupo, IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Color, c2Theme, C2_PALETTE } from './indicadores-c2-palette';
import { c2Color, c2Theme, C2_PALETTE, tonoDe } from './indicadores-c2-palette';
import { sortedPeriods } from './indicadores-periodos';
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
@@ -14,6 +14,9 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
const escape = (v: string) => v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
// CaMa's lines share one purple; the quartile or confidence band, when there is one, is the same blue.
const MORADO = { claro: '#9C42C2', oscuro: '#D2A4EA' } as const;
const FONDO_AZUL = '#9DBFE380';
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();
@@ -56,7 +59,7 @@ function ejes(data: IndicadorDatos, periodos: string[], suprimidos: string[], te
};
}
// 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) {
function banda(periodos: string[], bajo: (number | null)[], alto: (number | null)[], name: string, color: string, fillcolor = color + '40') {
const x: (string | null)[] = [], y: (number | null)[] = [];
let run: number[] = [];
const cerrar = () => {
@@ -69,7 +72,7 @@ function banda(periodos: string[], bajo: (number | null)[], alto: (number | null
};
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' };
return { type: 'scatter', mode: 'lines', name, x, y, fill: 'toself', fillcolor, 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<string, unknown>) => boolean) {
@@ -86,17 +89,24 @@ function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<str
return { validas, suprimidos, sinDato };
}
const campo = (filas: (Record<string, unknown> | null)[], key: string) => filas.map(row => numero(row?.[key]) ? row![key] as number : null);
// CaMa's line charts share the purple mark. A band, when the series has one, is blue; a line alone stays purple.
function colorDeLinea(id: string, tema: Tema) {
if (LINEAS[id]) return { linea: LINEAS[id], relleno: LINEAS[id] + '40' };
if (id.startsWith('cama_')) return { linea: MORADO[tema], relleno: FONDO_AZUL };
const linea = c2Theme(tema).line;
return { linea, relleno: linea + '40' };
}
type Trazo = Omit<HistoricoFigura, 'contrato'>;
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 = LINEAS[data.id] ?? c2Theme(tema).line;
const layout = ejes(data, periodos, suprimidos, tema, 'Porcentaje'), trazo = colorDeLinea(data.id, tema);
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 },
banda(periodos.map(etiquetaPeriodo), campo(validas, 'ic_bajo'), campo(validas, 'ic_alto'), 'Intervalo de confianza', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Porcentaje', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'valor'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `${row['valor']} %<br>${row['numerador']} de ${row['denominador']}<br>IC ${row['ic_bajo']} a ${row['ic_alto']} %` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: { ...layout, yaxis: { ...layout.yaxis, range: [0, 100], ticksuffix: ' %' } } },
@@ -107,10 +117,11 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): 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 trazo = colorDeLinea(data.id, tema);
return {
figure: { data: [
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 },
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', trazo.linea, trazo.relleno),
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: trazo.linea, width: 2 }, marker: { color: trazo.linea },
text: validas.map(row => row ? `Mediana: ${row['mediana']} días<br>Q1 a Q3: ${row['q1']} a ${row['q3']} días<br>${row['n']} ${unidad.plural}` : ''),
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
], layout: (() => {
@@ -141,15 +152,19 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
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'])));
const curso = { frio: 0, calido: 0, neutro: 0 };
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 tono = tonoDe(typeof meta['grupo'] === 'string' ? meta['grupo'] : id);
const slot = tono === 'neutro' ? i : curso[tono]++;
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}<extra>%{fullData.name}</extra>' };
marker: { color: c2Color(color, slot, tono) }, hovertemplate: '%{y}<extra>%{fullData.name}</extra>' };
}), layout: { ...ejes(data, periodos, suprimidos, tema, CONTEOS[data.id]?.eje ?? unidad.eje), barmode: 'stack', bargap: .15, hovermode: 'x unified' } },
comoLeer: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
comoLeer: data.id === 'cama_birads_456_paciente' ? ''
: CONTEOS[data.id]?.comoLeer ?? `Cada barra es el total de ${unidad.plural} del periodo, y sus partes muestran cuántas hay en cada categoría.`,
suprimidos, sinDato,
};
}
@@ -28,10 +28,15 @@ describe('Pestaña Histórico', () => {
http.match(() => true);
}
it('CaMa: Resumen, Histórico, Análisis epidemiológico, Seguimiento y Datos y definiciones, en ese orden', () => {
it('CaMa oculta Análisis y conserva Histórico y Análisis de Riesgos', () => {
abrir('cama', [item('cama_eu38a', 'C3r')]);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis epidemiológico', 'Seguimiento', 'Datos y definiciones']);
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
fixture.componentInstance.changeSection('analisis');
fixture.detectChanges();
expect(fixture.componentInstance.activeSection()).toBe('resumen');
expect(root().querySelector('#panel-analisis')).toBeNull();
http.expectNone(request => request.url.startsWith('/cama/analisis'));
});
it('cacu no tiene la pestaña Histórico', () => {
// Fails if the history tab of TEA or CaMa leaks into CaCu.
@@ -63,6 +63,20 @@ describe('Figuras de histórico', () => {
expect(traza(data, 0).y).toEqual([30, 10]);
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
});
it('las líneas de CaMa comparten el morado y, si hay banda, el fondo azul', () => {
const dias = (id: string, tema: 'claro' | 'oscuro') => {
const figure = historicoFigura({ ...base, id, contrato: 'C3r', filas: [{ periodo: '2024-01', suprimido: 0, n: 9, mediana: 20, q1: 10, q3: 30 }] }, tema).figure;
return { linea: (figure.data[1]['line'] as { color: string }).color, puntos: (figure.data[1]['marker'] as { color: string }).color, banda: figure.data[0]['fillcolor'] };
};
for (const id of ['cama_dias_toma_diagnostico', 'cama_eu38a', 'cama_dias_resultado_diagnostico']) {
expect(dias(id, 'claro')).toEqual({ linea: '#9C42C2', puntos: '#9C42C2', banda: '#9DBFE380' });
}
expect(dias('cama_dias_toma_diagnostico', 'oscuro')).toEqual({ linea: '#D2A4EA', puntos: '#D2A4EA', banda: '#9DBFE380' });
const tasa = historicoFigura({ ...base, id: 'cama_confirmacion_birads45', contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) }, 'claro').figure;
expect((tasa.data[1]['line'] as { color: string }).color).toBe('#9C42C2');
expect((tasa.data[1]['marker'] as { color: string }).color).toBe('#9C42C2');
expect(tasa.data[0]['fillcolor']).toBe('#9DBFE380');
});
it('las líneas usan el verde legible en cada tema', () => {
const data: IndicadorDatos = { ...base, contrato: 'C1', filas: base.periodos.map(p => c1(p, 50)) };
const color = (tema: 'claro' | 'oscuro') => (historicoFigura(data, tema).figure.data[1]['line'] as { color: string }).color;
@@ -14,6 +14,7 @@ import { IndicadoresHistoricoPeriodos, PeriodosDialogoDatos } from './indicadore
import { IndicadoresPeriodos } from './indicadores-periodos';
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
import { IndicadoresService } from './indicadores.service';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
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 };
@@ -26,14 +27,13 @@ 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_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ 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' },
];
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
@@ -62,19 +62,24 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
selector: 'app-indicadores-historico',
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
template: `
<div class="controles">
<span id="historico-intervalo">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
<div class="controles" [class.compacto]="dominio() === 'cama'">
<h2>Filtros</h2>
<div class="controles-fila">
<div class="interval">
<span id="historico-intervalo" class="field-label">Intervalo de análisis</span>
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
</mat-button-toggle-group>
</div>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>Periodos a mostrar</mat-label>
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
</mat-select>
</mat-form-field>
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
</div>
</div>
<div class="paneles">
@for (panel of paneles(); track panel.item.id) {
@@ -102,14 +107,19 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
}
<p class="nota">{{ panel.figura.comoLeer }}</p>
@if (panel.figura.comoLeer) { <p class="nota">{{ panel.figura.comoLeer }}</p> }
@if (panel.figura.suprimidos.length) {
<details class="nota-pie">
<summary>Datos suprimidos</summary>
<p>Datos suprimidos, sombreados en la figura: {{ panel.figura.suprimidos.join(', ') }}. @if (panel.item.contrato === 'C2') {El total de esos periodos está incompleto.}</p>
</details>
}
@if (panel.figura.sinDato.length) { <p class="nota">Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p> }
@if (panel.figura.sinDato.length) {
<details class="nota-pie" data-plegable="sin-dato">
<summary>Periodos sin dato ({{ panel.figura.sinDato.length }})</summary>
<p>Sin dato: {{ panel.figura.sinDato.join(', ') }}.</p>
</details>
}
}
}
</article>
@@ -117,9 +127,26 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
</div>
`,
styles: `
@use '@angular/material' as mat;
: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);
.controles { display: flex; flex-direction: column; align-items: stretch; 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); }
.controles h2 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
// Same field height as the summary filters. The theme also rewrites corners, which would turn the switch into a pill.
.controles.compacto {
@include mat.theme((density: -4));
--mat-sys-corner-extra-small: 2px;
--mat-sys-corner-small: 2px;
--mat-sys-corner-medium: 4px;
--mat-sys-corner-large: 4px;
--mat-sys-corner-extra-large: 6px;
--mat-sys-corner-full: 4px;
}
.controles-fila { display: flex; flex-wrap: wrap; align-items: end; gap: var(--issste-space-3); }
.interval { display: flex; flex-direction: column; align-items: flex-start; gap: .35rem; }
.interval mat-button-toggle-group { --mat-button-toggle-height: 40px; --mat-button-toggle-shape: 6px; }
.field-label { color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.2; }
.paneles { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
@container dashboard (min-width: 1304px) { .paneles { 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);
@@ -136,7 +163,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
.pasos { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-4); margin-top: var(--issste-space-3); }
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
h3 { margin: 0; font: var(--mat-sys-title-small); }
mat-form-field { min-width: 18rem; }
mat-form-field { flex: 0 1 14rem; min-width: 0; max-width: 24rem; }
`,
})
export class IndicadoresHistorico {
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
} else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
+13 -10
View File
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
};
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
id: 'cama_eu38a', title: 'Tiempo de mastografía a resultado', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
id: 'cama_eu38a', title: 'Tiempo de toma de mastografía a interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
};
// Institutional definitions retained for consumers outside the opportunity strip.
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
@@ -24,11 +24,11 @@ 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: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
c1Info: (n, d) => `${n} de ${d} biopsias con riesgo a carcinoma.`,
};
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de resultado a diagnóstico', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
id: 'cama_dias_resultado_diagnostico', title: 'Tiempo de interpretación radiológica 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
@@ -58,14 +58,14 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
],
cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
CAMA_TAMIZAJE_RESULTADO_KPI,
],
};
// 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.
// CaMa's four opportunity cards, in display order. Two of them have no measure in the FHIR catalog yet
// (`cama_tasa_deteccion_histopatologica` and `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,
@@ -83,8 +83,11 @@ export function camaKpiCards(published: (id: string) => boolean): KpiCardSlot[]
// 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.
// 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'];
// `cama_birads` is replaced by the exams' and patients' counts, and `cama_birads_cancer_invasor` is the
// epidemiological analysis' measure: neither has a card of its own.
export const CAMA_FUERA_DEL_RESUMEN: readonly string[] = ['cama_biopsias', 'cama_birads', 'cama_birads_cancer_invasor',
'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<Dominio, string> = { tea: 'TOTAL', cacu: 'total', cama: 'total' };

Some files were not shown because too many files have changed in this diff Show More