Compare commits

..

34 Commits

Author SHA1 Message Date
edgar e5aa205662 fix(indicadores): draw CaCu's proportions in the history
The WebApi names the group of a proportion `principal`; the page read it as `total` only for CaMa, so the EU13 and
IND1 trends of CaCu came out empty. The rename now applies to every domain, and IND1 is listed in CaCu's history under
the id the catalog gives it.
2026-11-21 21:48:42 -06:00
edgar 89f3d41e0c feat(indicadores): add the Histórico tab to CaCu
CaCu's history is a fixed list, like CaMa's, with a pending panel for each indicator the catalog does not publish.
The risk bands stay out until their batches are readable.
2026-11-21 17:54:23 -06:00
edgar 2e9dd39cf1 fix(indicadores): read a proportion's interval as percentages
The ic-bajo and ic-alto of a proportion's score travel as proportions; the rows hold percentages, like the value,
so the history trend draws its confidence band on the same axis.
2026-11-21 17:42:02 -06:00
Angel Capetillo Zavala bb957ec6a4 fix(indicadores): format the hover text of CaCu's donuts per sector 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 02e28e624b feat(indicadores): read CaCu category groups and stratified compositions from FHIR 2026-11-21 01:29:18 -06:00
Angel Capetillo Zavala 08161db1c4 feat(indicadores): map CaCu measures to the indicator ids the page reads 2026-11-21 01:27:59 -06:00
AlbertoPMDM ef4f606648 fix(tea): one card per EEG metric and the electrode map within its column
(cherry picked from commit b53322ed72)
2026-11-20 21:56:05 -06:00
Manuel Aurrecoechea Castillo c32d2b6012 feat(indicadores): show full domain names and share CaMa's summary
CaCu and TEA use the same menu labels and compact summary layout as cáncer de mama.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-20 19:28:27 -06:00
Angel Capetillo Zavala c2c6d9ef47 Merge feature/tea-eeg-analysis into dev (TEA candidate composition) 2026-11-20 14:44:48 -06:00
angel d4d3ea3837 Merge pull request 'Restore published CaMa histopathology and mammography counts' (#14) from fix/cama-reversion-selectiva into dev 2026-11-20 10:03:41 -06:00
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
AlbertoPMDM 04795a09cc feat(tea): read the EEG analysis's verdict, quality checks and age baselines 2026-11-19 15:43:27 -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
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
119 changed files with 6515 additions and 921 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 717 B

+5 -4
View File
@@ -37,10 +37,11 @@ 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) => {
it.each([['tea', 'Trastorno del espectro autista'], ['cacu', 'Cáncer cervicouterino'], ['cama', 'Cáncer de mama']] as const)('en /indicadores/%s muestra el título de la plataforma y el selector con «%s»', async (dominio, etiqueta) => {
await ir('/indicadores/' + dominio);
expect(root().querySelector('.platform-title')?.textContent).toBe('Plataforma de Indicadores');
expect(selector()?.textContent?.replace(/\s+/g, ' ').trim()).toBe(etiqueta + ' ▾');
@@ -59,7 +60,7 @@ describe('Encabezado del marco', () => {
it('el menú ofrece los otros dos dominios con sus rutas institucionales', async () => {
await ir('/indicadores/cama');
const items = await abrirMenu();
expect(items.map(a => a.textContent?.trim())).toEqual(['TEA', 'CaCu']);
expect(items.map(a => a.textContent?.trim())).toEqual(['Trastorno del espectro autista', 'Cáncer cervicouterino']);
expect(items.map(a => a.getAttribute('href'))).toEqual(['/indicadores/tea', '/indicadores/cacu']);
expect(selector()!.getAttribute('aria-expanded')).toBe('true');
});
@@ -68,7 +69,7 @@ describe('Encabezado del marco', () => {
const items = await abrirMenu();
items[1].click(); await fixture.whenStable(); fixture.detectChanges();
expect(router.url).toBe('/indicadores/cacu');
expect(selector()!.textContent).toContain('CaCu');
expect(selector()!.textContent).toContain('Cáncer cervicouterino');
// The choice is a router navigation (a history entry), not a page reload: going back lands on the previous domain.
const ubicacion = TestBed.inject(Location);
ubicacion.back(); await new Promise(r => setTimeout(r, 100));
+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: '' },
];
+69 -6
View File
@@ -117,12 +117,75 @@
.domain-selector--espera {
align-items: center; border-radius: var(--issste-radius); box-sizing: border-box; display: inline-flex; flex: 0 0 auto;
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
max-width: 100%; background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; line-height: 1.2;
min-height: 40px; padding: 0 16px; white-space: nowrap;
}
// 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; }
.app-shell--indicadores .brand { margin-inline-end: auto; }
.platform-title { order: 3; flex: 1 0 100%; margin: 4px 0 0; font-size: 1.125rem; min-width: 0; }
/* 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;
}
// Full domain names need their own track. On a wide header they sit beside the title;
// below 900px the name takes a row of its own so the logo and the exit stay together.
.app-shell--indicadores .site-header__content {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto auto;
grid-template-areas: "brand title domain salir";
align-items: center;
column-gap: 16px;
row-gap: 8px;
padding-block: 8px;
}
.app-shell--indicadores .brand { grid-area: brand; }
.app-shell--indicadores .platform-title { grid-area: title; margin: 0; overflow-wrap: normal; }
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { grid-area: domain; justify-self: end; }
.app-shell--indicadores .site-header__salir { grid-area: salir; margin-inline-start: 0; }
@media (max-width: 900px) {
.app-shell--indicadores .site-header__content {
grid-template-columns: auto minmax(0, 1fr);
grid-template-areas:
"brand salir"
"domain domain"
"title title";
}
.app-shell--indicadores .domain-selector,
.app-shell--indicadores .domain-selector--espera { justify-self: start; white-space: normal; }
.app-shell--indicadores .platform-title { font-size: 1.125rem; }
}
+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('Cáncer cervicouterino');
});
});
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');
});
});
});
+25 -3
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,13 +33,32 @@ 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' };
protected readonly domainLabels: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
private readonly url = toSignal(this.router.events.pipe(
filter((event) => event instanceof NavigationEnd), map(event => event.urlAfterRedirects)), { initialValue: this.router.url });
/** On an indicators page the header names its domain and switches to the others. */
protected readonly activeDomain = computed(() =>
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
protected readonly otherDomains = computed(() => DOMINIOS.filter(domain => domain !== this.activeDomain()));
/** 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);
@@ -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';
@@ -11,9 +13,9 @@ import { DataConnection, SourceTable } from '../domain/data-source';
import { ImportFlow } from '../domain/import-flow';
export const DOMAINS: { id: Domain; label: string; description: string }[] = [
{ id: 'cacu', label: 'CaCu', description: 'Cáncer cervicouterino' },
{ id: 'cacu', label: 'Cáncer cervicouterino', description: 'Cáncer cervicouterino' },
{ id: 'cama', label: 'Cáncer de mama', description: 'Cáncer de mama' },
{ id: 'tea', label: 'TEA', description: 'Trastorno del espectro autista' },
{ id: 'tea', label: 'Trastorno del espectro autista', description: 'Trastorno del espectro autista' },
];
/**
@@ -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 {
+7
View File
@@ -1,10 +1,17 @@
:host { display: contents; }
.domain-selector {
flex: 0 0 auto;
max-width: 100%;
height: auto;
min-height: 40px;
background-color: var(--issste-accent);
color: var(--issste-text);
font-weight: 700;
line-height: 1.2;
white-space: nowrap;
}
@media (max-width: 900px) {
.domain-selector { white-space: normal; text-align: start; padding-block: 8px; }
}
.domain-selector:hover { background-color: var(--issste-accent); filter: brightness(.94); }
.domain-selector:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
+2 -2
View File
@@ -30,9 +30,9 @@ export function code(concept: Concept | undefined): string | undefined {
export function display(concept: Concept | undefined): string | undefined {
return concept?.coding?.[0]?.display ?? concept?.text;
}
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URL).
// The code of a concept from `system` (a name under the project's CodeSystem base, or a full URI such as a URN).
export function codeIn(concept: Concept | undefined, system: string): string | undefined {
const url = system.includes('://') ? system : CODE_SYSTEM + system;
const url = system.includes(':') ? system : CODE_SYSTEM + system;
return concept?.coding?.find(c => c.system === url)?.code;
}
// The extensions named `name` (the last segment of their URL).
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,8 +1,8 @@
{
"cacu/CACU-CONFIRMACION-CITOLOGIA": {
"id": "CACU_CONFIRMACION_CITOLOGIA",
"id": "cacu_confirmacion_citologia",
"indicador": {
"id": "CACU_CONFIRMACION_CITOLOGIA",
"id": "cacu_confirmacion_citologia",
"version": "0.1.2",
"titulo": "Tasa de confirmación histopatológica",
"contrato": "C2",
@@ -19,7 +19,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_CONFIRMACION_CITOLOGIA",
"id": "cacu_confirmacion_citologia",
"version": "0.1.2",
"descripcion": "De las pacientes cuya última citología del periodo con resultado y calidad de espécimen satisfactoria es de alto grado (ASC-H, LIEAG o carcinoma in situ), cuántas tienen cada grado en la biopsia que esa citología originó, por resultado citológico. A la fecha de corte: sin un plazo máximo, una paciente «sin biopsia aún» puede pasar a un grado mientras lleguen reportes.",
"ficha": {
@@ -41,7 +41,7 @@
},
"datos": {
"total": {
"id": "CACU_CONFIRMACION_CITOLOGIA",
"id": "cacu_confirmacion_citologia",
"titulo": "Tasa de confirmación histopatológica",
"version": "0.1.2",
"contrato": "C2",
@@ -80,51 +80,14 @@
"filas": []
},
"citologia_alto_grado": {
"id": "CACU_CONFIRMACION_CITOLOGIA",
"titulo": "Tasa de confirmación histopatológica",
"version": "0.1.2",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "citologia_alto_grado",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 35,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:24.181623+00:00"
},
{
"periodo": "2025-S2",
"report_id": 44,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:24.682752+00:00"
}
],
"filas": []
"error": "Categoría no declarada en el estrato"
}
}
},
"cacu/CACU-DIAS-TOMA-DIAGNOSTICO": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
"id": "cacu_dias_toma_diagnostico",
"indicador": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
"id": "cacu_dias_toma_diagnostico",
"version": "0.2.3",
"titulo": "Tiempo de tamizaje a diagnóstico",
"contrato": "C3r",
@@ -139,7 +102,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
"id": "cacu_dias_toma_diagnostico",
"version": "0.2.3",
"descripcion": "Días naturales de la toma de cada citología del periodo 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 citologías, sean de tamizaje o no; se excluyen las de pacientes con un diagnóstico de cáncer cervicouterino anterior a la toma.",
"ficha": {
@@ -171,7 +134,7 @@
},
"datos": {
"total": {
"id": "CACU_DIAS_TOMA_DIAGNOSTICO",
"id": "cacu_dias_toma_diagnostico",
"titulo": "Tiempo de tamizaje a diagnóstico",
"version": "0.2.3",
"contrato": "C3r",
@@ -239,9 +202,9 @@
}
},
"cacu/CACU-EU-TIEMPO-REPORTE": {
"id": "CACU_EU_TIEMPO_REPORTE",
"id": "cacu_eu_tiempo_reporte",
"indicador": {
"id": "CACU_EU_TIEMPO_REPORTE",
"id": "cacu_eu_tiempo_reporte",
"version": "0.2.1",
"titulo": "Días de la toma de la citología a su resultado",
"contrato": "C3r",
@@ -256,7 +219,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_EU_TIEMPO_REPORTE",
"id": "cacu_eu_tiempo_reporte",
"version": "0.2.1",
"descripcion": "Días naturales de la toma de cada citología del periodo 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.",
"ficha": {
@@ -288,7 +251,7 @@
},
"datos": {
"total": {
"id": "CACU_EU_TIEMPO_REPORTE",
"id": "cacu_eu_tiempo_reporte",
"titulo": "Días de la toma de la citología a su resultado",
"version": "0.2.1",
"contrato": "C3r",
@@ -356,9 +319,9 @@
}
},
"cacu/CACU-EU13": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"indicador": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"version": "0.3.2",
"titulo": "Tasa de detección histopatológica",
"contrato": "C1",
@@ -376,7 +339,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"version": "0.3.2",
"descripcion": "De todas las mujeres tamizadas en el periodo, las que tienen una biopsia reportada con LIEAG (CIN 2 y 3), carcinoma in situ o carcinoma invasor, originada por una de sus citologías del periodo.",
"ficha": {
@@ -408,7 +371,7 @@
},
"datos": {
"total": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica",
"version": "0.3.2",
"contrato": "C1",
@@ -421,7 +384,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -447,7 +410,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -460,7 +423,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 1,
@@ -474,7 +437,7 @@
]
},
"grupo_edad": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica",
"version": "0.3.2",
"contrato": "C1",
@@ -500,7 +463,7 @@
"<25": "<25"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -526,7 +489,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "25-34",
"suprimido": 0,
"numerador": 0,
@@ -539,7 +502,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "35-44",
"suprimido": 0,
"numerador": 0,
@@ -552,7 +515,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "45-54",
"suprimido": 0,
"numerador": 1,
@@ -565,7 +528,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "55-64",
"suprimido": 0,
"numerador": 0,
@@ -578,7 +541,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "<25",
"suprimido": 0,
"numerador": 0,
@@ -592,7 +555,7 @@
]
},
"estatus_seguimiento": {
"id": "CACU_EU13",
"id": "cacu_eu13",
"titulo": "Tasa de detección histopatológica",
"version": "0.3.2",
"contrato": "C1",
@@ -610,7 +573,7 @@
"PRE_COLPOSCOPIA": "PRE_COLPOSCOPIA"
},
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -636,7 +599,7 @@
"filas": [
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": "PRE_COLPOSCOPIA",
"suprimido": 0,
"numerador": 1,
@@ -652,9 +615,9 @@
}
},
"cacu/CACU-EU7": {
"id": "CACU_EU7",
"id": "cacu_eu7",
"indicador": {
"id": "CACU_EU7",
"id": "cacu_eu7",
"version": "0.3.3",
"titulo": "Distribución de resultados citológicos",
"contrato": "C2",
@@ -672,7 +635,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_EU7",
"id": "cacu_eu7",
"version": "0.3.3",
"descripcion": "Cuántas pacientes caen en cada resultado citológico en el periodo, cada una en el de su última citología con resultado y calidad de espécimen satisfactoria. «Sin dato»: resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.",
"ficha": {
@@ -694,7 +657,7 @@
},
"datos": {
"total": {
"id": "CACU_EU7",
"id": "cacu_eu7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.3",
"contrato": "C2",
@@ -733,91 +696,17 @@
"filas": []
},
"grupo_edad": {
"id": "CACU_EU7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "grupo_edad",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 83,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:29.557925+00:00"
},
{
"periodo": "2025-S2",
"report_id": 92,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:31.081202+00:00"
}
],
"filas": []
"error": "Categoría no declarada en el estrato"
},
"estatus_seguimiento": {
"id": "CACU_EU7",
"titulo": "Distribución de resultados citológicos",
"version": "0.3.3",
"contrato": "C2",
"unidad": "paciente",
"tipo_periodo": "semestre",
"periodos": [
"2021-S1",
"2025-S2"
],
"estrato": "estatus_seguimiento",
"valores_estrato": [],
"etiquetas_estrato": {},
"grupos": {
"TOTAL": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
"notas": [],
"reportes": [
{
"periodo": "2021-S1",
"report_id": 83,
"periodo_inicio": "2021-01-01",
"periodo_fin": "2021-07-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:29.557925+00:00"
},
{
"periodo": "2025-S2",
"report_id": 92,
"periodo_inicio": "2025-07-01",
"periodo_fin": "2026-01-01",
"fecha_corte": "2026-11-16",
"generado_en": "2026-11-16T23:08:31.081202+00:00"
}
],
"filas": []
"error": "Categoría no declarada en el estrato"
}
}
},
"cacu/CACU-RIESGO-BANDA": {
"id": "CACU_RIESGO_BANDA",
"id": "cacu_riesgo_banda",
"indicador": {
"id": "CACU_RIESGO_BANDA",
"id": "cacu_riesgo_banda",
"version": "0.1.0",
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
"contrato": "C2",
@@ -831,7 +720,7 @@
"filtros": []
},
"metadatos": {
"id": "CACU_RIESGO_BANDA",
"id": "cacu_riesgo_banda",
"version": "0.1.0",
"descripcion": "Cuántas pacientes de la cohorte de vigilancia, con citología índice en el periodo, caen en cada banda de riesgo estimado de CIN2+. Cuenta el lote de evaluaciones vigente (confirmado). «Sin dato»: la paciente no tiene evaluación confirmada en ese lote.",
"ficha": {
@@ -853,7 +742,7 @@
},
"datos": {
"total": {
"id": "CACU_RIESGO_BANDA",
"id": "cacu_riesgo_banda",
"titulo": "Pacientes en vigilancia por banda de riesgo de CIN2+",
"version": "0.1.0",
"contrato": "C2",
@@ -894,9 +783,9 @@
}
},
"cacu/IND1": {
"id": "IND1",
"id": "ind1",
"indicador": {
"id": "IND1",
"id": "ind1",
"version": "0.3.2",
"titulo": "Pacientes con citología anómala",
"contrato": "C1",
@@ -911,7 +800,7 @@
"filtros": []
},
"metadatos": {
"id": "IND1",
"id": "ind1",
"version": "0.3.2",
"descripcion": "Proporción de pacientes con citología tomada en el periodo con al menos un resultado anómalo: ASC-US, LIEBG, ASC-H, LIEAG o carcinoma in situ (sistema Bethesda). Una paciente con varias citologías cuenta una vez.",
"ficha": {
@@ -943,7 +832,7 @@
},
"datos": {
"total": {
"id": "IND1",
"id": "ind1",
"titulo": "Pacientes con citología anómala",
"version": "0.3.2",
"contrato": "C1",
@@ -956,7 +845,7 @@
"estrato": null,
"valores_estrato": [],
"grupos": {
"principal": "principal"
"total": "Total"
},
"categorias": {},
"grupos_de_categoria": {},
@@ -982,7 +871,7 @@
"filas": [
{
"periodo": "2021-S1",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 0,
@@ -995,7 +884,7 @@
},
{
"periodo": "2025-S2",
"grupo": "principal",
"grupo": "total",
"estrato": null,
"suprimido": 0,
"numerador": 19,
@@ -36,7 +36,8 @@ describe('UX-06E.D.2.1 selector de representación', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h2').textContent).toBe('EEG con ≥ 20 min de registro');
expect(fixture.nativeElement.querySelector('.indicator-id')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
expect(fixture.nativeElement.querySelector('.catalog-metadata')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
// The internal panel heading is deliberately visually hidden and retains identity.
const copy = fixture.nativeElement.cloneNode(true) as HTMLElement;
copy.querySelectorAll('.visually-hidden').forEach(node => node.remove());
@@ -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">
@@ -133,8 +135,8 @@ export class IndicadorCatalogCard implements OnChanges, OnDestroy {
if (this.indicador && this.applied) untracked(() => this.updateNumeric());
});
}
// CaMa's cards carry no pin, representation selector or figure count, as in the mockup.
get sobrio() { return this.dominio === 'cama'; }
// Every domain follows CaMa's mockup: no pin, representation selector or figure count.
get sobrio() { return true; }
get pair() { return dualFigures(this.indicador); }
get isEu7() { return this.dominio === 'cacu' && this.indicador.id === 'cacu_eu7'; }
get isConfirmacion() { return this.dominio === 'cacu' && this.indicador.id === ID_CONFIRMACION; }
@@ -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!" class="donut-chart" (widthChanged)="ajustarAnchoDona($event)" [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,16 +3,25 @@
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; }
@@ -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,35 +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;
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]);
@@ -65,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();
@@ -111,11 +121,17 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
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.anchoDona);
this.barsFigure = barrasConteos(m, this.par, this.tema);
this.patientsFigure = donaPacientes(m, this.par, this.tema, this.anchoPacientes);
this.changeDetector.markForCheck();
}
ngOnDestroy() { this.subscription?.unsubscribe(); }
@@ -9,7 +9,7 @@ import { describePeriods, filterCompatibility, GlobalApplied } from './indicador
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
import { httpMessage } from './indicadores-http';
import { percentText } from './indicadores-format';
import { stratifiedCapabilities } from './indicadores-stratified';
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje,
periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario';
@@ -101,7 +101,8 @@ export class IndicadorEu7Escenario implements OnChanges, OnDestroy {
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2'
|| !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras')
|| !stratifiedCapabilities(this.indicador).includes(ESTRATO) || !compatibility.compatible) {
|| !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO))
|| !compatibility.compatible) {
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.';
this.status.set('incompatible'); return;
}
@@ -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> }
@@ -32,36 +39,39 @@
@if (model; as m) {
@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">
<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="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>
<div class="figures">
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
@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>
<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>
<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>
</div>
}
<p class="selection-status" role="status" aria-live="polite">{{ m.periodo }}, selección: {{ selectionLabel }}. {{ reading }}</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" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
@@ -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; }
@@ -30,9 +37,9 @@ import { MatCardModule } from '@angular/material/card';
clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.value { font-size: 1.75rem; font-weight: 500; line-height: 1.2; }
.value span { margin-inline-start: .3em; }
// CaMa's cards are as tall as their grid row.
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) mat-card { flex: 1 1 auto; height: auto; }
:host-context(.kpi-section) .value { font-size: 1.65rem; }
`,
})
export class IndicadorKpiCard {
@@ -40,12 +47,18 @@ export class IndicadorKpiCard {
@Input() value?: string | number | null;
@Input() unit?: string;
@Input() temporalReference?: string;
// The 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(' ');
@@ -39,7 +39,8 @@ describe('KPI búsqueda inicial del último dato visible', () => {
latest.flush(data(periods[0], 'suppressed'));
request(periods[1]).flush(data(periods[1])); fixture.detectChanges();
expect(fixture.componentInstance.result().value).toBe(5);
expect(fixture.nativeElement.textContent).toContain('Último dato visible, 2025-S1');
expect(fixture.componentInstance.temporalReference).toBe('Último dato visible, 2025-S1');
expect(fixture.nativeElement.textContent).not.toContain('Último dato visible');
expect(fixture.nativeElement.textContent).toContain('Existen reportes posteriores con datos ocultos por tamaño.');
http.expectNone(() => true);
});
@@ -183,14 +183,18 @@ 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.'),
]));
expect(fixture.nativeElement.querySelector('.kpi-period')?.textContent).toBe('Periodo 2025-S1');
expect(cards.every(card => !card.textContent?.includes('2025-S1'))).toBe(true);
expect(cards.filter(card => card.querySelector('.value')).every(card => card.querySelector('.kpi-state')?.classList.contains('visually-hidden'))).toBe(true);
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,14 +19,15 @@ 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]="true"
[showPeriod]="false" />
@if (result().state === 'Error de consulta') {
<button type="button" mat-stroked-button (click)="retry()" [attr.aria-label]="'Reintentar ' + definition.title">Reintentar consulta</button>
}`,
styles: `
:host { display: block; min-width: 0; }
:host-context(.kpi-section[data-domain='cama']) { display: flex; flex-direction: column; }
:host-context(.kpi-section[data-domain='cama']) app-indicador-kpi-card { flex: 1 1 auto; }
:host-context(.kpi-section) { display: flex; flex-direction: column; }
:host-context(.kpi-section) app-indicador-kpi-card { flex: 1 1 auto; }
`,
})
export class IndicadorKpiPanel implements OnChanges {
@@ -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',
@@ -161,14 +161,16 @@ describe('paleta C2 institucional y semántica', () => {
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', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
expect(seriesColors(['#D98E4A', undefined, undefined])).toEqual(['#D98E4A', C2_PALETTE.series[1], C2_PALETTE.series[2]]);
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(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('#D98E4A');
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();
});
@@ -1,6 +1,6 @@
import { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
import { DonutHierarchy } from './indicadores-donut-drilldown';
import { c2Theme, groupBase, seriesColors } 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 = seriesColors(categories.map(c => c.color));
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) => groupBase(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
@@ -8,19 +8,22 @@ describe('paleta del logo ISSSTELEON', () => {
expect(C2_PALETTE.series[0]).not.toBe(C2_PALETTE.series[1]);
});
it('reemplaza mezclas de partido por entradas distintas y conserva el gris de sin dato', () => {
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
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([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
expect(edad).toBe('#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(groupBase(1));
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]);
});
@@ -34,8 +37,7 @@ describe('paleta del logo ISSSTELEON', () => {
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']).toMatchObject({ color: expect.stringMatching(/^rgba\(\d+,\d+,\d+,0\.4\)$/) });
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
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]);
@@ -43,11 +45,7 @@ describe('paleta del logo ISSSTELEON', () => {
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.slice(2, 4));
expect(new Set([
(figure.data[0]['marker'] as { color: string }).color,
...(figure.layout['colorway'] as string[]),
]).size).toBe(3);
expect(figure.layout['colorway']).toEqual([C2_PALETTE.series[1], '#636efa']);
expect(recolorFigure(figure)).toBe(figure);
});
});
@@ -1,13 +1,16 @@
import { PlotlyFigure, Tema } from './indicadores.models';
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
// Sequential fills (heatmaps) use SCALE, from pale lime to deep teal.
// 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({
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([
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
'#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.
@@ -23,17 +26,56 @@ export function isAgeColor(color: string): boolean {
const key = parseColor(color)?.key;
return !!key && ageKeys.has(key);
}
export function c2Color(published: string | undefined, index: number): string {
// A published swatch stays. The series only fills a category that arrived without one.
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
return C2_PALETTE.series[index % C2_PALETTE.series.length];
/** 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 hue per group, then lighter and darker steps so siblings stay related but distinct. */
/** 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 order = [...new Set(groups)];
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
const stairs = new Map(order.map((id, i) => [id, steps(C2_PALETTE.series[i % C2_PALETTE.series.length], counts.get(id)!)]));
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;
@@ -51,7 +93,7 @@ export function institutionalize(colors: readonly string[]): string[] {
const foreign: string[] = [];
const seen = new Set<string>();
for (const item of parsed) {
if (!item || item.kind !== 'foreign' || ageKeys.has(item.key) || seen.has(item.key)) continue;
if (!item || !isCoffeeParsed(item) || seen.has(item.key)) continue;
seen.add(item.key);
foreign.push(item.key);
}
@@ -63,9 +105,14 @@ export function institutionalize(colors: readonly string[]): string[] {
});
}
/** Keep a published colour; only a missing one takes the next series entry. */
export function seriesColors(published: readonly (string | undefined)[]): string[] {
return published.map((color, index) => c2Color(color, index));
/** 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]> = {
@@ -101,10 +148,13 @@ function parseColor(input: string): Parsed | undefined {
}
const lum = luminance({ r, g, b });
const neutral = sat < 0.18;
const harmonious = !neutral && (
(hue >= 64 && hue <= 188 && sat >= 0.22)
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));
|| (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[] {
@@ -0,0 +1,223 @@
// What this module covers: CaCu's compositions as the page reads them from FHIR once the Measure publishes category
// groups and the reports their crossed strata: the groups, the rows by stratum (codes, captions, explicit zeros, totals),
// the contract errors that must never become zeros, the EU7 view by follow-up status and the histopathological
// confirmation, a period without units, and that measures without groups (CaMa's) read unchanged.
// Fixtures: `fixtures/cacu_fhir_measures.json` (the Measure bundle `GET /cacu/fhir/Measure` returns with the groups
// declared) and `fixtures/cacu_fhir_reportes_estratos.json` (real `GET /cacu/fhir/MeasureReport` answers of EU7 and the
// confirmation for 2025-S2, with units, and 2021-S1, without; synthetic data of the isolated installation, N_CACU=300).
import { Bundle, resources } from './fhir';
import { categorias, datosDeReportes, gruposDeCategoria, indicadorDeMeasure, Measure, Report } from './indicadores-fhir';
import { barras, dona, modelo } from './indicadores-eu7-escenario';
import { donaConfirmacion, modeloConfirmacion } from './indicadores-confirmacion-citologia';
import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified';
import { IndicadorDatos } from './indicadores.models';
import measuresData from './fixtures/cacu_fhir_measures.json';
import reportsData from './fixtures/cacu_fhir_reportes_estratos.json';
import camaData from './fixtures/cama_fhir_measures.json';
const measures = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const measure = (id: string) => measures.find(m => m.id === id)!;
const answers = reportsData as unknown as Record<string, Bundle>;
const reports = (key: string) => resources(answers[key], 'MeasureReport') as Report[];
const EU7 = 'CACU-EU7', CONF = 'CACU-CONFIRMACION-CITOLOGIA';
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
type Fila = Record<string, unknown>;
const n = (filas: Fila[], estrato: string | null, categoria: string) =>
filas.filter(f => f['estrato'] === estrato && f['categoria'] === categoria).reduce((s, f) => s + (f['n'] as number), 0);
describe('Grupos de categoría publicados por la Measure', () => {
it('EU7 y la confirmación leen el grupo de cada categoría y los nombres de los grupos, en su orden', () => {
// Pins down: the optional `grupo` inside each `categoria` and the `categoria-grupo` captions reach the page as the
// EU7 and confirmation views read them; «Sin biopsia aún» keeps no group. Fails if either is dropped or reordered.
expect(Object.fromEntries(Object.entries(categorias(measure(EU7))).map(([c, v]) => [c, v.grupo]))).toEqual({
NORMAL: 'NO_ANORMAL', 'ASC-US': 'ANORMAL', LIEBG: 'ANORMAL', 'ASC-H': 'ANORMAL', LIEAG: 'ANORMAL', CIS: 'ANORMAL', SIN_DATO: 'SIN_DATO' });
expect(Object.entries(gruposDeCategoria(measure(EU7)))).toEqual([
['NO_ANORMAL', 'Sin anomalía'], ['ANORMAL', 'Anormal'], ['SIN_DATO', 'Sin dato']]);
expect(categorias(measure(CONF))['SIN_BIOPSIA'].grupo).toBeNull();
expect(gruposDeCategoria(measure(CONF))).toEqual({ NO_ANORMAL: 'Menor que LIEAG', ANORMAL: 'LIEAG o más', SIN_DATO: 'Biopsia sin grado' });
});
it('una Measure sin grupos se lee como antes: sin grupo por categoría y sin grupos de categoría', () => {
// Pins down: groups are opt-in. CaMa's Measures declare none, so every category keeps `grupo: null` and the data
// carry no `grupos_de_categoria`. Fails if reading the new extensions changes what CaMa's views receive.
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
for (const m of cama) {
expect(Object.values(categorias(m)).every(c => c.grupo === null), m.id).toBe(true);
expect(gruposDeCategoria(m), m.id).toEqual({});
}
});
});
describe('Composiciones por estrato desde el estratificador cruzado', () => {
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre');
const porEstatus = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' });
it('cada estrato tiene una fila por categoría declarada, con su código y su etiqueta, y ceros explícitos', () => {
// Pins down: one row per (status, category), the status code as the value and its caption from the report, and a
// zero for every cell FHIR doesn't list (the report is complete). Fails if a cell goes missing or a code is replaced.
const valores = porEstatus['valores_estrato'] as string[];
expect(valores.length).toBeGreaterThan(0);
expect(porEstatus.filas.length).toBe(valores.length * Object.keys(porEstatus['categorias'] as object).length);
expect((porEstatus['etiquetas_estrato'] as Record<string, string>)['PRE_COLPOSCOPIA']).toBe('Pre colposcopia');
const listadas = (reports('eu7_2025S2')[0].group![0].stratifier as { code: unknown[]; stratum: unknown[] }[])
.find(s => s.code.length === 2 && JSON.stringify(s.code[0]).includes('estatus_seguimiento'))!.stratum.length;
expect(porEstatus.filas.filter(f => f['n'] === 0).length).toBe(porEstatus.filas.length - listadas);
expect(porEstatus.filas.every(f => f['suprimido'] === 0 && f['grupo'] === 'TOTAL')).toBe(true);
});
it('los conteos por estrato suman los de la distribución general, categoría por categoría y en total', () => {
// Pins down: the strata partition the period's units (112 patients in 2025-S2) and each category adds up across
// them; the per-stratum totals are published. Fails if the crossed stratifier is read with a shift or a loss.
const totales = porEstatus['totales_estrato'] as { n: number }[];
expect(totales.reduce((s, t) => s + t.n, 0)).toBe(112);
for (const categoria of Object.keys(general['categorias'] as object)) {
const porEstratos = (porEstatus['valores_estrato'] as string[]).reduce((s, e) => s + n(porEstatus.filas, e, categoria), 0);
expect(porEstratos, categoria).toBe(n(general.filas, null, categoria));
}
const porEdad = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'grupo_edad' });
expect((porEdad['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(112);
expect((porEdad['etiquetas_estrato'] as Record<string, string>)['25-34']).toBe('25-34');
});
it('una celda que falta, una categoría no declarada o un estratificador ausente son errores de contrato, no ceros', () => {
// Pins down: what can't be read as a complete partition fails loudly: cells that no longer add up to the units, a
// category the Measure doesn't declare, and a period with units but without the crossed stratifier. Fails if any
// of them is silently turned into a zero.
const sinCelda = clone(reports('eu7_2025S2'));
const cruzado = sinCelda[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as { stratum: unknown[] };
cruzado.stratum.shift();
expect(() => datosDeReportes(measure(EU7), sinCelda, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Los conteos por estrato no suman las unidades del periodo');
const ajena = clone(reports('eu7_2025S2'));
const celda = (ajena[0].group![0].stratifier!.find(s => Array.isArray(s.code) && s.code.length === 2) as unknown as
{ stratum: { component: { value: { coding: { code: string }[] } }[] }[] }).stratum[0];
celda.component[1].value.coding[0].code = 'GLANDULAR';
expect(() => datosDeReportes(measure(EU7), ajena, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Categoría no declarada en el estrato');
const sinCruce = clone(reports('eu7_2025S2'));
sinCruce[0].group![0].stratifier = sinCruce[0].group![0].stratifier!.slice(0, 1);
expect(() => datosDeReportes(measure(EU7), sinCruce, 'semestre', { estrato: 'estatus_seguimiento' }))
.toThrowError('Dimensión no admitida');
});
it('un periodo sin unidades no tiene filas por estrato y no es un error', () => {
// Pins down: 2021-S1 has no patients; its report has nothing to cross, so the stratified data carry the period but
// no rows, and the general distribution is all zeros. Fails if an empty period is read as an error or as data.
const vacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' });
expect(vacio.periodos).toEqual(['2021-S1']);
expect(vacio.filas).toEqual([]);
const generalVacio = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre');
expect(generalVacio.filas.every(f => f['n'] === 0)).toBe(true);
});
});
describe('Vistas propias de CaCu con los datos de FHIR', () => {
it('EU7: el modelo por escenario se construye y la dona y las barras tienen datos', () => {
// Pins down: with the groups and the rows by follow-up status, EU7's coordinated view builds its model (112
// patients in groups Anormal / Sin anomalía, «Sin dato» apart) and both figures have traces. Fails if the view
// falls back to «incompatible» with the data FHIR publishes.
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2025-S2');
expect(m.vacio).toBe(false);
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Sin anomalía', 'Anormal']);
expect(m.escenarios.map(e => e.etiqueta)).toContain('Pre colposcopia');
expect(dona(m, {}, 'claro').data.length).toBeGreaterThan(0);
expect(barras(m, {}, 'claro').data.length).toBeGreaterThan(0);
});
it('EU7: el texto emergente de cada sector de la dona nombra la categoría, los pacientes y el porcentaje', () => {
// Pins down: both rings carry one pre-formatted hover text per sector («2 pacientes, 2.1 % del total con
// resultado» for LIEAG, 2 of the 95 patients with a result) and their template reads it by name. A pie wraps
// `customdata` in an extra array, so a template that indexes it printed «2,2.1 pacientes, - %». Fails if the
// template goes back to indexing `customdata` or a sector loses its text.
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2025-S2');
const anillos = dona(m, {}, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
expect(anillos.length).toBe(2);
for (const anillo of anillos) {
expect(anillo['hovertemplate']).not.toContain('customdata');
expect(anillo['hovertemplate']).toContain('%{hovertext}');
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
}
const exterior = anillos.find(t => t['name'] === 'categorias')!;
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
expect(m.total).toBe(95);
expect(textos[etiquetas.indexOf('LIEAG')]).toBe('2 pacientes, 2.1 % del total con resultado');
expect(textos.every(t => /^\d+ pacientes, \d+(\.\d)? % del total con resultado$/.test(t))).toBe(true);
});
it('EU7: un periodo sin pacientes es un periodo vacío, no una respuesta incompatible', () => {
// Pins down: for 2021-S1 FHIR publishes the general distribution as explicit zeros and no scenario; the view reads
// it as empty. A positive count without scenarios is still rejected. Fails if an empty period shows
// «incompatible», or if a real mismatch is hidden as empty.
const general = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), reports('eu7_2021S1'), 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
const m = modelo(general, escenarios, '2021-S1');
expect(m.vacio).toBe(true);
expect(m.escenarios).toEqual([]);
const conPacientes = clone(general);
conPacientes.filas[0]['n'] = 3;
expect(() => modelo(conPacientes, escenarios, '2021-S1')).toThrow(/No hay escenarios que correspondan/);
});
it('EU7: el mismo reporte servido en dos respuestas es una sola procedencia aunque cambie la hora de la respuesta', () => {
// Pins down: the view asks for the general and the stratified data in two requests; the WebApi serves the same
// stored report (same id and cut-off) with each response's own `date`. That is one provenance; without report ids,
// a different generation time still means different reports. Fails if the view rejects FHIR's two responses of one
// report, or accepts two anonymous answers generated apart.
const segunda = clone(reports('eu7_2025S2'));
segunda[0].date = '2099-01-01T00:00:00Z';
const general = datosDeReportes(measure(EU7), reports('eu7_2025S2'), 'semestre') as IndicadorDatos;
const escenarios = datosDeReportes(measure(EU7), segunda, 'semestre', { estrato: 'estatus_seguimiento' }) as IndicadorDatos;
expect(modelo(general, escenarios, '2025-S2').vacio).toBe(false);
const anonimo = (d: IndicadorDatos) => ({ ...d, reportes: (d['reportes'] as Fila[]).map(r => ({ ...r, report_id: null })) }) as IndicadorDatos;
expect(() => modelo(anonimo(general), anonimo(escenarios), '2025-S2')).toThrow(/reportes distintos/);
});
it('confirmación: la tabla por citología y los dos grupos de grados se construyen', () => {
// Pins down: the confirmation by cytology result builds its table from the crossed stratifier (6 patients in
// 2025-S2), with its two groups and LIEAG's as the base view, and «Sin biopsia aún» / «Biopsia sin grado»
// apart. Fails if the view can't read FHIR's groups or strata.
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
const m = modeloConfirmacion(datos, '2025-S2');
expect(m.vacio).toBe(false);
expect(m.grupos.map(g => g.etiqueta)).toEqual(['Menor que LIEAG', 'LIEAG o más']);
expect(m.base).toBe('ANORMAL');
expect(m.aparte.map(a => a.id).sort()).toEqual(['SIN_BIOPSIA', 'SIN_DATO']);
expect((datos['totales_estrato'] as { n: number }[]).reduce((s, t) => s + t.n, 0)).toBe(6);
});
it('confirmación: el texto emergente de cada sector de la dona nombra el grado, las mujeres con biopsia y el porcentaje', () => {
// Pins down: both rings carry one pre-formatted hover text per sector («3 mujeres con biopsia, 75.0 %» for the
// grades LIEAG o más… of the 4 women with a biopsy in 2025-S2) and their template reads it by name, because a pie
// wraps `customdata` in an extra array and indexing it printed «3,75.0 % mujeres con biopsia, -». Fails if the
// template goes back to indexing `customdata` or a sector loses its text.
const datos = datosDeReportes(measure(CONF), reports('confirmacion_2025S2'), 'semestre', { estrato: 'citologia_alto_grado' }) as IndicadorDatos;
const m = modeloConfirmacion(datos, '2025-S2');
const anillos = donaConfirmacion(m, { grupo: m.base }, 'claro').data.filter(t => t['name'] === 'grupos' || t['name'] === 'categorias');
expect(anillos.length).toBe(2);
for (const anillo of anillos) {
expect(anillo['hovertemplate']).not.toContain('customdata');
expect(anillo['hovertemplate']).toContain('%{hovertext}');
expect((anillo['hovertext'] as string[]).length).toBe((anillo['values'] as number[]).length);
}
const exterior = anillos.find(t => t['name'] === 'categorias')!;
const etiquetas = exterior['labels'] as string[], textos = exterior['hovertext'] as string[];
expect(textos[etiquetas.indexOf('LIEAG (CIN 2 y 3)')]).toBe('3 mujeres con biopsia, 75.0 %');
expect(textos.every(t => /^\d+ mujeres con biopsia, \d+(\.\d)? %$/.test(t))).toBe(true);
});
it('la compuerta de EU7 usa los estratos que declara la Measure y no activa filtros para otras composiciones', () => {
// Pins down: EU7 declares `estatus_seguimiento`, so its view opens without local filters; the stratified
// capabilities of the generic figure panel stay empty for every CaCu and CaMa measure. Fails if the gate is lost
// or if filters appear for compositions that never had them.
const eu7 = indicadorDeMeasure(measure(EU7));
expect(declaraEstrato(eu7, 'estatus_seguimiento')).toBe(true);
expect(declaraEstrato(indicadorDeMeasure(measure(CONF)), 'estatus_seguimiento')).toBe(false);
expect(declaraEstrato(indicadorDeMeasure(measure('CACU-EU13')), 'estatus_seguimiento')).toBe(false);
const cama = resources(camaData as unknown as Bundle, 'Measure') as Measure[];
for (const item of [...measures, ...cama].map(indicadorDeMeasure)) expect(stratifiedCapabilities(item), item.id).toEqual([]);
});
});
@@ -0,0 +1,167 @@
// What this module covers: how CaCu's FHIR measures reach the indicator page: the page's id of each measure, and what the
// initial-period anchor (`cacu_eu7`) makes of a C2 Measure that publishes, or does not publish, its category labels.
// The Measure and the report are synthetic and minimal: the shape of `GET /cacu/fhir/Measure` and `/MeasureReport`.
import { Bundle, resources } from './fhir';
import { Measure, Report, datosDeReportes, indicadorDeMeasure, indicadorId } from './indicadores-fhir';
import { c2Figure } from './indicadores-c2-adapter';
import { FigureSelection } from './indicadores.models';
import measuresData from './fixtures/cacu_fhir_measures.json';
import { CACU_MEASURE_IDS } from './indicadores-cacu-fhir';
import { ID_CONFIRMACION } from './indicadores-confirmacion-citologia';
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN, kpiResult } from './indicadores-kpi';
import { GlobalApplied } from './indicadores-memory';
import { historicoFigura } from './indicadores-historico-figures';
const STRUCTURE = 'https://isssteleon.org/fhir/StructureDefinition';
const ENDPOINT = ['CACU-CONFIRMACION-CITOLOGIA', 'CACU-DIAS-TOMA-DIAGNOSTICO', 'CACU-EU-TIEMPO-REPORTE', 'CACU-EU13', 'CACU-EU7',
'CACU-RIESGO-BANDA', 'IND1'];
const etiqueta = (codigo: string, texto: string, color: string) => ({ url: `${STRUCTURE}/categoria`, extension: [
{ url: 'codigo', valueCode: codigo }, { url: 'etiqueta', valueString: texto }, { url: 'color', valueString: color }] });
const eu7 = (extra: object[]): Measure => ({
resourceType: 'Measure', id: 'CACU-EU7', version: '0.3.3', title: 'Distribución de resultados citológicos',
subjectCodeableConcept: { coding: [{ code: 'paciente' }] },
extension: [{ url: `${STRUCTURE}/contrato`, valueCode: 'C2' }, { url: `${STRUCTURE}/tipos-periodo`, valueCode: 'semestre' }, ...extra],
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [], stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [] }] }],
} as unknown as Measure);
const reporte = (): Report => ({
resourceType: 'MeasureReport', id: 'CACU-EU7-1', period: { start: '2025-07-01', end: '2025-12-31' },
group: [{ code: { coding: [{ code: 'TOTAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 12 }],
stratifier: [{ code: [{ coding: [{ code: 'resultado' }] }], stratum: [
{ value: { coding: [{ code: 'NORMAL' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 8 }] },
{ value: { coding: [{ code: 'ASC-US' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 3 }] },
{ value: { coding: [{ code: 'SIN_DATO' }] }, population: [{ code: { coding: [{ code: 'initial-population' }] }, count: 1 }] },
] }] }],
} as unknown as Report);
const aplicado: GlobalApplied = { tipo: 'semestre', selection: { mode: 'explicit', periodos: ['2025-S2'] }, revision: 0 };
const ancla = KPI_BY_DOMAIN.cacu[0];
describe('Identificadores de CaCu entre FHIR y la página', () => {
it('cada medida que publica el WebApi tiene el id de minúsculas que usa la página y ninguno se repite', () => {
// Pins down: the table covers the seven measures `GET /cacu/fhir/Measure` lists and the ids are unique. Fails if a
// measure is published without a correspondence (it would come back as `CACU_X`, which no card matches) or two
// measures collapse into one page id.
const ids = ENDPOINT.map(indicadorId);
expect(ids.sort()).toEqual(['cacu_confirmacion_citologia', 'cacu_dias_toma_diagnostico', 'cacu_eu13', 'cacu_eu7',
'cacu_eu_tiempo_reporte', 'cacu_riesgo_banda', 'ind1']);
expect(ENDPOINT.every(id => Object.hasOwn(CACU_MEASURE_IDS, id))).toBe(true);
});
it('los ids que la página busca (ancla, tiempos, confirmación) existen entre los publicados', () => {
// Pins down: the page's own constants (the KPI definitions of CaCu, the confirmation card's id and the result-time KPI)
// are values of the table. Fails if the page renames one of them without the table: the catalog would keep `CACU_EU7`
// while the page looks for `cacu_eu7`, and no initial period would be searched.
const publicados = Object.values(CACU_MEASURE_IDS);
for (const id of [...KPI_BY_DOMAIN.cacu.map(k => k.id), CACU_RESULTADO_KPI.id, ID_CONFIRMACION, 'cacu_eu7']) {
expect(publicados).toContain(id);
}
});
it('el catálogo de una medida de CaCu lleva el id de la página y sus figuras', () => {
// Pins down: the catalog entry takes the page id and the `figuras` the Measure publishes. Fails if the mapper stops
// using the CaCu table or drops the figures.
const item = indicadorDeMeasure(eu7([{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_donas' },
{ url: `${STRUCTURE}/figuras`, valueString: 'fig_c2_barras' }]));
expect(item.id).toBe('cacu_eu7');
expect(item.figuras).toEqual(['fig_c2_donas', 'fig_c2_barras']);
});
});
describe('El ancla de CaCu con y sin etiquetas de categoría publicadas', () => {
it('con etiquetas, los conteos del periodo son filas y el ancla muestra el total', () => {
// Pins down: a C2 Measure that publishes its categories gives one row per category and the anchor KPI the sum
// (12 patients), so the initial-period search can stop on the period. Fails if the rows stop following the Measure's
// categories or the anchor no longer accepts a CaCu partition.
const measure = eu7([etiqueta('NORMAL', 'Normal', '#9DBFE3'), etiqueta('ASC-US', 'ASC-US', '#2F6DB3'),
etiqueta('SIN_DATO', 'Sin dato', '#C9CDD2')]);
const datos = datosDeReportes(measure, [reporte()], 'semestre');
expect(datos.filas.map(f => [f['categoria'], f['n']])).toEqual([['NORMAL', 8], ['ASC-US', 3], ['SIN_DATO', 1]]);
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
expect(resultado.state).toBe('Disponible');
expect(resultado.value).toBe(12);
});
it('sin etiquetas, el mismo reporte no deja filas y el ancla no encuentra periodo', () => {
// Pins down the failure the Measure without `categoria` causes: the report counts 12 patients, but with no declared
// category there is no row, so the anchor reads «Sin filas utilizables» and the initial period stays empty. Fails
// if the page starts inventing categories from the report (it must keep asking the Measure).
const datos = datosDeReportes(eu7([]), [reporte()], 'semestre');
expect(datos.filas).toEqual([]);
expect(kpiResult(datos, ancla, 'cacu', aplicado).state).toBe('Sin filas utilizables');
});
});
// `fixtures/cacu_fhir_measures.json` is the Measure bundle `GET /cacu/fhir/Measure` returns from the dbt definitions once
// CaCu declares its figures and category labels (WebApi with the figures and labels declared in Transformation); the reports are built
// from the categories each Measure declares, as the WebApi would count them.
const publicadas = resources(measuresData as unknown as Bundle, 'Measure') as Measure[];
const medida = (id: string) => publicadas.find(m => m.id === id)!;
const declaradas = (m: Measure) => (m.extension ?? []).filter(e => e.url.endsWith('/categoria'))
.map(e => e.extension!.find(x => x.url === 'codigo')!.valueCode!);
const codigo = (c: string) => ({ coding: [{ code: c }] });
const reporteDe = (m: Measure, conteos: number[]): Report => ({
resourceType: 'MeasureReport', id: `${m.id}-1`, period: { start: '2025-07-01', end: '2025-12-31' },
group: [{ code: codigo('TOTAL'), population: [{ code: codigo('initial-population'), count: conteos.reduce((a, b) => a + b, 0) }],
stratifier: [{ code: [codigo('categoria')], stratum: declaradas(m).map((c, i) => ({
value: codigo(c), population: [{ code: codigo('initial-population'), count: conteos[i] }] })) }] }],
} as unknown as Report);
describe('Las medidas de CaCu como las publica el WebApi con figuras y etiquetas declaradas', () => {
it('el catálogo ofrece las figuras que cada contrato sabe dibujar y deja sin ellas las que aún no', () => {
// Pins down: C2 measures offer the donut and the bars, the two C3r the box plot, and the C1 and the risk bands none
// yet (no declared figure the renderer supports). Fails if a CaCu measure loses its figures or gains one that was not
// checked against the renderer.
const figuras = Object.fromEntries(publicadas.map(m => [indicadorDeMeasure(m).id, indicadorDeMeasure(m).figuras]));
expect(figuras).toEqual({
cacu_confirmacion_citologia: ['fig_c2_donas', 'fig_c2_barras'], cacu_dias_toma_diagnostico: ['fig_c3r_caja'],
cacu_eu_tiempo_reporte: ['fig_c3r_caja'], cacu_eu13: [], cacu_eu7: ['fig_c2_donas', 'fig_c2_barras'],
cacu_riesgo_banda: [], ind1: [],
});
});
it('con las etiquetas publicadas, el ancla muestra el total y el donut y las barras se dibujan', () => {
// Pins down the whole chain for the anchor: published categories -> rows -> «Pacientes evaluadas» total (16) ->
// supported C2 donut and bars. Fails if the page cannot read what the WebApi publishes for CaCu's distribution.
const eu7 = medida('CACU-EU7');
const datos = datosDeReportes(eu7, [reporteDe(eu7, [8, 3, 2, 1, 1, 0, 1])], 'semestre');
const resultado = kpiResult(datos, ancla, 'cacu', aplicado);
expect(resultado).toMatchObject({ state: 'Disponible', value: 16 });
for (const figura of ['fig_c2_donas', 'fig_c2_barras']) {
const dibujo = c2Figure(datos, { dominio: 'cacu', indicador: 'cacu_eu7', figura, tipoPeriodo: 'semestre', tema: 'claro',
periodos: ['2025-S2'] } as unknown as FigureSelection);
expect(dibujo.status).toBe('supported');
}
});
it('un C1 publicado con su intervalo de Wilson llena la banda del histórico, en porcentaje', () => {
// Pins down: the `ic-bajo` and `ic-alto` of a proportion's score (proportions) reach the rows as percentages and
// the history trend draws them as its band. Fails if the bounds are read unconverted or dropped.
const eu13 = medida('CACU-EU13');
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
const reporte13 = { resourceType: 'MeasureReport', id: 'CACU-EU13-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25, extension: [{ url: `${STRUCTURE}/ic-bajo`, valueDecimal: 0.0456 }, { url: `${STRUCTURE}/ic-alto`, valueDecimal: 0.6994 }] } }] } as unknown as Report;
const datos = datosDeReportes(eu13, [reporte13], 'semestre');
expect(datos.filas[0]).toMatchObject({ valor: 25, ic_bajo: 4.6, ic_alto: 69.9 });
const banda = (historicoFigura(datos, 'claro').figure as unknown as { data: { name: string; y: number[] }[] }).data[0];
expect(banda.name).toBe('Intervalo de confianza');
expect(banda.y).toEqual([69.9, 4.6]);
});
it('un C1 de CaCu cuyo grupo se llama principal dibuja su tendencia en el histórico', () => {
// Pins down: the WebApi names the group of a proportion `principal`; the page reads it as `total`, the group the
// history trend draws, for CaCu as for CaMa. Fails if the rows keep the group `principal` and the trend comes out
// empty, with its period listed as having no data.
const cuenta = (code: string, count: number) => ({ code: { coding: [{ code }] }, count });
for (const id of ['CACU-EU13', 'IND1']) {
const medida13 = medida(id);
const reporte = { resourceType: 'MeasureReport', id: id + '-1', period: { start: '2025-01-01', end: '2025-06-30' },
group: [{ code: { coding: [{ code: 'principal' }] }, population: [cuenta('initial-population', 4), cuenta('denominator', 4), cuenta('numerator', 1)],
measureScore: { value: 0.25 } }] } as unknown as Report;
const datos = datosDeReportes(medida13, [reporte], 'semestre');
expect(datos.filas[0]['grupo']).toBe('total');
const figura = historicoFigura(datos, 'claro');
expect((figura.figure as unknown as { data: { y: number[] }[] }).data[1].y).toEqual([25]);
expect(figura.sinDato).toEqual([]);
}
});
});
@@ -0,0 +1,15 @@
// How CaCu's FHIR measures map onto what the indicator page reads: the page's id of each measure.
//
// The WebApi names a measure `CACU-EU7`, `CACU-CONFIRMACION-CITOLOGIA` or `IND1`; the page, its KPI definitions, the
// initial-period anchor and the cards that have a view of their own (`cacu_eu7`, `cacu_confirmacion_citologia`, the
// time pair) all use the lower-case ids below. The generic rule would give `CACU_EU7`, which none of them matches, so
// the correspondence is explicit, as CaMa's is, and a measure outside it keeps the generic rule.
export const CACU_MEASURE_IDS: Readonly<Record<string, string>> = {
'CACU-CONFIRMACION-CITOLOGIA': 'cacu_confirmacion_citologia',
'CACU-DIAS-TOMA-DIAGNOSTICO': 'cacu_dias_toma_diagnostico',
'CACU-EU-TIEMPO-REPORTE': 'cacu_eu_tiempo_reporte',
'CACU-EU13': 'cacu_eu13',
'CACU-EU7': 'cacu_eu7',
'CACU-RIESGO-BANDA': 'cacu_riesgo_banda',
'IND1': 'ind1',
};
@@ -101,12 +101,12 @@ describe('CaCu: oportunidad y selección independiente de todos los reportes', (
expect(original.map(i => i.id)).toEqual(catalog.map(i => i.id));
expect(before[0].indicador.id).toBe('cacu_eu7');
page.togglePinned(original[0]); fixture.detectChanges();
expect(cards()[0]).toBe(card('cacu_eu13'));
expect(cards()[0]).toBe(card('cacu_eu7'));
page.changeIndicatorSelection(['ind1', 'cacu_eu13']); fixture.detectChanges();
expect(cards().map(c => c.indicador.id)).toEqual(['cacu_eu13', 'ind1']);
for (const id of ['ind1', 'cacu_eu13']) expect(card(id)).toBe(before.find(c => c.indicador.id === id));
page.showAllIndicators(); fixture.detectChanges();
expect(cards()[0].indicador.id).toBe('cacu_eu13');
expect(cards()[0].indicador.id).toBe('cacu_eu7');
expect(page.catalog()).toBe(original);
expect(TestBed.inject(IndicadoresMemory).isPinned('cacu', 'cacu_eu13')).toBe(true);
http.expectNone(() => true);
@@ -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', 'Días del resultado de la mastografía al diagnóstico', 'Tasa de detección histopatológica'].includes(t!)))
.toEqual([['Resultado histopatológico', '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');
});
});
@@ -50,10 +50,10 @@ describe('Identificadores de CaMa entre FHIR y la página', () => {
});
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.
// Pins down: only CaMa's table maps CaMa's measures, and TEA's keep `-` to `_` (CaCu has a table of its own, see
// indicadores-cacu-fhir.spec.ts). Fails if CaMa's 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');
expect(Object.hasOwn(CAMA_MEASURE_IDS, 'CACU-EU7')).toBe(false);
});
it('el catálogo lleva contrato, figuras y periodos de cada medida', () => {
@@ -308,3 +308,33 @@ describe('Tarjeta pareada de mastografías y pacientes BI-RADS 4, 5 y 6', () =>
expect(model.filas.map(f => f.pacientes)).toEqual([0, 20, 2]);
});
});
describe('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);
});
});
@@ -73,7 +73,7 @@ describe('Tasa de detección histopatológica (C1)', () => {
expect(d['grupos']).toEqual({ total: 'Total' });
expect(d.filas).toEqual([expect.objectContaining({ grupo: 'total', numerador, denominador, valor, suprimido: 0 })]);
expect(kpiResult(d, CAMA_TASA_DETECCION_KPI, 'cama', apply(periodo))).toMatchObject({
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con resultado maligno.` });
state: 'Disponible', value: valor.toFixed(1), info: `${numerador} de ${denominador} biopsias con riesgo a carcinoma.` });
});
it('el numerador nunca supera al denominador y la suma de los periodos es la de los reportes de biopsia del dominio', () => {
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
]);
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de 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');
@@ -1,5 +1,5 @@
// Covers the clinical section of CaMa's summary: its heading and counter, and the controls the mockup does not
// have (search, pins, floating navigation, representation selector, figure count), which CaCu and TEA keep.
// Covers the clinical section: its heading, and the controls the mockup does not have
// (search, pins, floating navigation, representation selector, figure count) in every domain.
// Fixtures are catalogs shaped like /<dominio>/indicadores; no figure is requested (the cards stay out of view).
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@@ -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;
@@ -105,18 +113,14 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
fixture.componentInstance.togglePinned(CAMA[5] as never); fixture.detectChanges();
expect(titles()).toEqual(before);
});
it.each(['tea', 'cacu'] as const)('%s conserva buscador, fijados y conteo de figuras', domain => {
// Fails if CaMa's simplified section leaks into the other domains.
it.each(['tea', 'cacu'] as const)('%s usa el mismo resumen clínico que CaMa: sin buscador, fijados ni conteo de figuras', domain => {
open(domain, OTRO(domain));
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');
});
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
open('cacu', OTRO('cacu'));
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
open('tea', OTRO('tea'));
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores gráficos');
expect(root().querySelector('#dashboard-title')?.textContent?.trim()).toBe(domain === 'tea' ? 'Trastorno del espectro autista' : 'Cáncer cervicouterino');
expect(root().querySelector('header .domain')).toBeNull();
expect(root().querySelector('.catalog-search')).toBeNull();
expect(root().querySelector('.pin-toggle')).toBeNull();
expect(section().textContent).not.toContain('figuras publicadas');
expect(root().textContent).not.toContain('indicadores publicados');
});
});
@@ -33,8 +33,7 @@ describe('Cambio de dominio con consultas pendientes', () => {
fixture.detectChanges();
expect(text()).not.toContain('Indicador de CaMa');
});
it('los controles propios de cada dominio se conservan al ir y volver', () => {
// CaCu keeps its multiple selection, search and pins; CaMa does not have them; neither state contaminates the other.
it('el resumen clínico es el mismo al ir y volver, y el catálogo no se mezcla', () => {
const abrir = (d: 'cacu' | 'cama', n: number) => {
fixture.componentInstance.changeDominio(d); fixture.detectChanges();
http.expectOne('/' + d + '/indicadores').flush(Array.from({ length: n }, (_, i) => item(`${d}_${i}`, `${d} ${i}`, 'C2'))); fixture.detectChanges();
@@ -42,8 +41,9 @@ describe('Cambio de dominio con consultas pendientes', () => {
};
const el = () => fixture.nativeElement as HTMLElement;
abrir('cacu', 6);
expect(el().querySelector('.catalog-search')).not.toBeNull();
expect(el().querySelectorAll('.pin-toggle').length).toBe(6);
expect(el().querySelector('.catalog-search')).toBeNull();
expect(el().querySelector('.pin-toggle')).toBeNull();
expect(el().querySelector('#dashboard-title')?.textContent?.trim()).toBe('Cáncer cervicouterino');
expect(el().textContent).toContain('Intervalo de análisis');
abrir('cama', 6);
expect(el().querySelector('.catalog-search')).toBeNull();
@@ -51,9 +51,8 @@ describe('Cambio de dominio con consultas pendientes', () => {
expect(el().textContent).not.toContain('Buscar indicadores');
expect(el().textContent).not.toContain('cacu_');
abrir('cacu', 6);
// On the way back the page state (not only the DOM) says CaCu has its search again.
expect(fixture.componentInstance.dominio).toBe('cacu');
expect(fixture.componentInstance.searchVisible()).toBe(true);
expect(fixture.componentInstance.searchVisible()).toBe(false);
expect(el().textContent).toContain('Intervalo de análisis');
expect(el().textContent).not.toContain('cama_');
});
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } 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):
@@ -106,12 +106,11 @@ export function modeloConfirmacion(datos: IndicadorDatos, periodo: string): Mode
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 ordenGrupos = [...new Set(conColor.map(g => g.grupo))];
const bases = basesPorGrupo(conColor.map(g => g.grupo));
const grupos = [...new Set(grados.map(g => g.grupo))].map(id => {
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
const propios = grados.filter(g => g.grupo === id);
const indice = ordenGrupos.indexOf(id);
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
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.
@@ -229,17 +228,18 @@ export function donaConfirmacion(m: ModeloConfirmacion, sel: SeleccionConfirmaci
const interior = m.grupos.map(g => g.grados.reduce((s, c) => s + m.totales[c]!, 0));
const exterior = m.grados.map(g => m.totales[g.id]!);
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} mujeres con biopsia, %{customdata[1]}<extra></extra>' };
const custom = (values: number[]) => values.map(n => [miles(n), shareText(n, total)]);
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
const hoverText = (values: number[]) => values.map(n => `${miles(n)} mujeres con biopsia, ${shareText(n, total)}`);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] }, textinfo: 'text', textposition: 'inside',
text: [`<b>${miles(k)}</b><br>de ${miles(total)} con biopsia`], 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] },
labels: m.grupos.map(g => escapar(g.etiqueta)), customdata: custom(interior),
labels: m.grupos.map(g => escapar(g.etiqueta)), hovertext: hoverText(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, g.grados.some(c => activos.has(c)) ? 1 : .3)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.grados.map(g => escapar(g.etiqueta)), customdata: custom(exterior),
labels: m.grados.map(g => escapar(g.etiqueta)), hovertext: hoverText(exterior),
marker: { colors: m.grados.map(g => rgba(g.color, activos.has(g.id) ? 1 : .3)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
@@ -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 = {
@@ -89,6 +89,16 @@ describe('Conteos pareados de CaMa: lo que se puede sumar', () => {
expect(dona.data[0].values).toEqual([15, 2, 0, 0, 18, 0]);
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', () => {
@@ -116,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([
@@ -145,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']),
];
@@ -192,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.
@@ -50,7 +50,7 @@ const COLOR_NEUTRO = '#8A9199';
export interface CategoriaConteo { id: string; etiqueta: string; color: string; n: number | null; }
export interface FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
export interface ModeloConteos {
periodo: string; examenes: CategoriaConteo[]; sinDato: number | null; filas: FilaConteo[];
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,7 +80,10 @@ 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 => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
@@ -93,7 +96,9 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
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: de(filasE, catExamenes, 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 => ({
@@ -106,14 +111,15 @@ export function modelosConteos(par: ParConteos, examenes: IndicadorDatos, pacien
}));
}
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;
const ALTO_DONA = 400, MARGEN_DONA = 8;
const DIAMETRO_MAXIMO_DONA = 270;
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): 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 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)));
@@ -122,7 +128,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
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 = m.examenes.map(c => escapar(c.etiqueta));
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,
@@ -151,7 +157,7 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
});
});
return { data: [{ type: 'pie', hole: .54, sort: false, direction: 'clockwise', values: n, labels: etiquetas,
marker: { colors: m.examenes.map(c => c.color), line: { color: p.background, width: 2 } }, textinfo: 'none',
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>' }],
@@ -160,15 +166,24 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
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: par.unidades.examenes },
{ ...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) => ({
@@ -19,7 +19,9 @@ export class IndicadoresDefinitions {
@Input() loading = false;
@Input() error = '';
readonly retry = output<void>();
readonly domainNames: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
readonly domainNames: Record<Dominio, string> = {
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
};
readonly periodNames: Record<TipoPeriodo, string> = { semestre: 'Semestral', mes: 'Mensual' };
readonly figureDisplayName = figureDisplayName;
readonly periodInterpretation = PERIOD_INTERPRETATION;
@@ -1,5 +1,5 @@
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
import { c2Theme, groupBase, paintByGroup } 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.
@@ -119,15 +119,21 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
return active[0];
};
const rg = reporte(general), re = reporte(porEscenario);
if (!!rg !== !!re || (rg && re && ['report_id', 'fecha_corte', 'generado_en', 'kit_version', 'toml_sha', 'parametros_sha']
.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
// With a report id on both sides, the report is identified by it and its cut-off and versions: a FHIR report's
// `date` (`generado_en`) is when the answer was served, so the same stored report served twice differs only there.
// Without ids, the generation time is still part of the provenance.
const identificados = rg?.['report_id'] != null && re?.['report_id'] != null;
const procedencia = ['report_id', 'fecha_corte', ...(identificados ? [] : ['generado_en']), 'kit_version', 'toml_sha', 'parametros_sha'];
if (!!rg !== !!re || (rg && re && procedencia.some(key => rg[key] !== re[key]))) return fail('Las respuestas EU7 provienen de reportes distintos.');
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 baseCategorias = cats.filter(c => c.id !== SIN_DATO).sort((a, b) => (orden.get(a.id) ?? Infinity) - (orden.get(b.id) ?? Infinity));
const colores = paintByGroup(baseCategorias.map(c => c.grupo));
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, i) => ({ id, etiqueta: nombres[id], color: groupBase(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.');
@@ -143,17 +149,20 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
return { id, etiqueta: etiquetas[id] as string, celdas: cells, estado: estadoEscenario,
den: estadoEscenario === 'Publicado' ? suma(categorias.map(c => cells[c.id])) : null };
});
// A period without patients may publish its general distribution as explicit zeros (FHIR's complete report) and no
// scenario at all: that's an empty period, not a mismatch. A null or positive count without scenarios still is one.
const generalEnCeros = g.size > 0 && [...g.values()].every(row => row['n'] === 0);
// Compare only fully published sums. Never derive a hidden value by subtraction.
if (escenarios.length) {
for (const c of cats) {
const total = suma(escenarios.map(s => s.celdas[c.id]));
if (celdas[c.id].n !== null && total !== null && celdas[c.id].n !== total) return fail('La distribución por escenario difiere de la general.');
}
} else if (g.size) return fail('No hay escenarios que correspondan a los datos generales.');
} else if (g.size && !generalEnCeros) return fail('No hay escenarios que correspondan a los datos generales.');
if (!g.size && e.size) return fail('Hay escenarios sin datos generales correspondientes.');
return { periodo, categorias, grupos, celdas, escenarios, sinDato: celdas[SIN_DATO],
sinDatoEtiqueta: cats.find(c => c.id === SIN_DATO)!.etiqueta,
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size,
total: !g.size ? 0 : suma(categorias.map(c => celdas[c.id])), vacio: !g.size || (generalEnCeros && !escenarios.length),
notas: [...new Set([...(general.notas ?? []), ...(porEscenario.notas ?? [])])] };
}
const hijas = (m: Modelo, grupo: string) => m.categorias.filter(c => c.grupo === grupo);
@@ -191,19 +200,20 @@ export function dona(m: Modelo, sel: Seleccion, tema: Tema): PlotlyFigure {
};
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, textinfo: 'text',
insidetextorientation: 'horizontal', showlegend: false, textposition: 'inside' };
const hover = { hovertemplate: '%{label}<br>%{customdata[0]} pacientes, %{customdata[1]} % del total con resultado<extra></extra>' };
const custom = (values: number[]) => values.map(n => [miles(n), percentNumber(100 * n / m.total!)]);
// A pie wraps `customdata` in one more array in its hover template, so the text is formatted per point instead.
const hover = { hovertemplate: '%{label}<br>%{hovertext}<extra></extra>' };
const hoverText = (values: number[]) => values.map(n => `${miles(n)} pacientes, ${percentNumber(100 * n / m.total!)} % del total con resultado`);
return { data: [
{ ...comun, name: 'centro', values: [1], labels: ['centro'], domain: { x: [.32, .68], y: [.32, .68] },
text: [`<b>${miles(centro)}</b><br>${escapar(seleccionEtiqueta(m, sel))}`], textfont: { size: 18, color: p.text },
marker: { colors: [p.background] }, hovertemplate: (sel.grupo || sel.categoria ? 'Volver' : 'Pacientes con resultado') + '<extra></extra>' },
{ ...comun, ...hover, name: 'grupos', values: interior, hole: .62, domain: { x: [.16, .84], y: [.16, .84] },
labels: m.grupos.map(g => escapar(g.etiqueta)), text: rotulos(interior, m.grupos.map(g => g.etiqueta), false),
textfont: { color: '#FFFFFF' }, customdata: custom(interior),
textfont: { color: '#FFFFFF' }, hovertext: hoverText(interior),
marker: { colors: m.grupos.map(g => rgba(g.color, sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
labels: m.categorias.map(c => escapar(c.etiqueta)), text: rotulos(exterior, m.categorias.map(c => c.etiqueta), true),
textfont: { size: 11 }, customdata: custom(exterior),
textfont: { size: 11 }, hovertext: hoverText(exterior),
marker: { colors: m.categorias.map(c => rgba(c.color, sel.categoria && c.id !== sel.categoria ? .3 : 1)), line: { color: p.background, width: 2 } } },
], layout: { autosize: true, height: 440, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
config: { displayModeBar: false } };
File diff suppressed because one or more lines are too long
@@ -173,14 +173,15 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(response.paginacion).toEqual({ page: 1, page_size: 5, total_items: 6, total_pages: 2 });
expect(response.items[0]).toMatchObject({ id_seudonimo: 'P-4A59E9D8B4', grupo_edad: '16-23 meses', ultimo_eeg: '2025-05-20', mchat: 12,
css_ados2: 7, modulo_ados2: '1', estado_caso: 'completo', alteraciones_eeg: 'anormal', alteraciones: ['ritmo_posterior'], pendientes: [] });
expect(response.resumen_eeg).toMatchObject({ normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.resumen_eeg).toMatchObject({ validadas: true, con_eeg_valido: 3, normales: 2, anormales: 1, sin_eeg: 3 });
expect(response.tipos_alteracion.map(t => t.codigo)).toContain('ritmo_posterior');
});
it('el resumen del paciente arma el ADOS-2, la calidad, las alteraciones y su mapa', async () => {
// Pins down: ADOS-2 domains whose totals add up (the page checks it), quality criteria in channels or dB, each
// metric's state and effects from the code system, and one map per evaluable metric from its electrodes. Fails if
// the summary stops passing the page's checks or a map appears for a metric without electrodes.
// Pins down: the age group from the summary's episode, ADOS-2 domains whose totals add up (the page checks it),
// the EEG analysis's checks as its report writes them (value or text, A/N, decisive), each metric's state, effects
// and median from the code system and its observation, and one map per evaluable metric from its electrodes'
// z-scores. Fails if the summary stops passing the page's checks or a map appears for a metric without electrodes.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
@@ -188,13 +189,27 @@ describe('Seguimiento de TEA sobre FHIR', () => {
expect(detalle.grupo_edad).toBe('16-23 meses');
expect(detalle.ados2).toMatchObject({ modulo: '1', css: 7, clasificacion: 'autismo', nivel_css: 'moderado' });
expect(detalle.eeg!.calidad).toBe('bueno');
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'linea')).toMatchObject({ valor: 3.5, unidad: 'dB' });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'line-noise')).toMatchObject({ valor: 3.5, unidad: 'dB', nivel: 'bueno', decisivo: false, electrodo: null });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'clean-windows')).toMatchObject({ valor: 95, decisivo: true });
expect(detalle.eeg!.criterios_calidad.find(c => c.codigo === 'triage-level')?.valor).toBe('completo');
const ritmo = detalle.eeg!.alteraciones.find(a => a.codigo === 'ritmo_posterior')!;
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08 });
expect(ritmo).toMatchObject({ estado: 'disminuido', valor_z: -4.08, referencia: { min: 4.5, max: 7, mediana: 5.75 }, sin_evaluar: null });
expect(ritmo.efectos).toContain('Ritmo más lento de lo esperado para la edad.');
expect(detalle.eeg!.mapas.map(m => m.codigo)).toEqual(['ritmo_posterior']);
});
it('el mapa de electrodos del reporte no da una segunda tarjeta a su métrica', async () => {
// Pins down: the report's result lists each metric's observation and its electrode-map one, both coded under the
// metric's code, and only the metric observation becomes a card. Fails if the alteraciones filter stops skipping
// `electrodos-*` observations and the metric shows up twice.
const answer = firstValueFrom(service.detalle('P-4A59E9D8B4'));
http.expectOne('/tea/fhir/Patient/P-4A59E9D8B4/$resumen-tea').flush(fx.resumenPaciente);
http.expectOne('/tea/fhir/CodeSystem/tea-eeg-metrica').flush(fx.metricasEeg);
const detalle = await answer;
const codigos = detalle.eeg!.alteraciones.map(a => a.codigo);
expect(codigos.filter(c => c === 'ritmo_posterior').length).toBe(1);
});
it('el mapa toma el valor de cada electrodo y deja en blanco lo que ninguno alcanza', () => {
// Pins down: the electrode's own z at its position, regions averaged from the measured electrodes only, and no
// value far from every electrode. Fails if the map paints the whole head from a few occipital electrodes.
@@ -13,6 +13,7 @@ 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';
import { CACU_MEASURE_IDS } from './indicadores-cacu-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
@@ -40,8 +41,8 @@ const POPULATION_GROUP: Record<string, string> = {
};
// `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, '_');
// and CaCu's have an explicit correspondence (`CAMA-BIRADS456-PACIENTE` -> `cama_birads_456_paciente`, `CACU-EU7` -> `cacu_eu7`).
export const indicadorId = (measureId: string) => CAMA_MEASURE_IDS[measureId] ?? CACU_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;
@@ -55,11 +56,24 @@ function decimal(score: Score | undefined, name: string): number | null {
return typeof value === 'number' ? value : null;
}
const round1 = (value: number) => Math.round(value * 10) / 10;
// A proportion's bounds travel as proportions; the rows hold percentages, like `valor`.
const percent = (value: number | null) => value === null ? null : round1(value * 100);
// A category's group is optional (`grupo` inside its `categoria`): a Measure that declares none, like CaMa's and TEA's,
// keeps every category ungrouped.
export function categorias(measure: Measure): Record<string, Categoria> {
return Object.fromEntries(extensions(measure, 'categoria').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null, grupo: null }]] : [];
return codigo && etiqueta ? [[codigo, { etiqueta, color: extension(e, 'color')?.valueString ?? null,
grupo: extension(e, 'grupo')?.valueCode ?? null }]] : [];
}));
}
// The groups a composition's categories belong to (`categoria-grupo`: code and caption), in the Measure's order; empty
// when the Measure declares none.
export function gruposDeCategoria(measure: Measure): Record<string, string> {
return Object.fromEntries(extensions(measure, 'categoria-grupo').flatMap(e => {
const codigo = extension(e, 'codigo')?.valueCode, etiqueta = extension(e, 'etiqueta')?.valueString;
return codigo && etiqueta ? [[codigo, etiqueta]] : [];
}));
}
function contrato(measure: Measure): string {
@@ -134,7 +148,7 @@ function proporcion(populations: Population[] | undefined, score: Score | undefi
return {
suprimido: 0, numerador, denominador,
valor: typeof score?.value === 'number' ? round1(score.value * 100) : null,
ic_bajo: decimal(score, 'ic-bajo'), ic_alto: decimal(score, 'ic-alto'),
ic_bajo: percent(decimal(score, 'ic-bajo')), ic_alto: percent(decimal(score, 'ic-alto')),
n_sin_evento: numerador !== null && denominador !== null ? denominador - numerador : null,
n_excluido: count(populations, 'denominator-exclusion') ?? 0,
};
@@ -193,6 +207,34 @@ function cruceDeHistopatologia(group: Group, estrato: string): Map<string, numbe
return celdas;
}
// A composition (C2) by one of its strata, from the report's stratifier that crosses the stratum with the category
// (`[estrato, categoria]`, as the WebApi publishes it): each stratum value with its caption, and each cell's count.
// FHIR lists only the cells that have units and the report is complete, so a cell it doesn't list is a zero; a stratum
// value nobody falls in isn't listed at all. A report with no units has no cell to cross. A missing component, a
// category the Measure doesn't declare, a repeated cell or cells that don't add up to the period's units are contract
// errors, never a silent zero. FHIR publishes no suppression marker, so nothing here is read as suppressed.
function cruceDeComposicion(group: Group, estrato: string, declaradas: readonly string[]) {
const unidades = count(group.population, 'initial-population');
const valores = new Map<string, string>(), celdas = new Map<string, number>();
const stratifier = group.stratifier?.find(s => Array.isArray(s.code) && s.code.length === 2 && code(s.code[0]) === estrato);
if (!stratifier && unidades === 0) return { valores, celdas };
if (!stratifier) throw new Error('Dimensión no admitida');
let suma = 0;
for (const stratum of stratifier.stratum ?? []) {
const del = stratum.component?.find(c => code(c.code) === estrato), cat = stratum.component?.find(c => code(c.code) !== estrato);
const valor = code(del?.value), categoria = code(cat?.value), n = stratum.population?.[0]?.count;
if (!valor || !categoria || typeof n !== 'number' || !Number.isSafeInteger(n) || n < 0) throw new Error('Celda del estrato incompleta');
if (!declaradas.includes(categoria)) throw new Error('Categoría no declarada en el estrato');
const e = estratoValor(valor), clave = `${e}|${categoria}`;
if (celdas.has(clave)) throw new Error('Celda del estrato repetida');
if (!valores.has(e)) valores.set(e, display(del!.value) ?? e);
celdas.set(clave, n);
suma += n;
}
if (unidades !== null && suma !== unidades) throw new Error('Los conteos por estrato no suman las unidades del periodo');
return { valores, 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), estrato = scope.estrato, cama = esMedidaCama(measure.id);
@@ -200,6 +242,8 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
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';
// Any other composition asked by a stratum is read from its crossed stratifier (`cruceDeComposicion`).
const porEstrato = kind === 'C2' && estrato !== undefined && !cruzado;
const cats: Record<string, Categoria> = cruzado
? Object.fromEntries(Object.entries(declaradas).map(([codigo, c]) => {
const m = CATEGORIA_HISTOPATOLOGIA_PAGINA[codigo];
@@ -209,10 +253,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
: { ...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`.
// The 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;
return kind === 'C1' && grupo === GRUPO_PRINCIPAL_FHIR ? GRUPO_PRINCIPAL_PAGINA : grupo;
};
const grupos = Object.fromEntries((measure.group ?? []).map(g => {
const id = nombre(code(g.code));
@@ -241,6 +285,21 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
});
continue;
}
if (porEstrato) {
const declaradasEnOrden = Object.keys(cats);
const { valores: delPeriodo, celdas } = cruceDeComposicion(group, estrato!, declaradasEnOrden);
for (const [e, etiqueta] of delPeriodo) {
let total = 0;
declaradasEnOrden.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 });
if (!valores.has(e)) valores.set(e, etiqueta);
}
continue;
}
if (kind === 'C2') {
const strata = group.stratifier?.[0]?.stratum ?? [];
const counts = new Map(strata.map(s => [code(s.value), s.population?.[0]?.count ?? 0]));
@@ -280,10 +339,10 @@ export function datosDeReportes(measure: Measure, reports: Report[], tipo: TipoP
periodos,
estrato: estrato ?? null,
...(estrato ? { valores_estrato: [...valores.keys()], etiquetas_estrato: cruzado ? {} : Object.fromEntries(valores) } : { valores_estrato: [] }),
...(cruzado ? { totales_estrato: totales } : {}),
...(cruzado || porEstrato ? { totales_estrato: totales } : {}),
grupos,
categorias: cats,
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : {},
grupos_de_categoria: cruzado ? { ...GRUPOS_HISTOPATOLOGIA_PAGINA } : gruposDeCategoria(measure),
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,13 +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.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 seleccion = f.nativeElement.querySelector('.selection-status') as HTMLElement;
expect(grafica.nextElementSibling?.classList.contains('legend')).toBe(true);
expect(grafica.nextElementSibling?.nextElementSibling).toBe(seleccion);
expect(seleccion.textContent).toContain('selección: Maligno');
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']);
@@ -259,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();
@@ -282,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');
});
@@ -292,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';
@@ -31,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[]; }
@@ -77,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. */
@@ -105,15 +117,22 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
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 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: id === 'MALIGNO' ? 'Maligno' : id === 'NO_MALIGNO' ? 'No maligno' : 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;
@@ -212,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>',
@@ -234,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;
@@ -244,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 } };
}
@@ -0,0 +1,42 @@
// Covers CaCu's history tab: its fixed list of indicators, in order, with a pending panel for each one the catalog
// does not publish. Catalogs are synthetic, shaped like /cacu/indicadores; the tab stays inactive, so nothing is
// requested.
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MatDialog } from '@angular/material/dialog';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import { HISTORICO_CACU, IndicadoresHistorico } from './indicadores-historico';
import { Indicador } from './indicadores.models';
@Component({ selector: 'app-plotly-chart', inputs: ['figure', 'label', 'showNotes'], template: '' })
class ChartStub {}
const item = (id: string, contrato: string): Indicador => ({ id, titulo: id, contrato, figuras: [], tipos_periodo: ['semestre', 'mes'] }) as unknown as Indicador;
describe('Histórico de CaCu', () => {
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresHistorico>>, http: HttpTestingController;
function montar(catalog: Indicador[]) {
TestBed.configureTestingModule({ imports: [IndicadoresHistorico], providers: [provideHttpClient(), provideHttpClientTesting(), { provide: MatDialog, useValue: { open: vi.fn() } }] });
TestBed.overrideComponent(IndicadoresHistorico, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
fixture = TestBed.createComponent(IndicadoresHistorico); http = TestBed.inject(HttpTestingController);
fixture.componentRef.setInput('dominio', 'cacu'); fixture.componentRef.setInput('catalog', catalog);
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', false);
fixture.detectChanges();
}
afterEach(() => { fixture?.destroy(); http.match(() => true); http.verify(); });
const paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
it('lista los seis indicadores en orden y deja pendientes los que el catálogo no publica', () => {
// Pins down: the tab shows the fixed list, not the whole catalog, so the risk bands stay out and an indicator
// the catalog lacks keeps its place as a pending panel. Fails if the list changes, or the catalog's order or
// extra measures leak into the tab.
montar([item('cacu_riesgo_banda', 'C2'), item('ind1', 'C1'), item('cacu_eu13', 'C1')]);
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CACU.map(e => e.titulo));
const pendientes = paneles().filter(p => p.textContent!.includes('Integración pendiente')).map(p => p.querySelector('h2')!.textContent);
expect(pendientes).toEqual(['Distribución de resultados citológicos', 'Tasa de confirmación histopatológica',
'Días de la toma de la citología a su resultado', 'Tiempo de tamizaje a diagnóstico']);
http.expectNone(() => true);
});
});
@@ -79,11 +79,15 @@ 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', '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);
});
@@ -99,7 +103,8 @@ describe('Histórico de CaMa', () => {
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')!.textContent!.length).toBeGreaterThan(0);
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);
@@ -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,
};
}
@@ -1,4 +1,4 @@
// Covers the history tab in the page: it exists for CaMa only, sits between Resumen and Seguimiento, and its
// Covers the history tab in the page: it exists for TEA, CaMa and CaCu, sits between Resumen and Seguimiento, and its
// panel loads nothing until it is opened. Catalogs are synthetic, shaped like /<dominio>/indicadores.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
@@ -38,12 +38,13 @@ describe('Pestaña Histórico', () => {
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.
it('cacu tiene Histórico pero no Análisis epidemiológico', () => {
// Fails if CaCu loses its history tab or gains CaMa's analysis tab.
abrir('cama', []);
abrir('cacu', [item('cacu_x', 'C2')]);
expect(tabs()).toEqual(['Resumen', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).toBeNull();
expect(tabs()).toEqual(['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(root().querySelector('#panel-historico')).not.toBeNull();
expect(root().querySelector('#panel-analisis')).toBeNull();
});
it('tea tiene Histórico pero no Análisis epidemiológico', () => {
abrir('cama', []);
@@ -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 };
@@ -27,15 +28,26 @@ const PERSONALIZADO = -1;
// publish is drawn as a pending panel instead of being left out, so what is missing stays visible.
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_mastografia', titulo: 'Porcentaje individual de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6' },
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 o 6' },
{ id: 'cama_birads_456_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cama_dias_toma_diagnostico', titulo: 'Días de tamizaje a diagnóstico' },
{ 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' },
];
// CaCu's history, built like CaMa's: a fixed list, with the same pending panel for what the catalog does not publish.
// The risk bands are left out until their batches are readable.
export const HISTORICO_CACU: readonly { id: string; titulo: string }[] = [
{ id: 'cacu_eu7', titulo: 'Distribución de resultados citológicos' },
{ id: 'ind1', titulo: 'Pacientes con citología anómala' },
{ id: 'cacu_eu13', titulo: 'Tasa de detección histopatológica' },
{ id: 'cacu_confirmacion_citologia', titulo: 'Tasa de confirmación histopatológica' },
{ id: 'cacu_eu_tiempo_reporte', titulo: 'Días de la toma de la citología a su resultado' },
{ id: 'cacu_dias_toma_diagnostico', titulo: 'Tiempo de tamizaje a diagnóstico' },
];
const HISTORICO_FIJO: Readonly<Partial<Record<string, readonly { id: string; titulo: string }[]>>> = { cama: HISTORICO_CAMA, cacu: HISTORICO_CACU };
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): Panel[] {
const pasos = TIEMPOS.map(id => paneles.find(p => p.item.id === id));
@@ -62,19 +74,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 compacto">
<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,7 +119,7 @@ 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>
@@ -122,9 +139,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);
@@ -141,7 +175,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 {
@@ -149,9 +183,11 @@ export class IndicadoresHistorico {
readonly catalog = input.required<readonly Indicador[]>();
readonly tema = input.required<Tema>();
readonly active = input(false);
// The indicators the tab draws: CaMa's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => this.dominio() === 'cama'
? HISTORICO_CAMA.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog());
// The indicators the tab draws: a domain's fixed list, where the catalog publishes it; the whole catalog elsewhere.
private readonly publicados = computed(() => {
const fijo = HISTORICO_FIJO[this.dominio()];
return fijo ? fijo.flatMap(entrada => this.catalog().filter(item => item.id === entrada.id)) : this.catalog();
});
// Only the granularities some indicator publishes; monthly first when there is one.
readonly tipos = computed(() => (['mes', 'semestre'] as const).filter(tipo => this.publicados().some(item => item.tipos_periodo.includes(tipo))));
readonly elegido = signal<TipoPeriodo | undefined>(undefined);
@@ -219,9 +255,10 @@ export class IndicadoresHistorico {
return { item, rango, estado: 'error', mensaje: error instanceof Error ? error.message : 'Datos de histórico inválidos' };
}
};
if (this.dominio() === 'cama') {
const fijo = HISTORICO_FIJO[this.dominio()];
if (fijo) {
if (!this.publicados().length) return [];
return HISTORICO_CAMA.map((entrada): Panel => {
return fijo.map((entrada): Panel => {
const item = this.catalog().find(i => i.id === entrada.id);
return item ? { ...panelDe(item), item: { ...entrada, contrato: item.contrato } } : { item: entrada, estado: 'pendiente' };
});
@@ -47,7 +47,7 @@ describe.each(['cacu', 'cama'] as const)('P0 búsqueda del ancla C2 de %s', doma
it('conserva los identificadores y la población vigente del ancla, sin recuperar el ancla histórica', () => {
if (domain === 'cama') {
expect(anchor.id).toBe('cama_birads_456_paciente');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 y 6');
expect(anchor.title).toBe('Pacientes evaluadas con BI-RADS 4, 5 o 6');
expect(KPI_BY_DOMAIN.cama.map(d => d.id)).toEqual(['cama_birads_456_paciente', 'cama_eu38a']);
} else expect(anchor.id).toBe('cacu_eu7');
const run = start(); inventory(); request(periods[0]).flush(data(periods[0]));
@@ -14,7 +14,7 @@ export const CACU_RESULTADO_KPI: KpiDefinition = {
id: 'cacu_eu_tiempo_reporte', title: 'Días de toma a resultado', contrato: 'C3r', unit: 'días (mediana)', singleAppliedPeriod: true,
};
export const CAMA_TAMIZAJE_RESULTADO_KPI: KpiDefinition = {
id: 'cama_eu38a', title: 'Tiempo de 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,7 +58,7 @@ export const KPI_BY_DOMAIN: Record<Dominio, KpiDefinition[]> = {
{ id: 'cacu_dias_toma_diagnostico', title: 'Tiempo de tamizaje a diagnóstico', contrato: 'C3r', unit: 'días (mediana)' },
],
cama: [
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 y 6', contrato: 'C2', unit: 'pacientes' },
{ id: 'cama_birads_456_paciente', title: 'Pacientes evaluadas con BI-RADS 4, 5 o 6', contrato: 'C2', unit: 'pacientes' },
CAMA_TAMIZAJE_RESULTADO_KPI,
],
};
@@ -7,6 +7,8 @@ import { provideRouter, Router } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { routes } from '../../app.routes';
import { LoginPage } from '../../auth/login-page';
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
import { IndicadoresPage } from './indicadores-page';
@@ -22,6 +24,7 @@ class ChartStub { figure?: PlotlyFigure; }
describe('UX-04 navegación Angular', () => {
let http: HttpTestingController;
async function setup() {
iniciarSesionVisual();
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
@@ -39,7 +42,14 @@ describe('UX-04 navegación Angular', () => {
req.flush({ data: [{ y: [0, null] }], layout: {} });
return req;
}
afterEach(() => { http.verify(); vi.unstubAllGlobals(); });
afterEach(() => { http.verify(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
it.each(['tea', 'cacu', 'cama'] as const)('sin sesión visual, /indicadores/%s presenta LoginPage y conserva returnUrl', async domain => {
const harness = await setup();
limpiarSesionVisual();
await harness.navigateByUrl('/indicadores/' + domain, LoginPage);
expect(TestBed.inject(Router).url).toBe('/login?returnUrl=%2Findicadores%2F' + domain);
http.expectNone(() => true);
});
it.each(['tea', 'cacu', 'cama'] as const)('navegación %s mantiene tres enlaces, estado, decoración y foco independiente', async domain => {
const harness = await setup();
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
@@ -4,8 +4,7 @@
<h1 id="dashboard-title">Ficha del paciente</h1>
<p>Consulta individual de seguimiento de {{ domainLabels[dominio] }}</p>
} @else {
@if (dominio !== 'cama') { <span class="domain">{{ domainTitles[dominio] }}, investigación</span> }
<h1 id="dashboard-title">{{ dominio === 'cama' ? 'Cáncer de mama' : 'Indicadores' }}</h1>
<h1 id="dashboard-title">{{ domainTitles[dominio] }}</h1>
<p>Explora los indicadores de {{ domainLabels[dominio] }}.</p>
}
</header>
@@ -22,11 +21,8 @@
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
@if (!catalogLoading() && filters; as state) {
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
<h2 id="global-filters-title" class="section-title">{{ dominio === 'cama' ? 'Filtros generales' : 'Filtros generales de ' + domainLabels[dominio] }}</h2>
@if (dominio !== 'cama') {
<p class="section-description">{{ dominio === 'cacu' ? 'La selección se aplica a los indicadores de oportunidad y las gráficas, salvo las que indican selección independiente: Todos con reporte.' : 'La selección aplicada se comparte entre las figuras y los indicadores destacados de este proyecto.' }}</p>
}
<app-indicador-period-filters [state]="state" [compact]="dominio === 'cama'" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
<h2 id="global-filters-title" class="section-title">Filtros</h2>
<app-indicador-period-filters [state]="state" [compact]="true" [types]="filterTypes()" [availability]="availability()" [initialPresentation]="initialPeriodBlocked"
(retryAvailability)="retryAvailability()"
(edited)="editFilters()" (apply)="applyFilters()" />
</section>
@@ -50,10 +46,13 @@
@if (kpis.length && !initialPeriodBlocked) {
<section class="kpi-section" aria-labelledby="kpi-section-title" [attr.data-domain]="dominio">
@let resumen = teaResumenPeriodo;
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
<div class="kpi-heading">
<h2 id="kpi-section-title" class="section-title">Indicadores de oportunidad</h2>
@if (periodoCompartido) { <p class="kpi-period">Periodo {{ periodoCompartido }}</p> }
</div>
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
<!-- With the summary the panels keep loading the data, but their cards are not shown. -->
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : 0)">
<div class="kpi-grid" [class.kpi-grid-oculto]="resumen" [style.--kpi-count]="kpis.length + (dominio === 'cacu' ? 2 : dominio === 'cama' ? 1 : 0)">
@for (card of kpis; track dominio + ':' + card.definition.id) {
@if (card.pending) {
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
@@ -66,6 +65,9 @@
@if (dominio === 'cacu') {
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible" />
} @else if (dominio === 'cama') {
<app-indicador-kpi-card title="Tiempo de diagnóstico a tratamiento" state="Indicador no disponible"
additionalInfo="Este indicador aún no está publicado por el catálogo institucional." />
}
</div>
</section>
@@ -73,10 +75,7 @@
<section class="graphic-section" aria-labelledby="graphic-section-title">
<div class="catalog-heading">
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
@if (!catalogLoading() && !catalogError() && catalog().length) {
<p class="catalog-count" role="status">{{ shownIndicators }} {{ shownIndicators === 1 ? 'indicador publicado' : 'indicadores publicados' }}</p>
}
<h2 id="graphic-section-title" class="section-title">Indicadores clínicos</h2>
</div>
@if (catalogLoading()) {
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
@@ -3,18 +3,20 @@
// own `:host`) -- not present upstream, whose shell lays this out differently.
// The workspace shell clips overflow, so the page scrolls itself.
:host { display: block; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; padding: 0 var(--space-6) var(--space-7); }
.dashboard { max-width: 1440px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
.dashboard { max-width: 1680px; margin: 0 auto; min-width: 0; container: dashboard / inline-size; }
h1 { font-family: var(--issste-font-heading); font-size: 1.75rem; font-weight: 500; line-height: 1.25; letter-spacing: 0; margin: .5rem 0; }
header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
.state { padding: 1.25rem; margin: 0; }
// CaMa's filter block is one compact row, as in the reference.
.global-filters[data-domain='cama'] { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); }
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.global-filters .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
.section-title { font-family: var(--issste-font-heading); font-size: 1.25rem; font-weight: 500; line-height: 1.3; margin: 0; overflow-wrap: anywhere; }
.section-description { color: var(--issste-text-secondary); margin: var(--issste-space-2) 0 var(--issste-space-4); overflow-wrap: anywhere; }
.kpi-section, .graphic-section { min-width: 0; }
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
.kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2);
padding: var(--issste-space-4) var(--issste-space-5) var(--issste-space-6); border: 1px solid var(--issste-border);
border-radius: var(--issste-radius); background: var(--issste-surface); }
.kpi-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: var(--issste-space-3); }
.kpi-section > .kpi-heading { margin-bottom: var(--issste-space-4); }
.kpi-period { margin: .15rem 0 0; color: var(--issste-text-secondary); font-size: .75rem; line-height: 1.35; white-space: nowrap; }
.graphic-section { margin-top: var(--issste-space-6); }
.kpi-grid, .catalog-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); }
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
.catalog-grid { align-items: stretch; }
@@ -22,7 +24,6 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
.reporte-acciones span { color: var(--issste-text-secondary); font: var(--mat-sys-body-medium); }
.catalog-grid > app-indicador-catalog-card { min-width: 0; margin: 0; }
.catalog-heading { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--issste-space-3); margin-bottom: var(--issste-space-4); }
.catalog-count { margin: 0 0 0 auto; text-align: right; color: var(--issste-text-secondary); overflow-wrap: anywhere; }
.catalog-search { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: var(--issste-space-3); margin-top: var(--issste-space-4); }
.catalog-search mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
.catalog-search button { min-height: 48px; }
@@ -35,19 +36,12 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
h1 { font-size: 1.5rem; }
}
.global-filters { margin-block: var(--issste-space-6); padding: clamp(.75rem, 2vw, 1.5rem); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
.global-filters { margin-block: var(--issste-space-4); padding: var(--issste-space-3) var(--issste-space-4); border: 1px solid var(--issste-border); border-radius: var(--issste-radius); background: var(--issste-surface); min-width: 0; }
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
// Five opportunity cards: at least ~280px per card; retain existing TEA/CaMa grids.
// CaMa's opportunity cards: one size, four in a row on wide screens and two by two below.
.kpi-section[data-domain='cama'] .kpi-grid { grid-auto-rows: 1fr; }
@container dashboard (min-width: 600px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@container dashboard (min-width: 1100px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
.kpi-section[data-domain='cacu'] .kpi-grid {
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
align-items: stretch;
}
.kpi-section .kpi-grid { grid-auto-rows: 1fr; }
@container dashboard (min-width: 1350px) { .kpi-section .kpi-grid { grid-template-columns: repeat(min(5, var(--kpi-count)), minmax(0, 1fr)); } }
.section-tabs { display: flex; justify-content: center; flex-wrap: wrap; gap: var(--issste-space-1);
border-block-start: 2px solid var(--issste-accent); border-block-end: 1px solid var(--issste-border);
@@ -54,15 +54,15 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
});
it('cambia al encabezado de ficha sin destruir el estado de las pestañas', () => {
load();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(true); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Ficha del paciente');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de TEA');
expect(fixture.nativeElement.textContent).toContain('Consulta individual de seguimiento de trastorno del espectro autista');
expect(fixture.nativeElement.querySelector('.section-tabs')).toBeNull();
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('dashboard-title');
fixture.debugElement.query(By.directive(IndicadoresTracking)).componentInstance.fichaPacienteAbierta.emit(false); fixture.detectChanges();
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Indicadores');
expect(fixture.nativeElement.querySelector('#dashboard-title')?.textContent.trim()).toBe('Trastorno del espectro autista');
expect(fixture.nativeElement.querySelectorAll('.section-tabs [role="tab"]')).toHaveLength(4);
expect(fixture.nativeElement.querySelector('#panel-seguimiento')?.getAttribute('aria-labelledby')).toBe('tab-seguimiento');
expect(page.activeSection()).toBe('resumen');
@@ -93,8 +93,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(Array.from(sections).map(section => section.getAttribute('aria-labelledby'))).toEqual(['global-filters-title', 'graphic-section-title']);
// Cada figura trae su tabla de valores: no hay resumen de indicadores al final de la página.
expect(fixture.nativeElement.querySelector('app-indicadores-numeric-summary')).toBeNull();
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
toggle(0); toggle(1); flushAll();
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]);
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']);
@@ -108,13 +107,14 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(host.querySelector('mat-select')).toBeNull();
expect(host.querySelector('.figure-skeleton').textContent).toContain('pendiente');
expect(host.textContent).not.toContain('Contrato C1');
expect(host.querySelector('.catalog-metadata').textContent.trim()).toBe('2 figuras publicadas');
expect(host.querySelector('.catalog-metadata')).toBeNull();
expect(host.querySelector('.pin-toggle')).toBeNull();
http.expectNone(() => true);
});
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
load([item, { ...second, vistas: ['historico'] }]);
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
expect(fixture.nativeElement.querySelector('.catalog-count').textContent).toContain('1 indicador publicado');
expect(fixture.nativeElement.textContent).not.toContain('indicador publicado');
expect(page.catalog()).toHaveLength(2);
http.expectNone(r => r.url.endsWith('/figuras/f1'));
});
@@ -123,7 +123,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
const header = host.querySelector('header'); toggle(); flushAll();
const panel = panels()[0]; cards()[0].setVisible(false); fixture.detectChanges();
expect(host.querySelector('header')).toBe(header); expect(panels()[0]).toBe(panel);
expect(host.querySelector('.catalog-metadata')).toBeTruthy(); http.expectNone(() => true);
expect(host.querySelector('.catalog-metadata')).toBeNull(); http.expectNone(() => true);
});
it('UX-06C: conserva título largo completo y el control separado de la identidad', () => {
const title = 'Distribución de indicadores con un título extenso y múltiples palabras para revisión responsive';
@@ -132,7 +132,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
expect(header.querySelector('h2')?.textContent).toBe(title);
expect(header.querySelector('.card-identity button')).toBeNull();
expect(header.querySelector('button')).toBeNull();
expect(fixture.nativeElement.querySelector('.pin-toggle').getAttribute('aria-label')).toContain(title);
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
http.expectNone(() => true);
});
it('UX-06B la navegación entre dominios es la del encabezado: la página no la duplica', () => {
@@ -325,7 +325,8 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
toggle(index); toggle(index); flushAll(); await fixture.whenStable();
expect(control().entry.draft.mode).toBe('empty'); expect(control().state.applied?.selection.mode).toBe('todos');
const state = panels()[0].result(); const saves = vi.spyOn(TestBed.inject(IndicadoresMemory), 'saveGlobal');
const select = fixture.debugElement.queryAll(By.directive(MatSelect)).find(e => e.componentInstance.multiple)!;
expect(fixture.debugElement.queryAll(By.directive(MatSelect)).some(e => e.componentInstance.multiple)).toBe(false);
const select = fixture.debugElement.query(By.directive(MatSelect));
const writes = vi.spyOn(select.injector.get(NgModel).control, 'setValue');
for (let i = 0; i < 3; i++) {
select.componentInstance.open(); fixture.detectChanges(); await fixture.whenStable();
@@ -32,6 +32,7 @@ import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
import { IndicadoresHistorico } from './indicadores-historico';
import { IndicadorHistopatologiaPendiente } from './indicador-histopatologia-pendiente';
import { TITULO_MASTOGRAFIAS_CAMA } from './indicadores-figure-labels';
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
@@ -57,7 +58,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
})
export class IndicadoresPage {
get sections(): readonly { id: DashboardSection; label: string }[] { return this.dominio === 'cama' ? SECTIONS_CAMA : this.conHistorico ? SECTIONS_WITH_HISTORY : SECTIONS; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama'; }
get conHistorico() { return this.dominio === 'tea' || this.dominio === 'cama' || this.dominio === 'cacu'; }
get conAnalisis() { return CAMA_ANALYSIS_ENABLED && this.dominio === 'cama'; }
readonly activeSection = signal<DashboardSection>('resumen');
readonly fichaPacienteAbierta = signal(false);
@@ -101,6 +102,14 @@ export class IndicadoresPage {
private readonly indicatorSelect = viewChild<MatSelect>('indicatorSelect');
private readonly graphicCards = viewChildren(IndicadorCatalogCard);
readonly kpiPanels = viewChildren(IndicadorKpiPanel);
// The opportunity cards share the period their own query already resolved.
get periodoCompartido(): string {
const deConsulta = this.kpiPanels().map(panel => panel.temporalReference.trim())
.find(text => /^\d{4}-(?:S[12]|0[1-9]|1[0-2])$/.test(text));
if (deConsulta) return deConsulta;
const applied = this.filters?.applied;
return applied?.selection.mode === 'explicit' && applied.selection.periodos.length === 1 ? applied.selection.periodos[0] : '';
}
private readonly observedRegions = new Map<Element, IndicadorCatalogCard>();
private renderedCards: readonly IndicadorCatalogCard[] = [];
private visibilityObserver?: IntersectionObserver;
@@ -292,9 +301,12 @@ export class IndicadoresPage {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute, { optional: true });
dominio: Dominio = 'tea';
readonly domainLabels: Record<Dominio, string> = { tea: 'TEA', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama' };
// At the start of the header line.
readonly domainTitles: Record<Dominio, string> = { ...this.domainLabels, cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama' };
readonly domainLabels: Record<Dominio, string> = {
tea: 'trastorno del espectro autista', cacu: 'cáncer cervicouterino', cama: 'cáncer de mama',
};
readonly domainTitles: Record<Dominio, string> = {
tea: 'Trastorno del espectro autista', cacu: 'Cáncer cervicouterino', cama: 'Cáncer de mama',
};
readonly kpisByDomain = { ...KPI_BY_DOMAIN, tea: [...KPI_BY_DOMAIN.tea, ...KPI_RESUMEN_TEA] };
figureApplied(item: Indicador) { return figureApplied(this.dominio, item.id, this.filters!.applied); }
independentPeriods(item: Indicador) { return independentFigurePeriods(this.dominio, item.id); }
@@ -323,7 +335,6 @@ export class IndicadoresPage {
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
}
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
get shownIndicators() { return this.catalogOrder().length; }
get availableKpis() { return this.kpisByDomain[this.dominio].filter(definition => this.catalog().some(item => item.id === definition.id)); }
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
get teaResumenPeriodo(): string | undefined {
@@ -347,9 +358,9 @@ export class IndicadoresPage {
readonly catalog = signal<Indicador[]>([]);
// Ids of the indicators to render; null shows the whole catalog.
readonly indicatorSelection = signal<string[] | null>(null);
// CaMa follows the mockup: no search box and no pins; its cards are the ones the summary draws.
readonly searchVisible = computed(() => { const total = this.catalogOrder().length; return this.dominio !== 'cama' && total >= 2; });
// Stable presentation priority; pins still take precedence in the grid.
// The summary follows CaMa's mockup: no search box and no pins in any domain.
readonly searchVisible = computed(() => false);
// Stable presentation order. Pins no longer reorder the summary.
readonly catalogOrder = computed(() => {
const catalog = this.catalog();
return this.dominio === 'cacu'
@@ -366,8 +377,7 @@ export class IndicadoresPage {
});
readonly searchResults = computed(() => {
const selected = new Set(this.selectedIndicators());
const items = this.catalogOrder().filter(item => selected.has(item.id));
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
return { items: this.catalogOrder().filter(item => selected.has(item.id)) };
});
readonly catalogLoading = signal(true);
readonly catalogError = signal('');
@@ -484,7 +494,8 @@ export class IndicadoresPage {
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
this.catalogLoading.set(false);
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
this.catalog.set(items);
this.catalog.set(this.dominio === 'cama' ? items.map(item => item.id === 'cama_birads_456_mastografia'
? { ...item, titulo: TITULO_MASTOGRAFIAS_CAMA } : item) : items);
this.filtersEdited();
this.catalogError.set(error);
this.availabilityRequests.next();
@@ -97,14 +97,17 @@ describe('P0.1 selección publicada y último periodo por KPI', () => {
const control = editor(); control.changeTipo('mes'); control.select(['2025-10']); fixture.detectChanges();
expect(control.options).toEqual(['2026-01', '2025-10', '2025-02']);
expect(fixture.nativeElement.querySelector('.period-builder')).toBeNull();
expect(fixture.nativeElement.textContent).toContain('Existe reporte en al menos un indicador');
expect(fixture.nativeElement.querySelector('.fields.compact')).not.toBeNull();
expect(fixture.nativeElement.textContent).not.toContain('Existe reporte en al menos un indicador');
expect(fixture.componentInstance.filters!.applied.selection.mode).toBe('todos'); http.expectNone(() => true);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
const single = flushDatos('cacu'); expect(single).toHaveLength(2);
expect(single.every(r => r.request.params.get('periodos') === '2025-10')).toBe(true);
control.select(['2025-10', '2025-02']); fixture.detectChanges(); http.expectNone(() => true);
expect(control.selectedPeriods).toEqual(['2025-10']);
expect(control.selectedPeriods).toEqual(['2025-02']);
fixture.componentInstance.applyFilters(); fixture.detectChanges();
const replaced = flushDatos('cacu');
expect(replaced.every(r => r.request.params.get('periodos') === '2025-02')).toBe(true);
expect(panels().every(p => p.result().state !== 'Selección no consolidable')).toBe(true);
http.expectNone(() => true);
await fixture.whenStable();
@@ -35,46 +35,40 @@ describe('UX-06E.D.3.B fijación temporal', () => {
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function card(id: string) { return cards().find(c => c.indicador.id === id)!; }
function ids() { return cards().map(c => c.indicador.id); }
function button(id: string): HTMLButtonElement { return card(id).host.nativeElement.querySelector('.pin-toggle')!; }
async function settle() { await fixture.whenStable(); for (let i = 0; i < 12; i++) await Promise.resolve(); fixture.detectChanges(); }
async function pin(id: string) { button(id).click(); fixture.detectChanges(); await settle(); }
async function pin(id: string) { page.togglePinned(card(id).indicador); fixture.detectChanges(); await settle(); }
function respond() { http.match(r => r.url.includes('/figuras/')).forEach(r => r.flush({ data: [{ y: [1] }], layout: {} })); fixture.detectChanges(); }
it('fija y desfija con control nativo, texto, estado accesible y sin HTTP', async () => {
const control = button('i3');
expect(control.type).toBe('button'); expect(control.tabIndex).toBe(0);
expect(control.textContent).toContain('Fijar indicador'); expect(control.getAttribute('aria-pressed')).toBe('false');
expect(control.getAttribute('aria-label')).toContain('Fijar indicador');
for (const key of ['Enter', ' ']) {
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true });
control.dispatchEvent(event); expect(event.defaultPrevented).toBe(false);
}
await pin('i3'); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']);
expect(button('i3')).toBe(control); expect(control.getAttribute('aria-pressed')).toBe('true');
expect(control.textContent).toContain('Desfijar indicador'); expect(control.getAttribute('aria-label')).toContain('Desfijar indicador');
await pin('i3'); expect(ids()).toEqual(items.map(i => i.id)); expect(control.getAttribute('aria-pressed')).toBe('false');
it('no muestra el control de fijar y la memoria no reordena las tarjetas', async () => {
expect(fixture.nativeElement.querySelector('.pin-toggle')).toBeNull();
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id));
await pin('i3');
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(false);
expect(ids()).toEqual(items.map(i => i.id));
http.expectNone(() => true);
});
it('varios fijados conservan orden del catálogo, independientemente del orden de clics', async () => {
it('varios fijados no alteran el orden del catálogo', async () => {
const original = page.catalog(), snapshot = JSON.stringify(original);
await pin('i4'); await pin('i2'); await pin('i0');
expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
await pin('i2'); expect(ids()).toEqual(['i0', 'i4', 'i1', 'i2', 'i3']);
await pin('i2'); expect(ids()).toEqual(['i0', 'i2', 'i4', 'i1', 'i3']);
expect(ids()).toEqual(items.map(i => i.id));
await pin('i2'); expect(ids()).toEqual(items.map(i => i.id));
expect(page.catalog()).toBe(original); expect(JSON.stringify(original)).toBe(snapshot); http.expectNone(() => true);
});
it('la selección de indicadores conserva la prioridad de los fijados', async () => {
it('la selección de indicadores conserva el orden del catálogo', async () => {
await pin('i3'); await pin('i4');
page.changeIndicatorSelection(['i1', 'i3', 'i4']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i3', 'i4', 'i1']);
expect(ids()).toEqual(['i1', 'i3', 'i4']);
await pin('i1'); expect(ids()).toEqual(['i1', 'i3', 'i4']);
expect(cards()).toHaveLength(3); http.expectNone(() => true);
});
it('Mostrar todos restaura el catálogo con los fijados primero', async () => {
it('Mostrar todos restaura el catálogo en su orden', async () => {
await pin('i3'); page.changeIndicatorSelection(['i0']); fixture.detectChanges(); await settle();
expect(ids()).toEqual(['i0']);
fixture.nativeElement.querySelector('.catalog-search button').click(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(['i3', 'i0', 'i1', 'i2', 'i4']); http.expectNone(() => true);
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
page.showAllIndicators(); fixture.detectChanges(); await settle();
expect(page.indicatorSelection()).toBeNull(); expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
});
it('un fijado sin seleccionar no se muestra', async () => {
await pin('i2'); page.changeIndicatorSelection(['i0', 'i1']); fixture.detectChanges(); await settle();
@@ -82,11 +76,16 @@ describe('UX-06E.D.3.B fijación temporal', () => {
});
it('memoria independiente por dominio y persistente al recrear la página', async () => {
await pin('i3'); page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
const memory = TestBed.inject(IndicadoresMemory);
expect(memory.isPinned('cacu', 'i1')).toBe(true);
expect(memory.isPinned('tea', 'i3')).toBe(true);
expect(memory.isPinned('cama', 'i1')).toBe(false);
page.changeDominio('cacu'); load('cacu'); expect(ids()).toEqual(items.map(i => i.id));
page.changeDominio('tea'); load(); expect(ids()).toEqual(items.map(i => i.id));
fixture.destroy(); create(); load();
expect(TestBed.inject(IndicadoresMemory).isPinned('tea', 'i3')).toBe(true);
expect(ids()).toEqual(items.map(i => i.id)); http.expectNone(() => true);
});
it('no usa Storage y una nueva memoria reinicia la fijación', async () => {
const read = vi.spyOn(Storage.prototype, 'getItem'), write = vi.spyOn(Storage.prototype, 'setItem');
@@ -94,10 +93,12 @@ describe('UX-06E.D.3.B fijación temporal', () => {
expect(new IndicadoresMemory().isPinned('tea', 'i2')).toBe(false);
expect(read).not.toHaveBeenCalled(); expect(write).not.toHaveBeenCalled(); http.expectNone(() => true);
});
it('mover la tarjeta conserva foco en su botón existente', async () => {
const control = button('i4'); control.focus(); await pin('i4');
expect(control.isConnected).toBe(true); expect(document.activeElement).toBe(control);
await pin('i4'); expect(document.activeElement).toBe(control); http.expectNone(() => true);
it('fijar no mueve la tarjeta ni pide figuras', async () => {
const before = cards();
await pin('i4');
expect(cards()).toEqual(before);
await pin('i4');
expect(cards()).toEqual(before); http.expectNone(() => true);
});
it('preserva figura seleccionada, estado de visibilidad, panel y host Plotly', async () => {
card('i3').setVisible(true); fixture.detectChanges(); respond(); await settle();
@@ -11,6 +11,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { routes } from '../../app.routes';
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
import fixtureData from './fixtures/cama_seguimiento.json';
import { CAMA_ANALYSIS_ENABLED, IndicadoresPage } from './indicadores-page';
@@ -41,13 +42,14 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
let http: HttpTestingController;
const corte = hoyIso();
beforeEach(() => {
iniciarSesionVisual();
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
async function entrar() {
const harness = await RouterTestingHarness.create();
@@ -161,7 +163,7 @@ describe('Recorrido de cáncer de mama: análisis, lista, ficha y regreso', () =
http.expectOne('/' + dominio + '/indicadores').flush([]); await e.asentar();
expect(e.page.seleccionSeguimiento()).toBeUndefined();
expect(Array.from(e.root.querySelectorAll('[role="tab"]')).map(t => t.textContent?.trim())).toEqual(
dominio === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones']);
['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones']);
expect(e.root.querySelector('#panel-analisis')).toBeNull();
}
e.page.changeDominio('cama'); e.harness.detectChanges();
@@ -11,7 +11,7 @@ describe('Regresión del mapeo FHIR en CaCu y TEA', () => {
it('las 16 medidas se mapean igual que antes: ids, catálogo, ficha y filas de datos', () => {
// Pins down: ids, catalog entries, sheets and data rows of CaCu's seven and TEA's nine measures, over real reports,
// equal the recorded ones; an error counts as a result too. Fails if a change meant for CaMa (its id table, its
// group name, its undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// undeclared categories, its sheet code) reaches another domain. If the new result is the right one,
// regenerate the recorded mapping and say why in the change.
const actual = mapeoDeCacuYTea({ indicadorId, indicadorDeMeasure, metadatosDeMeasure, datosDeReportes });
expect(Object.keys(actual)).toEqual(Object.keys(esperado));
@@ -4,7 +4,6 @@ import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';
import { IndicadoresPage } from './indicadores-page';
import { IndicadorCatalogCard } from './indicador-catalog-card';
import { IndicadorFigurePanel } from './indicador-figure-panel';
@@ -40,24 +39,20 @@ describe('Selección de indicadores gráficos', () => {
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
function ids() { return cards().map(c => c.indicador.id); }
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel); }
function select() { return fixture.debugElement.query(By.css('.catalog-search mat-select'))?.componentInstance as MatSelect | undefined; }
function showAll(): HTMLButtonElement { return fixture.nativeElement.querySelector('.catalog-search button'); }
function result() { return (fixture.nativeElement.querySelector('#catalog-search-result') as HTMLElement).textContent!.trim(); }
function choose(selection: string[]) { page.changeIndicatorSelection(selection); fixture.detectChanges(); }
it.each([0, 1, 2, 5])('muestra el selector desde dos indicadores: catálogo de %i', count => {
it.each([0, 1, 2, 5])('no ofrece buscador y muestra el catálogo completo: %i indicadores', count => {
load(Array.from({ length: count }, (_, i) => ({ ...items[0], id: 'id-' + i })));
expect(!!select()).toBe(count >= 2); expect(cards()).toHaveLength(count);
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(cards()).toHaveLength(count);
http.expectNone(() => true);
});
it('lista todo el catálogo, con todos seleccionados al inicio', () => {
load();
expect(select()!.multiple).toBe(true);
expect(select()!.options.map(o => o._getHostElement().querySelector('.option-title')!.textContent)).toEqual(items.map(i => i.titulo));
expect(fixture.nativeElement.querySelector('.catalog-search')).toBeNull();
expect(page.selectedIndicators()).toEqual(items.map(i => i.id));
expect(page.selectionSummary()).toBe('Todos los indicadores');
expect(result()).toBe('Mostrando 5 de 5 indicadores.');
expect(showAll().disabled).toBe(true);
expect(fixture.nativeElement.textContent).not.toContain('Mostrando 5 de 5 indicadores.');
http.expectNone(() => true);
});
it('solo renderiza los seleccionados y conserva las tarjetas que siguen visibles', () => {
@@ -66,8 +61,7 @@ describe('Selección de indicadores gráficos', () => {
expect(ids()).toEqual(['B02', 'E05']);
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
expect(page.selectionSummary()).toBe('2 indicadores');
expect(result()).toBe('Mostrando 2 de 5 indicadores.');
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('5 indicadores publicados');
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
expect(page.catalog()).toBe(original);
http.expectNone(() => true);
@@ -76,9 +70,8 @@ describe('Selección de indicadores gráficos', () => {
load(); choose([]);
expect(cards()).toHaveLength(0); expect(panels()).toHaveLength(0);
expect(fixture.nativeElement.textContent).toContain('No hay indicadores seleccionados');
expect(showAll().disabled).toBe(false);
showAll().click(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull(); expect(showAll().disabled).toBe(true);
page.showAllIndicators(); fixture.detectChanges();
expect(ids()).toEqual(items.map(i => i.id)); expect(page.indicatorSelection()).toBeNull();
http.expectNone(() => true);
});
it('marcar todos equivale a no filtrar', () => {
@@ -90,26 +83,18 @@ describe('Selección de indicadores gráficos', () => {
choose(['A01']);
expect(Array.from(fixture.nativeElement.querySelectorAll('app-indicador-kpi-panel'))).toEqual(kpis);
});
it('«Ir» lleva a la tarjeta sin alternar la opción y muestra el indicador si estaba oculto', async () => {
it('ir a un indicador oculto lo vuelve a mostrar y desplaza hasta su tarjeta', async () => {
const scroll = vi.fn();
Element.prototype.scrollIntoView = scroll;
load(); choose(['A01']);
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
const go = (id: string) => Array.from(document.querySelectorAll<HTMLAnchorElement>('.indicator-select-panel .option-go'))
.find(a => a.closest('mat-option')!.textContent!.includes(items.find(i => i.id === id)!.titulo))!;
expect(go('D04').getAttribute('aria-label')).toBe('Ir a Seguimiento');
// The scroll waits until the panel has finished closing.
const settle = (calls: number) => vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(calls); });
go('D04').click(); fixture.detectChanges(); await fixture.whenStable();
expect(document.querySelector('.indicator-select-panel')).toBeNull();
page.goToIndicator('D04'); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
expect(select()!.panelOpen).toBe(false);
await settle(1);
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(1); });
expect((scroll.mock.contexts[0] as HTMLElement).querySelector('h2')?.textContent).toContain('Seguimiento');
select()!.open(); fixture.detectChanges(); await fixture.whenStable();
go('A01').click(); fixture.detectChanges(); await fixture.whenStable();
// Already visible: the selection is untouched.
page.goToIndicator('A01'); fixture.detectChanges(); await fixture.whenStable();
expect(page.selectedIndicators()).toEqual(['A01', 'D04']);
await settle(2);
await vi.waitFor(async () => { fixture.detectChanges(); await fixture.whenStable(); expect(scroll).toHaveBeenCalledTimes(2); });
http.match(() => true).forEach(r => r.flush({ data: [], layout: {} }));
});
it('no muestra el botón flotante de navegación por indicadores', () => {
@@ -6,6 +6,7 @@ import { provideRouter } from '@angular/router';
import { RouterTestingHarness } from '@angular/router/testing';
import { By } from '@angular/platform-browser';
import { routes } from '../../app.routes';
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
import { IndicadoresPage } from './indicadores-page';
import { IndicadoresDefinitions } from './indicadores-definitions';
import { IndicadorCatalogCard } from './indicador-catalog-card';
@@ -24,12 +25,13 @@ const catalog: Indicador[] = [
describe('Secciones compartidas por dominio', () => {
let http: HttpTestingController;
beforeEach(() => {
iniciarSesionVisual();
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
http = TestBed.inject(HttpTestingController);
});
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
const harness = await RouterTestingHarness.create();
@@ -37,9 +39,9 @@ describe('Secciones compartidas por dominio', () => {
http.expectOne('/' + domain + '/indicadores').flush(catalog); harness.detectChanges();
const root = harness.routeNativeElement!;
const tabs = Array.from(root.querySelectorAll<HTMLButtonElement>('[role="tab"]'));
// TEA and CaMa also have Histórico; CaMa labels Seguimiento as Análisis de Riesgos; CaCu keeps its three.
// TEA, CaMa and CaCu have Histórico; CaMa labels Seguimiento as Análisis de Riesgos.
const esperadas = domain === 'cama' ? ['Resumen', 'Histórico', 'Análisis de Riesgos', 'Datos y definiciones']
: domain === 'tea' ? ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'] : ['Resumen', 'Seguimiento', 'Datos y definiciones'];
: ['Resumen', 'Histórico', 'Seguimiento', 'Datos y definiciones'];
expect(tabs.map(t => t.textContent?.trim())).toEqual(esperadas);
expect(tabs.map(t => t.getAttribute('aria-selected'))).toEqual(esperadas.map((_, i) => String(i === 0)));
const tab = (id: string) => tabs.find(t => t.id === 'tab-' + id)!;
@@ -10,6 +10,13 @@ export function stratifiedCapabilities(item: Indicador): DimensionEstrato[] {
&& typeof f.etiqueta === 'string' && Array.isArray(f.valores) && f.valores.length > 0
&& f.valores.every(v => typeof v?.valor === 'string' && typeof v.etiqueta === 'string'))) : [];
}
// Whether a composition declares `estrato` among its strata: the catalog from FHIR carries the Measure's declared strata
// (`estratos`) and no local filters. Only views that read one fixed stratum use it (CaCu's EU7 by follow-up status);
// it doesn't turn on stratified figures or filters for other C2 measures.
export function declaraEstrato(item: Indicador, estrato: DimensionEstrato): boolean {
const declarados = (item as Indicador & { estratos?: unknown }).estratos;
return item.contrato === 'C2' && Array.isArray(declarados) && declarados.includes(estrato);
}
export interface StratifiedCell { category: string; stratum: string; value: number | null; status: 'Publicado' | 'Suprimido' | 'No disponible'; }
export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato, period: string, tema: Tema, selection: DonutSelection = {}): { figure: PlotlyFigure; cells: StratifiedCell[] } {
if (data.contrato !== 'C2' || data['estrato'] !== dimension || data.periodos.length !== 1 || data.periodos[0] !== period
@@ -43,7 +50,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
const cells: StratifiedCell[] = [];
const theme = c2Theme(tema);
const palette = seriesColors(categories.map(([, c]) => c.color));
const palette = seriesColors(categories.map(([, c]) => c.color), categories.map(([id]) => id));
const figure: PlotlyFigure = { data: strata.map((s, series) => {
const selected = categories.map(([id, c]) => {
const row = rows.get(JSON.stringify([id, s]));
@@ -61,15 +61,23 @@
@if (teaData; as response) {
<section class="resumen-eeg" aria-labelledby="resumen-eeg-titulo">
<h3 id="resumen-eeg-titulo">EEG de los pacientes filtrados</h3>
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
}
</dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
@if (response.resumen_eeg.validadas) {
<dl>
<div><dt>Normales</dt><dd>{{ response.resumen_eeg.normales }}</dd></div>
<div><dt>Anormales</dt><dd>{{ response.resumen_eeg.anormales }}</dd></div>
<div><dt>Sin EEG</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
@for (a of response.resumen_eeg.por_alteracion; track a.codigo) {
<div class="tipo"><dt>{{ a.etiqueta }}</dt><dd>{{ a.n }}</dd></div>
}
</dl>
<p>Un paciente con dos alteraciones cuenta en ambas, así que los tipos pueden sumar más que los anormales.</p>
} @else {
<dl>
<div><dt>Con EEG válido</dt><dd>{{ response.resumen_eeg.con_eeg_valido }}</dd></div>
<div><dt>Sin EEG válido</dt><dd>{{ response.resumen_eeg.sin_eeg }}</dd></div>
</dl>
<p>Las alteraciones del EEG se muestran cuando se validen sus curvas de referencia.</p>
}
</section>
<div class="tracking-table" role="region" aria-label="Lista de seguimiento" tabindex="0">
<table>
@@ -12,7 +12,7 @@ import { PacienteDetalleState } from './paciente-detalle/paciente-detalle.state'
import { Dominio } from './indicadores.models';
import { ETIQUETA_IDENTIDAD, IdentidadPaciente, identidadDe } from './paciente-identidad';
import { IndicadoresService } from './indicadores.service';
import { ALTERACIONES_EEG, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { ALTERACIONES_EEG, EEG_VALIDO, ESTADOS_CASO, GRUPOS_EDAD_TEA, RANGOS_CSS, RANGOS_MCHAT, TeaSeguimientoPaciente, TeaSeguimientoResponse, TeaSeguimientoService } from './tea-seguimiento.service';
import { TeaPacienteResumen } from './tea-paciente-resumen';
@Component({
@@ -98,6 +98,8 @@ export class IndicadoresTracking implements OnChanges {
if (result.data) {
const data = result.data;
this.tiposAlteracion = data.tipos_alteracion;
// Until the alterations are validated, the EEG filter can only tell a valid EEG from none.
this.statuses = data.resumen_eeg.validadas ? ALTERACIONES_EEG : EEG_VALIDO;
this.applied = { ...this.applied, corte: data.corte, meses: data.ventana.meses, estatus: data.filtros.alteraciones_eeg ?? undefined, page: data.paginacion.page, page_size: data.paginacion.page_size };
this.draft = { ...this.applied };
}
@@ -186,11 +186,11 @@ describe('UX-06E.D.3.A tarjetas permanentes y visibilidad controlada', () => {
const target = before[0].visibilityRegion!.nativeElement; notify(); page.togglePinned(items[4]); await render();
page.changeIndicatorSelection([items[3].id, items[4].id]); await render(); positions(cards().map((_, i) => [1200 + i * 1000, 0]));
observer().emit(target); await idle(); http.expectNone(() => true);
// The pinned indicator leads; the other selected one keeps its component.
expect(cards()).toEqual([before[4], before[3]]);
positions(cards().map((_, i) => [i === 1 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
// Pins no longer reorder; the selected indicators keep catalog order and their components.
expect(cards()).toEqual([before[3], before[4]]);
positions(cards().map((_, i) => [i === 0 ? 200 : 1200 + i * 1000, 0])); notify(); await confirm();
http.expectOne(r => r.url.includes('/i3/figuras/')).flush({ data: [], layout: {} }); await render();
expect(cards()[1].selectedFigure).toBe('f');
expect(cards()[0].selectedFigure).toBe('f');
});
it.each([{ data: [], layout: {} }, { data: [{ y: [null, null] }], layout: { annotations: [{ text: 'Valores ocultos por supresión.' }] } }])('resultado vacío o suprimido termina skeleton y conserva JSON: %j', async figure => {
await load([items[0]]); positions([[200, 0]]); notify(); await confirm();
@@ -142,6 +142,23 @@ describe('UX-04 validación defensiva HTTP', () => {
describe('contrato datos exclusivo de KPI', () => {
beforeEach(() => TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] }));
it('conserva los conteos, totales y celdas suprimidas que publica WebApi para mastografías de CaMa', () => {
const http = TestBed.inject(HttpTestingController);
const payload = {
id: 'cama_birads_456_mastografia', contrato: 'C2', tipo_periodo: 'semestre', periodos: ['2025-S1', '2025-S2'],
filas: [
{ periodo: '2025-S1', categoria: 'BIRADS_4', n: 15, suprimido: 0 },
{ periodo: '2025-S1', categoria: 'BIRADS_5', n: 0, suprimido: 0 },
{ periodo: '2025-S2', categoria: 'BIRADS_4', n: null, suprimido: 1 },
],
totales_estrato: [{ periodo: '2025-S1', estrato: 'BIRADS_4', n: 15, suprimido: 0 }],
};
let result: unknown;
TestBed.inject(IndicadoresService).datos('cama', payload.id, 'semestre', payload.periodos).subscribe(value => result = value);
http.expectOne(req => req.url === `/cama/indicadores/${payload.id}/datos`).flush(payload);
expect(result).toEqual(payload);
http.verify();
});
it('envía sólo periodos explícitos sin intervalo de tiempo ni tema y conserva filas y notas', () => {
const http = TestBed.inject(HttpTestingController); let result: unknown;
TestBed.inject(IndicadoresService).datos('cacu', 'cacu_eu7', 'mes', ['2025-01']).subscribe(v => result = v);
@@ -0,0 +1,76 @@
// Covers the histologic-type classification and its column in the follow-up table. It uses the CaMa follow-up
// fixture (fixtures/cama_seguimiento.json), to which each test adds a synthetic `tipo_histologico` per row.
import fixtureData from './fixtures/cama_seguimiento.json';
import { clasificacionHistologica, MAPEO_HISTOLOGICO, SIN_CLASIFICAR } from './mapeo-histologico';
import { seguimientoTablaResponse } from './seguimiento-tabla.service';
const respuesta = () => structuredClone(fixtureData) as unknown as { columnas: { clave: string; etiqueta: string }[]; items: Record<string, string | number | null>[] };
describe('Clasificación histológica', () => {
it.each([
['Ductal (NST)', 'Carcinoma invasor'], ['Lobulillar', 'Carcinoma invasor'], ['Ductal-lobulillar mixto', 'Carcinoma invasor'],
['Mucinoso', 'Carcinoma invasor'], ['Paget', 'Carcinoma in situ'], ['Papilar', 'Revisar (Benigno / In situ / Invasor)'],
['Tubular', 'Carcinoma invasor'], ['cribiforme', 'Revisar (In situ / Invasor)'], ['Micropapilar', 'Revisar (In situ / Invasor)'],
['Inflamatorio', 'Carcinoma invasor'], ['Medular', 'Carcinoma invasor'], ['Otros', 'Revisar (Benigno / In situ / Invasor)'],
['SIN MAPEAR', 'Sin clasificar'],
])('asigna a «%s» la clasificación «%s»', (tipo, clasificacion) => {
// Fails if a type is moved to another group or dropped from the mapping.
expect(clasificacionHistologica(tipo)).toBe(clasificacion);
});
it('la categoría combinada «Tubular / cribiforme» del gráfico es carcinoma invasor', () => {
// Fails if the chart's merged category stops being classified, which would leave its patients unclassified.
expect(clasificacionHistologica('Tubular / cribiforme')).toBe('Carcinoma invasor');
});
it('un tipo fuera del mapeo, incluido uno heredado del prototipo de objeto, es «Sin clasificar»', () => {
// Fails if the lookup returns inherited properties such as «constructor» instead of the fallback.
for (const tipo of ['Desconocido', '', 'constructor', 'toString']) expect(clasificacionHistologica(tipo)).toBe(SIN_CLASIFICAR);
});
it('el mapeo conserva sus trece tipos y sus cuatro clasificaciones directas', () => {
// Fails if a type is added or removed without reviewing its classification.
expect(Object.keys(MAPEO_HISTOLOGICO)).toHaveLength(14);
expect(new Set(Object.values(MAPEO_HISTOLOGICO))).toEqual(new Set([
'Carcinoma invasor', 'Carcinoma in situ', 'Revisar (Benigno / In situ / Invasor)', 'Revisar (In situ / Invasor)', 'Sin clasificar']));
});
});
describe('Seguimiento: columna de clasificación histológica', () => {
const tipos = ['Ductal (NST)', 'Paget', 'Otros', 'SIN MAPEAR', 'Zzz'];
it('cada paciente recibe la clasificación de su propio tipo, en una columna tras el tipo o tras el resultado de la biopsia', () => {
// Fails if the classification is computed from another row or placed away from the biopsy columns.
const datos = respuesta();
const conBiopsia = datos.items.filter(item => item['biopsia'] !== null);
conBiopsia.forEach((item, i) => { item['tipo_histologico'] = tipos[i % tipos.length]; });
const r = seguimientoTablaResponse(datos);
const claves = r.columnas.map(c => c.clave);
expect(claves[claves.indexOf('biopsia') + 1]).toBe('clasificacion_histologica');
expect(r.columnas.find(c => c.clave === 'clasificacion_histologica')!.etiqueta).toBe('Clasificación histológica');
for (const item of r.items.filter(item => typeof item['tipo_histologico'] === 'string')) {
expect(item['clasificacion_histologica']).toBe(clasificacionHistologica(item['tipo_histologico'] as string));
}
});
it('con una columna de tipo, la clasificación va justo después de ella', () => {
// Fails if the derived column ignores the type's own column and lands elsewhere.
const datos = respuesta();
datos.columnas.splice(datos.columnas.findIndex(c => c.clave === 'biopsia') + 1, 0, { clave: 'tipo_histologico', etiqueta: 'Tipo histológico' });
datos.items.forEach(item => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Lobulillar'; });
const claves = seguimientoTablaResponse(datos).columnas.map(c => c.clave);
expect(claves.slice(claves.indexOf('tipo_histologico'), claves.indexOf('tipo_histologico') + 2)).toEqual(['tipo_histologico', 'clasificacion_histologica']);
});
it('un paciente sin tipo no recibe clasificación y los demás campos quedan como llegaron', () => {
// Fails if a patient without biopsy is shown as «Sin clasificar», or if other row values are altered.
const datos = respuesta();
datos.items.forEach((item, i) => { item['tipo_histologico'] = item['biopsia'] === null ? null : 'Medular'; });
const original = structuredClone(datos.items);
const r = seguimientoTablaResponse(datos);
r.items.forEach((item, i) => {
if (original[i]['tipo_histologico'] === null) expect('clasificacion_histologica' in item).toBe(false);
expect({ ...item, clasificacion_histologica: undefined }).toEqual({ ...original[i], clasificacion_histologica: undefined });
});
});
it('una lista sin tipo histológico no cambia', () => {
// Fails if the column appears while the API does not send the field.
const r = seguimientoTablaResponse(respuesta());
expect(r.columnas.map(c => c.clave)).not.toContain('clasificacion_histologica');
expect(r.items.some(item => 'clasificacion_histologica' in item)).toBe(false);
});
});
@@ -0,0 +1,23 @@
// Groups the histologic type of a biopsy into the classification shown beside it.
export const SIN_CLASIFICAR = 'Sin clasificar';
export const MAPEO_HISTOLOGICO: Readonly<Record<string, string>> = {
'Ductal (NST)': 'Carcinoma invasor',
'Lobulillar': 'Carcinoma invasor',
'Ductal-lobulillar mixto': 'Carcinoma invasor',
'Mucinoso': 'Carcinoma invasor',
'Paget': 'Carcinoma in situ',
'Papilar': 'Revisar (Benigno / In situ / Invasor)',
'Tubular': 'Carcinoma invasor',
'Tubular / cribiforme': 'Carcinoma invasor',
'cribiforme': 'Revisar (In situ / Invasor)',
'Micropapilar': 'Revisar (In situ / Invasor)',
'Inflamatorio': 'Carcinoma invasor',
'Medular': 'Carcinoma invasor',
'Otros': 'Revisar (Benigno / In situ / Invasor)',
'SIN MAPEAR': SIN_CLASIFICAR,
};
/** The classification of a histologic type; a type outside the mapping is «Sin clasificar». */
export const clasificacionHistologica = (tipo: string) =>
Object.hasOwn(MAPEO_HISTOLOGICO, tipo) ? MAPEO_HISTOLOGICO[tipo] : SIN_CLASIFICAR;
@@ -4,6 +4,7 @@ import { map } from 'rxjs';
import { isoDate } from './cacu-seguimiento.models';
import { identidadesDe } from './paciente-identidad';
import { etiquetaDeFiltro } from './etiquetas-cohorte';
import { clasificacionHistologica } from './mapeo-histologico';
import { Dominio, requireDominio } from './indicadores.models';
// A follow-up list whose filters and columns come with the answer, so the view needs no code of its own per
@@ -96,10 +97,33 @@ export function seguimientoTablaResponse(v: unknown): SeguimientoTablaResponse {
|| !v['items'].every(item => record(item) && Object.values(item).every(valor)) || !identidadesDe(v['items'] as Record<string, unknown>[])) {
throw new SeguimientoInvalido('Respuesta de seguimiento inválida');
}
const respuesta = v as unknown as SeguimientoTablaResponse;
const respuesta = clasificarHistologia(v as unknown as SeguimientoTablaResponse);
return respuesta.cohorte ? etiquetarCohorte(respuesta) : respuesta;
}
const TIPO_HISTOLOGICO = 'tipo_histologico';
const CLASIFICACION_HISTOLOGICA = 'clasificacion_histologica';
/**
* A list that carries the histologic type of each patient (`tipo_histologico`) also shows its classification, computed
* from that same value in the same row, in a column placed after the type's (or after the biopsy result when the type
* has no column). Rows without a type, and lists without the field, are left as received.
*/
export function clasificarHistologia(r: SeguimientoTablaResponse): SeguimientoTablaResponse {
if (!r.items.some(item => typeof item[TIPO_HISTOLOGICO] === 'string') || r.columnas.some(c => c.clave === CLASIFICACION_HISTOLOGICA)) return r;
const columnas = [...r.columnas];
const despuesDe = [TIPO_HISTOLOGICO, 'biopsia'].map(k => columnas.findIndex(c => c.clave === k)).find(i => i >= 0) ?? columnas.length - 1;
columnas.splice(despuesDe + 1, 0, { clave: CLASIFICACION_HISTOLOGICA, etiqueta: 'Clasificación histológica' });
return {
...r,
columnas,
items: r.items.map(item => {
const tipo = item[TIPO_HISTOLOGICO];
return typeof tipo === 'string' ? { ...item, [CLASIFICACION_HISTOLOGICA]: clasificacionHistologica(tipo) } : item;
}),
};
}
/**
* A cohort's list announces its filters with the code as the label and carries the codes as values. The answer is
* rewritten once, here, so the table, the record and the files all show «BI-RADS 5» and «50 a 59 años»; the code stays
@@ -11,7 +11,7 @@
<p class="meta">Módulo {{ a.modulo }} · {{ a.algoritmo }} · {{ a.fecha }}</p>
<div class="headline">
<span class="css" [attr.data-nivel]="a.nivel_css">CSS {{ a.css }}<small>de 10</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacion[a.clasificacion] }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
<span><strong>{{ nivelCss[a.nivel_css] }}</strong><small>Clasificación: {{ clasificacionDe(a) }}</small><small>Total del algoritmo: {{ a.total }} / {{ a.total_maximo }}</small></span>
</div>
@for (dom of a.dominios; track dom.codigo) {
<div class="dominio">
@@ -37,18 +37,24 @@
</section>
<section class="panel calidad" aria-label="Calidad del EEG">
<h3>Calidad del EEG @if (d.eeg) { <span class="mock">Datos de ejemplo</span> }</h3>
<h3>Calidad del EEG</h3>
@if (d.eeg; as e) {
<p class="meta">{{ e.fecha }} · {{ e.duracion_min }} min · {{ e.canales }} canales</p>
<p class="meta">{{ e.fecha }}@if (e.duracion_min !== null) { · {{ e.duracion_min }} min }@if (e.canales !== null) { · {{ e.canales }} canales }</p>
<div class="headline">
<span class="css" [attr.data-calidad]="e.calidad"><strong>{{ calidad[e.calidad] }}</strong></span>
<small>La calificación general es la peor de sus criterios.</small>
<small>{{ e.calidad === 'sin_analizar' ? 'El análisis del EEG aún no lo revisa.' : 'Veredicto del análisis del EEG, según las reglas siguientes.' }}</small>
</div>
<dl>
@for (c of e.criterios_calidad; track c.codigo) {
<dt>{{ c.etiqueta }}</dt><dd [attr.data-calidad]="c.nivel">{{ c.valor }} {{ c.unidad === 'canales' ? 'de ' + e.canales : c.unidad }}</dd>
@for (c of delEstudio(e); track c.codigo) {
<dt>{{ c.etiqueta }}@if (c.decisivo) {<small> (decisiva)</small>}</dt><dd [attr.data-calidad]="c.nivel">{{ valorDe(c) }}</dd>
}
</dl>
@if (canalesMalos(e).length) {
<p class="efectos-titulo">Canales descartados</p>
<ul class="canales-malos">
@for (c of canalesMalos(e); track $index) { <li><strong>{{ c.electrodo }}</strong> · {{ c.etiqueta }}</li> }
</ul>
}
} @else { <p>Sin EEG registrado.</p> }
</section>
@@ -56,7 +62,7 @@
<div class="alteraciones-zona" [class.abierta]="mapaActual(e)">
<section class="panel alteraciones" aria-label="Alteraciones del EEG">
<h3>Alteraciones del EEG <span class="mock">Datos de ejemplo</span></h3>
<p class="meta">Referencia neurotípica para {{ d.grupo_edad }} y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
<p class="meta">Curvas de referencia por edad ({{ d.grupo_edad || 'edad sin dato' }}) y efectos asociados de ejemplo, pendientes de validación médica. Elige una alteración para ver sus zonas más afectadas.</p>
@if (!alteradas(e).length) { <p class="sin-alteraciones">Sin alteraciones en las métricas evaluadas.</p> }
<ul class="metricas">
@for (m of e.alteraciones; track m.codigo) {
@@ -66,10 +72,10 @@
[attr.aria-controls]="'zonas-' + d.id_seudonimo" (click)="elegirMapa(e, m.codigo)">{{ m.etiqueta }}</button>
<span class="estado">{{ estado[m.estado] }}</span>
</div>
@if (m.valor !== null) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ m.referencia.min }}–{{ m.referencia.max }} · z = {{ m.valor_z }}</p>
@if (m.referencia; as r) {
<p class="valor">{{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · referencia {{ r.min }}–{{ r.max }}@if (r.mediana !== null) { (mediana {{ r.mediana }}) } · z = {{ m.valor_z }}</p>
} @else {
<p class="valor">Sin registro de sueño en el estudio.</p>
<p class="valor">@if (m.valor !== null) { {{ m.valor }}{{ m.unidad ? ' ' + m.unidad : '' }} · }{{ sinEvaluar(m) }}</p>
}
@if (m.efectos.length) {
<p class="efectos-titulo">Posibles efectos asociados</p>

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