Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56b3ac6b0c | |||
| f6603ae76e | |||
| 21ae95b5ed | |||
| ce2e86c045 | |||
| 0f8eb0ec94 | |||
| 2f6d419453 | |||
| f34f9e1607 | |||
| c7dd134fce | |||
| 03cc9c9800 | |||
| de3d247d0d | |||
| ee87bcb8d0 | |||
| aaeea7a7b0 | |||
| 7f17681409 | |||
| d72c18756f | |||
| fefa28ae7a | |||
| a217ddae38 | |||
| 97fcb37761 |
@@ -14,3 +14,30 @@ npx ng build # compilación de producción en dist/WebApp
|
|||||||
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
`ng serve` envía las rutas de la API a WebApi en `localhost:5050`
|
||||||
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
(`proxy.conf.json`). La imagen de Docker (`Dockerfile`) sirve la compilación con
|
||||||
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
nginx (`nginx.conf`), que reenvía esas mismas rutas al servicio `webapi`.
|
||||||
|
|
||||||
|
## Fuente de histopatología BI-RADS
|
||||||
|
|
||||||
|
La compilación estándar incorpora la fuente sintética de la tarjeta de
|
||||||
|
histopatología en **CaMa → Resumen**. La dona y las barras usan el mismo
|
||||||
|
fixture. El catálogo, los filtros generales y los demás indicadores siguen
|
||||||
|
usando WebApi. Si el catálogo carga sin la medida de histopatología, Resumen
|
||||||
|
incluye la tarjeta con su fuente local.
|
||||||
|
|
||||||
|
El archivo
|
||||||
|
`src/app/features/indicadores/fixtures/cama_histopatologia_birads_demo_sintetica.json`
|
||||||
|
contiene conteos inventados, sin validez clínica. Define los 12 subtipos en orden
|
||||||
|
con sus identificadores y colores. Cada mes remite a un perfil de conteos por
|
||||||
|
estrato BI-RADS que incluye resultados benignos, subtipos, casos sin biopsia
|
||||||
|
reportada y casos sin dato. Abarca enero de 2025 a diciembre de 2026. Los semestres
|
||||||
|
suman esos mismos meses. Un periodo fuera de cobertura queda sin resultados.
|
||||||
|
|
||||||
|
El anillo interior usa el total con resultado de biopsia. El exterior reparte
|
||||||
|
el grupo «Riesgo a carcinoma» entre sus 12 subtipos. Las barras y el centro
|
||||||
|
muestran el subconjunto elegido sobre el total con resultado, por BI-RADS y del
|
||||||
|
periodo completo, respectivamente. La leyenda permite elegir subtipos incluso
|
||||||
|
cuando el sector es demasiado pequeño.
|
||||||
|
|
||||||
|
Cuando se valide la matriz clínica de subtipos, el adaptador FHIR podrá construir
|
||||||
|
el mismo modelo de presentación con los conteos, estratos, denominadores y
|
||||||
|
reglas de supresión aprobados. Los componentes de visualización ya consumen
|
||||||
|
ese modelo tanto para las tasas como para los anillos.
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 717 B |
@@ -37,7 +37,8 @@ describe('Encabezado del marco', () => {
|
|||||||
|
|
||||||
it('las rutas de los tres dominios existen en el enrutador de la aplicación', () => {
|
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.
|
// 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}`);
|
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', '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) => {
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export const appConfig: ApplicationConfig = {
|
|||||||
providers: [
|
providers: [
|
||||||
provideBrowserGlobalErrorListeners(),
|
provideBrowserGlobalErrorListeners(),
|
||||||
provideRouter(routes),
|
provideRouter(routes),
|
||||||
|
// La sesión es del navegador (`auth/auth.service.ts`): no hay interceptor
|
||||||
|
// porque la WebApi no responde 401.
|
||||||
provideHttpClient(),
|
provideHttpClient(),
|
||||||
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
// The indicator page reads the WebApi's FHIR endpoint; without these lines it reads the indicator JSON contract
|
||||||
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
// (`/<domain>/indicadores/<id>/datos`, `/tea/seguimiento`).
|
||||||
|
|||||||
+42
-23
@@ -1,33 +1,52 @@
|
|||||||
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
<div class="app-shell" [class.app-shell--workspace]="workspace()" [class.app-shell--indicadores]="!!activeDomain()">
|
||||||
<header class="site-header">
|
@if (!sinCromo()) {
|
||||||
<div class="site-header__content">
|
<header class="site-header">
|
||||||
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
<div class="site-header__content">
|
||||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
<a class="brand" routerLink="/" aria-label="ISSSTELEON, inicio">
|
||||||
</a>
|
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||||
@if (activeDomain(); as domain) {
|
</a>
|
||||||
<span class="platform-title">{{ title }}</span>
|
@if (activeDomain(); as domain) {
|
||||||
@defer (on immediate) {
|
<span class="platform-title">{{ title }}</span>
|
||||||
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
@if (otherDomains().length) {
|
||||||
} @placeholder {
|
@defer (on immediate) {
|
||||||
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
<app-domain-selector [actual]="domain" [otros]="otherDomains()" [labels]="domainLabels" />
|
||||||
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
} @placeholder {
|
||||||
}
|
<!-- Same size as the selector until its code arrives, so the header does not jump. -->
|
||||||
} @else {
|
<span class="domain-selector domain-selector--espera" aria-hidden="true">{{ domainLabels[domain] }}</span>
|
||||||
<nav class="site-header__nav" aria-label="Secciones">
|
}
|
||||||
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
} @else {
|
||||||
@if (breadcrumb(); as crumb) {
|
<!-- An account with a single domain has nothing to switch to: the domain is a label. -->
|
||||||
<span class="site-header__crumb" aria-current="page">› {{ crumb }}</span>
|
<span class="domain-selector domain-selector--espera">{{ domainLabels[domain] }}</span>
|
||||||
}
|
}
|
||||||
</nav>
|
} @else {
|
||||||
}
|
<nav class="site-header__nav" aria-label="Secciones">
|
||||||
</div>
|
<a class="site-header__section" routerLink="/">Análisis de información</a>
|
||||||
</header>
|
@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">
|
<main class="app-main">
|
||||||
<router-outlet />
|
<router-outlet />
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
@if (!workspace()) {
|
@if (!workspace() && !sinCromo()) {
|
||||||
<footer class="site-footer">
|
<footer class="site-footer">
|
||||||
<div class="site-footer__content">
|
<div class="site-footer__content">
|
||||||
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
<img src="assets/branding/isssteleon-logo.png" alt="ISSSTELEON" />
|
||||||
|
|||||||
+57
-37
@@ -1,49 +1,69 @@
|
|||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
import { Home } from './home';
|
import { Home } from './home';
|
||||||
|
import { authGuard } from './auth/auth.guard';
|
||||||
|
import { dominioGuard } from './auth/dominio.guard';
|
||||||
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
import { DOMINIOS } from './features/indicadores/indicadores.models';
|
||||||
|
|
||||||
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
const loadIndicadores = () => import('./features/indicadores/indicadores-page').then(module => module.IndicadoresPage);
|
||||||
|
|
||||||
export const routes: Routes = [
|
export const routes: Routes = [
|
||||||
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
|
||||||
{
|
{
|
||||||
path: 'indicadores/tea-estatus',
|
path: 'login',
|
||||||
title: 'Casos por estatus | ISSSTELEON',
|
title: 'Inicio de sesión | ISSSTELEON',
|
||||||
loadComponent: () => import('./features/indicadores/tea-status-page').then(m => m.TeaStatusPage),
|
loadComponent: () => import('./auth/login-page').then((m) => m.LoginPage),
|
||||||
data: { workspace: true, breadcrumb: 'Casos por estatus' },
|
// Sin encabezado ni pie: la pantalla ocupa la ventana completa.
|
||||||
|
data: { sinCromo: true },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'conectar',
|
// Todo lo demás vive detrás de la sesión; el guard corre en cada ruta hija.
|
||||||
title: 'Conectar datos | ISSSTELEON',
|
path: '',
|
||||||
// Lazy: the workspace (and the ~15 Material modules it uses) only
|
canActivateChild: [authGuard],
|
||||||
// downloads when someone actually opens it.
|
children: [
|
||||||
loadComponent: () => import('./connect/components/connect-page/connect-page').then((m) => m.ConnectPage),
|
{ path: '', component: Home, title: 'Análisis de información | ISSSTELEON' },
|
||||||
data: { workspace: true, breadcrumb: 'Conectar datos' },
|
{
|
||||||
|
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: '' },
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -120,6 +120,46 @@
|
|||||||
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
background-color: var(--issste-accent); color: var(--issste-text); font-weight: 700; min-height: 40px; padding: 0 16px; white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Session exit: the same action look as the home buttons, in header size. */
|
||||||
|
.site-header__salir {
|
||||||
|
align-items: center;
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid var(--color-action);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--color-text);
|
||||||
|
cursor: pointer;
|
||||||
|
display: inline-flex;
|
||||||
|
flex: none;
|
||||||
|
font: inherit;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
gap: 6px;
|
||||||
|
margin-inline-start: var(--space-4);
|
||||||
|
min-height: 34px;
|
||||||
|
padding: 0 var(--space-3);
|
||||||
|
transition:
|
||||||
|
background-color 0.2s ease,
|
||||||
|
border-color 0.2s ease,
|
||||||
|
color 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir:hover {
|
||||||
|
background: var(--color-action-hover);
|
||||||
|
border-color: var(--color-action);
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir:focus-visible {
|
||||||
|
outline: 2px solid var(--color-action);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.site-header__salir mat-icon {
|
||||||
|
color: var(--color-action);
|
||||||
|
font-size: 18px;
|
||||||
|
height: 18px;
|
||||||
|
width: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
// Narrow screens: logo and selector share the first row and the title takes the second, so neither is squeezed.
|
||||||
@media (max-width: 599px) {
|
@media (max-width: 599px) {
|
||||||
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
.app-shell--indicadores .site-header__content { flex-wrap: wrap; row-gap: 0; padding-block: 6px 8px; }
|
||||||
|
|||||||
+96
-25
@@ -1,46 +1,117 @@
|
|||||||
|
import { signal } from '@angular/core';
|
||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { provideRouter, Router } from '@angular/router';
|
|
||||||
import { provideHttpClient } from '@angular/common/http';
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
import { provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { provideRouter, Router } from '@angular/router';
|
||||||
|
import { of } from 'rxjs';
|
||||||
import { App } from './app';
|
import { App } from './app';
|
||||||
import { routes } from './app.routes';
|
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', () => {
|
describe('App', () => {
|
||||||
beforeEach(async () => {
|
|
||||||
await TestBed.configureTestingModule({
|
|
||||||
imports: [App],
|
|
||||||
providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting()],
|
|
||||||
}).compileComponents();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function render(url: string) {
|
async function render(url: string) {
|
||||||
const fixture = TestBed.createComponent(App);
|
const fixture = TestBed.createComponent(App);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
await TestBed.inject(Router).navigateByUrl(url);
|
await TestBed.inject(Router).navigateByUrl(url).catch(() => false);
|
||||||
await fixture.whenStable();
|
await fixture.whenStable();
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
return fixture.nativeElement as HTMLElement;
|
return fixture.nativeElement as HTMLElement;
|
||||||
}
|
}
|
||||||
|
|
||||||
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
describe('con sesión de administrador', () => {
|
||||||
const page = await render('/');
|
beforeEach(() => montar(TODOS));
|
||||||
expect(page.querySelector('.brand img')?.getAttribute('alt')).toBe('ISSSTELEON');
|
|
||||||
expect(page.querySelector('h1')?.textContent).toContain('Analiza tu información');
|
it('renders the ISSSTELEON shell and home page with its footer', async () => {
|
||||||
expect(page.querySelector('.home__action')?.getAttribute('href')).toBe('/conectar');
|
const page = await render('/');
|
||||||
expect(page.querySelector('.site-footer')).not.toBeNull();
|
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 () => {
|
describe('con una cuenta de un solo dominio', () => {
|
||||||
const page = await render('/conectar');
|
beforeEach(() => montar({ usuario: 'cacu', nombre: 'Equipo CaCu', dominios: ['cacu'] }));
|
||||||
expect(page.querySelector('app-connect-page')).not.toBeNull();
|
|
||||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Conectar datos');
|
it('no deja abrir el dominio ajeno: la manda al suyo', async () => {
|
||||||
expect(page.querySelector('.site-footer')).toBeNull();
|
// Fails if the domain scope exists only on the server: the interface would show an empty page.
|
||||||
|
await render('/indicadores/cama');
|
||||||
|
expect(TestBed.inject(Router).url).toBe('/indicadores/cacu');
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
|
it('el encabezado no ofrece los otros dominios', async () => {
|
||||||
|
const page = await render('/indicadores/cacu');
|
||||||
|
expect(page.querySelector('app-domain-selector')).toBeNull();
|
||||||
|
expect(page.querySelector('.domain-selector--espera')?.textContent).toContain('CaCu');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('/gobernanza opens the governance workspace (breadcrumb, no footer)', async () => {
|
describe('sin sesión', () => {
|
||||||
const page = await render('/gobernanza');
|
beforeEach(() => montar(null));
|
||||||
expect(page.querySelector('app-governance-page')).not.toBeNull();
|
|
||||||
expect(page.querySelector('.site-header__crumb')?.textContent).toContain('Gobernanza de modelos');
|
it('cualquier ruta manda al inicio de sesión y no muestra el marco', async () => {
|
||||||
expect(page.querySelector('.site-footer')).toBeNull();
|
const page = await render('/conectar');
|
||||||
|
expect(TestBed.inject(Router).url).toContain('/login');
|
||||||
|
expect(page.querySelector('.login')).not.toBeNull();
|
||||||
|
expect(page.querySelector('.site-header')).toBeNull();
|
||||||
|
expect(page.querySelector('.site-footer')).toBeNull();
|
||||||
|
expect(page.querySelector('app-connect-page')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('el destino pedido viaja en returnUrl para volver después de entrar', async () => {
|
||||||
|
await render('/gobernanza');
|
||||||
|
expect(TestBed.inject(Router).url).toContain('returnUrl=%2Fgobernanza');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+22
-2
@@ -1,12 +1,14 @@
|
|||||||
import { Component, computed, inject } from '@angular/core';
|
import { Component, computed, inject } from '@angular/core';
|
||||||
import { toSignal } from '@angular/core/rxjs-interop';
|
import { toSignal } from '@angular/core/rxjs-interop';
|
||||||
|
import { MatIconModule } from '@angular/material/icon';
|
||||||
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
import { ActivatedRoute, NavigationEnd, Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||||
import { filter, map } from 'rxjs';
|
import { filter, map } from 'rxjs';
|
||||||
|
import { AuthService } from './auth/auth.service';
|
||||||
import { DomainSelector } from './domain-selector';
|
import { DomainSelector } from './domain-selector';
|
||||||
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
imports: [RouterLink, RouterOutlet, DomainSelector],
|
imports: [MatIconModule, RouterLink, RouterOutlet, DomainSelector],
|
||||||
selector: 'app-root',
|
selector: 'app-root',
|
||||||
styleUrl: './app.scss',
|
styleUrl: './app.scss',
|
||||||
templateUrl: './app.html',
|
templateUrl: './app.html',
|
||||||
@@ -14,6 +16,7 @@ import { Dominio, DOMINIOS } from './features/indicadores/indicadores.models';
|
|||||||
export class App {
|
export class App {
|
||||||
private readonly router = inject(Router);
|
private readonly router = inject(Router);
|
||||||
private readonly route = inject(ActivatedRoute);
|
private readonly route = inject(ActivatedRoute);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
|
|
||||||
private readonly leafRouteData = toSignal(
|
private readonly leafRouteData = toSignal(
|
||||||
this.router.events.pipe(
|
this.router.events.pipe(
|
||||||
@@ -30,7 +33,10 @@ export class App {
|
|||||||
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
/** Full-height workspace routes (`data.workspace`) drop the marketing footer. */
|
||||||
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
readonly workspace = computed(() => !!this.leafRouteData()['workspace']);
|
||||||
readonly breadcrumb = computed(() => this.leafRouteData()['breadcrumb'] as string | undefined);
|
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 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: 'TEA', cacu: 'CaCu', cama: 'Cáncer de mama' };
|
||||||
private readonly url = toSignal(this.router.events.pipe(
|
private readonly url = toSignal(this.router.events.pipe(
|
||||||
@@ -38,5 +44,19 @@ export class App {
|
|||||||
/** On an indicators page the header names its domain and switches to the others. */
|
/** On an indicators page the header names its domain and switches to the others. */
|
||||||
protected readonly activeDomain = computed(() =>
|
protected readonly activeDomain = computed(() =>
|
||||||
DOMINIOS.find(domain => new RegExp(`^/indicadores/${domain}(?:[/?#]|$)`).test(this.url())));
|
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']),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 } }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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(['/']);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
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'"
|
[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 [value]="domain.id" [attr.aria-label]="domain.description">{{ domain.label }}</mat-button-toggle>
|
||||||
}
|
}
|
||||||
</mat-button-toggle-group>
|
</mat-button-toggle-group>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { DragDropModule } from '@angular/cdk/drag-drop';
|
import { DragDropModule } from '@angular/cdk/drag-drop';
|
||||||
import { DecimalPipe } from '@angular/common';
|
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 { MatBadgeModule } from '@angular/material/badge';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
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 { MatToolbarModule } from '@angular/material/toolbar';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { Domain, TargetMeta } from '../../api/api.types';
|
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 { DataConnection, SourceTable } from '../../domain/data-source';
|
||||||
import { PdfConnection } from '../../domain/pdf-source';
|
import { PdfConnection } from '../../domain/pdf-source';
|
||||||
import { SqlConnection } from '../../domain/sql-source';
|
import { SqlConnection } from '../../domain/sql-source';
|
||||||
@@ -59,11 +61,13 @@ import { SqlQueryDialog, SqlQueryResult } from '../sql-query-dialog/sql-query-di
|
|||||||
})
|
})
|
||||||
export class ConnectPage {
|
export class ConnectPage {
|
||||||
readonly store = inject(ConnectWorkspaceStore);
|
readonly store = inject(ConnectWorkspaceStore);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
private readonly dialog = inject(MatDialog);
|
private readonly dialog = inject(MatDialog);
|
||||||
private readonly snackBar = inject(MatSnackBar);
|
private readonly snackBar = inject(MatSnackBar);
|
||||||
private readonly injector = inject(Injector);
|
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 paneOpen = signal(true);
|
||||||
readonly validatingAll = signal(false);
|
readonly validatingAll = signal(false);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { TestBed } from '@angular/core/testing';
|
import { TestBed } from '@angular/core/testing';
|
||||||
import { Observable, firstValueFrom, of } from 'rxjs';
|
import { Observable, firstValueFrom, of } from 'rxjs';
|
||||||
|
import { AuthService } from '../../auth/auth.service';
|
||||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
|
import { BatchResult, ConflictStrategy, ImportSourcePayload, TargetMeta } from '../api/api.types';
|
||||||
import { ImportsApi } from '../api/imports.api';
|
import { ImportsApi } from '../api/imports.api';
|
||||||
import { SourceGateway } from '../api/source-gateway';
|
import { SourceGateway } from '../api/source-gateway';
|
||||||
@@ -32,6 +33,8 @@ describe('ConnectWorkspaceStore', () => {
|
|||||||
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
{ provide: TargetsApi, useValue: { list: () => of([PACIENTE, NOTA, tama]) } },
|
||||||
{ provide: ImportsApi, useValue: imports },
|
{ provide: ImportsApi, useValue: imports },
|
||||||
{ provide: SourceGateway, useValue: {} },
|
{ 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);
|
store = TestBed.inject(ConnectWorkspaceStore);
|
||||||
@@ -52,6 +55,25 @@ describe('ConnectWorkspaceStore', () => {
|
|||||||
expect(store.domain()).toBe('cacu');
|
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', () => {
|
it('removing a connection removes the flows built on its tables', () => {
|
||||||
const { connection } = flowFrom('a.csv', PACIENTE);
|
const { connection } = flowFrom('a.csv', PACIENTE);
|
||||||
flowFrom('b.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 { toSignal } from '@angular/core/rxjs-interop';
|
||||||
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
|
import { Observable, catchError, from, of, switchMap, tap } from 'rxjs';
|
||||||
import { BatchResult, ConflictStrategy, ConnectorInfo, Domain, TargetMeta, apiErrorMessage } from '../api/api.types';
|
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 { ConnectorsApi } from '../api/connectors.api';
|
||||||
import { ImportsApi } from '../api/imports.api';
|
import { ImportsApi } from '../api/imports.api';
|
||||||
import { SourceGateway } from '../api/source-gateway';
|
import { SourceGateway } from '../api/source-gateway';
|
||||||
@@ -29,6 +31,7 @@ export const DOMAINS: { id: Domain; label: string; description: string }[] = [
|
|||||||
export class ConnectWorkspaceStore {
|
export class ConnectWorkspaceStore {
|
||||||
private readonly gateway = inject(SourceGateway);
|
private readonly gateway = inject(SourceGateway);
|
||||||
private readonly importsApi = inject(ImportsApi);
|
private readonly importsApi = inject(ImportsApi);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
|
|
||||||
private readonly targetsError = signal<string | null>(null);
|
private readonly targetsError = signal<string | null>(null);
|
||||||
readonly allTargets = toSignal(
|
readonly allTargets = toSignal(
|
||||||
@@ -50,7 +53,8 @@ export class ConnectWorkspaceStore {
|
|||||||
});
|
});
|
||||||
readonly acceptedExtensions = computed(() => acceptedExtensions(this.connectors()));
|
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 _connections = signal<DataConnection[]>([]);
|
||||||
private readonly _flows = signal<ImportFlow[]>([]);
|
private readonly _flows = signal<ImportFlow[]>([]);
|
||||||
private readonly _selectedFlowId = signal<string | null>(null);
|
private readonly _selectedFlowId = signal<string | null>(null);
|
||||||
@@ -128,7 +132,12 @@ export class ConnectWorkspaceStore {
|
|||||||
});
|
});
|
||||||
|
|
||||||
setDomain(domain: Domain): void {
|
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 {
|
setOnConflict(strategy: ConflictStrategy): void {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
{
|
||||||
|
"origen": "Sintético (WebApp). Conteos inventados para demostrar la visualización; sin significado clínico.",
|
||||||
|
"categorias": [
|
||||||
|
{ "id": "DUCTAL_NST", "etiqueta": "Ductal (NST)", "color": "#AD386D" },
|
||||||
|
{ "id": "LOBULILLAR", "etiqueta": "Lobulillar", "color": "#5C55BB" },
|
||||||
|
{ "id": "OTROS", "etiqueta": "Otros", "color": "#007F86" },
|
||||||
|
{ "id": "DUCTAL_LOBULILLAR", "etiqueta": "Ductal-lobulillar mixto", "color": "#8767C9" },
|
||||||
|
{ "id": "MUCINOSO", "etiqueta": "Mucinoso", "color": "#3274BF" },
|
||||||
|
{ "id": "PAGET", "etiqueta": "Paget", "color": "#D35C91" },
|
||||||
|
{ "id": "PAPILAR", "etiqueta": "Papilar", "color": "#537723" },
|
||||||
|
{ "id": "TUBULAR_CRIBIFORME", "etiqueta": "Tubular / cribiforme", "color": "#9454AA" },
|
||||||
|
{ "id": "MICROPAPILAR", "etiqueta": "Micropapilar", "color": "#C24938" },
|
||||||
|
{ "id": "SIN_MAPEAR", "etiqueta": "SIN MAPEAR", "color": "#68778B" },
|
||||||
|
{ "id": "INFLAMATORIO", "etiqueta": "Inflamatorio", "color": "#A4932A" },
|
||||||
|
{ "id": "MEDULAR", "etiqueta": "Medular", "color": "#438573" }
|
||||||
|
],
|
||||||
|
"meses": {
|
||||||
|
"2025-01": "A", "2025-02": "B", "2025-03": "A", "2025-04": "B", "2025-05": "B", "2025-06": "A",
|
||||||
|
"2025-07": "B", "2025-08": "A", "2025-09": "B", "2025-10": "A", "2025-11": "B", "2025-12": "B",
|
||||||
|
"2026-01": "A", "2026-02": "B", "2026-03": "A", "2026-04": "A", "2026-05": "B", "2026-06": "A",
|
||||||
|
"2026-07": "A", "2026-08": "B", "2026-09": "B", "2026-10": "B", "2026-11": "A", "2026-12": "B"
|
||||||
|
},
|
||||||
|
"perfiles": {
|
||||||
|
"A": {
|
||||||
|
"BIRADS_4": { "benignos": 54, "subtipos": [8, 3, 2, 1, 1, 0, 1, 0, 0, 1, 0, 0], "sinBiopsia": 5, "sinDato": 1 },
|
||||||
|
"BIRADS_4A": { "benignos": 93, "subtipos": [5, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0], "sinBiopsia": 9, "sinDato": 2 },
|
||||||
|
"BIRADS_4B": { "benignos": 67, "subtipos": [19, 5, 3, 2, 1, 1, 1, 1, 0, 1, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
|
||||||
|
"BIRADS_4C": { "benignos": 30, "subtipos": [33, 9, 5, 4, 3, 1, 2, 2, 1, 2, 1, 1], "sinBiopsia": 4, "sinDato": 1 },
|
||||||
|
"BIRADS_5": { "benignos": 10, "subtipos": [48, 12, 8, 6, 4, 3, 3, 2, 2, 2, 2, 1], "sinBiopsia": 3, "sinDato": 1 },
|
||||||
|
"BIRADS_6": { "benignos": 0, "subtipos": [15, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0], "sinBiopsia": 0, "sinDato": 1 }
|
||||||
|
},
|
||||||
|
"B": {
|
||||||
|
"BIRADS_4": { "benignos": 49, "subtipos": [7, 2, 2, 1, 0, 0, 1, 0, 0, 2, 0, 1], "sinBiopsia": 6, "sinDato": 2 },
|
||||||
|
"BIRADS_4A": { "benignos": 86, "subtipos": [6, 2, 0, 1, 0, 0, 1, 1, 0, 2, 0, 0], "sinBiopsia": 7, "sinDato": 1 },
|
||||||
|
"BIRADS_4B": { "benignos": 66, "subtipos": [15, 4, 4, 2, 2, 0, 1, 1, 1, 1, 0, 0], "sinBiopsia": 4, "sinDato": 1 },
|
||||||
|
"BIRADS_4C": { "benignos": 35, "subtipos": [31, 8, 5, 3, 2, 1, 3, 2, 1, 1, 1, 1], "sinBiopsia": 5, "sinDato": 2 },
|
||||||
|
"BIRADS_5": { "benignos": 9, "subtipos": [44, 14, 7, 7, 5, 4, 3, 2, 2, 1, 2, 1], "sinBiopsia": 2, "sinDato": 2 },
|
||||||
|
"BIRADS_6": { "benignos": 0, "subtipos": [17, 5, 3, 1, 2, 1, 0, 1, 1, 2, 1, 1], "sinBiopsia": 0, "sinDato": 0 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import { provideHttpClient } from '@angular/common/http';
|
||||||
|
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
|
||||||
|
import { TestBed } from '@angular/core/testing';
|
||||||
|
import { By } from '@angular/platform-browser';
|
||||||
|
import { provideRouter } from '@angular/router';
|
||||||
|
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||||
|
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||||
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
|
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
|
||||||
|
import { recolorFigure } from './indicadores-c2-palette';
|
||||||
|
import { categoriasExteriores, donaHistopatologia, figuraTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
||||||
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
|
|
||||||
|
const nombres = [
|
||||||
|
'Ductal (NST)', 'Lobulillar', 'Otros', 'Ductal-lobulillar mixto', 'Mucinoso', 'Paget', 'Papilar',
|
||||||
|
'Tubular / cribiforme', 'Micropapilar', 'SIN MAPEAR', 'Inflamatorio', 'Medular',
|
||||||
|
];
|
||||||
|
const [modelo] = modelosHistopatologiaDemo('mes', ['2025-02']);
|
||||||
|
const suma = (valores: number[]) => valores.reduce((a, b) => a + b, 0);
|
||||||
|
|
||||||
|
describe('Fuente sintética de histopatología CaMa', () => {
|
||||||
|
it('dibuja los 12 subtipos en orden, con colores distintos y con el subtotal del grupo exterior', () => {
|
||||||
|
const seleccion = seleccionBase(modelo);
|
||||||
|
const [, interior, exterior] = recolorFigure(donaHistopatologia(modelo, seleccion, 'claro')).data;
|
||||||
|
expect(exterior['labels']).toEqual(nombres);
|
||||||
|
expect(categoriasExteriores(modelo).map(c => c.etiqueta)).toEqual(nombres);
|
||||||
|
const colores = categoriasExteriores(modelo).map(c => c.color);
|
||||||
|
expect(new Set(colores).size).toBe(12);
|
||||||
|
expect(exterior['marker']).toMatchObject({ colors: colores });
|
||||||
|
expect(interior['labels']).toEqual(['No maligno', 'Riesgo a carcinoma']);
|
||||||
|
expect(suma(exterior['values'] as number[])).toBe((interior['values'] as number[])[1]);
|
||||||
|
expect(suma(interior['values'] as number[])).toBe(modelo.conResultado);
|
||||||
|
expect((exterior['values'] as number[]).every(n => n > 0)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mantiene SIN MAPEAR en mayúsculas y evita porcentajes indefinidos en un anillo sin casos', () => {
|
||||||
|
const figura = figuraTasas(modelo, { grupo: modelo.base, categoria: 'SIN_MAPEAR' }, 'claro');
|
||||||
|
expect(figura.layout['xaxis']).toMatchObject({ title: { text: 'Porcentaje con SIN MAPEAR' } });
|
||||||
|
const benignos = modelo.totales['BENIGNO'];
|
||||||
|
const totales = { ...modelo.totales, ...Object.fromEntries(categoriasExteriores(modelo).map(c => [c.id, 0])) };
|
||||||
|
const sinCasos = { ...modelo, totales, conResultado: benignos };
|
||||||
|
const exterior = donaHistopatologia(sinCasos, seleccionBase(sinCasos), 'claro').data[2];
|
||||||
|
expect(exterior['customdata']).toEqual(nombres.map(() => ['0', '—']));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reconcilia barras, anillos y tabla para cada selección, incluidos los ceros', () => {
|
||||||
|
for (const { id, grupo } of modelo.categorias) {
|
||||||
|
const seleccion = { grupo, categoria: id };
|
||||||
|
const valores = tasas(modelo, seleccion);
|
||||||
|
expect(suma(valores.map(t => t.k!))).toBe(modelo.totales[id]);
|
||||||
|
for (const { fila, k, valor, bajo, alto } of valores) {
|
||||||
|
expect(k).toBe(fila.celdas[id].n);
|
||||||
|
expect(valor).toBe(100 * k! / fila.den!);
|
||||||
|
expect(bajo).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(alto).toBeLessThanOrEqual(100);
|
||||||
|
expect(fila.total.n).toBe(fila.den! + fila.aparte['SIN_BIOPSIA'].n! + fila.aparte['SIN_DATO'].n!);
|
||||||
|
}
|
||||||
|
const [barra] = figuraTasas(modelo, seleccion, 'oscuro', true).data;
|
||||||
|
expect(barra['type']).toBe('bar');
|
||||||
|
expect(barra['x']).toEqual(valores.map(t => t.valor));
|
||||||
|
}
|
||||||
|
expect(tasas(modelo, { grupo: modelo.base, categoria: 'MICROPAPILAR' })[0].valor).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('agrega los mismos meses en cada semestre y devuelve vacío fuera de cobertura', () => {
|
||||||
|
const semestres = modelosHistopatologiaDemo('semestre');
|
||||||
|
expect(semestres.map(m => m.periodo)).toEqual(['2025-S1', '2025-S2', '2026-S1', '2026-S2']);
|
||||||
|
const primerSemestre = modelosHistopatologiaDemo('mes').filter(m => m.periodo <= '2025-06');
|
||||||
|
for (const { id } of modelo.categorias) {
|
||||||
|
expect(semestres[0].totales[id]).toBe(suma(primerSemestre.map(m => m.totales[id]!)));
|
||||||
|
}
|
||||||
|
expect(modelosHistopatologiaDemo('mes', ['2025-03', '2025-02']).map(m => m.periodo)).toEqual(['2025-03', '2025-02']);
|
||||||
|
expect(modelosHistopatologiaDemo('mes', ['2024-10'])).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([true, false])('Resumen usa los datos incorporados con medida publicada = %s', publicada => {
|
||||||
|
TestBed.configureTestingModule({ imports: [IndicadoresPage], providers: [
|
||||||
|
provideRouter([]), provideHttpClient(), provideHttpClientTesting(),
|
||||||
|
{ provide: PLOTLY_LOADER, useValue: () => new Promise(() => {}) },
|
||||||
|
] });
|
||||||
|
const http = TestBed.inject(HttpTestingController);
|
||||||
|
const memory = TestBed.inject(IndicadoresMemory);
|
||||||
|
for (const dominio of ['cama', 'cacu', 'tea'] as const) memory.finishInitialKpiPresentation(dominio);
|
||||||
|
const f = TestBed.createComponent(IndicadoresPage);
|
||||||
|
const catalogo = (id: string) => [{ id, titulo: 'Indicador publicado', contrato: 'C2', figuras: [], tipos_periodo: ['semestre', 'mes'] }];
|
||||||
|
http.expectOne('/tea/indicadores').flush(catalogo('tea_prueba'));
|
||||||
|
f.componentInstance.changeDominio('cama');
|
||||||
|
const idsCama = ['cama_birads_456_mastografia', 'cama_birads_456_paciente'];
|
||||||
|
if (publicada) idsCama.push('cama_histopatologia_birads');
|
||||||
|
http.expectOne('/cama/indicadores').flush(idsCama.flatMap(catalogo));
|
||||||
|
f.detectChanges();
|
||||||
|
const tarjeta = f.debugElement.query(node => node.componentInstance instanceof IndicadorHistopatologiaCama);
|
||||||
|
expect(tarjeta).toBeTruthy();
|
||||||
|
const histo = tarjeta.componentInstance as IndicadorHistopatologiaCama;
|
||||||
|
const card = f.debugElement.queryAll(By.directive(IndicadorCatalogCard))
|
||||||
|
.map(node => node.componentInstance as IndicadorCatalogCard)
|
||||||
|
.find(item => item.indicador.id === 'cama_histopatologia_birads')!;
|
||||||
|
card.setVisible(true);
|
||||||
|
f.detectChanges();
|
||||||
|
expect(histo.status()).toBe('ready');
|
||||||
|
expect(histo.contextPeriod).toBe('2026-S2');
|
||||||
|
expect(f.nativeElement.textContent).toContain('Tiempo de diagnóstico a tratamiento');
|
||||||
|
expect(f.componentInstance.catalog().map(item => item.id)).toEqual(idsCama);
|
||||||
|
expect(f.nativeElement.querySelector('app-indicador-conteos-pareados')).not.toBeNull();
|
||||||
|
expect([...tarjeta.nativeElement.querySelectorAll('.child')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(nombres);
|
||||||
|
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
|
||||||
|
|
||||||
|
histo.plotClicked({ points: [{ data: { name: 'categorias' }, pointNumber: 9 }] });
|
||||||
|
f.detectChanges();
|
||||||
|
expect(histo.selectionLabel).toBe('SIN MAPEAR');
|
||||||
|
expect(histo.ratesFigure!.data[0]['x']).toEqual(tasas(histo.model!, histo.selection!).map(t => t.valor));
|
||||||
|
expect(tarjeta.nativeElement.querySelector('.child[aria-pressed=true]').textContent.trim()).toBe('SIN MAPEAR');
|
||||||
|
histo.plotClicked({ points: [{ data: { name: 'grupos' }, pointNumber: 0 }] });
|
||||||
|
expect(histo.selectionLabel).toBe('No maligno');
|
||||||
|
histo.plotClicked({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] });
|
||||||
|
expect(histo.selectionLabel).toBe('Riesgo a carcinoma');
|
||||||
|
histo.changePeriod(-1);
|
||||||
|
expect(histo.contextPeriod).toBe('2026-S1');
|
||||||
|
histo.showHelp();
|
||||||
|
f.detectChanges();
|
||||||
|
expect(tarjeta.nativeElement.querySelector('.methodology').textContent).toContain('El exterior muestra solo la distribución de los subtipos');
|
||||||
|
http.expectNone(req => /cama_histopatologia_birads\/(datos|metadatos)$/.test(req.url));
|
||||||
|
|
||||||
|
for (const dominio of ['cacu', 'tea'] as const) {
|
||||||
|
f.componentInstance.changeDominio(dominio);
|
||||||
|
http.expectOne('/' + dominio + '/indicadores').flush(catalogo(dominio + '_prueba'));
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.nativeElement.querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||||
|
expect(f.nativeElement.querySelector('.catalog-grid').textContent).toContain('Indicador publicado');
|
||||||
|
}
|
||||||
|
f.destroy();
|
||||||
|
http.match(() => true);
|
||||||
|
http.verify();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import fixture from './fixtures/cama_histopatologia_birads_demo_sintetica.json';
|
||||||
|
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||||
|
import { Celda } from './indicadores-confirmacion-citologia';
|
||||||
|
import {
|
||||||
|
APARTE, ESTRATOS_BIRADS, ETIQUETA_ESTRATO, FilaBirads, ModeloHistopatologia,
|
||||||
|
} from './indicadores-histopatologia-cama';
|
||||||
|
import { TipoPeriodo } from './indicadores.models';
|
||||||
|
|
||||||
|
const RIESGO = 'RIESGO_CARCINOMA';
|
||||||
|
const NO_MALIGNO = 'NO_MALIGNO';
|
||||||
|
const BENIGNO = 'BENIGNO';
|
||||||
|
const subtipos = fixture.categorias.map(c => ({ ...c, grupo: RIESGO }));
|
||||||
|
const categorias = [
|
||||||
|
...subtipos,
|
||||||
|
{ id: BENIGNO, etiqueta: 'Benigno', color: C2_PALETTE.frios[0], grupo: NO_MALIGNO },
|
||||||
|
];
|
||||||
|
const grupos = [
|
||||||
|
{ id: NO_MALIGNO, etiqueta: 'No maligno', color: C2_PALETTE.frios[3], categorias: [BENIGNO] },
|
||||||
|
{ id: RIESGO, etiqueta: 'Riesgo a carcinoma', color: C2_PALETTE.calidos[0], categorias: subtipos.map(c => c.id) },
|
||||||
|
];
|
||||||
|
|
||||||
|
const meses = Object.entries(fixture.meses).map(([mes, perfil]) => ({
|
||||||
|
mes,
|
||||||
|
semestre: mes.slice(0, 4) + (mes.slice(5) <= '06' ? '-S1' : '-S2'),
|
||||||
|
perfil: fixture.perfiles[perfil as keyof typeof fixture.perfiles],
|
||||||
|
}));
|
||||||
|
const sumar = (valores: number[]) => valores.reduce((total, n) => total + n, 0);
|
||||||
|
const publicada = (n: number) => ({ n, estado: 'Publicado' as const });
|
||||||
|
|
||||||
|
export function modelosHistopatologiaDemo(tipo: TipoPeriodo, solicitados?: readonly string[]): ModeloHistopatologia[] {
|
||||||
|
const disponibles = [...new Set(meses.map(mes => mes[tipo]))].sort();
|
||||||
|
const periodos = solicitados ? solicitados.filter(p => disponibles.includes(p)) : disponibles;
|
||||||
|
return periodos.map(periodo => {
|
||||||
|
const enPeriodo = meses.filter(mes => mes[tipo] === periodo);
|
||||||
|
const filas: FilaBirads[] = ESTRATOS_BIRADS.map(id => {
|
||||||
|
const datos = enPeriodo.map(mes => mes.perfil[id]);
|
||||||
|
const celdas: Record<string, Celda> = Object.fromEntries(subtipos.map((subtipo, i) =>
|
||||||
|
[subtipo.id, publicada(sumar(datos.map(d => d.subtipos[i])))]
|
||||||
|
));
|
||||||
|
celdas[BENIGNO] = publicada(sumar(datos.map(d => d.benignos)));
|
||||||
|
const den = sumar(Object.values(celdas).map(celda => celda.n!));
|
||||||
|
const sinBiopsia = sumar(datos.map(d => d.sinBiopsia));
|
||||||
|
const sinDato = sumar(datos.map(d => d.sinDato));
|
||||||
|
return { id, etiqueta: ETIQUETA_ESTRATO[id], celdas, den, estado: 'Publicado',
|
||||||
|
aparte: { SIN_BIOPSIA: publicada(sinBiopsia), SIN_DATO: publicada(sinDato) },
|
||||||
|
total: publicada(den + sinBiopsia + sinDato) };
|
||||||
|
});
|
||||||
|
const totales = Object.fromEntries(categorias.map(c => [c.id, sumar(filas.map(fila => fila.celdas[c.id].n!))]));
|
||||||
|
return { periodo, categorias, grupos, base: RIESGO, filas, totales,
|
||||||
|
conResultado: sumar(Object.values(totales)), aparte: [...APARTE], vacio: false, notas: [],
|
||||||
|
grupoAnilloExterior: RIESGO };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -30,11 +30,13 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
imports: [MatButtonModule, MatCardModule, MatIconModule, IndicadorFigurePanel, IndicadorEu7Escenario, IndicadorTiemposPareados, IndicadorConfirmacionCitologia, IndicadorHistopatologiaCama, IndicadorConteosPareados],
|
||||||
template: `
|
template: `
|
||||||
<mat-card>
|
<mat-card>
|
||||||
<header>
|
@if (!conteos) {
|
||||||
<div class="card-identity">
|
<header>
|
||||||
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
<div class="card-identity">
|
||||||
</div>
|
<h2 [id]="titleId" tabindex="-1">{{ indicador.titulo }}</h2>
|
||||||
</header>
|
</div>
|
||||||
|
</header>
|
||||||
|
}
|
||||||
@if (!sobrio) {
|
@if (!sobrio) {
|
||||||
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
<button class="pin-toggle" mat-button type="button" [attr.aria-pressed]="pinned"
|
||||||
[attr.aria-label]="(pinned ? 'Desfijar indicador' : 'Fijar indicador') + ', ' + indicador.titulo"
|
[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' }}
|
<mat-icon aria-hidden="true">push_pin</mat-icon>{{ pinned ? 'Desfijar indicador' : 'Fijar indicador' }}
|
||||||
</button>
|
</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 (!sobrio) { <p class="catalog-metadata">{{ indicador.figuras.length }} figuras publicadas</p> }
|
||||||
@if (isEu7) {
|
@if (isEu7) {
|
||||||
<div #visibilityRegion class="eu7-region">
|
<div #visibilityRegion class="eu7-region">
|
||||||
@@ -54,7 +56,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
</div>
|
</div>
|
||||||
} @else if (isHistopatologia) {
|
} @else if (isHistopatologia) {
|
||||||
<div #visibilityRegion class="confirmacion-region">
|
<div #visibilityRegion class="confirmacion-region">
|
||||||
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" [metadata]="metadata" (metadataRequested)="loadMetadata()" />
|
<app-indicador-histopatologia-cama [dominio]="dominio" [indicador]="indicador" [tema]="tema" [applied]="applied" [visible]="visible" />
|
||||||
</div>
|
</div>
|
||||||
} @else if (tiempos; as par) {
|
} @else if (tiempos; as par) {
|
||||||
<div #visibilityRegion class="tiempos-region">
|
<div #visibilityRegion class="tiempos-region">
|
||||||
@@ -62,7 +64,7 @@ import { parConteos } from './indicadores-conteos-pareados';
|
|||||||
</div>
|
</div>
|
||||||
} @else if (conteos; as par) {
|
} @else if (conteos; as par) {
|
||||||
<div #visibilityRegion class="conteos-region">
|
<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>
|
</div>
|
||||||
} @else if (selectedFigure) {
|
} @else if (selectedFigure) {
|
||||||
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
<div #visibilityRegion class="graphic-region" [class.dual-panels]="isDual">
|
||||||
|
|||||||
@@ -5,6 +5,15 @@ p, h3, summary { overflow-wrap: anywhere; }
|
|||||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
.selection-status { font-weight: 600; }
|
.selection-status { font-weight: 600; }
|
||||||
.legend { display: grid; gap: .6rem; margin-block: 1rem; }
|
.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; }
|
.keys { display: flex; flex-wrap: wrap; gap: .5rem; }
|
||||||
.legend > button { justify-self: start; }
|
.legend > button { justify-self: start; }
|
||||||
button { min-height: 44px; max-width: 100%; padding: .5rem .8rem; border: 1px solid var(--issste-border);
|
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; }
|
table { border-collapse: collapse; width: 100%; margin-block: 1rem; }
|
||||||
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
th, td { padding: .5rem; text-align: start; border-bottom: 1px solid var(--issste-border); }
|
||||||
caption { text-align: start; font-weight: 600; }
|
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 h3 { margin: 0 0 .25rem; }
|
||||||
.reading-guide + .reading-guide { margin-top: 1rem; }
|
.reading-guide + .reading-guide { margin-top: 1rem; }
|
||||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
.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 { margin: 0; padding-inline-start: 1.25rem; color: var(--issste-text-secondary); }
|
||||||
.rate-states:empty { display: none; }
|
.rate-states:empty { display: none; }
|
||||||
/* Rates on the left, donut on the right (the reverse of EU7). */
|
/* 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)">
|
<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()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@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> }
|
@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> }
|
@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) {
|
@if (status() === 'ready' && model; as m) {
|
||||||
|
@let tituloMastografias = 'Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6, ' + m.periodo;
|
||||||
|
@let tituloPacientes = 'Porcentaje de pacientes con resultados de BI-RADS 4, 5 o 6, ' + m.periodo;
|
||||||
@if (pages.length > 1) {
|
@if (pages.length > 1) {
|
||||||
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
<nav class="periods" [attr.aria-label]="'Periodos, ' + indicador.titulo">
|
||||||
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" aria-label="Periodo anterior" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
@@ -32,22 +17,43 @@
|
|||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
<div class="figures">
|
<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) {
|
@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> }
|
} @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> }
|
@if (m.sinDato) { <p class="note">Fuera de la dona: {{ texto(m.sinDato) }} {{ par.unidades.examenes }} sin categoría.</p> }
|
||||||
</section>
|
</section>
|
||||||
<section class="figure"><h3>{{ par.unidades.pacientes | titlecase }} y {{ par.unidades.examenes }}, {{ m.periodo }}</h3>
|
<section class="figure">
|
||||||
<app-plotly-chart [figure]="barsFigure!" [showNotes]="false" [label]="indicador.titulo + ', barras por familia de BI-RADS, ' + m.periodo" />
|
<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> }
|
@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>
|
</section>
|
||||||
</div>
|
</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> }
|
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||||
<details class="published-values"><summary>Valores publicados</summary>
|
<details class="published-values"><summary>Valores publicados</summary>
|
||||||
<div class="table-scroll" role="region" [attr.aria-label]="'Tabla de valores, ' + indicador.titulo" tabindex="0">
|
<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>
|
<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>
|
<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>
|
</table>
|
||||||
|
|||||||
@@ -3,16 +3,25 @@
|
|||||||
p, h3, summary { overflow-wrap: anywhere; }
|
p, h3, summary { overflow-wrap: anywhere; }
|
||||||
.applied-summary, .note { color: var(--issste-text-secondary); }
|
.applied-summary, .note { color: var(--issste-text-secondary); }
|
||||||
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
.methodology { padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
||||||
.reading-guide h3 { margin: 0 0 .25rem; }
|
.figure-head { position: relative; display: flex; align-items: flex-start; justify-content: space-between; gap: .75rem; }
|
||||||
.reading-guide ul { margin: .5rem 0 0; padding-inline-start: 1.25rem; }
|
.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; }
|
h3 { font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
||||||
.periods { display: flex; align-items: center; gap: var(--issste-space-3); }
|
.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);
|
.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; }
|
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); cursor: pointer; }
|
||||||
.periods button:disabled { opacity: .5; cursor: default; }
|
.periods button:disabled { opacity: .5; cursor: default; }
|
||||||
// The two figures share the card in equal halves; one above the other on a narrow card.
|
// 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); }
|
.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; }
|
||||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
.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; }
|
app-plotly-chart { --plot-height: 400px; }
|
||||||
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
// Keep space for the outside labels and let the existing plot viewport scroll on very narrow cards.
|
||||||
.donut-chart { --plot-min-width: 230px; }
|
.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 { HttpErrorResponse } from '@angular/common/http';
|
||||||
import { TitleCasePipe } from '@angular/common';
|
import { TitleCasePipe } from '@angular/common';
|
||||||
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
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 { filterCompatibility, GlobalApplied } from './indicadores-memory';
|
||||||
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
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({
|
@Component({
|
||||||
selector: 'app-indicador-conteos-pareados',
|
selector: 'app-indicador-conteos-pareados',
|
||||||
@@ -25,35 +25,45 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() visible = true;
|
@Input() visible = true;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
|
||||||
readonly metadataRequested = output<void>();
|
|
||||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
||||||
message = '';
|
message = '';
|
||||||
periodIndex = 0;
|
periodIndex = 0;
|
||||||
pages: ModeloConteos[] = [];
|
pages: ModeloConteos[] = [];
|
||||||
donutFigure?: PlotlyFigure;
|
donutFigure?: PlotlyFigure;
|
||||||
barsFigure?: PlotlyFigure;
|
patientsFigure?: PlotlyFigure;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
private readonly snapshots = inject(IndicadoresSnapshots);
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
private subscription?: Subscription;
|
private subscription?: Subscription;
|
||||||
private key = '';
|
private key = '';
|
||||||
private loaded = false;
|
private loaded = false;
|
||||||
private anchoDona = 390;
|
private anchoDona = 390;
|
||||||
|
private anchoPacientes = 390;
|
||||||
|
|
||||||
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
get model(): ModeloConteos | undefined { return this.pages[this.periodIndex]; }
|
||||||
get total() { return this.model ? totalExamenes(this.model) : null; }
|
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'); }
|
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); }
|
textoPacientes(n: number | null) { return n === null && this.model && !this.model.pacientesVerificados ? 'Pendiente' : this.texto(n); }
|
||||||
helpOpen = false;
|
helpWhich: 'examenes' | 'pacientes' | null = null;
|
||||||
// "Cómo leer": what the kit publishes for the exams' donut. The bars combine two indicators, so the kit's
|
private helpPinned: 'examenes' | 'pacientes' | null = null;
|
||||||
// description of its own bars does not apply to them and is not used.
|
toggleHelp(which: 'examenes' | 'pacientes') {
|
||||||
get donutGuide() {
|
if (this.helpPinned === which) { this.helpPinned = null; this.helpWhich = null; return; }
|
||||||
const detail = this.metadata?.figuras_detalle?.find(item => item.figura === 'fig_c2_donas');
|
this.helpPinned = which;
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
this.openHelp(which);
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
}
|
||||||
return descripcion || como_leer.length ? { descripcion, como_leer } : undefined;
|
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) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([this.par.examenes, this.par.pacientes, this.indicador.tipos_periodo]);
|
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();
|
else if (this.model && changes['tema']) this.draw();
|
||||||
}
|
}
|
||||||
retry() { if (this.visible) this.load(); }
|
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() {
|
private load() {
|
||||||
this.subscription?.unsubscribe();
|
this.subscription?.unsubscribe();
|
||||||
this.loaded = true; this.clear();
|
this.loaded = true; this.clear();
|
||||||
@@ -111,11 +121,17 @@ export class IndicadorConteosPareados implements OnChanges, OnDestroy {
|
|||||||
const m = this.model;
|
const m = this.model;
|
||||||
if (m) this.donutFigure = donaConteos(m, this.par, this.tema, ancho);
|
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() {
|
private draw() {
|
||||||
const m = this.model;
|
const m = this.model;
|
||||||
if (!m) return;
|
if (!m) return;
|
||||||
this.donutFigure = donaConteos(m, this.par, this.tema, this.anchoDona);
|
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();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
ngOnDestroy() { this.subscription?.unsubscribe(); }
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
|||||||
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
import { figureInterpretation, PERIOD_INTERPRETATION } from './indicadores-methodology';
|
||||||
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
import { DonutHierarchy, DonutLegendEntry, DonutSelection, donutSimpleView, donutView } from './indicadores-donut-drilldown';
|
||||||
import { FigureHighlight, highlightAt, highlightFigure, highlightLabel, highlightRows, HighlightSelection, toggleHighlight } from './indicadores-highlight';
|
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.
|
// The panel owns requests; the card receives the original and its presentation copy.
|
||||||
export interface FigureState {
|
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) ?? []; }
|
get visibleChildren() { return this.state.hierarchy?.children.filter(c => c.parent === this.activeParent) ?? []; }
|
||||||
legendColor(label: string, parent: boolean): string {
|
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 labels = trace?.['labels'], marker = trace?.['marker'] as { colors?: unknown[] } | undefined;
|
||||||
const color = Array.isArray(labels) ? marker?.colors?.[labels.indexOf(label)] : 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';
|
return typeof color === 'string' && /^#[0-9a-f]{6}$/i.test(color) ? color : 'currentColor';
|
||||||
|
|||||||
@@ -1,27 +1,27 @@
|
|||||||
<section class="confirmacion" aria-label="Resultado histopatológico por categoría BI-RADS">
|
<section class="confirmacion histo" aria-label="Resultado histopatológico por categoría BI-RADS">
|
||||||
<p class="applied-summary">Filtro general aplicado: {{ appliedSummary }}</p>
|
<div class="histo-meta">
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="helpOpen" (click)="toggleHelp()">Cómo leer</button>
|
<p class="view-context">
|
||||||
@if (helpOpen) {
|
<span>{{ intervalLabel }}</span>
|
||||||
<div class="methodology">
|
@if (contextPeriod) { <span>Periodo {{ contextPeriod }}</span> }
|
||||||
<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>
|
</p>
|
||||||
@if (metadata) {
|
<div class="help" (mouseenter)="showHelp()" (mouseleave)="hideHelp()" (focusin)="showHelp()" (focusout)="onHelpFocusOut($event)">
|
||||||
@for (guide of readingGuide; track guide.figura) {
|
<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>
|
||||||
<section class="reading-guide" [attr.aria-label]="'Cómo leer: ' + guide.nombre">
|
@if (helpOpen) {
|
||||||
<h3>{{ guide.nombre }}</h3>
|
<div class="methodology" id="histo-como-leer" role="tooltip">
|
||||||
@if (guide.descripcion) { <p>{{ guide.descripcion }}</p> }
|
<p>Cada barra muestra el porcentaje de pacientes con resultado de biopsia en la categoría BI-RADS que corresponde a la selección. La línea indica el intervalo de confianza de 95 %. «Sin biopsia reportada» y «Sin dato» se muestran aparte en la tabla.</p>
|
||||||
@if (guide.como_leer.length) { <ul>@for (line of guide.como_leer; track $index) { <li>{{ line }}</li> }</ul> }
|
<p>El anillo interior compara los grupos entre todas las pacientes con resultado. El exterior muestra solo la distribución de los subtipos dentro de «Riesgo a carcinoma». Selecciona un sector o su etiqueta para actualizar las barras.</p>
|
||||||
</section>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
|
||||||
@switch (status()) {
|
@switch (status()) {
|
||||||
@case ('deferred') { <p role="status">La vista se cargará al acercarse a esta región.</p> }
|
@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> }
|
@case ('incompatible') { <p role="alert">{{ message }}</p> }
|
||||||
@case ('error') { <div role="alert"><p>{{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
|
||||||
@case ('incompatible') { <div role="alert"><p>Respuesta incompatible: {{ message }}</p><button mat-stroked-button type="button" (click)="retry()">Reintentar</button></div> }
|
|
||||||
}
|
}
|
||||||
@if (status() === 'ready' || status() === 'empty') {
|
@if (status() === 'empty') {
|
||||||
|
<p role="status">No hay resultados de biopsia para el periodo seleccionado.</p>
|
||||||
|
}
|
||||||
|
@if (status() === 'ready') {
|
||||||
@if (periods.length > 1) {
|
@if (periods.length > 1) {
|
||||||
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
|
<nav class="periods" aria-label="Periodos de la histopatología por BI-RADS">
|
||||||
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
<button type="button" aria-label="Periodo anterior de la histopatología" [disabled]="periodIndex === 0" (click)="changePeriod(-1)">‹</button>
|
||||||
@@ -30,40 +30,40 @@
|
|||||||
</nav>
|
</nav>
|
||||||
}
|
}
|
||||||
@if (model; as m) {
|
@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> }
|
<div class="legend">
|
||||||
@else {
|
<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 categoriasExteriores(m); 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">
|
<div class="figures">
|
||||||
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
<section class="figure rates"><h3>Por categoría BI-RADS, {{ m.periodo }}</h3>
|
||||||
@if (ratesFigure) {
|
@if (ratesFigure) {
|
||||||
<app-plotly-chart [figure]="ratesFigure" [showNotes]="false" [label]="'Histopatología, tasas por categoría BI-RADS, ' + m.periodo + ', ' + selectionLabel" />
|
<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>
|
||||||
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
<section class="figure donut"><h3>Resultado de la biopsia, {{ m.periodo }}</h3>
|
||||||
@if (m.conResultado !== null && m.conResultado > 0 && donutFigure) {
|
@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> }
|
} @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>
|
</section>
|
||||||
</div>
|
</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> }
|
@for (note of m.notas; track $index) { <p class="note">{{ note }}</p> }
|
||||||
<details class="published-values"><summary>Valores publicados</summary>
|
<details class="published-values"><summary>Ver valores</summary>
|
||||||
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
<div class="table-scroll" role="region" aria-label="Tabla de pacientes por categoría BI-RADS y resultado de biopsia" tabindex="0">
|
||||||
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
|
<table><caption>Pacientes por categoría BI-RADS y resultado de la biopsia, {{ m.periodo }}</caption>
|
||||||
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
|
<thead><tr><th scope="col">Categoría BI-RADS</th>@for (c of m.categorias; track c.id) { <th scope="col">{{ c.etiqueta }}</th> }<th scope="col">Con resultado</th>@for (a of m.aparte; track a.id) { <th scope="col">{{ a.etiqueta }}</th> }<th scope="col">Total de pacientes</th></tr></thead>
|
||||||
|
|||||||
@@ -1,28 +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 { 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 { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models';
|
import { Dominio, Indicador, 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 { snapshotKey } from './indicadores-snapshots';
|
||||||
import { httpMessage } from './indicadores-http';
|
|
||||||
import { Celda } from './indicadores-confirmacion-citologia';
|
import { Celda } from './indicadores-confirmacion-citologia';
|
||||||
import { clicHistopatologia, donaHistopatologia, ESTRATO_BIRADS, estadoTasa, figuraTasas, HistopatologiaIncompatible, ID_HISTOPATOLOGIA,
|
import { categoriasExteriores, clicHistopatologia, donaHistopatologia, figuraTasas, ID_HISTOPATOLOGIA,
|
||||||
lectura, ModeloHistopatologia, modeloHistopatologia, periodosHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta, tasas } from './indicadores-histopatologia-cama';
|
ModeloHistopatologia, SeleccionHistopatologia, seleccionBase, seleccionEtiqueta } from './indicadores-histopatologia-cama';
|
||||||
|
import { modelosHistopatologiaDemo } from './histopatologia-cama-demo';
|
||||||
// Figures of the kit whose "Cómo leer" describes this coordinated view.
|
|
||||||
const FIGURAS = [['fig_c2_donas', 'Dona de resultados de la biopsia'], ['fig_c2_barras', 'Tasas por categoría BI-RADS']] as const;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CaMa's histopathological result by BI-RADS: rates with their interval per category, and a two-ring donut of the
|
|
||||||
* result of the biopsy, drawn from one stratified C2 response. Data in, figures out: it asks the snapshot service
|
|
||||||
* for the matrix and hands it to the pure adapter in `indicadores-histopatologia-cama`.
|
|
||||||
*/
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-histopatologia-cama',
|
selector: 'app-indicador-histopatologia-cama',
|
||||||
imports: [MatButtonModule, MatProgressBarModule, PlotlyChart],
|
imports: [PlotlyChart],
|
||||||
templateUrl: './indicador-histopatologia-cama.html',
|
templateUrl: './indicador-histopatologia-cama.html',
|
||||||
styleUrl: './indicador-confirmacion-citologia.scss',
|
styleUrl: './indicador-confirmacion-citologia.scss',
|
||||||
})
|
})
|
||||||
@@ -32,9 +19,7 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
@Input({ required: true }) tema!: Tema;
|
@Input({ required: true }) tema!: Tema;
|
||||||
@Input({ required: true }) applied!: GlobalApplied;
|
@Input({ required: true }) applied!: GlobalApplied;
|
||||||
@Input() visible = true;
|
@Input() visible = true;
|
||||||
@Input() metadata?: IndicadorMetadatos;
|
readonly status = signal<'deferred' | 'ready' | 'empty' | 'incompatible'>('deferred');
|
||||||
readonly metadataRequested = output<void>();
|
|
||||||
readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred');
|
|
||||||
message = '';
|
message = '';
|
||||||
selection?: SeleccionHistopatologia;
|
selection?: SeleccionHistopatologia;
|
||||||
periods: string[] = [];
|
periods: string[] = [];
|
||||||
@@ -43,9 +28,9 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
donutFigure?: PlotlyFigure;
|
donutFigure?: PlotlyFigure;
|
||||||
ratesFigure?: PlotlyFigure;
|
ratesFigure?: PlotlyFigure;
|
||||||
helpOpen = false;
|
helpOpen = false;
|
||||||
private readonly snapshots = inject(IndicadoresSnapshots);
|
readonly categoriasExteriores = categoriasExteriores;
|
||||||
|
private helpPinned = false;
|
||||||
private readonly changeDetector = inject(ChangeDetectorRef);
|
private readonly changeDetector = inject(ChangeDetectorRef);
|
||||||
private subscription?: Subscription;
|
|
||||||
private key = '';
|
private key = '';
|
||||||
private loaded = false;
|
private loaded = false;
|
||||||
private pages: ModeloHistopatologia[] = [];
|
private pages: ModeloHistopatologia[] = [];
|
||||||
@@ -54,73 +39,58 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
private readonly alCambiarAncho = () => this.draw();
|
private readonly alCambiarAncho = () => this.draw();
|
||||||
constructor() { this.estrecho?.addEventListener('change', this.alCambiarAncho); }
|
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 selectionLabel() { return this.model && this.selection ? seleccionEtiqueta(this.model, this.selection) : ''; }
|
||||||
get reading() { return this.model && this.selection ? lectura(this.model, this.selection) : ''; }
|
|
||||||
get isBase() { return !!this.model && !!this.selection && !this.selection.categoria && this.selection.grupo === this.model.base; }
|
|
||||||
get rates() { return this.model && this.selection ? tasas(this.model, this.selection) : []; }
|
|
||||||
readonly estadoTasa = estadoTasa;
|
|
||||||
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); }
|
||||||
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
denText(den: number | null, estado: string) { return den === null ? estado : den.toLocaleString('es-MX'); }
|
||||||
get readingGuide() {
|
toggleHelp() {
|
||||||
const details = this.metadata?.figuras_detalle ?? [];
|
if (this.helpPinned) { this.helpPinned = false; this.helpOpen = false; return; }
|
||||||
return FIGURAS.flatMap(([figura, nombre]) => {
|
this.helpPinned = true;
|
||||||
const detail = details.find(item => item.figura === figura);
|
this.showHelp();
|
||||||
const descripcion = detail?.descripcion?.trim() ?? '';
|
}
|
||||||
const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0);
|
showHelp() {
|
||||||
return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : [];
|
if (this.helpOpen) return;
|
||||||
});
|
this.helpOpen = true;
|
||||||
|
}
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); }
|
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges) {
|
ngOnChanges(changes: SimpleChanges) {
|
||||||
const key = snapshotKey(this.dominio, this.indicador, this.applied, { estrato: ESTRATO_BIRADS })
|
const key = snapshotKey(this.dominio, this.indicador, this.applied)
|
||||||
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras]);
|
+ JSON.stringify([this.indicador.contrato, this.indicador.tipos_periodo]);
|
||||||
if (key !== this.key) {
|
if (key !== this.key) {
|
||||||
this.subscription?.unsubscribe(); this.key = key; this.loaded = false;
|
this.key = key; this.loaded = false;
|
||||||
this.clear();
|
this.clear();
|
||||||
if (!this.visible) { this.status.set('deferred'); return; }
|
if (!this.visible) { this.status.set('deferred'); return; }
|
||||||
this.load();
|
this.load();
|
||||||
} else if (this.visible && !this.loaded) this.load();
|
} else if (this.visible && !this.loaded) this.load();
|
||||||
else if (this.model && changes['tema']) this.draw();
|
else if (this.model && changes['tema']) this.draw();
|
||||||
}
|
}
|
||||||
retry() { if (this.visible) this.load(); }
|
|
||||||
private clear() {
|
private clear() {
|
||||||
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
this.pages = []; this.periods = []; this.model = undefined; this.selection = undefined;
|
||||||
this.donutFigure = undefined; this.ratesFigure = undefined;
|
this.donutFigure = undefined; this.ratesFigure = undefined;
|
||||||
}
|
}
|
||||||
private load() {
|
private load() {
|
||||||
this.subscription?.unsubscribe();
|
|
||||||
this.loaded = true; this.clear();
|
this.loaded = true; this.clear();
|
||||||
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo);
|
||||||
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
if (this.dominio !== 'cama' || this.indicador.id !== ID_HISTOPATOLOGIA || this.indicador.contrato !== 'C2' || !compatibility.compatible) {
|
||||||
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista.';
|
||||||
this.status.set('incompatible'); return;
|
this.status.set('incompatible'); return;
|
||||||
}
|
}
|
||||||
const key = this.key;
|
const { tipo, selection } = this.applied;
|
||||||
const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined;
|
this.pages = modelosHistopatologiaDemo(tipo, selection.mode === 'explicit' ? selection.periodos : undefined);
|
||||||
this.status.set('loading');
|
this.periods = this.pages.map(modelo => modelo.periodo);
|
||||||
this.subscription = this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version,
|
this.periodIndex = Math.max(0, this.periods.length - 1);
|
||||||
{ estrato: ESTRATO_BIRADS }).pipe(timeout({ first: 40000 })).subscribe({
|
this.activatePeriod();
|
||||||
next: datos => {
|
|
||||||
if (key !== this.key) return;
|
|
||||||
try {
|
|
||||||
this.periods = periodosHistopatologia(datos, this.applied.tipo, periods);
|
|
||||||
this.pages = this.periods.map(p => modeloHistopatologia(datos, p));
|
|
||||||
// The most recent period first; navigation goes back.
|
|
||||||
this.periodIndex = Math.max(0, this.periods.length - 1); this.activatePeriod();
|
|
||||||
} catch (error) { this.failure(error); }
|
|
||||||
},
|
|
||||||
error: error => { if (key === this.key) this.failure(error); },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
private failure(error: unknown) {
|
|
||||||
this.clear();
|
|
||||||
this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.'
|
|
||||||
: error instanceof HistopatologiaIncompatible ? error.message : httpMessage(error);
|
|
||||||
this.status.set(error instanceof HistopatologiaIncompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError)
|
|
||||||
? 'incompatible' : 'error');
|
|
||||||
this.changeDetector.markForCheck();
|
|
||||||
}
|
}
|
||||||
private activatePeriod() {
|
private activatePeriod() {
|
||||||
this.model = this.pages[this.periodIndex];
|
this.model = this.pages[this.periodIndex];
|
||||||
@@ -145,5 +115,5 @@ export class IndicadorHistopatologiaCama implements OnChanges, OnDestroy {
|
|||||||
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
this.ratesFigure = figuraTasas(this.model, this.selection, this.tema, !!this.estrecho?.matches);
|
||||||
this.changeDetector.markForCheck();
|
this.changeDetector.markForCheck();
|
||||||
}
|
}
|
||||||
ngOnDestroy() { this.subscription?.unsubscribe(); this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
ngOnDestroy() { this.estrecho?.removeEventListener('change', this.alCambiarAncho); }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
import { Component, signal } from '@angular/core';
|
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
|
||||||
import { MatCardModule } from '@angular/material/card';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* CaMa's histopathological result by BI-RADS category, while the catalog does not publish its indicator
|
|
||||||
* (`cama_histopatologia_birads`). It keeps the card's place and structure, with no figure and no number.
|
|
||||||
*/
|
|
||||||
@Component({
|
|
||||||
selector: 'app-indicador-histopatologia-pendiente',
|
|
||||||
host: { class: 'dual-card' },
|
|
||||||
imports: [MatButtonModule, MatCardModule],
|
|
||||||
template: `
|
|
||||||
<mat-card>
|
|
||||||
<h2>Resultado histopatológico por categoría BI-RADS</h2>
|
|
||||||
<button mat-button type="button" class="methodology-toggle" [attr.aria-expanded]="ayuda()" (click)="ayuda.set(!ayuda())">Cómo leer</button>
|
|
||||||
@if (ayuda()) {
|
|
||||||
<div class="methodology">
|
|
||||||
<p>Cuando el catálogo publique el indicador, esta tarjeta mostrará, por categoría BI-RADS, el porcentaje de biopsias con resultado maligno y su intervalo de confianza, y la distribución del resultado de la biopsia en una dona que se puede recorrer por grupo y por resultado.</p>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
<p class="estado" role="status"><strong>Integración pendiente.</strong> Este indicador aún no está publicado por el catálogo institucional.</p>
|
|
||||||
<div class="figures">
|
|
||||||
<section class="figure"><h3>Por categoría BI-RADS</h3><div class="vacio">Sin datos publicados</div></section>
|
|
||||||
<section class="figure"><h3>Resultado de la biopsia</h3><div class="vacio">Sin datos publicados</div></section>
|
|
||||||
</div>
|
|
||||||
</mat-card>
|
|
||||||
`,
|
|
||||||
styles: `
|
|
||||||
:host { display: flex; min-width: 0; margin: 0; grid-column: 1 / -1; }
|
|
||||||
mat-card { flex: 1; min-width: 0; padding: clamp(.75rem, 2vw, 1.5rem); background: var(--issste-surface); color: var(--issste-text);
|
|
||||||
border: 1px solid var(--issste-border); border-radius: var(--issste-radius); box-shadow: none; }
|
|
||||||
h2 { margin: 0; font-family: var(--issste-font-heading); font-weight: 500; font-size: 1.125rem; line-height: 1.3; overflow-wrap: anywhere; }
|
|
||||||
h3 { margin: 0; font-size: 1rem; font-weight: 500; line-height: 1.5; }
|
|
||||||
p { margin: var(--issste-space-3) 0 0; overflow-wrap: anywhere; }
|
|
||||||
.estado { color: var(--issste-text-secondary); }
|
|
||||||
.methodology { margin-top: var(--issste-space-3); padding: 1rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius); }
|
|
||||||
.methodology p { margin: 0; }
|
|
||||||
.figures { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--issste-space-6); margin-top: var(--issste-space-3); }
|
|
||||||
@media (min-width: 1100px) { .figures { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
|
||||||
.vacio { display: grid; place-items: center; min-height: 12rem; margin-top: var(--issste-space-3); color: var(--issste-text-secondary);
|
|
||||||
border: 1px dashed var(--issste-border); border-radius: var(--issste-radius); }
|
|
||||||
button:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 3px; }
|
|
||||||
`,
|
|
||||||
})
|
|
||||||
export class IndicadorHistopatologiaPendiente {
|
|
||||||
readonly ayuda = signal(false);
|
|
||||||
}
|
|
||||||
@@ -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').textContent).toContain('Valor de prueba');
|
||||||
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
expect(fixture.nativeElement.querySelector('.value span').textContent).toBe('Unidad de prueba');
|
||||||
expect(fixture.nativeElement.textContent).toContain('Referencia 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('.kpi-state').textContent).toBe('Estado de prueba');
|
||||||
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
expect(fixture.nativeElement.querySelector('.additional-info').textContent).toBe('Información de prueba');
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
expect(fixture.nativeElement.textContent).not.toContain('Definición provisional');
|
||||||
|
|||||||
@@ -12,16 +12,23 @@ import { MatCardModule } from '@angular/material/card';
|
|||||||
@if (value !== null && value !== undefined) {
|
@if (value !== null && value !== undefined) {
|
||||||
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
<p class="value">{{ value }}@if (unit) { <span>{{ unit }}</span> }</p>
|
||||||
}
|
}
|
||||||
@if (temporalReference) { <p>{{ temporalReference }}</p> }
|
<div class="kpi-foot">
|
||||||
<p class="kpi-state" role="status" [class.visually-hidden]="quietWhenAvailable && state === 'Disponible'">{{ state }}</p>
|
@if (temporalReference) {
|
||||||
@if (informationLine) { <p class="additional-info">{{ informationLine }}</p> }
|
<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>
|
</mat-card>
|
||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: block; min-width: 0; }
|
:host { display: flex; flex-direction: column; height: 100%; min-width: 0; }
|
||||||
mat-card { box-sizing: border-box; height: 100%; padding: var(--issste-space-6);
|
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);
|
background: var(--issste-surface); color: var(--issste-text); border: 1px solid var(--issste-border);
|
||||||
border-radius: var(--issste-radius); box-shadow: none; }
|
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 { margin: 0; font-family: var(--issste-font-heading); font-size: 1rem; font-weight: 500; line-height: 1.3; }
|
||||||
h3, p { overflow-wrap: anywhere; }
|
h3, p { overflow-wrap: anywhere; }
|
||||||
p { margin: var(--issste-space-3) 0 0; }
|
p { margin: var(--issste-space-3) 0 0; }
|
||||||
@@ -46,6 +53,10 @@ export class IndicadorKpiCard {
|
|||||||
// A card that shows its value needs no "Disponible" line.
|
// A card that shows its value needs no "Disponible" line.
|
||||||
@Input() quietWhenAvailable = false;
|
@Input() quietWhenAvailable = false;
|
||||||
@Input() additionalInfo?: string;
|
@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 {
|
get informationLine(): string | undefined {
|
||||||
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
const lines = [this.additionalInfo, ...this.notes].map(value => value?.trim()).filter((value): value is string => !!value);
|
||||||
return [...new Set(lines)].join(' ');
|
return [...new Set(lines)].join(' ');
|
||||||
|
|||||||
@@ -183,10 +183,12 @@ 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.'] }));
|
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();
|
fixture.detectChanges();
|
||||||
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
const cards = [...fixture.nativeElement.querySelectorAll('app-indicador-kpi-card')];
|
||||||
expect(cards).toHaveLength(domain === 'cacu' ? 5 : 4);
|
expect(cards).toHaveLength(5);
|
||||||
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')?.firstChild?.textContent?.trim())).toEqual(['5', undefined, '7', undefined, 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('.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']);
|
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(cards.map(card => card.textContent)).toEqual(expect.arrayContaining([
|
||||||
expect.stringContaining('2025-S1'),
|
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.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.'),
|
||||||
|
|||||||
@@ -2,11 +2,13 @@
|
|||||||
<section aria-label="Editor de filtros generales del proyecto">
|
<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> }
|
@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">
|
<div class="fields compact">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
<div class="interval">
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
</mat-select>
|
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
</mat-form-field>
|
@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-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
<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">
|
<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> }
|
@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">
|
<div class="fields">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Intervalo de análisis</mat-label>
|
<div class="interval">
|
||||||
<mat-select [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
<span class="field-label" id="filtro-intervalo">Intervalo de análisis</span>
|
||||||
@for (tipo of types; track tipo) { <mat-option [value]="tipo">{{ tipo === 'mes' ? 'Mensual' : 'Semestral' }}</mat-option> }
|
<mat-button-toggle-group aria-labelledby="filtro-intervalo" hideSingleSelectionIndicator [ngModel]="state.tipo" (ngModelChange)="changeTipo($event)">
|
||||||
</mat-select>
|
@if (types.includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
</mat-form-field>
|
@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-form-field appearance="outline" subscriptSizing="dynamic"><mat-label>Periodo seleccionado</mat-label>
|
||||||
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
<mat-select [ngModel]="selectedPeriods[0] ?? null" (ngModelChange)="select($event ? [$event] : [])">
|
||||||
<mat-select-trigger><span class="select-value">{{ selectedPeriods[0] }}</span></mat-select-trigger>
|
<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; }
|
: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.
|
// 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) 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) .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) .apply-button { min-height: 40px; }
|
||||||
:host(.compacto) .period-builder button { min-height: 40px; }
|
:host(.compacto) .period-builder button { min-height: 40px; }
|
||||||
section { min-width: 0; }
|
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; }
|
mat-form-field { flex: 1 1 14rem; min-width: 0; max-width: 24rem; }
|
||||||
.period-builder mat-form-field { flex: 0 1 10rem; }
|
.period-builder mat-form-field { flex: 0 1 10rem; }
|
||||||
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
.period-builder button { margin-top: var(--issste-space-2); min-height: 44px; }
|
||||||
|
|||||||
@@ -138,16 +138,11 @@ describe('UX-04 control asistido', () => {
|
|||||||
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
fixture.nativeElement.querySelector('button[mat-flat-button]').click();
|
||||||
expect(apply).toHaveBeenCalledTimes(1);
|
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);
|
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');
|
expect(labels).not.toContain('Modalidad');
|
||||||
const select = fixture.debugElement.queryAll(By.css('mat-form-field'))
|
expect([...fixture.nativeElement.querySelectorAll('mat-button-toggle')].map((b: HTMLElement) => b.textContent!.trim())).toEqual(['Mensual', 'Semestral']);
|
||||||
.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();
|
|
||||||
});
|
});
|
||||||
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
it('al cambiar de intervalo elige el periodo más reciente con reporte', () => {
|
||||||
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
fixture.componentRef.setInput('availability', { status: 'ready', byIndicator: {}, errors: {},
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
|
import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core';
|
||||||
import { FormsModule } from '@angular/forms';
|
import { FormsModule } from '@angular/forms';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||||
import { MatInputModule } from '@angular/material/input';
|
import { MatInputModule } from '@angular/material/input';
|
||||||
import { MatSelectModule } from '@angular/material/select';
|
import { MatSelectModule } from '@angular/material/select';
|
||||||
@@ -10,7 +11,7 @@ import { describePeriods, newEditor, FilterState, pending, validDraft } from './
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicador-period-filters',
|
selector: 'app-indicador-period-filters',
|
||||||
imports: [FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
imports: [FormsModule, MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatInputModule, MatSelectModule],
|
||||||
host: { '[class.compacto]': 'compact' },
|
host: { '[class.compacto]': 'compact' },
|
||||||
templateUrl: './indicador-period-filters.html',
|
templateUrl: './indicador-period-filters.html',
|
||||||
styleUrl: './indicador-period-filters.scss',
|
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 => {
|
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 data = c2Fixture(); (data['categorias'] as Record<string, Record<string, unknown>>)['A']['color'] = '#D98E4A';
|
||||||
const figure = supported(data, { ...selection, tema }).figure;
|
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((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(['#D98E4A', 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['paper_bgcolor']).toBe(C2_PALETTE[tema].background);
|
||||||
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
expect(figure.layout['font']).toMatchObject({ color: C2_PALETTE[tema].text });
|
||||||
expect(C2_PALETTE.states.noData).toBe('#C9CDD2'); expect(c2Color('#C9CDD2',0)).toBe('#C9CDD2');
|
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, 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(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(c2Color(C2_PALETTE.edades[0], 0)).toBe(C2_PALETTE.edades[0]);
|
||||||
expect(figure.config?.['responsive']).not.toBe(false); expect(figure.layout['width']).toBeUndefined();
|
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 { FigureSelection, IndicadorDatos, parsePeriodos, PlotlyFigure } from './indicadores.models';
|
||||||
import { DonutHierarchy } from './indicadores-donut-drilldown';
|
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; }
|
export interface C2Category { id: string; label: string; parentId?: string; value: number; color?: string; }
|
||||||
// Normalized presentation nodes and a selection path are independent of Plotly.
|
// 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 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 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 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 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,
|
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 },
|
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>' }];
|
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),
|
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)),
|
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] } });
|
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
|
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]);
|
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', () => {
|
it('cambia el café y el anaranjado por la serie, y deja azul, rojo, gris y edad', () => {
|
||||||
const [azul, rojo, naranja, amarillo, guinda, sinDato, edad] = institutionalize([
|
const [cafe, otroCafe, rojo, azul, sinDato, edad] = institutionalize([
|
||||||
'#0044CC', '#C41E3A', '#FF6B00', '#FFD100', '#7A2E0E', '#C9CDD2', '#2F6DB3',
|
'#B55A1F', '#D9822B', '#C41E3A', '#0044CC', '#C9CDD2', '#2F6DB3',
|
||||||
]);
|
]);
|
||||||
expect([azul, rojo, naranja, amarillo, guinda]).toEqual(C2_PALETTE.series.slice(0, 5));
|
expect([cafe, otroCafe]).toEqual(C2_PALETTE.series.slice(0, 2));
|
||||||
expect(edad).toBe('#2F6DB3');
|
expect(rojo).toBe('#C41E3A');
|
||||||
|
expect(azul).toBe('#0044CC');
|
||||||
expect(sinDato).toBe('#C9CDD2');
|
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', () => {
|
it('da a cada grupo un matiz y a sus categorías pasos distintos de ese matiz', () => {
|
||||||
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
const colors = paintByGroup(['benigno', 'benigno', 'benigno', 'maligno']);
|
||||||
expect(new Set(colors.slice(0, 3)).size).toBe(3);
|
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(colors[0]).not.toBe(colors[3]);
|
||||||
expect(groupBase(0)).toBe(C2_PALETTE.series[0]);
|
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'] },
|
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]['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).toBe('rgba(0,68,204,0.4)');
|
||||||
expect((figure.data[0]['error_x'] as { color: string }).color).not.toContain('0,68,204');
|
|
||||||
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
expect((figure.data[0]['line'] as { color: string }).color).toBe('#C9CDD2');
|
||||||
const scale = figure.data[0]['colorscale'] as [number, string][];
|
const scale = figure.data[0]['colorscale'] as [number, string][];
|
||||||
expect(scale.map(stop => stop[0])).toEqual([0, 0.5, 1]);
|
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(scale[0][1]).not.toBe(scale[1][1]);
|
||||||
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
expect(figure.layout['font']).toEqual({ color: '#081839' });
|
||||||
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
expect(figure.layout['paper_bgcolor']).toBe('#FFFFFF');
|
||||||
expect(figure.layout['colorway']).toEqual(C2_PALETTE.series.slice(2, 4));
|
expect(figure.layout['colorway']).toEqual([C2_PALETTE.series[1], '#636efa']);
|
||||||
expect(new Set([
|
|
||||||
(figure.data[0]['marker'] as { color: string }).color,
|
|
||||||
...(figure.layout['colorway'] as string[]),
|
|
||||||
]).size).toBe(3);
|
|
||||||
expect(recolorFigure(figure)).toBe(figure);
|
expect(recolorFigure(figure)).toBe(figure);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
import { PlotlyFigure, Tema } from './indicadores.models';
|
import { PlotlyFigure, Tema } from './indicadores.models';
|
||||||
|
|
||||||
// Categorical palette anchored on the logo lime (#a8c243) and the theme teal (#5f9ea0).
|
// Logo lime plus the analogous and complementary hues chosen for the charts.
|
||||||
// Neighboring entries differ in hue so series stay distinct, and none is a party colour:
|
// Cool greens, teal and blue are the normal side. Rose, violet and purple are the abnormal side.
|
||||||
// no royal blue, red, orange, yellow or guinda. Neutrals stay neutral.
|
// Neutrals stay neutral. Sequential fills run from pale lime to deep teal.
|
||||||
// Sequential fills (heatmaps) use SCALE, 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({
|
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([
|
series: Object.freeze([
|
||||||
'#5c7014', '#0e7568', '#6a6448', '#3d6b38',
|
'#A8C243', '#42C29C', '#C24269', '#9C42C2',
|
||||||
'#5a6170', '#3a5a48', '#3e5c6a', '#4a5a38',
|
'#69C242', '#5C42C2', '#42C25C', '#4269C2',
|
||||||
]),
|
]),
|
||||||
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
scale: Object.freeze(['#e4eed4', '#a8c243', '#2f6f68', '#1a3330']),
|
||||||
// Age groups of the EEG indicators (M21, M22). Kept apart from the series on purpose.
|
// 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;
|
const key = parseColor(color)?.key;
|
||||||
return !!key && ageKeys.has(key);
|
return !!key && ageKeys.has(key);
|
||||||
}
|
}
|
||||||
export function c2Color(published: string | undefined, index: number): string {
|
/** Orange, tan and coffee. Age gold and the palette's own stone are not included. */
|
||||||
// A published swatch stays. The series only fills a category that arrived without one.
|
function isCoffeeParsed(item: Parsed | undefined): boolean {
|
||||||
if (published && (/^#[0-9a-f]{6}$/i.test(published) || isAgeColor(published))) return published;
|
if (!item || item.kind === 'neutral' || ageKeys.has(item.key)) return false;
|
||||||
return C2_PALETTE.series[index % C2_PALETTE.series.length];
|
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[] {
|
export function paintByGroup(groups: readonly string[]): string[] {
|
||||||
const order = [...new Set(groups)];
|
const bases = basesPorGrupo(groups);
|
||||||
const counts = new Map(order.map(id => [id, groups.filter(g => g === id).length]));
|
const counts = new Map([...bases.keys()].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 stairs = new Map([...bases].map(([id, color]) => [id, steps(color, counts.get(id)!)]));
|
||||||
const cursor = new Map<string, number>();
|
const cursor = new Map<string, number>();
|
||||||
return groups.map(id => {
|
return groups.map(id => {
|
||||||
const index = cursor.get(id) ?? 0;
|
const index = cursor.get(id) ?? 0;
|
||||||
@@ -51,7 +93,7 @@ export function institutionalize(colors: readonly string[]): string[] {
|
|||||||
const foreign: string[] = [];
|
const foreign: string[] = [];
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
for (const item of parsed) {
|
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);
|
seen.add(item.key);
|
||||||
foreign.push(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. */
|
/** Coffee published colours take the cool or warm pool of their metadata id. */
|
||||||
export function seriesColors(published: readonly (string | undefined)[]): string[] {
|
export function seriesColors(published: readonly (string | undefined)[], claves?: readonly (string | undefined)[]): string[] {
|
||||||
return published.map((color, index) => c2Color(color, index));
|
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]> = {
|
const NAMED: Record<string, [number, number, number]> = {
|
||||||
@@ -101,10 +148,13 @@ function parseColor(input: string): Parsed | undefined {
|
|||||||
}
|
}
|
||||||
const lum = luminance({ r, g, b });
|
const lum = luminance({ r, g, b });
|
||||||
const neutral = sat < 0.18;
|
const neutral = sat < 0.18;
|
||||||
const harmonious = !neutral && (
|
const swatch = '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
|
||||||
(hue >= 64 && hue <= 188 && sat >= 0.22)
|
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 > 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' };
|
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[] {
|
function steps(base: string, count: number): string[] {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { provideRouter } from '@angular/router';
|
|||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { MatDialog } from '@angular/material/dialog';
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||||
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
import tasaVisible from './fixtures/cama_tasa_deteccion_visible.json';
|
||||||
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
import tasaSuprimida from './fixtures/cama_tasa_deteccion_suprimido.json';
|
||||||
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
import diasVisible from './fixtures/cama_dias_resultado_visible.json';
|
||||||
@@ -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.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([
|
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]]);
|
['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.figure.layout['barmode']).toBe('stack');
|
||||||
expect(f.comoLeer).toContain('pacientes');
|
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('dominio', 'cama'); fixture.componentRef.setInput('catalog', REALES);
|
||||||
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
fixture.componentRef.setInput('tema', 'claro'); fixture.componentRef.setInput('active', true);
|
||||||
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
fixture.componentInstance.elegido.set('semestre'); fixture.detectChanges();
|
||||||
const respuestas: Record<string, unknown> = visibles
|
const respuestas: Record<string, unknown> = {
|
||||||
? { cama_tasa_deteccion_histopatologica: tasaVisible, cama_dias_resultado_diagnostico: diasVisible, cama_histopatologia_birads: generalFixture }
|
cama_dias_resultado_diagnostico: visibles ? diasVisible : diasSuprimido,
|
||||||
: { cama_tasa_deteccion_histopatologica: tasaSuprimida, cama_dias_resultado_diagnostico: diasSuprimido, cama_histopatologia_birads: generalFixture };
|
cama_histopatologia_birads: generalFixture,
|
||||||
|
};
|
||||||
const pedidos: string[] = [];
|
const pedidos: string[] = [];
|
||||||
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
for (let ola = http.match(() => true); ola.length; ola = http.match(() => true)) {
|
||||||
for (const r of ola) {
|
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 paneles = () => [...(fixture.nativeElement as HTMLElement).querySelectorAll('article.panel')] as HTMLElement[];
|
||||||
const graficas = () => fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
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);
|
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([
|
expect(pedidos.filter(p => p.includes('/datos'))).toEqual([
|
||||||
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
'/cama/indicadores/cama_histopatologia_birads/datos?periodos=2025-S1',
|
||||||
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1',
|
'/cama/indicadores/cama_dias_resultado_diagnostico/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
||||||
'/cama/indicadores/cama_tasa_deteccion_histopatologica/datos?periodos=2025-S1'].sort((a, b) => pedidos.indexOf(a) - pedidos.indexOf(b)));
|
|
||||||
const titulos = paneles().map(p => [p.querySelector('h2')!.textContent, p.textContent!.includes('Integración pendiente') ? 'pendiente' : 'dibujado']);
|
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!)))
|
expect(titulos.map(([t]) => t)).not.toContain('Tasa de detección histopatológica');
|
||||||
.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(titulos.filter(([, estado]) => estado === 'dibujado'))
|
||||||
expect(graficas()).toHaveLength(3);
|
.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, 2]);
|
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);
|
montar(false);
|
||||||
const texto = paneles().map(p => p.textContent!);
|
const texto = paneles().map(p => p.textContent!);
|
||||||
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(2);
|
expect(texto.filter(t => t.includes('Datos suprimidos, sombreados en la figura: 2025 S1.'))).toHaveLength(1);
|
||||||
expect(graficas()).toHaveLength(3);
|
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', () => {
|
it('la nota de datos suprimidos es una nota al pie colapsable y llega cerrada; al abrirla muestra el texto completo', () => {
|
||||||
montar(false);
|
montar(false);
|
||||||
const notas = [...(fixture.nativeElement as HTMLElement).querySelectorAll('details.nota-pie')] as HTMLDetailsElement[];
|
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) {
|
for (const nota of notas) {
|
||||||
expect(nota.open).toBe(false);
|
expect(nota.open).toBe(false);
|
||||||
expect(nota.querySelector('summary')!.textContent!.trim()).toBe('Datos suprimidos');
|
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;
|
notas[0].open = true;
|
||||||
expect(notas[0].open).toBe(true);
|
expect(notas[0].open).toBe(true);
|
||||||
expect(notas[1].open).toBe(false);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -201,16 +203,20 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
|||||||
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
const tarjetas = () => [...root().querySelectorAll('.catalog-grid > *')] as HTMLElement[];
|
||||||
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
const completo = () => [...KPI_BY_DOMAIN.cama.map(propios), ...REALES];
|
||||||
|
|
||||||
it('las cuatro tarjetas de oportunidad tienen datos, ninguna pendiente, con los valores publicados', () => {
|
it('muestra los valores de las cuatro medidas publicadas y deja diagnóstico a tratamiento sin dato', () => {
|
||||||
cargar(completo());
|
// Fails if the unavailable slot displays a value or displaces the published measures.
|
||||||
expect(kpis()).toHaveLength(4);
|
const pedidos = cargar(completo());
|
||||||
|
expect(kpis()).toHaveLength(5);
|
||||||
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
expect(root().querySelector('.kpi-grid')!.textContent).not.toContain('Integración pendiente');
|
||||||
|
expect(pedidos.filter(id => id === 'cama_tasa_deteccion_histopatologica')).toHaveLength(1);
|
||||||
|
expect(kpis()[1].querySelector('h3')?.textContent).toBe('Tasa de confirmación histopatológica');
|
||||||
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
|
expect(kpis()[1].textContent).toContain('0 de 1 biopsias con resultado maligno.');
|
||||||
expect(kpis()[3].textContent).toContain('6.5'); expect(kpis()[3].textContent).toContain('Q1 a Q3: 2.25 a 12.5 días.');
|
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', () => {
|
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());
|
const pedidos = cargar(completo());
|
||||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
|
||||||
const primera = tarjetas()[0];
|
const primera = tarjetas()[0];
|
||||||
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
expect(primera.tagName).toBe('APP-INDICADOR-CATALOG-CARD');
|
||||||
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||||
@@ -224,13 +230,10 @@ describe('CaMa Resumen con CAM-01, CAM-02 y CAM-03 publicados', () => {
|
|||||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
|
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_tasa_deteccion_histopatologica');
|
||||||
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
|
expect(CAMA_FUERA_DEL_RESUMEN).toContain('cama_dias_resultado_diagnostico');
|
||||||
});
|
});
|
||||||
it('sin CAM-03 en el catálogo la tarjeta sigue pendiente, como antes', () => {
|
it('sin CAM-03 en el catálogo conserva el KPI y la tarjeta con fuente local', () => {
|
||||||
cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
const pedidos = cargar([...KPI_BY_DOMAIN.cama.map(propios), ...REALES.filter(i => i.id !== 'cama_histopatologia_birads')]);
|
||||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).not.toBeNull();
|
expect(kpis()).toHaveLength(5);
|
||||||
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
expect(root().querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||||
});
|
expect(pedidos).not.toContain('cama_histopatologia_birads');
|
||||||
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');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ describe('Tarjetas de oportunidad de CaMa: definiciones', () => {
|
|||||||
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
['cama_dias_resultado_diagnostico', 'C3r', 'días (mediana)'],
|
||||||
]);
|
]);
|
||||||
expect(CAMA_OPORTUNIDAD_KPIS.map(d => d.title)).toEqual([
|
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 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica', 'Tiempo de interpretación radiológica a diagnóstico']);
|
||||||
expect(KPI_BY_DOMAIN.cama[0]).toBe(CAMA_OPORTUNIDAD_KPIS[0]);
|
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', () => {
|
it('solo las tarjetas con indicador en el catálogo entran en KPI_BY_DOMAIN, que es lo que se consulta sin pedirlo', () => {
|
||||||
@@ -208,26 +208,31 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|||||||
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
const cards = () => [...fixture.nativeElement.querySelectorAll('.kpi-grid app-indicador-kpi-card')] as HTMLElement[];
|
||||||
const text = (card: HTMLElement, selector: string) => card.querySelector(selector)?.textContent?.trim();
|
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', () => {
|
it('con el catálogo actual: dos tarjetas con datos, dos pendientes y diagnóstico a tratamiento sin dato ni consulta', () => {
|
||||||
// Fails if a pending indicator is requested, or if a pending card is drawn with a number.
|
// 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()]) });
|
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([...new Set(urls)].sort()).toEqual(KPI_BY_DOMAIN.cama.map(d => `/cama/indicadores/${d.id}/datos`).sort());
|
||||||
expect(urls.some(url => url.includes('cama_confirmacion_birads45') || url.includes('cama_dias_toma_diagnostico'))).toBe(false);
|
|
||||||
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
expect(fixture.nativeElement.querySelector('#kpi-section-title').textContent).toBe('Indicadores de oportunidad');
|
||||||
expect(cards().map(card => text(card, 'h3'))).toEqual([
|
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']);
|
'Pacientes evaluadas con BI-RADS 4, 5 y 6', 'Tasa de confirmación histopatológica', 'Tiempo de toma de mastografía interpretación radiológica',
|
||||||
expect(cards().map(card => text(card, '.value'))).toEqual(['5pacientes', undefined, '7días (mediana)', undefined]);
|
'Tiempo de interpretación radiológica a diagnóstico', 'Tiempo de diagnóstico a tratamiento']);
|
||||||
expect(cards().map(card => text(card, '.kpi-state'))).toEqual(['Disponible', 'Integración pendiente', 'Disponible', 'Integración pendiente']);
|
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).toContain('aún no está publicado');
|
||||||
expect(cards()[1].textContent).not.toMatch(/\d/);
|
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', () => {
|
it('dibuja los cuatro indicadores publicados y mantiene diagnóstico a tratamiento sin valor', () => {
|
||||||
// Fails if a published opportunity indicator is not queried and drawn.
|
// 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]);
|
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_tasa_deteccion_histopatologica'))).toBe(true);
|
||||||
expect(urls.some(url => url.includes('cama_dias_resultado_diagnostico'))).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().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 resultado maligno.');
|
||||||
});
|
});
|
||||||
@@ -249,7 +254,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|||||||
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
expect(text(cards()[2], '.kpi-state')).toBe('Error de consulta'); expect(text(cards()[2], '.value')).toBeUndefined();
|
||||||
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
expect(text(cards()[0], '.value')).toBe('5pacientes');
|
||||||
expect(fixture.nativeElement.textContent).not.toContain('private');
|
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 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', () => {
|
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.
|
// Fails if cama_biopsias comes back to the summary, or if the filter also hides other indicators.
|
||||||
@@ -266,7 +271,7 @@ describe('Tarjetas de oportunidad de CaMa en la página', () => {
|
|||||||
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
|
expect(fixture.nativeElement.querySelector('header .domain')).toBeNull();
|
||||||
expect(text).not.toContain('Cáncer de mama, investigación');
|
expect(text).not.toContain('Cáncer de mama, investigación');
|
||||||
expect(text).toContain('Explora los indicadores de cáncer de mama.');
|
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(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('Se aplica a los indicadores de oportunidad y las gráficas, salvo las de selección independiente.');
|
||||||
expect(text).not.toContain('Filtro general aplicado');
|
expect(text).not.toContain('Filtro general aplicado');
|
||||||
@@ -312,7 +317,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', () => {
|
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.
|
// Fails if the multi-period controls or the editing summaries come back to CaMa.
|
||||||
mount(true);
|
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();
|
expect(fixture.nativeElement.querySelector('.fields.compact .apply-button')).not.toBeNull();
|
||||||
const text = fixture.nativeElement.textContent as string;
|
const text = fixture.nativeElement.textContent as string;
|
||||||
expect(text).not.toContain('Modalidad');
|
expect(text).not.toContain('Modalidad');
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const item = (id: string, titulo: string, contrato: string, figuras: string[]) =
|
|||||||
// The catalog 18080 publishes for CaMa.
|
// The catalog 18080 publishes for CaMa.
|
||||||
const CAMA = [
|
const CAMA = [
|
||||||
item('cama_biopsias', 'Distribución de resultados de biopsia', 'C2', ['fig_c2_donas', 'fig_c2_barras']),
|
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_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_confirmacion_birads45', 'Tasa de confirmación histopatológica', 'C1', ['fig_c1_puntos']),
|
||||||
item('cama_dias_toma_diagnostico', 'Tiempo de tamizaje a diagnóstico', 'C3r', ['fig_c3r_caja']),
|
item('cama_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 section = () => root().querySelector('.graphic-section') as HTMLElement;
|
||||||
const titles = () => [...root().querySelectorAll('.catalog-grid app-indicador-catalog-card h2')].map(e => e.textContent?.trim());
|
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', () => {
|
it('CaMa: «Indicadores clínicos» muestra las tarjetas de la sección, sin el conteo de publicados', () => {
|
||||||
// Fails if the heading or the counter go back to the whole catalog (6) while a card is not drawn.
|
// Fails if the heading goes back to the whole catalog while a card is not drawn.
|
||||||
open('cama', CAMA);
|
open('cama', CAMA);
|
||||||
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
expect(root().querySelector('#graphic-section-title')?.textContent).toBe('Indicadores clínicos');
|
||||||
expect(titles()).not.toContain('Distribución de resultados de biopsia');
|
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.
|
// The patients' counts go on the exams' card, so the partner indicator has no card of its own.
|
||||||
expect(titles()).not.toContain('Porcentaje de pacientes con resultados de BI-RADS 4, 5 y 6');
|
expect(titles()).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.
|
// The paired card has no card title; each donut names itself.
|
||||||
expect(titles()).toEqual(['Porcentaje individual de mastografías']);
|
expect(titles()).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
|
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', () => {
|
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.
|
// Fails if confirmation, screening-to-diagnosis or exam-to-result come back to the summary, or leave Datos y definiciones.
|
||||||
@@ -65,26 +67,27 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
expect(root().querySelector('#panel-datos')!.textContent).toContain(titulo);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
it('CaMa: la tarjeta histopatológica ocupa su lugar como pendiente, sin cifras ni figuras', () => {
|
it('CaMa: Datos y definiciones muestra el nombre general de mastografías aunque el catálogo entregue el anterior', () => {
|
||||||
open('cama', CAMA);
|
open('cama', CAMA);
|
||||||
const tarjeta = root().querySelector('app-indicador-histopatologia-pendiente') as HTMLElement;
|
const nombres = [...root().querySelectorAll('#panel-datos summary')].map(summary => summary.textContent?.trim());
|
||||||
expect(tarjeta).not.toBeNull();
|
expect(nombres).toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 o 6');
|
||||||
expect(tarjeta.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
expect(nombres).not.toContain(CAMA[1].titulo);
|
||||||
expect(tarjeta.querySelector('[role=status]')?.textContent).toContain('Integración pendiente');
|
|
||||||
expect([...tarjeta.querySelectorAll('h3')].map(e => e.textContent)).toEqual(['Por categoría BI-RADS', 'Resultado de la biopsia']);
|
|
||||||
expect(tarjeta.querySelector('app-plotly-chart, canvas, svg')).toBeNull();
|
|
||||||
expect(/[0-9]/.test(tarjeta.textContent!)).toBe(false);
|
|
||||||
// It comes first, as in the reference, and is not counted as a published indicator.
|
|
||||||
expect(root().querySelector('.catalog-grid')!.firstElementChild).toBe(tarjeta);
|
|
||||||
});
|
});
|
||||||
it('CaMa: si el catálogo publica el indicador histopatológico, la tarjeta pendiente deja de dibujarse', () => {
|
it('CaMa: la tarjeta de histopatología tiene su lugar aunque la medida no figure en el catálogo', () => {
|
||||||
|
open('cama', CAMA);
|
||||||
|
const primera = root().querySelector('.catalog-grid')!.firstElementChild!;
|
||||||
|
expect(primera.querySelector('app-indicador-histopatologia-cama')).not.toBeNull();
|
||||||
|
expect(primera.querySelector('h2')?.textContent).toBe('Resultado histopatológico por categoría BI-RADS');
|
||||||
|
expect(fixture.componentInstance.catalog().map(item => item.id)).not.toContain('cama_histopatologia_birads');
|
||||||
|
});
|
||||||
|
it('CaMa: si el catálogo publica la medida, Resumen dibuja una sola tarjeta de histopatología', () => {
|
||||||
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
open('cama', [...CAMA, item('cama_histopatologia_birads', 'Resultado histopatológico por categoría BI-RADS', 'C2', ['fig_c2_donas'])]);
|
||||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
expect(root().querySelectorAll('app-indicador-histopatologia-cama')).toHaveLength(1);
|
||||||
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
|
expect(titles()).toContain('Resultado histopatológico por categoría BI-RADS');
|
||||||
});
|
});
|
||||||
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica pendiente', domain => {
|
it.each(['tea', 'cacu'] as const)('%s no dibuja la tarjeta histopatológica de CaMa', domain => {
|
||||||
open(domain, OTRO(domain));
|
open(domain, OTRO(domain));
|
||||||
expect(root().querySelector('app-indicador-histopatologia-pendiente')).toBeNull();
|
expect(root().querySelector('app-indicador-histopatologia-cama')).toBeNull();
|
||||||
});
|
});
|
||||||
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
|
it('CaMa: sin buscador, indicadores fijados, navegación flotante, selector de representación ni conteo de figuras', () => {
|
||||||
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
|
// Fails if any of the controls the mockup does not have comes back to CaMa's summary.
|
||||||
@@ -111,7 +114,7 @@ describe('Resumen clínico de CaMa y los demás dominios', () => {
|
|||||||
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
expect(root().querySelector('.catalog-search')).not.toBeNull();
|
||||||
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
expect(root().querySelectorAll('.pin-toggle').length).toBe(6);
|
||||||
expect(section().textContent).toContain('2 figuras publicadas');
|
expect(section().textContent).toContain('2 figuras publicadas');
|
||||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('6 indicadores publicados');
|
expect(root().textContent).not.toContain('indicadores publicados');
|
||||||
});
|
});
|
||||||
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
it('CaCu conserva su encabezado «Indicadores clínicos» y TEA «Indicadores gráficos»', () => {
|
||||||
open('cacu', OTRO('cacu'));
|
open('cacu', OTRO('cacu'));
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
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';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
|
||||||
// Histopathological confirmation of high-grade cytology (cacu_confirmacion_citologia):
|
// 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 colores = paintByGroup(conColor.map(g => g.grupo));
|
||||||
const colorDe = new Map(conColor.map((g, i) => [g.id, colores[i]]));
|
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 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 => {
|
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.
|
// Off-catalogue grades keep the neutral fallback and do not take the group hue.
|
||||||
const propios = grados.filter(g => g.grupo === id);
|
const propios = grados.filter(g => g.grupo === id);
|
||||||
const indice = ordenGrupos.indexOf(id);
|
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: bases.get(id) ?? COLOR_RESPALDO,
|
||||||
return { id, etiqueta: etiquetaGrupo(nombres[id])!, color: indice < 0 ? COLOR_RESPALDO : groupBase(indice),
|
|
||||||
grados: propios.map(g => g.id) };
|
grados: propios.map(g => g.id) };
|
||||||
});
|
});
|
||||||
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
// The base view is the group of LIEAG ("LIEAG o más"): the true positives.
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { IndicadorConteosPareados } from './indicador-conteos-pareados';
|
|||||||
import { IndicadoresMemory } from './indicadores-memory';
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { IndicadorDatos } from './indicadores.models';
|
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 PAR = parConteos('cama', 'cama_birads_456_mastografia')!;
|
||||||
const CATEGORIAS = {
|
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.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']);
|
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', () => {
|
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> };
|
const barras = barrasConteos(m, PAR, 'claro') as unknown as { layout: Record<string, unknown> };
|
||||||
expect(barras.layout['annotations']).toBeUndefined();
|
expect(barras.layout['annotations']).toBeUndefined();
|
||||||
expect(JSON.stringify(barras)).not.toMatch(/≈|por paciente|razón/i);
|
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']);
|
expect(Object.keys(m.filas[0])).toEqual(['id', 'etiqueta', 'pacientes', 'examenes']);
|
||||||
});
|
});
|
||||||
it.each([
|
it.each([
|
||||||
@@ -145,7 +156,7 @@ describe('Tarjeta pareada de CaMa en la página', () => {
|
|||||||
let fixture: ReturnType<typeof TestBed.createComponent<IndicadoresPage>>, http: HttpTestingController;
|
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 item = (id: string, titulo: string, contrato: string, figuras: string[]) => ({ id, titulo, contrato, figuras, tipos_periodo: ['semestre', 'mes'] });
|
||||||
const CATALOGO = [
|
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_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_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.
|
// 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());
|
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.
|
// Confirmation is in Histórico and in Datos y definiciones, not in CaMa's summary.
|
||||||
expect(titulos).toEqual(['Porcentaje individual de mastografías']);
|
// The pair has no card title; each donut has its own heading.
|
||||||
expect(root().querySelector('.catalog-count')?.textContent?.trim()).toBe('1 indicador publicado');
|
expect(titulos).toEqual(['Resultado histopatológico por categoría BI-RADS']);
|
||||||
|
expect(root().textContent).not.toContain('Porcentaje de mastografías con resultado en la clasificación de BI-RADS 4, 5 y 6');
|
||||||
|
expect(root().textContent).not.toContain('indicador publicado');
|
||||||
});
|
});
|
||||||
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
|
it('al hacerse visible pide los dos conteos del mismo periodo y dibuja dona, barras y tabla con sus valores', () => {
|
||||||
abrir();
|
abrir();
|
||||||
const texto = (s: string) => root().querySelector(s)?.textContent?.replace(/\s+/g, ' ').trim();
|
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());
|
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 y 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);
|
const graficas = fixture.debugElement.queryAll(By.directive(ChartStub)).map(d => d.componentInstance as ChartStub);
|
||||||
expect(graficas).toHaveLength(2);
|
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()));
|
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(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');
|
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', () => {
|
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' }));
|
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()));
|
const filas = [...root().querySelectorAll('.published-values tbody tr')].map(tr => [...tr.children].map(c => c.textContent?.trim()));
|
||||||
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
|
expect(filas).toEqual([['BI-RADS 4', 'Pendiente', '15'], ['BI-RADS 5', 'Pendiente', '18'], ['BI-RADS 6', 'Pendiente', '0']]);
|
||||||
expect(root().textContent).toContain('Pacientes pendientes');
|
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', () => {
|
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.
|
// 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 { 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';
|
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.
|
// 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 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 FilaConteo { id: string; etiqueta: string; pacientes: number | null; examenes: number | null; }
|
||||||
export interface ModeloConteos {
|
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.
|
// False when the patients' version is not one whose definition was checked: their cells stay unknown.
|
||||||
pacientesVerificados: boolean; notas: string[];
|
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 : '';
|
const publicada = registro(cat[id]) && typeof cat[id]['etiqueta'] === 'string' ? cat[id]['etiqueta'] as string : '';
|
||||||
return publicada && publicada !== id ? publicada : ETIQUETA_RESPALDO[id] ?? id;
|
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);
|
const todas = par.grupos.flatMap(g => g.categorias);
|
||||||
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|
if (par.categoriasExamen.some(id => !OPCIONALES.has(id) && !Object.hasOwn(catExamenes, id))
|
||||||
|| todas.some(id => !OPCIONALES.has(id) && (!Object.hasOwn(catPacientes, id) || !Object.hasOwn(catExamenes, id)))) {
|
|| 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);
|
OPCIONALES.has(id) && !Object.hasOwn(cat, id) ? 0 : cuenta(filas, periodo, id);
|
||||||
return periodos.map(periodo => ({
|
return periodos.map(periodo => ({
|
||||||
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.
|
// 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,
|
sinDato: Object.hasOwn(catExamenes, 'SIN_DATO') ? cuenta(filasE, periodo, 'SIN_DATO') : 0,
|
||||||
filas: par.grupos.map(g => ({
|
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 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 ALTO_DONA = 400, MARGEN_DONA = 8;
|
||||||
const DIAMETRO_MAXIMO_DONA = 270;
|
const DIAMETRO_MAXIMO_DONA = 270;
|
||||||
|
|
||||||
export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho = 390): PlotlyFigure {
|
function donaDe(categorias: CategoriaConteo[], unidad: string, tema: Tema, ancho: number): PlotlyFigure {
|
||||||
const total = totalExamenes(m);
|
const total = sumar(categorias.map(c => c.n));
|
||||||
if (!total) return { data: [], layout: {} };
|
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.
|
// 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 margenEtiquetas = Math.min(90, 59 + Math.max(0, ancho - 230) * .2);
|
||||||
const diametro = Math.max(1, Math.min(DIAMETRO_MAXIMO_DONA, ancho - 2 * (MARGEN_DONA + margenEtiquetas)));
|
const 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 fuenteEtiqueta = Math.round(8 + (margenEtiquetas - 59) / 10);
|
||||||
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
|
const fuenteUnidad = Math.min(11, Math.max(7, Math.round(radio / 7)));
|
||||||
const separacionCentro = fuenteUnidad === 7 ? 6 : fuenteUnidad < 11 ? 7 : 8;
|
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 porcentajes = n.map(v => percentNumber(100 * v / total));
|
||||||
const centro = { x: .5, y: .5, xref: 'paper', yref: 'paper', showarrow: false };
|
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,
|
// 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,
|
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] },
|
domain: { x: [0, 1], y: [.5 - fraccionVertical, .5 + fraccionVertical] },
|
||||||
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
|
customdata: n.map((v, i) => [miles(v), porcentajes[i]]),
|
||||||
hovertemplate: '%{value}<extra></extra>' }],
|
hovertemplate: '%{value}<extra></extra>' }],
|
||||||
@@ -160,15 +166,24 @@ export function donaConteos(m: ModeloConteos, par: ParConteos, tema: Tema, ancho
|
|||||||
shapes: llamadas.map(({ shape }) => shape),
|
shapes: llamadas.map(({ shape }) => shape),
|
||||||
annotations: [
|
annotations: [
|
||||||
{ ...centro, yshift: separacionCentro, font: { size: fuenteUnidad + 3, color: p.text }, text: `<b>${miles(total)}</b>` },
|
{ ...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),
|
...llamadas.map(({ annotation }) => annotation),
|
||||||
] }, config: { displayModeBar: false } };
|
] }, 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. */
|
/** 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 {
|
export function barrasConteos(m: ModeloConteos, par: ParConteos, tema: Tema): PlotlyFigure {
|
||||||
const p = c2Theme(tema), y = m.filas.map(f => escapar(f.etiqueta));
|
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') =>
|
const textoDe = (v: number | null, clave: 'pacientes' | 'examenes') =>
|
||||||
v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato';
|
v !== null ? miles(v) : clave === 'pacientes' && !m.pacientesVerificados ? 'Pendiente' : 'Sin dato';
|
||||||
const traza = (clave: 'pacientes' | 'examenes', color: string) => ({
|
const traza = (clave: 'pacientes' | 'examenes', color: string) => ({
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
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';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
|
|
||||||
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
// Adapted from entregable_eu7_dona_escenario/eu7-dona-escenario.ts.
|
||||||
@@ -125,9 +125,11 @@ export function modelo(general: IndicadorDatos, porEscenario: IndicadorDatos, pe
|
|||||||
// Missing rows remain unavailable. Catalog order is used only for the accessible
|
// 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.
|
// 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 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 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 celdas = Object.fromEntries(cats.map(c => [c.id, celda(g.get(JSON.stringify([null, c.id])))]));
|
||||||
const totals = porEscenario['totales_estrato'];
|
const totals = porEscenario['totales_estrato'];
|
||||||
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
if (totals !== undefined && (!Array.isArray(totals) || !totals.every(registro))) return fail('Totales de escenario inválidos.');
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
// Presentation labels for representations confirmed in the published catalog.
|
// Presentation labels for representations confirmed in the published catalog.
|
||||||
// Exact IDs remain the option values and HTTP identities; never infer a type
|
// 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.
|
// 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>> = {
|
const FIGURE_LABELS: Readonly<Record<string, string>> = {
|
||||||
fig_c1_barras_alteracion: 'Barras por alteración',
|
fig_c1_barras_alteracion: 'Barras por alteración',
|
||||||
fig_c1_barras_apiladas_edad: 'Barras apiladas por grupo de edad',
|
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);
|
load(undefined, domain);
|
||||||
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
expect(fixture.debugElement.queryAll(By.directive(IndicadorPeriodFilters))).toHaveLength(1);
|
||||||
const sections = fixture.nativeElement.querySelectorAll('#panel-resumen > section') as NodeListOf<HTMLElement>;
|
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]);
|
expect(sections[0].querySelector('#global-filters-title')!.textContent!.trim()).toBe('Filtros');
|
||||||
if (domain === 'cama') expect(sections[0].textContent).not.toContain('Filtros generales de ');
|
|
||||||
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
|
expect(fixture.nativeElement.querySelectorAll('.kpi-section app-indicador-kpi-card')).toHaveLength(0);
|
||||||
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
|
expect(sections[1].getAttribute('aria-labelledby')).toBe('graphic-section-title');
|
||||||
expect(page.filters!.applied.selection.mode).toBe('todos');
|
expect(page.filters!.applied.selection.mode).toBe('todos');
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows,
|
// Covers CaMa's histopathology by BI-RADS (CAM-03): the adapter that turns the published C2 matrix into rows,
|
||||||
// rates and figures, and the view that draws it. The fixtures are what WebApi publishes for the synthetic
|
// rates and figures, and the catalog wiring of the local view. The fixtures are what WebApi publishes for the synthetic
|
||||||
// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per
|
// demonstration data (fixtures/cama_histopatologia_birads_*.json: six strata, six categories, one patient per
|
||||||
// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator).
|
// period; BIRADS_4 is a row of its own and BENIGNO/RIESGO_B3/IN_SITU/INVASOR make the denominator).
|
||||||
import { Component, input, output } from '@angular/core';
|
import { Component, input, output } from '@angular/core';
|
||||||
@@ -11,6 +11,7 @@ import estratoFixture from './fixtures/cama_histopatologia_birads_estrato.json';
|
|||||||
import generalFixture from './fixtures/cama_histopatologia_birads_general.json';
|
import generalFixture from './fixtures/cama_histopatologia_birads_general.json';
|
||||||
import catalogoFixture from './fixtures/cama_catalogo_f4c.json';
|
import catalogoFixture from './fixtures/cama_catalogo_f4c.json';
|
||||||
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
import { IndicadorHistopatologiaCama } from './indicador-histopatologia-cama';
|
||||||
|
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
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';
|
periodosHistopatologia, rangoTasas, seleccionBase, tasas } from './indicadores-histopatologia-cama';
|
||||||
|
|
||||||
@Component({ selector: 'app-plotly-chart', template: '' })
|
@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 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)!;
|
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.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.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.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([
|
expect(m.grupos.map(g => [g.id, g.etiqueta, g.categorias])).toEqual([
|
||||||
['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]);
|
['NO_MALIGNO', 'No maligno', ['BENIGNO', 'RIESGO_B3']], ['MALIGNO', 'Maligno', ['IN_SITU', 'INVASOR']]]);
|
||||||
expect(m.base).toBe('MALIGNO');
|
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((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();
|
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');
|
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[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[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');
|
const otra = donaHistopatologia(m, { grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' }, 'claro');
|
||||||
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
expect(otra.data[2]['values']).toEqual(d.data[2]['values']);
|
||||||
const colores = (otra.data[2]['marker'] as { colors: string[] }).colors;
|
expect((otra.data[2]['marker'] as { colors: string[] }).colors).toEqual(m.categorias.map(c => c.color));
|
||||||
expect(colores[1]).toMatch(/,1\)$/); expect(colores[0]).toMatch(/,0.3\)$/);
|
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']);
|
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', () => {
|
it('el histórico usa el C2 general con las seis categorías, sin necesidad del estrato', () => {
|
||||||
@@ -225,114 +235,32 @@ describe('Histopatología por BI-RADS: componente', () => {
|
|||||||
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
f.componentRef.setInput('tema', 'claro'); f.componentRef.setInput('applied', applied);
|
||||||
});
|
});
|
||||||
afterEach(() => { f.destroy(); http.verify(); });
|
afterEach(() => { f.destroy(); http.verify(); });
|
||||||
const solicitud = () => http.expectOne(req => req.url === '/cama/indicadores/cama_histopatologia_birads/datos');
|
it('carga las dos figuras al hacerse visible y redibuja en tema oscuro sin consultar WebApi', () => {
|
||||||
function flush(body: unknown = estratoFixture) {
|
f.componentRef.setInput('visible', false);
|
||||||
const r = solicitud();
|
f.detectChanges();
|
||||||
expect(r.request.params.get('estrato')).toBe('birads'); expect(r.request.params.get('periodos')).toBe(PERIODO);
|
expect(f.componentInstance.status()).toBe('deferred');
|
||||||
r.flush(body as Record<string, unknown>); f.detectChanges();
|
f.componentRef.setInput('visible', true);
|
||||||
}
|
f.detectChanges();
|
||||||
const boton = (texto: string) => [...f.nativeElement.querySelectorAll('.keys button')].find((b: Element) => b.textContent!.trim() === texto) as HTMLButtonElement;
|
expect(f.componentInstance.status()).toBe('ready');
|
||||||
|
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(2);
|
||||||
it('carga diferida, tasas a la izquierda y dona a la derecha, leyenda accesible y tabla de valores', () => {
|
expect(f.componentInstance.selectionLabel).toBe('Riesgo a carcinoma');
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
f.componentRef.setInput('tema', 'oscuro');
|
||||||
expect(f.componentInstance.status()).toBe('deferred'); http.expectNone(() => true);
|
f.detectChanges();
|
||||||
f.componentRef.setInput('visible', true); f.detectChanges(); expect(f.componentInstance.status()).toBe('loading');
|
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839');
|
||||||
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']);
|
|
||||||
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 table = f.nativeElement.querySelector('table') as HTMLTableElement;
|
|
||||||
expect([...table.querySelectorAll('thead th')].map(th => th.textContent)).toEqual(
|
|
||||||
['Categoría BI-RADS', 'Benigno', 'Lesión de riesgo (B3)', 'Carcinoma in situ', 'Carcinoma invasor', 'Con resultado', 'Sin biopsia reportada', 'Sin dato', 'Total de pacientes']);
|
|
||||||
expect([...table.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(td => td.textContent))).toEqual([
|
|
||||||
['BI-RADS 4 sin subtipo', '2', '0', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4A', '1', '1', '1', '2', '5', '1', '1', '7'],
|
|
||||||
['BI-RADS 4B', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 4C', '1', '1', '1', '1', '4', '1', '1', '6'],
|
|
||||||
['BI-RADS 5', '1', '1', '1', '1', '4', '1', '1', '6'], ['BI-RADS 6', '1', '1', '1', '1', '4', '1', '1', '6']]);
|
|
||||||
expect(f.nativeElement.querySelector('.note').textContent).toContain('Convención provisional;');
|
|
||||||
});
|
|
||||||
it('seleccionar una categoría, volver al grupo y volver al estado general; el centro de la dona también vuelve', () => {
|
|
||||||
f.detectChanges(); flush();
|
|
||||||
const charts = f.debugElement.queryAll(By.directive(ChartStub)).map(c => c.componentInstance as ChartStub);
|
|
||||||
const volver = () => [...f.nativeElement.querySelectorAll('.legend > button')].find((b: Element) => b.textContent!.trim() === 'Volver') as HTMLButtonElement;
|
|
||||||
expect(volver().disabled).toBe(true);
|
|
||||||
const b3 = boton('Lesión de riesgo (B3)'); b3.click(); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
|
||||||
expect(b3.getAttribute('aria-pressed')).toBe('true'); expect(volver().disabled).toBe(false);
|
|
||||||
expect(f.nativeElement.querySelector('.selection-status').textContent).toContain('Proporción con resultado lesión de riesgo (B3)');
|
|
||||||
b3.click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO' });
|
|
||||||
boton('Carcinoma invasor').click(); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO', categoria: 'INVASOR' });
|
|
||||||
volver().click(); f.detectChanges(); expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
|
||||||
charts[1].plotClick.emit({ points: [{ data: { name: 'categorias' }, pointNumber: 1 }] }); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'NO_MALIGNO', categoria: 'RIESGO_B3' });
|
|
||||||
charts[1].plotClick.emit({ points: [{ data: { name: 'centro' }, pointNumber: 0 }] }); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
|
||||||
charts[1].plotClick.emit({ points: [] }); charts[1].plotClick.emit(null); f.detectChanges();
|
|
||||||
expect(f.componentInstance.selection).toEqual({ grupo: 'MALIGNO' });
|
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
});
|
});
|
||||||
it('una celda suprimida: la fila lo dice, la dona no suma un total parcial y el resto de las tasas se conserva', () => {
|
|
||||||
const d = estrato(); Object.assign(fila(d, 'BIRADS_4C', 'BENIGNO'), { n: null, suprimido: 1 });
|
it('aplica el periodo mensual y deja la vista vacía para un mes sin conteos', () => {
|
||||||
f.detectChanges(); flush(d);
|
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2025-02'] }, revision: 2 });
|
||||||
|
f.detectChanges();
|
||||||
|
expect(f.componentInstance.contextPeriod).toBe('2025-02');
|
||||||
expect(f.componentInstance.status()).toBe('ready');
|
expect(f.componentInstance.status()).toBe('ready');
|
||||||
expect(f.nativeElement.querySelector('.donut').textContent).toContain('Dona no disponible: hay celdas suprimidas o datos incompletos');
|
f.componentRef.setInput('applied', { tipo: 'mes', selection: { mode: 'explicit', periodos: ['2024-02'] }, revision: 3 });
|
||||||
expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 4C: Suprimido');
|
f.detectChanges();
|
||||||
const tabla = [...f.nativeElement.querySelectorAll('tbody tr')].map((tr: Element) => [...tr.children].map(td => td.textContent));
|
|
||||||
expect(tabla[3][1]).toBe('Suprimido'); expect(tabla[3][5]).toBe('Suprimido'); expect(tabla[0][5]).toBe('4');
|
|
||||||
});
|
|
||||||
it('un estrato no publicado se lee «No disponible» en la tabla y en las tasas, y no como cero', () => {
|
|
||||||
const d = estrato(); d.filas = d.filas.filter(r => r['estrato'] !== 'BIRADS_6'); d.valores_estrato = d.valores_estrato.filter(v => v !== 'BIRADS_6');
|
|
||||||
d.totales_estrato = d.totales_estrato.filter(t => t['estrato'] !== 'BIRADS_6');
|
|
||||||
f.detectChanges(); flush(d);
|
|
||||||
const ultima = [...f.nativeElement.querySelectorAll('tbody tr')].pop() as HTMLElement;
|
|
||||||
expect([...ultima.children].map(td => td.textContent)).toEqual(['BI-RADS 6', ...Array(8).fill('No disponible')]);
|
|
||||||
expect(f.nativeElement.querySelector('.rate-states').textContent).toContain('BI-RADS 6: No disponible');
|
|
||||||
});
|
|
||||||
it('sin filas en el periodo lo dice y conserva la tabla vacía', () => {
|
|
||||||
const d = estrato(); d.filas = []; d.totales_estrato = [];
|
|
||||||
f.detectChanges(); flush(d);
|
|
||||||
expect(f.componentInstance.status()).toBe('empty');
|
expect(f.componentInstance.status()).toBe('empty');
|
||||||
expect(f.nativeElement.textContent).toContain('No hay pacientes con resultado de mastografía BI-RADS 4, 5 o 6 publicadas para este periodo.');
|
expect(f.nativeElement.textContent).toContain('No hay resultados de biopsia para el periodo seleccionado.');
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
||||||
});
|
http.expectNone(() => true);
|
||||||
it('error se anuncia con reintento que recupera; una respuesta fuera de contrato es incompatible y no dibuja', () => {
|
|
||||||
f.detectChanges();
|
|
||||||
solicitud().flush({}, { status: 500, statusText: 'Error' }); f.detectChanges();
|
|
||||||
expect(f.componentInstance.status()).toBe('error'); expect(f.nativeElement.querySelector('[role=alert]')).not.toBeNull();
|
|
||||||
f.componentInstance.retry(); flush({ ...estrato(), estrato: 'otro' });
|
|
||||||
expect(f.componentInstance.status()).toBe('incompatible');
|
|
||||||
expect(f.nativeElement.querySelector('[role=alert]').textContent).toContain('Respuesta incompatible');
|
|
||||||
expect(f.debugElement.queryAll(By.directive(ChartStub))).toHaveLength(0);
|
|
||||||
});
|
|
||||||
it('un filtro general incompatible, otro dominio u otro indicador no piden datos', () => {
|
|
||||||
f.componentRef.setInput('indicador', { ...indicador, tipos_periodo: ['mes'] }); f.detectChanges();
|
|
||||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
|
||||||
f.componentRef.setInput('indicador', indicador); f.componentRef.setInput('dominio', 'cacu'); f.detectChanges();
|
|
||||||
expect(f.componentInstance.status()).toBe('incompatible'); http.expectNone(() => true);
|
|
||||||
});
|
|
||||||
it('el tema oscuro redibuja con la paleta oscura sin pedir otra vez', () => {
|
|
||||||
f.detectChanges(); flush();
|
|
||||||
f.componentRef.setInput('tema', 'oscuro'); f.detectChanges();
|
|
||||||
expect(f.componentInstance.ratesFigure!.layout['paper_bgcolor']).toBe('#081839'); http.expectNone(() => true);
|
|
||||||
});
|
|
||||||
it('«Cómo leer» explica el denominador y añade lo que el servicio publique de las dos figuras, nada más', () => {
|
|
||||||
f.componentRef.setInput('visible', false); f.detectChanges();
|
|
||||||
const pedido = vi.fn(); f.componentInstance.metadataRequested.subscribe(pedido);
|
|
||||||
(f.nativeElement.querySelector('.methodology-toggle') as HTMLButtonElement).click(); f.detectChanges();
|
|
||||||
expect(pedido).toHaveBeenCalledTimes(1);
|
|
||||||
expect(f.nativeElement.querySelector('.methodology').textContent).toContain('no entran en el denominador');
|
|
||||||
f.componentRef.setInput('metadata', { descripcion: 'No va', figuras_detalle: [
|
|
||||||
{ figura: 'fig_c2_barras', descripcion: 'Tasas.', como_leer: ['Lee las tasas.'] }, { figura: 'fig_c2_apiladas', descripcion: 'Otra', como_leer: ['No.'] }] });
|
|
||||||
f.detectChanges();
|
|
||||||
const ayuda = f.nativeElement.querySelector('.methodology') as HTMLElement;
|
|
||||||
expect([...ayuda.querySelectorAll('li')].map(li => li.textContent)).toEqual(['Lee las tasas.']);
|
|
||||||
for (const ausente of ['No va', 'Otra', 'No.']) expect(ayuda.textContent).not.toContain(ausente);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => {
|
it('la tarjeta del catálogo conecta la vista solo para cama_histopatologia_birads de CaMa', () => {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { IndicadorDatos, PlotlyFigure, Tema } from './indicadores.models';
|
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 { Celda, wilson } from './indicadores-confirmacion-citologia';
|
||||||
import { percentNumber, shareText } from './indicadores-format';
|
import { percentNumber, shareText } from './indicadores-format';
|
||||||
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||||
@@ -15,7 +15,7 @@ export const ESTRATO_BIRADS = 'birads';
|
|||||||
// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never
|
// The six strata of the contract, in the order they are published. BIRADS_4 is a row of its own and is never
|
||||||
// split among 4A/4B/4C nor added to them.
|
// split among 4A/4B/4C nor added to them.
|
||||||
export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
|
export const ESTRATOS_BIRADS = ['BIRADS_4', 'BIRADS_4A', 'BIRADS_4B', 'BIRADS_4C', 'BIRADS_5', 'BIRADS_6'] as const;
|
||||||
const ETIQUETA_ESTRATO: Readonly<Record<string, string>> = {
|
export const ETIQUETA_ESTRATO: Readonly<Record<typeof ESTRATOS_BIRADS[number], string>> = {
|
||||||
BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6',
|
BIRADS_4: 'BI-RADS 4 sin subtipo', BIRADS_4A: 'BI-RADS 4A', BIRADS_4B: 'BI-RADS 4B', BIRADS_4C: 'BI-RADS 4C', BIRADS_5: 'BI-RADS 5', BIRADS_6: 'BI-RADS 6',
|
||||||
};
|
};
|
||||||
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
|
// The categories with a biopsy result: their sum is the denominator of every rate. NO_MALIGNO holds the first two
|
||||||
@@ -31,24 +31,31 @@ 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.
|
// The group the base view reads: the malignant results, the true positives of the suspicion.
|
||||||
const CATEGORIA_BASE = 'INVASOR';
|
const CATEGORIA_BASE = 'INVASOR';
|
||||||
const COLOR_RESPALDO = '#8A9199';
|
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 Categoria { id: string; etiqueta: string; color: string; grupo: string; }
|
||||||
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
|
export interface GrupoCategorias { id: string; etiqueta: string; color: string; categorias: string[]; }
|
||||||
export interface FilaBirads {
|
export interface FilaBirads {
|
||||||
id: string; etiqueta: string;
|
id: string; etiqueta: string;
|
||||||
// The four categories with a result.
|
// Categories with a biopsy result.
|
||||||
celdas: Record<string, Celda>;
|
celdas: Record<string, Celda>;
|
||||||
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
|
// SIN_BIOPSIA and SIN_DATO, when the catalog publishes them.
|
||||||
aparte: Record<string, Celda>;
|
aparte: Record<string, Celda>;
|
||||||
// Patients of the stratum, as the response publishes them.
|
// Patients of the stratum, as the response publishes them.
|
||||||
total: Celda;
|
total: Celda;
|
||||||
// Patients with a biopsy result: the denominator. Null while any of the four cells is unknown.
|
// Patients with a biopsy result: the denominator. Null while any result cell is unknown.
|
||||||
den: number | null; estado: Celda['estado'];
|
den: number | null; estado: Celda['estado'];
|
||||||
}
|
}
|
||||||
export interface ModeloHistopatologia {
|
export interface ModeloHistopatologia {
|
||||||
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
|
periodo: string; categorias: Categoria[]; grupos: GrupoCategorias[]; base: string;
|
||||||
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
|
filas: FilaBirads[]; totales: Record<string, number | null>; conResultado: number | null;
|
||||||
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
aparte: { id: string; etiqueta: string }[]; vacio: boolean; notas: string[];
|
||||||
|
// When set, the outer ring shows the subtype distribution within this group.
|
||||||
|
grupoAnilloExterior?: string;
|
||||||
}
|
}
|
||||||
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
|
export interface SeleccionHistopatologia { grupo: string; categoria?: string; }
|
||||||
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
export interface Tasa { fila: FilaBirads; k: number | null; valor: number | null; bajo: number | null; alto: number | null; }
|
||||||
@@ -61,7 +68,7 @@ const escapar = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').re
|
|||||||
const miles = (v: number) => v.toLocaleString('es-MX');
|
const miles = (v: number) => v.toLocaleString('es-MX');
|
||||||
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
const esTotal = (grupo: unknown) => typeof grupo === 'string' && grupo.toUpperCase() === 'TOTAL';
|
||||||
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
|
// A label inside a sentence: «Lesión de riesgo (B3)» reads «lesión de riesgo (B3)», keeping the code's capitals.
|
||||||
const enFrase = (v: string) => v.charAt(0).toLowerCase() + v.slice(1);
|
const enFrase = (v: string) => v === v.toUpperCase() ? v : v.charAt(0).toLowerCase() + v.slice(1);
|
||||||
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
const etiquetaGrupo = (v: unknown) => texto(v) ? v : registro(v) && texto(v['etiqueta']) ? v['etiqueta'] : undefined;
|
||||||
|
|
||||||
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
|
// 0 is a published count; a suppressed cell has no count; a cell the response does not carry is not available.
|
||||||
@@ -77,9 +84,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)
|
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('');
|
.toString(16).padStart(2, '0')).join('');
|
||||||
}
|
}
|
||||||
function rgba(hex: string, alfa: number): string {
|
const ZOOM_GRUPO = 1.12;
|
||||||
const v = parseInt(hex.slice(1), 16);
|
const ZOOM_HIJO = 1.08;
|
||||||
return `rgba(${v >> 16},${(v >> 8) & 255},${v & 255},${alfa})`;
|
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. */
|
/** Validated periods of one stratified response, in request order or sorted. */
|
||||||
@@ -105,15 +119,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))) {
|
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.');
|
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 categorias: Categoria[] = CON_RESULTADO.filter(id => Object.hasOwn(cats, id)).map(id => {
|
||||||
const c = cats[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'])))
|
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.');
|
|| 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 grupos: GrupoCategorias[] = [...new Set(categorias.map(c => c.grupo))].map(id => {
|
||||||
const propias = categorias.filter(c => c.grupo === 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.');
|
if (grupos.length !== 2) return fail('Se esperaban dos grupos de resultados.');
|
||||||
const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo;
|
const base = categorias.find(c => c.id === CATEGORIA_BASE)!.grupo;
|
||||||
@@ -164,6 +185,9 @@ export function modeloHistopatologia(datos: IndicadorDatos, periodo: string): Mo
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
|
export function seleccionBase(m: ModeloHistopatologia): SeleccionHistopatologia { return { grupo: m.base }; }
|
||||||
|
export function categoriasExteriores(m: ModeloHistopatologia): Categoria[] {
|
||||||
|
return m.grupoAnilloExterior ? m.categorias.filter(c => c.grupo === m.grupoAnilloExterior) : m.categorias;
|
||||||
|
}
|
||||||
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
|
export function seleccionadas(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string[] {
|
||||||
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
|
return sel.categoria ? [sel.categoria] : m.grupos.find(g => g.id === sel.grupo)?.categorias ?? [];
|
||||||
}
|
}
|
||||||
@@ -175,12 +199,15 @@ export function clicHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistop
|
|||||||
if (traza === 'centro') return seleccionBase(m);
|
if (traza === 'centro') return seleccionBase(m);
|
||||||
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
if (traza === 'grupos') { const g = m.grupos[indice]; return g ? { grupo: g.id } : sel; }
|
||||||
if (traza !== 'categorias') return sel;
|
if (traza !== 'categorias') return sel;
|
||||||
const c = m.categorias[indice];
|
const c = categoriasExteriores(m)[indice];
|
||||||
if (!c) return sel;
|
if (!c) return sel;
|
||||||
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
return sel.categoria === c.id ? { grupo: c.grupo } : { grupo: c.grupo, categoria: c.id };
|
||||||
}
|
}
|
||||||
/** The axis title says what the rate reads. */
|
/** The axis title says what the rate reads. */
|
||||||
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
export function lectura(m: ModeloHistopatologia, sel: SeleccionHistopatologia): string {
|
||||||
|
if (m.grupoAnilloExterior) {
|
||||||
|
return 'Proporción con ' + enFrase(seleccionEtiqueta(m, sel)) + ' entre pacientes con resultado de biopsia';
|
||||||
|
}
|
||||||
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
|
if (!sel.categoria && sel.grupo === m.base) return 'Pacientes con resultado maligno entre las que tienen resultado de biopsia';
|
||||||
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
|
if (!sel.categoria) return 'Pacientes con resultado no maligno entre las que tienen resultado de biopsia';
|
||||||
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
|
return 'Proporción con resultado ' + enFrase(seleccionEtiqueta(m, sel));
|
||||||
@@ -210,13 +237,19 @@ export function rangoTasas(valores: Tasa[]): [number, number] {
|
|||||||
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
|
// `estrecho`: a phone-width plot, where the labels wrap and the axis keeps only what fits.
|
||||||
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
|
export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema, estrecho = false): PlotlyFigure {
|
||||||
const p = c2Theme(tema);
|
const p = c2Theme(tema);
|
||||||
|
const barras = !!m.grupoAnilloExterior;
|
||||||
const valores = tasas(m, sel);
|
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 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 y = valores.map(t => t.fila.etiqueta);
|
||||||
|
const colores = sel.categoria || barras ? y.map(() => color) : y.map((_, i) => familia[i % familia.length]);
|
||||||
|
const rango = rangoTasas(valores);
|
||||||
return { data: [{
|
return { data: [{
|
||||||
type: 'scatter', mode: 'markers', uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
...(barras ? { type: 'bar', orientation: 'h', width: .5 } : { type: 'scatter', mode: 'markers' }),
|
||||||
marker: { size: 12, color }, cliponaxis: false,
|
uid: 'tasas', name: 'tasas', y, x: valores.map(t => t.valor),
|
||||||
error_x: { type: 'data', symmetric: false, color, thickness: 2, width: 6,
|
marker: barras ? { color: colores } : { size: 12, color: colores }, cliponaxis: false,
|
||||||
|
error_x: { type: 'data', symmetric: false, color: barras ? p.text : colores, thickness: 2, width: 6,
|
||||||
array: valores.map(t => t.valor === null ? 0 : t.alto! - t.valor), arrayminus: valores.map(t => t.valor === null ? 0 : t.valor - t.bajo!) },
|
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!)]),
|
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>',
|
hovertemplate: '%{y}<br><b>%{customdata[0]}</b> (%{customdata[1]}/%{customdata[2]})<br>IC 95 %: %{customdata[3]}–%{customdata[4]} %<extra></extra>',
|
||||||
@@ -226,34 +259,58 @@ export function figuraTasas(m: ModeloHistopatologia, sel: SeleccionHistopatologi
|
|||||||
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
|
margin: { l: 8, r: estrecho ? 72 : 84, t: 16, b: 64 },
|
||||||
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
|
yaxis: { type: 'category', categoryorder: 'array', categoryarray: [...y].reverse(), fixedrange: true, automargin: true,
|
||||||
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
|
...(estrecho ? { tickmode: 'array', tickvals: y, ticktext: y.map(v => v.replace(' sin subtipo', '<br>sin subtipo')) } : {}) },
|
||||||
xaxis: { range: rangoTasas(valores), ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
xaxis: { range: barras ? [0, rango[1]] : rango, ticksuffix: ' %', nticks: estrecho ? 3 : 5, tickangle: 0, gridcolor: p.grid, zeroline: false, fixedrange: true,
|
||||||
title: { text: estrecho ? 'Porcentaje' : 'Porcentaje con resultado ' + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
title: { text: estrecho ? 'Porcentaje' : (barras ? 'Porcentaje con ' : 'Porcentaje con resultado ') + enFrase(seleccionEtiqueta(m, sel)), standoff: 8 } },
|
||||||
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
annotations: valores.map(t => ({ x: 1, xref: 'paper', xanchor: 'left', xshift: 8, y: t.fila.etiqueta, yref: 'y', showarrow: false, align: 'left',
|
||||||
font: { size: estrecho ? 11 : 12, color: p.text },
|
font: { size: estrecho ? 11 : 12, color: p.text },
|
||||||
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
text: t.k === null ? estadoTasa(t) : `<b>${shareText(t.k, t.fila.den!)}</b><br>${t.k}/${t.fila.den}` })),
|
||||||
}, config: { displayModeBar: false } };
|
}, 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 {
|
export function donaHistopatologia(m: ModeloHistopatologia, sel: SeleccionHistopatologia, tema: Tema): PlotlyFigure {
|
||||||
if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} };
|
if (m.conResultado === null || m.conResultado === 0) return { data: [], layout: {} };
|
||||||
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
|
const p = c2Theme(tema), activos = new Set(seleccionadas(m, sel)), total = m.conResultado;
|
||||||
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
const k = [...activos].reduce((s, c) => s + m.totales[c]!, 0);
|
||||||
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
|
const interior = m.grupos.map(g => g.categorias.reduce((s, c) => s + m.totales[c]!, 0));
|
||||||
const exterior = m.categorias.map(c => m.totales[c.id]!);
|
const categorias = categoriasExteriores(m);
|
||||||
|
const exterior = categorias.map(c => m.totales[c.id]!);
|
||||||
|
const centro = m.grupoAnilloExterior
|
||||||
|
? `<b>${miles(k)}</b><br>de ${miles(total)}<br>con resultado`
|
||||||
|
: `<b>${miles(k)}</b><br>de ${miles(total)} con resultado`;
|
||||||
const comun = { type: 'pie', sort: false, direction: 'clockwise', rotation: 0, showlegend: false, textinfo: 'none' };
|
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 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 custom = (values: number[]) => {
|
||||||
|
const subtotal = values.reduce((s, n) => s + n, 0);
|
||||||
|
return values.map(n => [miles(n), subtotal === 0 ? '—' : shareText(n, subtotal)]);
|
||||||
|
};
|
||||||
|
const hoverExterior = m.grupoAnilloExterior
|
||||||
|
? { hovertemplate: '%{label}<br>%{customdata[0]} pacientes (%{customdata[1]} del grupo Riesgo a carcinoma)<extra></extra>' }
|
||||||
|
: hover;
|
||||||
|
const zoomGrupo = (id: string, hijos: readonly string[]) =>
|
||||||
|
sel.categoria ? (hijos.includes(sel.categoria) ? ZOOM_PADRE : 1) : sel.grupo === id ? ZOOM_GRUPO : 1;
|
||||||
|
const zoomCategoria = (id: string) => sel.categoria === id ? ZOOM_ELEGIDO : !sel.categoria && activos.has(id) ? ZOOM_HIJO : 1;
|
||||||
|
const zoomDe = (values: number[]) => Math.max(1, ...values);
|
||||||
|
const tinta = (colores: string[], zoom: number[]) => colores.map((color, i) => zoom[i] > 1 ? color : 'rgba(0,0,0,0)');
|
||||||
|
const gruposZoom = m.grupos.map(g => zoomGrupo(g.id, g.categorias));
|
||||||
|
const categoriasZoom = 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: [
|
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 },
|
text: [centro], textfont: { size: 16, color: p.text },
|
||||||
marker: { colors: [p.background] }, hovertemplate: 'Volver a ' + escapar(m.grupos.find(g => g.id === m.base)!.etiqueta) + '<extra></extra>' },
|
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),
|
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 } } },
|
marker: { colors: m.grupos.map(g => g.color), line: { color: p.background, width: 2 } } },
|
||||||
{ ...comun, ...hover, name: 'categorias', values: exterior, hole: .74, domain: { x: [0, 1], y: [0, 1] },
|
{ ...comun, ...hoverExterior, name: 'categorias', values: exterior, hole: .74, domain: caja(CAJA_CATEGORIA, 1),
|
||||||
labels: m.categorias.map(c => escapar(c.etiqueta)), customdata: custom(exterior),
|
labels: 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 } } },
|
marker: { colors: categorias.map(c => c.color), line: { color: p.background, width: m.grupoAnilloExterior ? 1 : 2 } } },
|
||||||
], layout: { autosize: true, height: 360, margin: { t: 10, l: 10, r: 10, b: 10 }, paper_bgcolor: p.background, font: { color: p.text } },
|
anillo('grupos', interior, m.grupos.map(g => escapar(g.etiqueta)), .62, CAJA_GRUPO, gruposZoom, m.grupos.map(g => g.color)),
|
||||||
|
{ ...anillo('categorias', exterior, categorias.map(c => escapar(c.etiqueta)), .74, CAJA_CATEGORIA, categoriasZoom, categorias.map(c => c.color)), ...hoverExterior },
|
||||||
|
], layout: { autosize: true, height: 360, margin: { t: 16, l: 16, r: 16, b: 16 }, paper_bgcolor: p.background, font: { color: p.text } },
|
||||||
config: { displayModeBar: false } };
|
config: { displayModeBar: false } };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,11 +79,15 @@ describe('Histórico de CaMa', () => {
|
|||||||
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
|
expect([...ids].sort()).toEqual(PUBLICADOS.map(i => i.id).sort());
|
||||||
expect(vistos.some(u => u.includes('cama_biopsias'))).toBe(false);
|
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();
|
montar(CATALOGO, true); responder();
|
||||||
expect(paneles().map(p => p.querySelector('h2')?.textContent)).toEqual(HISTORICO_CAMA.map(e => e.titulo));
|
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);
|
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(graficas()).toHaveLength(5);
|
||||||
expect(paneles().filter(p => p.textContent!.includes('Integración pendiente') && p.querySelector('app-plotly-chart')).length).toBe(0);
|
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('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(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('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 }));
|
plegable.querySelector('summary')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
expect(plegable.open).toBe(true);
|
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
|
// 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.
|
// never turned into a number. Fixtures are synthetic rows shaped like /cama/indicadores/<id>/datos.
|
||||||
import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures';
|
import { etiquetaPeriodo, cronologico, historicoFigura } from './indicadores-historico-figures';
|
||||||
|
import { C2_PALETTE } from './indicadores-c2-palette';
|
||||||
import { IndicadorDatos } from './indicadores.models';
|
import { IndicadorDatos } from './indicadores.models';
|
||||||
|
|
||||||
type Fig = { data: Record<string, unknown>[]; layout: Record<string, unknown> };
|
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', () => {
|
it('apila las categorías en el orden que publica el indicador, con sus colores y etiquetas', () => {
|
||||||
const f = fig(d(completo));
|
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.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.data[0]['y']).toEqual([4, 4, 4, 4]);
|
||||||
expect(f.layout['barmode']).toBe('stack');
|
expect(f.layout['barmode']).toBe('stack');
|
||||||
expect((f.layout['yaxis'] as { title: { text: string } }).title.text).toBe('Pacientes');
|
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.figure as unknown as Fig).layout['yaxis']).toMatchObject({ title: { text: 'Mastografías' } });
|
||||||
expect(r.comoLeer).toContain('mastografías');
|
expect(r.comoLeer).toContain('mastografías');
|
||||||
});
|
});
|
||||||
|
it('Pacientes evaluadas con BI-RADS 4, 5 y 6 conserva la gráfica y omite la explicación de la barra', () => {
|
||||||
|
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', () => {
|
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.
|
// Fails if the known cells of a partly suppressed period pass for its total.
|
||||||
const filas = completo.map(f => f['periodo'] === '2025-02' && f['categoria'] === 'B4' ? { ...f, n: null, suprimido: 1 } : f);
|
const 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 { 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 { sortedPeriods } from './indicadores-periodos';
|
||||||
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
import { M28_COMPLETO, M28_EN_PROCESO } from './indicadores-kpi';
|
||||||
|
|
||||||
@@ -14,6 +14,12 @@ const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v ===
|
|||||||
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
const escape = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||||
// The EEG indicators avoid green; their colours are shared with their age groups' palette.
|
// 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] };
|
const LINEAS: Readonly<Record<string, string>> = { M21_diagnosticados_con_eeg: C2_PALETTE.edades[0], M22_diagnosticados_sin_eeg: C2_PALETTE.edades[2] };
|
||||||
|
// CaMa's day-count lines sit next to the histopathology bars, so they borrow that figure's blue, purple and rose.
|
||||||
|
const DIAS: Readonly<Record<string, { claro: string; oscuro: string; relleno: string }>> = {
|
||||||
|
cama_dias_toma_diagnostico: { claro: '#2F6DB3', oscuro: '#9DBFE3', relleno: '#9DBFE380' },
|
||||||
|
cama_eu38a: { claro: '#9C42C2', oscuro: '#D2A4EA', relleno: '#9C42C240' },
|
||||||
|
cama_dias_resultado_diagnostico: { claro: '#C24269', oscuro: '#E7A3B8', relleno: '#C2426940' },
|
||||||
|
};
|
||||||
const numero = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
|
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.
|
// sortedPeriods lists the newest first, for selectors; time here runs left to right.
|
||||||
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
|
export const cronologico = (periodos: readonly string[]) => sortedPeriods(periodos).reverse();
|
||||||
@@ -56,7 +62,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.
|
// 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)[] = [];
|
const x: (string | null)[] = [], y: (number | null)[] = [];
|
||||||
let run: number[] = [];
|
let run: number[] = [];
|
||||||
const cerrar = () => {
|
const cerrar = () => {
|
||||||
@@ -69,7 +75,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(); });
|
periodos.forEach((_, i) => { if (bajo[i] !== null && alto[i] !== null) run.push(i); else cerrar(); });
|
||||||
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.
|
// 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) {
|
function serie(data: IndicadorDatos, periodos: string[], valor: (row: Record<string, unknown>) => boolean) {
|
||||||
@@ -107,10 +113,13 @@ function porcentaje(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
function mediana(data: IndicadorDatos, tema: Tema, opciones: HistoricoOpciones): Trazo {
|
||||||
const periodos = validar(data), unidad = unidadDe(data);
|
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 { validas, suprimidos, sinDato } = serie(data, periodos, row => numero(row['mediana']) && numero(row['n']) && row['n'] > 0);
|
||||||
|
const propio = DIAS[data.id];
|
||||||
|
const linea = propio ? (tema === 'oscuro' ? propio.oscuro : propio.claro) : c2Theme(tema).line;
|
||||||
|
const relleno = propio && tema === 'claro' ? propio.relleno : linea + '40';
|
||||||
return {
|
return {
|
||||||
figure: { data: [
|
figure: { data: [
|
||||||
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', c2Theme(tema).line),
|
banda(periodos.map(etiquetaPeriodo), campo(validas, 'q1'), campo(validas, 'q3'), 'Primer a tercer cuartil', linea, relleno),
|
||||||
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: c2Theme(tema).line, width: 2 },
|
{ type: 'scatter', mode: 'lines+markers', name: 'Mediana', x: periodos.map(etiquetaPeriodo), y: campo(validas, 'mediana'), connectgaps: false, line: { color: linea, width: 2 }, marker: { color: 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}` : ''),
|
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>' },
|
hovertemplate: '%{x}<br>%{text}<extra></extra>' },
|
||||||
], layout: (() => {
|
], layout: (() => {
|
||||||
@@ -141,15 +150,19 @@ function conteo(data: IndicadorDatos, tema: Tema): Trazo {
|
|||||||
const estadoDe = (periodo: string) => orden.map(id => celdas.get(JSON.stringify([id, periodo])));
|
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 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 sinDato = periodos.filter(p => !suprimidos.includes(p) && estadoDe(p).some(row => !numero(row?.['n'])));
|
||||||
|
const curso = { frio: 0, calido: 0, neutro: 0 };
|
||||||
return {
|
return {
|
||||||
figure: { data: orden.map((id, i) => {
|
figure: { data: orden.map((id, i) => {
|
||||||
const meta = record(catalogo[id]) ? catalogo[id] : {};
|
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 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; });
|
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,
|
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' } },
|
}), 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,
|
suprimidos, sinDato,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,6 +63,16 @@ describe('Figuras de histórico', () => {
|
|||||||
expect(traza(data, 0).y).toEqual([30, 10]);
|
expect(traza(data, 0).y).toEqual([30, 10]);
|
||||||
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
|
expect(sinDato).toEqual(['feb 2024']); expect(suprimidos).toEqual([]);
|
||||||
});
|
});
|
||||||
|
it('las líneas de días de CaMa usan el azul, el morado y el rosa de la histopatología', () => {
|
||||||
|
const color = (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, banda: figure.data[0]['fillcolor'] };
|
||||||
|
};
|
||||||
|
expect(color('cama_dias_toma_diagnostico', 'claro')).toEqual({ linea: '#2F6DB3', banda: '#9DBFE380' });
|
||||||
|
expect(color('cama_eu38a', 'claro')).toEqual({ linea: '#9C42C2', banda: '#9C42C240' });
|
||||||
|
expect(color('cama_dias_resultado_diagnostico', 'claro')).toEqual({ linea: '#C24269', banda: '#C2426940' });
|
||||||
|
expect(color('cama_dias_toma_diagnostico', 'oscuro').linea).toBe('#9DBFE3');
|
||||||
|
});
|
||||||
it('las líneas usan el verde legible en cada tema', () => {
|
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 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;
|
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 { IndicadoresPeriodos } from './indicadores-periodos';
|
||||||
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
import { Dominio, Indicador, IndicadorDatos, Tema, TipoPeriodo } from './indicadores.models';
|
||||||
import { IndicadoresService } from './indicadores.service';
|
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');
|
const unidad = (tipo: TipoPeriodo, n: number) => tipo === 'mes' ? (n === 1 ? 'mes' : 'meses') : (n === 1 ? 'semestre' : 'semestres');
|
||||||
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
type Carga = { estado: 'listo'; datos: IndicadorDatos } | { estado: 'vacio' } | { estado: 'error'; mensaje: string };
|
||||||
@@ -28,12 +29,11 @@ const PERSONALIZADO = -1;
|
|||||||
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
export const HISTORICO_CAMA: readonly { id: string; titulo: string }[] = [
|
||||||
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
{ id: 'cama_histopatologia_birads', titulo: 'Resultado histopatológico' },
|
||||||
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 y 6' },
|
{ id: 'cama_birads_456_paciente', titulo: 'Pacientes evaluadas con BI-RADS 4, 5 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_mastografia', titulo: TITULO_MASTOGRAFIAS_CAMA },
|
||||||
{ id: 'cama_confirmacion_birads45', titulo: 'Tasa de confirmación histopatológica' },
|
{ 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_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_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_dias_resultado_diagnostico', titulo: 'Días del resultado de la mastografía al diagnóstico' },
|
||||||
{ id: 'cama_tasa_deteccion_histopatologica', titulo: 'Tasa de detección histopatológica' },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
// The screening steps go together as small charts, and the case counts are followed by their in-process share.
|
||||||
@@ -63,18 +63,23 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
|||||||
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
imports: [MatButtonModule, MatButtonToggleModule, MatFormFieldModule, MatProgressBarModule, MatSelectModule, PlotlyChart],
|
||||||
template: `
|
template: `
|
||||||
<div class="controles">
|
<div class="controles">
|
||||||
<span id="historico-intervalo">Intervalo de análisis</span>
|
<h2>Filtros</h2>
|
||||||
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
|
<div class="controles-fila">
|
||||||
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
<div class="interval">
|
||||||
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
<span id="historico-intervalo" class="field-label">Intervalo de análisis</span>
|
||||||
</mat-button-toggle-group>
|
<mat-button-toggle-group aria-labelledby="historico-intervalo" hideSingleSelectionIndicator [value]="tipo()" (change)="elegido.set($event.value)">
|
||||||
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
@if (tipos().includes('mes')) { <mat-button-toggle value="mes">Mensual</mat-button-toggle> }
|
||||||
<mat-label>Periodos a mostrar</mat-label>
|
@if (tipos().includes('semestre')) { <mat-button-toggle value="semestre">Semestral</mat-button-toggle> }
|
||||||
<mat-select #selector [value]="ventana()" (selectionChange)="elegirVentana($event.value)">
|
</mat-button-toggle-group>
|
||||||
@for (opcion of opciones(); track opcion.valor) { <mat-option [value]="opcion.valor">{{ opcion.etiqueta }}</mat-option> }
|
</div>
|
||||||
</mat-select>
|
<mat-form-field appearance="outline" subscriptSizing="dynamic">
|
||||||
</mat-form-field>
|
<mat-label>Periodos a mostrar</mat-label>
|
||||||
@if (ventana() === PERSONALIZADO) { <button type="button" mat-stroked-button (click)="abrirPersonalizado()">Cambiar periodos</button> }
|
<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>
|
||||||
<div class="paneles">
|
<div class="paneles">
|
||||||
@for (panel of paneles(); track panel.item.id) {
|
@for (panel of paneles(); track panel.item.id) {
|
||||||
@@ -102,7 +107,7 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
|||||||
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
<app-plotly-chart [style.--plot-height]="'400px'" [showNotes]="false" [figure]="panel.figura.figure"
|
||||||
[label]="'Histórico de ' + panel.item.titulo + (panel.rango ? ', ' + panel.rango : '')" />
|
[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) {
|
@if (panel.figura.suprimidos.length) {
|
||||||
<details class="nota-pie">
|
<details class="nota-pie">
|
||||||
<summary>Datos suprimidos</summary>
|
<summary>Datos suprimidos</summary>
|
||||||
@@ -123,8 +128,13 @@ function agrupar(paneles: (Panel & { datos?: IndicadorDatos })[], tema: Tema): P
|
|||||||
`,
|
`,
|
||||||
styles: `
|
styles: `
|
||||||
:host { display: block; min-width: 0; }
|
: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); }
|
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; }
|
||||||
|
.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); }
|
.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)); } }
|
@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);
|
.panel { box-sizing: border-box; min-width: 0; padding: var(--issste-space-6); background: var(--issste-surface); color: var(--issste-text);
|
||||||
@@ -141,7 +151,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); }
|
.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)); } }
|
@container dashboard (min-width: 960px) { .pasos { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
|
||||||
h3 { margin: 0; font: var(--mat-sys-title-small); }
|
h3 { margin: 0; font: var(--mat-sys-title-small); }
|
||||||
mat-form-field { min-width: 18rem; }
|
mat-form-field { flex: 0 1 14rem; width: 14rem; min-width: 14rem; max-width: 24rem; }
|
||||||
`,
|
`,
|
||||||
})
|
})
|
||||||
export class IndicadoresHistorico {
|
export class IndicadoresHistorico {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { IndicadorCatalogCard } from './indicador-catalog-card';
|
|||||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { CACU_RESULTADO_KPI, KPI_BY_DOMAIN } from './indicadores-kpi';
|
import { CACU_RESULTADO_KPI, ID_HISTOPATOLOGIA_CAMA, KPI_BY_DOMAIN } from './indicadores-kpi';
|
||||||
import { pending } from './indicadores-memory';
|
import { pending } from './indicadores-memory';
|
||||||
import { Indicador } from './indicadores.models';
|
import { Indicador } from './indicadores.models';
|
||||||
|
|
||||||
@@ -64,7 +64,11 @@ describe.each(['tea', 'cacu', 'cama'] as const)('P0 autoridad temporal compartid
|
|||||||
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
return requests.filter(r => !r.request.url.endsWith('/' + CACU_RESULTADO_KPI.id + '/datos'));
|
||||||
}
|
}
|
||||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorKpiPanel)).map(e => e.componentInstance as IndicadorKpiPanel).filter(panel => panel.definition.id !== CACU_RESULTADO_KPI.id); }
|
||||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||||
|
function cards() {
|
||||||
|
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||||
|
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||||
|
}
|
||||||
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
function editor() { return fixture.debugElement.query(By.directive(IndicadorPeriodFilters)).componentInstance as IndicadorPeriodFilters; }
|
||||||
// The shared request queue runs four at a time: flushing a batch starts the next.
|
// The shared request queue runs four at a time: flushing a batch starts the next.
|
||||||
function flushPanels(period: string, expected = definitions.length - 1) {
|
function flushPanels(period: string, expected = definitions.length - 1) {
|
||||||
|
|||||||
@@ -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,
|
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 = {
|
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 interpretación radiológica', contrato: 'C3r', unit: 'días (mediana)', requiresObservations: true,
|
||||||
};
|
};
|
||||||
// Institutional definitions retained for consumers outside the opportunity strip.
|
// Institutional definitions retained for consumers outside the opportunity strip.
|
||||||
export const CAMA_CONFIRMACION_KPI: KpiDefinition = {
|
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)',
|
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 = {
|
export const CAMA_TASA_DETECCION_KPI: KpiDefinition = {
|
||||||
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de detección histopatológica', contrato: 'C1', unit: '%',
|
id: 'cama_tasa_deteccion_histopatologica', title: 'Tasa de confirmación histopatológica', contrato: 'C1', unit: '%',
|
||||||
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
c1Info: (n, d) => `${n} de ${d} biopsias con resultado maligno.`,
|
||||||
};
|
};
|
||||||
export const CAMA_RESULTADO_DIAGNOSTICO_KPI: KpiDefinition = {
|
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
|
// 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
|
// in indicadores_kit, except the C2 patient counts, whose card shows the sum of the categories
|
||||||
|
|||||||
@@ -7,12 +7,15 @@ import { provideRouter, Router } from '@angular/router';
|
|||||||
import { RouterTestingHarness } from '@angular/router/testing';
|
import { RouterTestingHarness } from '@angular/router/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { routes } from '../../app.routes';
|
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 { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { IndicadoresPage } from './indicadores-page';
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
import { IndicadorFigureCard } from './indicador-figure-card';
|
import { IndicadorFigureCard } from './indicador-figure-card';
|
||||||
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
import { IndicadorPeriodFilters } from './indicador-period-filters';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||||
import { PlotlyFigure } from './indicadores.models';
|
import { PlotlyFigure } from './indicadores.models';
|
||||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||||
|
|
||||||
@@ -22,6 +25,7 @@ class ChartStub { figure?: PlotlyFigure; }
|
|||||||
describe('UX-04 navegación Angular', () => {
|
describe('UX-04 navegación Angular', () => {
|
||||||
let http: HttpTestingController;
|
let http: HttpTestingController;
|
||||||
async function setup() {
|
async function setup() {
|
||||||
|
iniciarSesionVisual();
|
||||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
@@ -33,13 +37,22 @@ describe('UX-04 navegación Angular', () => {
|
|||||||
harness.detectChanges();
|
harness.detectChanges();
|
||||||
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
const page = harness.routeDebugElement!.componentInstance as IndicadoresPage;
|
||||||
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
vi.spyOn(page as unknown as { evaluateVisibility(): void }, 'evaluateVisibility').mockImplementation(() => {});
|
||||||
const card = harness.routeDebugElement!.query(By.directive(IndicadorCatalogCard)).componentInstance as IndicadorCatalogCard;
|
// CaMa leads with the histopathology card, which reads a local source; the figure request comes from the next one.
|
||||||
|
const card = harness.routeDebugElement!.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||||
|
.find(item => item.indicador.id !== ID_HISTOPATOLOGIA_CAMA)!;
|
||||||
if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
|
if (!card.visible) { card.setVisible(true); harness.detectChanges(); }
|
||||||
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
const req = http.expectOne(r => r.url.includes('/figuras/'));
|
||||||
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
req.flush({ data: [{ y: [0, null] }], layout: {} });
|
||||||
return req;
|
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 => {
|
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();
|
const harness = await setup();
|
||||||
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
await harness.navigateByUrl('/indicadores/' + domain, IndicadoresPage);
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
<div id="panel-resumen" class="section-panel" role="tabpanel" aria-labelledby="tab-resumen" tabindex="0" [hidden]="activeSection() !== 'resumen'">
|
||||||
@if (!catalogLoading() && filters; as state) {
|
@if (!catalogLoading() && filters; as state) {
|
||||||
<section class="global-filters" aria-labelledby="global-filters-title" [attr.data-domain]="dominio">
|
<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>
|
<h2 id="global-filters-title" class="section-title">Filtros</h2>
|
||||||
@if (dominio !== 'cama') {
|
@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>
|
<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>
|
||||||
}
|
}
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
<h2 id="kpi-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores de oportunidad' : resumen ? 'Resumen' : 'Indicadores destacados' }}</h2>
|
||||||
@if (resumen) { <app-tea-resumen-periodo [periodo]="resumen" [paneles]="kpiPanels()" /> }
|
@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. -->
|
<!-- 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) {
|
@for (card of kpis; track dominio + ':' + card.definition.id) {
|
||||||
@if (card.pending) {
|
@if (card.pending) {
|
||||||
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
<app-indicador-kpi-card [title]="card.definition.title" state="Integración pendiente"
|
||||||
@@ -66,6 +66,9 @@
|
|||||||
@if (dominio === 'cacu') {
|
@if (dominio === 'cacu') {
|
||||||
<app-indicador-kpi-card title="Tiempo de tamizaje a tratamiento" state="Indicador no disponible" />
|
<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" />
|
<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>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -74,9 +77,6 @@
|
|||||||
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
<section class="graphic-section" aria-labelledby="graphic-section-title">
|
||||||
<div class="catalog-heading">
|
<div class="catalog-heading">
|
||||||
<h2 id="graphic-section-title" class="section-title">{{ dominio === 'cacu' || dominio === 'cama' ? 'Indicadores clínicos' : 'Indicadores gráficos' }}</h2>
|
<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>
|
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
@if (catalogLoading()) {
|
@if (catalogLoading()) {
|
||||||
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
|
<mat-progress-bar mode="indeterminate" aria-label="Cargando catálogo" />
|
||||||
@@ -117,7 +117,6 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
<div class="catalog-grid">
|
<div class="catalog-grid">
|
||||||
@if (histopatologiaPendiente) { <app-indicador-histopatologia-pendiente /> }
|
|
||||||
@for (item of searchResults().items; track cardIdentity(item)) {
|
@for (item of searchResults().items; track cardIdentity(item)) {
|
||||||
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
<app-indicador-catalog-card [id]="cardElementId(item)" [dominio]="dominio" [indicador]="item" [tema]="tema" [applied]="figureApplied(item)" [independentPeriods]="independentPeriods(item)"
|
||||||
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
[pinned]="isPinned(item)" (pinChanged)="togglePinned(item)" />
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
// own `:host`) -- not present upstream, whose shell lays this out differently.
|
// own `:host`) -- not present upstream, whose shell lays this out differently.
|
||||||
// The workspace shell clips overflow, so the page scrolls itself.
|
// 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); }
|
: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; }
|
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; }
|
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); }
|
.domain { color: var(--mat-sys-primary); font: var(--mat-sys-label-large); }
|
||||||
@@ -13,8 +13,11 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
.global-filters[data-domain='cama'] .section-title { font-size: 1rem; margin-bottom: var(--issste-space-3); }
|
.global-filters[data-domain='cama'] .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-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; }
|
.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; }
|
.kpi-section, .graphic-section { box-sizing: border-box; min-width: 0; margin-inline: var(--space-2);
|
||||||
.graphic-section { margin-top: var(--issste-space-6); padding-top: var(--issste-space-6); border-top: 1px solid var(--issste-border); }
|
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-section > .section-title { margin-bottom: var(--issste-space-4); }
|
||||||
|
.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-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; }
|
.kpi-section .kpi-grid.kpi-grid-oculto { display: none; }
|
||||||
.catalog-grid { align-items: stretch; }
|
.catalog-grid { align-items: stretch; }
|
||||||
@@ -22,7 +25,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); }
|
.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-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-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 { 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 mat-form-field { width: 100%; min-width: 0; max-width: 32rem; }
|
||||||
.catalog-search button { min-height: 48px; }
|
.catalog-search button { min-height: 48px; }
|
||||||
@@ -39,11 +41,8 @@ header p { color: var(--mat-sys-on-surface-variant); margin-bottom: 1.5rem; }
|
|||||||
|
|
||||||
@container dashboard (min-width: 1000px) { .kpi-grid { grid-template-columns: repeat(min(3, var(--kpi-count)), minmax(0, 1fr)); } }
|
@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; }
|
.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: 1350px) { .kpi-section[data-domain='cama'] .kpi-grid { grid-template-columns: repeat(5, 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 {
|
.kpi-section[data-domain='cacu'] .kpi-grid {
|
||||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 18rem), 1fr));
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { MatSelect } from '@angular/material/select';
|
|||||||
import { NgModel } from '@angular/forms';
|
import { NgModel } from '@angular/forms';
|
||||||
import { IndicadoresMemory } from './indicadores-memory';
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
|
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||||
import { Indicador, PlotlyFigure } from './indicadores.models';
|
import { Indicador, PlotlyFigure } from './indicadores.models';
|
||||||
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
import { syntheticCatalogs } from './indicadores.synthetic-fixtures';
|
||||||
|
|
||||||
@@ -37,7 +38,11 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
function load(items: Indicador[] = [item, second], domain = 'tea') {
|
||||||
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
http.expectOne('/' + domain + '/indicadores').flush(items); fixture.detectChanges();
|
||||||
}
|
}
|
||||||
function cards() { return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard); }
|
// CaMa's summary always adds the histopathology card, whose source is local and makes no request; these tests drive the catalog's own cards.
|
||||||
|
function cards() {
|
||||||
|
return fixture.debugElement.queryAll(By.directive(IndicadorCatalogCard)).map(e => e.componentInstance as IndicadorCatalogCard)
|
||||||
|
.filter(card => card.indicador.id !== ID_HISTOPATOLOGIA_CAMA);
|
||||||
|
}
|
||||||
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
|
function panels() { return fixture.debugElement.queryAll(By.directive(IndicadorFigurePanel)).map(e => e.componentInstance as IndicadorFigurePanel).filter(p => p.result().status !== 'deferred'); }
|
||||||
function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
|
function toggle(index = 0) { cards()[index].setVisible(true); fixture.detectChanges(); }
|
||||||
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
|
function request(figure: string) { return http.expectOne(r => r.url.endsWith('/figuras/' + figure)); }
|
||||||
@@ -93,8 +98,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']);
|
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.
|
// 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('app-indicadores-numeric-summary')).toBeNull();
|
||||||
expect(fixture.nativeElement.querySelector('.catalog-count').textContent.trim()).toBe('2 indicadores publicados');
|
expect(fixture.nativeElement.textContent).not.toContain('indicadores publicados');
|
||||||
expect(getComputedStyle(fixture.nativeElement.querySelector('.catalog-count')).textAlign).toBe('right');
|
|
||||||
toggle(0); toggle(1); flushAll();
|
toggle(0); toggle(1); flushAll();
|
||||||
expect(Array.from(grid.children).map(host => host.querySelectorAll('app-indicador-figure-panel').length)).toEqual([1, 1]);
|
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']);
|
expect(panels().map(panel => panel.figuraId)).toEqual(['f1', 'g']);
|
||||||
@@ -114,7 +118,7 @@ describe('UX-06E.D.3.A catálogo permanentemente desplegado', () => {
|
|||||||
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
|
it('Resumen omite los indicadores publicados solo para otra pestaña', () => {
|
||||||
load([item, { ...second, vistas: ['historico'] }]);
|
load([item, { ...second, vistas: ['historico'] }]);
|
||||||
expect(page.searchResults().items.map(i => i.id)).toEqual([item.id]);
|
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);
|
expect(page.catalog()).toHaveLength(2);
|
||||||
http.expectNone(r => r.url.endsWith('/figuras/f1'));
|
http.expectNone(r => r.url.endsWith('/figuras/f1'));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import { IndicadoresTracking } from './indicadores-tracking';
|
|||||||
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
import { SeleccionSeguimiento } from './indicadores-seguimiento-tabla';
|
||||||
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
import { IndicadoresAnalisis, SeleccionPacientes } from './indicadores-analisis';
|
||||||
import { IndicadoresHistorico } from './indicadores-historico';
|
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';
|
type DashboardSection = 'resumen' | 'historico' | 'analisis' | 'seguimiento' | 'datos';
|
||||||
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
const SECTIONS: readonly { id: DashboardSection; label: string }[] = [
|
||||||
@@ -51,7 +51,7 @@ const SECTIONS_CAMA: readonly { id: DashboardSection; label: string }[] = [
|
|||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-indicadores-page',
|
selector: 'app-indicadores-page',
|
||||||
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorHistopatologiaPendiente, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
imports: [FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatInputModule, MatIconModule, MatSelectModule, MatProgressBarModule, IndicadorCatalogCard, IndicadorKpiPanel, IndicadorKpiCard, IndicadorPeriodFilters, IndicadoresDefinitions, IndicadoresTracking, IndicadoresHistorico, TeaResumenPeriodo],
|
||||||
templateUrl: './indicadores-page.html',
|
templateUrl: './indicadores-page.html',
|
||||||
styleUrl: './indicadores-page.scss',
|
styleUrl: './indicadores-page.scss',
|
||||||
})
|
})
|
||||||
@@ -314,16 +314,16 @@ export class IndicadoresPage {
|
|||||||
private cardsDeCama(catalog: Indicador[]) {
|
private cardsDeCama(catalog: Indicador[]) {
|
||||||
const ids = catalog.map(item => item.id);
|
const ids = catalog.map(item => item.id);
|
||||||
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
const cards = catalog.filter(item => !CAMA_FUERA_DEL_RESUMEN.includes(item.id) && !esSocioConteos(this.dominio, item.id, ids));
|
||||||
// The histopathology card keeps its place, first, whether pending or published.
|
if (!ids.includes(ID_HISTOPATOLOGIA_CAMA)) {
|
||||||
|
cards.unshift({
|
||||||
|
id: ID_HISTOPATOLOGIA_CAMA, titulo: 'Resultado histopatológico por categoría BI-RADS',
|
||||||
|
contrato: 'C2', tipos_periodo: ['semestre', 'mes'], figuras: ['fig_c2_barras', 'fig_c2_donas'],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// The histopathology card comes first, including when only the local source is available.
|
||||||
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
return [...cards.filter(item => item.id === ID_HISTOPATOLOGIA_CAMA), ...cards.filter(item => item.id !== ID_HISTOPATOLOGIA_CAMA)];
|
||||||
}
|
}
|
||||||
// CaMa's histopathology card keeps its place, as pending, while the catalog does not publish its indicator.
|
|
||||||
get histopatologiaPendiente() {
|
|
||||||
return this.dominio === 'cama' && !this.catalogLoading() && !this.catalogError() && this.catalog().length > 0
|
|
||||||
&& !this.catalog().some(item => item.id === ID_HISTOPATOLOGIA_CAMA);
|
|
||||||
}
|
|
||||||
// How many indicators the graphic section shows: all the catalog, except in CaMa, which draws only some of them.
|
// 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)); }
|
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.
|
// TEA shows a summary paragraph instead of its cards for exactly one explicitly chosen period.
|
||||||
get teaResumenPeriodo(): string | undefined {
|
get teaResumenPeriodo(): string | undefined {
|
||||||
@@ -365,8 +365,8 @@ export class IndicadoresPage {
|
|||||||
return selected.length + ' indicadores';
|
return selected.length + ' indicadores';
|
||||||
});
|
});
|
||||||
readonly searchResults = computed(() => {
|
readonly searchResults = computed(() => {
|
||||||
const selected = new Set(this.selectedIndicators());
|
const selected = this.indicatorSelection();
|
||||||
const items = this.catalogOrder().filter(item => selected.has(item.id));
|
const items = selected === null ? this.catalogOrder() : this.catalogOrder().filter(item => selected.includes(item.id));
|
||||||
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
return { items: [...items.filter(item => this.isPinned(item)), ...items.filter(item => !this.isPinned(item))] };
|
||||||
});
|
});
|
||||||
readonly catalogLoading = signal(true);
|
readonly catalogLoading = signal(true);
|
||||||
@@ -484,7 +484,8 @@ export class IndicadoresPage {
|
|||||||
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
}), takeUntilDestroyed(this.destroyRef)).subscribe(({ items, error }) => {
|
||||||
this.catalogLoading.set(false);
|
this.catalogLoading.set(false);
|
||||||
this.filters = items.length ? this.memory.restoreGlobal(this.dominio, domainTypes(items)) : undefined;
|
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.filtersEdited();
|
||||||
this.catalogError.set(error);
|
this.catalogError.set(error);
|
||||||
this.availabilityRequests.next();
|
this.availabilityRequests.next();
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { IndicadoresPage } from './indicadores-page';
|
|||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
import { IndicadorFigurePanel } from './indicador-figure-panel';
|
||||||
import { IndicadoresMemory } from './indicadores-memory';
|
import { IndicadoresMemory } from './indicadores-memory';
|
||||||
|
import { ID_HISTOPATOLOGIA_CAMA } from './indicadores-kpi';
|
||||||
import { Indicador } from './indicadores.models';
|
import { Indicador } from './indicadores.models';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
import { PLOTLY_LOADER } from '../../shared/plotly/plotly-runtime';
|
||||||
@@ -83,7 +84,8 @@ describe('UX-06E.D.3.B fijación temporal', () => {
|
|||||||
it('memoria independiente por dominio y persistente al recrear la página', async () => {
|
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));
|
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.
|
// CaMa has no pin control (the mockup has none), so it neither keeps nor applies pins.
|
||||||
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual(items.map(i => i.id));
|
// Its summary also leads with the histopathology card, which is not part of the catalog and cannot be pinned.
|
||||||
|
await pin('i1'); page.changeDominio('cama'); load('cama'); expect(ids()).toEqual([ID_HISTOPATOLOGIA_CAMA, ...items.map(i => i.id)]);
|
||||||
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
page.changeDominio('cacu'); load('cacu'); expect(ids()[0]).toBe('i1');
|
||||||
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
page.changeDominio('tea'); load(); expect(ids()[0]).toBe('i3');
|
||||||
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
fixture.destroy(); create(); load(); expect(ids()[0]).toBe('i3'); http.expectNone(() => true);
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { HttpTestingController, provideHttpClientTesting } from '@angular/common
|
|||||||
import { provideRouter } from '@angular/router';
|
import { provideRouter } from '@angular/router';
|
||||||
import { RouterTestingHarness } from '@angular/router/testing';
|
import { RouterTestingHarness } from '@angular/router/testing';
|
||||||
import { routes } from '../../app.routes';
|
import { routes } from '../../app.routes';
|
||||||
|
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
|
||||||
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
import { PlotlyChart } from '../../shared/plotly/plotly-chart';
|
||||||
import fixtureData from './fixtures/cama_seguimiento.json';
|
import fixtureData from './fixtures/cama_seguimiento.json';
|
||||||
import { CAMA_ANALYSIS_ENABLED, IndicadoresPage } from './indicadores-page';
|
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;
|
let http: HttpTestingController;
|
||||||
const corte = hoyIso();
|
const corte = hoyIso();
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
iniciarSesionVisual();
|
||||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(withInterceptors([sinAnalisisDescriptivo])), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
TestBed.overrideComponent(IndicadoresAnalisis, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
http = TestBed.inject(HttpTestingController);
|
http = TestBed.inject(HttpTestingController);
|
||||||
});
|
});
|
||||||
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
|
afterEach(() => { http.verify(); vi.restoreAllMocks(); vi.unstubAllGlobals(); limpiarSesionVisual(); });
|
||||||
|
|
||||||
async function entrar() {
|
async function entrar() {
|
||||||
const harness = await RouterTestingHarness.create();
|
const harness = await RouterTestingHarness.create();
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ describe('Selección de indicadores gráficos', () => {
|
|||||||
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
expect(cards()[0]).toBe(before[1]); expect(cards()[1]).toBe(before[4]);
|
||||||
expect(page.selectionSummary()).toBe('2 indicadores');
|
expect(page.selectionSummary()).toBe('2 indicadores');
|
||||||
expect(result()).toBe('Mostrando 2 de 5 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');
|
choose(['M02_sexo']); expect(ids()).toEqual(['M02_sexo']); expect(page.selectionSummary()).toBe('Distribución por sexo');
|
||||||
expect(page.catalog()).toBe(original);
|
expect(page.catalog()).toBe(original);
|
||||||
http.expectNone(() => true);
|
http.expectNone(() => true);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { provideRouter } from '@angular/router';
|
|||||||
import { RouterTestingHarness } from '@angular/router/testing';
|
import { RouterTestingHarness } from '@angular/router/testing';
|
||||||
import { By } from '@angular/platform-browser';
|
import { By } from '@angular/platform-browser';
|
||||||
import { routes } from '../../app.routes';
|
import { routes } from '../../app.routes';
|
||||||
|
import { iniciarSesionVisual, limpiarSesionVisual } from '../../auth/auth.testing';
|
||||||
import { IndicadoresPage } from './indicadores-page';
|
import { IndicadoresPage } from './indicadores-page';
|
||||||
import { IndicadoresDefinitions } from './indicadores-definitions';
|
import { IndicadoresDefinitions } from './indicadores-definitions';
|
||||||
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
import { IndicadorCatalogCard } from './indicador-catalog-card';
|
||||||
@@ -24,12 +25,13 @@ const catalog: Indicador[] = [
|
|||||||
describe('Secciones compartidas por dominio', () => {
|
describe('Secciones compartidas por dominio', () => {
|
||||||
let http: HttpTestingController;
|
let http: HttpTestingController;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
iniciarSesionVisual();
|
||||||
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
vi.stubGlobal('IntersectionObserver', class { observe() {} unobserve() {} disconnect() {} });
|
||||||
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
TestBed.configureTestingModule({ providers: [provideRouter(routes), provideHttpClient(), provideHttpClientTesting(), periodAvailabilityProvider, kpiQueriesProvider] });
|
||||||
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
TestBed.overrideComponent(IndicadorFigureCard, { remove: { imports: [PlotlyChart] }, add: { imports: [ChartStub] } });
|
||||||
http = TestBed.inject(HttpTestingController);
|
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 => {
|
it.each(DOMINIOS)('entrada directa en %s presenta sus pestañas y Resumen seleccionado', async domain => {
|
||||||
const harness = await RouterTestingHarness.create();
|
const harness = await RouterTestingHarness.create();
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export function stratifiedBars(data: IndicadorDatos, dimension: DimensionEstrato
|
|||||||
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
if (new Set(categories.map(([, c]) => c.label)).size !== categories.length) throw new Error('Etiquetas ambiguas');
|
||||||
const cells: StratifiedCell[] = [];
|
const cells: StratifiedCell[] = [];
|
||||||
const theme = c2Theme(tema);
|
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 figure: PlotlyFigure = { data: strata.map((s, series) => {
|
||||||
const selected = categories.map(([id, c]) => {
|
const selected = categories.map(([id, c]) => {
|
||||||
const row = rows.get(JSON.stringify([id, s]));
|
const row = rows.get(JSON.stringify([id, s]));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<div class="experiments">
|
<div class="experiments">
|
||||||
<div class="experiments__toolbar">
|
<div class="experiments__toolbar">
|
||||||
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
||||||
@for (option of domains; track option.id) {
|
@for (option of domains(); track option.id) {
|
||||||
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
||||||
}
|
}
|
||||||
</mat-button-toggle-group>
|
</mat-button-toggle-group>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { DatePipe } from '@angular/common';
|
import { DatePipe } from '@angular/common';
|
||||||
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
|
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
import { MatButtonToggleModule } from '@angular/material/button-toggle';
|
||||||
@@ -10,6 +10,8 @@ import { MatTableModule } from '@angular/material/table';
|
|||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { Subscription, timer } from 'rxjs';
|
import { Subscription, timer } from 'rxjs';
|
||||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||||
|
import { AuthService } from '../../../auth/auth.service';
|
||||||
|
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
|
||||||
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
||||||
import { GovernanceApi } from '../../api/governance.api';
|
import { GovernanceApi } from '../../api/governance.api';
|
||||||
import { Experiment, ExperimentDetail, ExperimentStatus } from '../../api/governance.types';
|
import { Experiment, ExperimentDetail, ExperimentStatus } from '../../api/governance.types';
|
||||||
@@ -36,11 +38,16 @@ const POLL_MS = 5000;
|
|||||||
})
|
})
|
||||||
export class ExperimentsPanel implements OnInit {
|
export class ExperimentsPanel implements OnInit {
|
||||||
readonly api = inject(GovernanceApi);
|
readonly api = inject(GovernanceApi);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
private readonly dialog = inject(MatDialog);
|
private readonly dialog = inject(MatDialog);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))];
|
/** Only the account's domains; «Todos» only when it reaches all of them. */
|
||||||
readonly domain = signal<string | null>(null);
|
readonly domains = computed<{ id: string | null; label: string }[]>(() => [
|
||||||
|
...(alcanzaTodos(this.auth, DOMAINS) ? [{ id: null, label: 'Todos' }] : []),
|
||||||
|
...dominiosPermitidos(this.auth, DOMAINS).map((d) => ({ id: d.id as string | null, label: d.label })),
|
||||||
|
]);
|
||||||
|
readonly domain = signal<string | null>(dominioInicial(this.auth, DOMAINS));
|
||||||
readonly experiments = signal<Experiment[]>([]);
|
readonly experiments = signal<Experiment[]>([]);
|
||||||
readonly details = signal<Record<string, ExperimentDetail>>({});
|
readonly details = signal<Record<string, ExperimentDetail>>({});
|
||||||
readonly loading = signal(false);
|
readonly loading = signal(false);
|
||||||
@@ -57,6 +64,7 @@ export class ExperimentsPanel implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setDomain(domain: string | null): void {
|
setDomain(domain: string | null): void {
|
||||||
|
if (domain !== null && !this.auth.puedeVer(domain)) return;
|
||||||
this.domain.set(domain);
|
this.domain.set(domain);
|
||||||
this.reload();
|
this.reload();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<div class="models">
|
<div class="models">
|
||||||
<div class="models__toolbar">
|
<div class="models__toolbar">
|
||||||
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
<mat-button-toggle-group hideSingleSelectionIndicator [value]="domain()" (change)="setDomain($event.value)" aria-label="Dominio">
|
||||||
@for (option of domains; track option.id) {
|
@for (option of domains(); track option.id) {
|
||||||
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
<mat-button-toggle [value]="option.id">{{ option.label }}</mat-button-toggle>
|
||||||
}
|
}
|
||||||
</mat-button-toggle-group>
|
</mat-button-toggle-group>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { DatePipe } from '@angular/common';
|
import { DatePipe } from '@angular/common';
|
||||||
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
|
import { Component, DestroyRef, OnInit, computed, inject, signal } from '@angular/core';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatDialog } from '@angular/material/dialog';
|
import { MatDialog } from '@angular/material/dialog';
|
||||||
@@ -11,6 +11,8 @@ import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
|||||||
import { MatTableModule } from '@angular/material/table';
|
import { MatTableModule } from '@angular/material/table';
|
||||||
import { MatTooltipModule } from '@angular/material/tooltip';
|
import { MatTooltipModule } from '@angular/material/tooltip';
|
||||||
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
import { DOMAINS } from '../../../connect/state/connect-workspace.store';
|
||||||
|
import { AuthService } from '../../../auth/auth.service';
|
||||||
|
import { alcanzaTodos, dominioInicial, dominiosPermitidos } from '../../../auth/dominios';
|
||||||
import { apiErrorMessage } from '../../../connect/api/api.types';
|
import { apiErrorMessage } from '../../../connect/api/api.types';
|
||||||
import { GovernanceApi } from '../../api/governance.api';
|
import { GovernanceApi } from '../../api/governance.api';
|
||||||
import { ModelVersion } from '../../api/governance.types';
|
import { ModelVersion } from '../../api/governance.types';
|
||||||
@@ -45,12 +47,17 @@ const TRAINABLE = { domain: 'cacu', scenario: 'cin2_logistic' };
|
|||||||
})
|
})
|
||||||
export class ModelVersionsPanel implements OnInit {
|
export class ModelVersionsPanel implements OnInit {
|
||||||
private readonly api = inject(GovernanceApi);
|
private readonly api = inject(GovernanceApi);
|
||||||
|
private readonly auth = inject(AuthService);
|
||||||
private readonly snackBar = inject(MatSnackBar);
|
private readonly snackBar = inject(MatSnackBar);
|
||||||
private readonly dialog = inject(MatDialog);
|
private readonly dialog = inject(MatDialog);
|
||||||
private readonly destroyRef = inject(DestroyRef);
|
private readonly destroyRef = inject(DestroyRef);
|
||||||
|
|
||||||
readonly domains = [{ id: null, label: 'Todos' }, ...DOMAINS.map((d) => ({ id: d.id as string | null, label: d.label }))];
|
/** Only the account's domains; «Todos» only when it reaches all of them. */
|
||||||
readonly domain = signal<string | null>(null);
|
readonly domains = computed<{ id: string | null; label: string }[]>(() => [
|
||||||
|
...(alcanzaTodos(this.auth, DOMAINS) ? [{ id: null, label: 'Todos' }] : []),
|
||||||
|
...dominiosPermitidos(this.auth, DOMAINS).map((d) => ({ id: d.id as string | null, label: d.label })),
|
||||||
|
]);
|
||||||
|
readonly domain = signal<string | null>(dominioInicial(this.auth, DOMAINS));
|
||||||
readonly versions = signal<ModelVersion[]>([]);
|
readonly versions = signal<ModelVersion[]>([]);
|
||||||
readonly loading = signal(false);
|
readonly loading = signal(false);
|
||||||
readonly loadError = signal<string | null>(null);
|
readonly loadError = signal<string | null>(null);
|
||||||
@@ -63,6 +70,7 @@ export class ModelVersionsPanel implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setDomain(domain: string | null): void {
|
setDomain(domain: string | null): void {
|
||||||
|
if (domain !== null && !this.auth.puedeVer(domain)) return;
|
||||||
this.domain.set(domain);
|
this.domain.set(domain);
|
||||||
this.reload();
|
this.reload();
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -10,15 +10,15 @@
|
|||||||
<mat-icon aria-hidden="true">upload_file</mat-icon>
|
<mat-icon aria-hidden="true">upload_file</mat-icon>
|
||||||
<span>Cargar información</span>
|
<span>Cargar información</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="home__action home__action--secondary" routerLink="/indicadores">
|
<a class="home__action" routerLink="/indicadores">
|
||||||
<mat-icon aria-hidden="true">insights</mat-icon>
|
<mat-icon aria-hidden="true">insights</mat-icon>
|
||||||
<span>Indicadores</span>
|
<span>Indicadores</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="home__action home__action--secondary" routerLink="/bitacora">
|
<a class="home__action" routerLink="/bitacora">
|
||||||
<mat-icon aria-hidden="true">fact_check</mat-icon>
|
<mat-icon aria-hidden="true">fact_check</mat-icon>
|
||||||
<span>Bitácora de cargas</span>
|
<span>Bitácora de cargas</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="home__action home__action--secondary" routerLink="/gobernanza">
|
<a class="home__action" routerLink="/gobernanza">
|
||||||
<mat-icon aria-hidden="true">verified</mat-icon>
|
<mat-icon aria-hidden="true">verified</mat-icon>
|
||||||
<span>Gobernanza de modelos</span>
|
<span>Gobernanza de modelos</span>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
+6
-14
@@ -54,8 +54,8 @@ h1 {
|
|||||||
.home__action {
|
.home__action {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
background: #f8f9fa;
|
background: transparent;
|
||||||
border: 1px solid #e9ecef;
|
border: 1px solid var(--color-action);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
@@ -72,9 +72,10 @@ h1 {
|
|||||||
transform 0.2s ease;
|
transform 0.2s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The four actions share one look: the first one used to be the filled variant. */
|
||||||
.home__action:hover {
|
.home__action:hover {
|
||||||
background: #e9ecef;
|
background: var(--color-action-hover);
|
||||||
border-color: #5f9ea0;
|
border-color: var(--color-action);
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,18 +89,9 @@ h1 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.home__action mat-icon {
|
.home__action mat-icon {
|
||||||
color: #5f9ea0;
|
color: var(--color-action);
|
||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.home__action--secondary {
|
|
||||||
background: transparent;
|
|
||||||
border-color: #5f9ea0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.home__action--secondary:hover {
|
|
||||||
background: #f1f6f6;
|
|
||||||
}
|
|
||||||
.steps {
|
.steps {
|
||||||
align-items: center;
|
align-items: center;
|
||||||
color: var(--color-text-secondary);
|
color: var(--color-text-secondary);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { AfterViewInit, Component, inject, ElementRef, Input, OnChanges, OnDestr
|
|||||||
import { MatButtonModule } from '@angular/material/button';
|
import { MatButtonModule } from '@angular/material/button';
|
||||||
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||||
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
import { PlotlyFigure } from '../../features/indicadores/indicadores.models';
|
||||||
|
import { recolorFigure } from '../../features/indicadores/indicadores-c2-palette';
|
||||||
import { PlotlyController } from './plotly-controller';
|
import { PlotlyController } from './plotly-controller';
|
||||||
import { PLOTLY_LOADER } from './plotly-runtime';
|
import { PLOTLY_LOADER } from './plotly-runtime';
|
||||||
|
|
||||||
@@ -68,12 +69,12 @@ export class PlotlyChart implements AfterViewInit, OnChanges, OnDestroy {
|
|||||||
this.observer = new ResizeObserver(this.windowResize);
|
this.observer = new ResizeObserver(this.windowResize);
|
||||||
this.observer.observe(this.host.nativeElement);
|
this.observer.observe(this.host.nativeElement);
|
||||||
} else window.addEventListener('resize', this.windowResize);
|
} else window.addEventListener('resize', this.windowResize);
|
||||||
this.controller.setFigure(this.figure);
|
this.controller.setFigure(recolorFigure(this.figure));
|
||||||
// Also supply the initial width in browsers without ResizeObserver.
|
// Also supply the initial width in browsers without ResizeObserver.
|
||||||
this.windowResize();
|
this.windowResize();
|
||||||
}
|
}
|
||||||
ngOnChanges() { if (this.figure) this.controller?.setFigure(this.figure); }
|
ngOnChanges() { if (this.figure) this.controller?.setFigure(recolorFigure(this.figure)); }
|
||||||
retry() { this.controller?.setFigure(this.figure); }
|
retry() { this.controller?.setFigure(recolorFigure(this.figure)); }
|
||||||
ngOnDestroy() {
|
ngOnDestroy() {
|
||||||
this.observer?.disconnect();
|
this.observer?.disconnect();
|
||||||
if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame);
|
if (this.widthFrame !== undefined) cancelAnimationFrame(this.widthFrame);
|
||||||
|
|||||||
@@ -280,6 +280,10 @@ describe('PlotlyController transiciones opcionales', () => {
|
|||||||
expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']);
|
expect(dimmed.data[1]['values']).toEqual([4, 6]); expect(dimmed.data[1]['text']).toEqual(['4', '6']);
|
||||||
expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
expect((dimmed.data[1]['marker'] as { colors: string[] }).colors).toEqual(['rgba(10,20,30,0.65)', 'rgba(10,20,30,0.65)']);
|
||||||
expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]);
|
expect(pieFrame(pie([4, 6]), pie([4, 6]), .5).data[1]).toEqual(pie([4, 6]).data[1]);
|
||||||
|
const grown = pieFrame({ ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0] })) },
|
||||||
|
{ ...pie([4, 6]), data: pie([4, 6]).data.map(t => ({ ...t, pull: [0, 0.12] })) }, .5);
|
||||||
|
expect(grown.data[1]['pull']).toEqual([0, 0.06]);
|
||||||
|
expect(grown.data[1]['text']).toEqual(['4', '6']);
|
||||||
});
|
});
|
||||||
it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => {
|
it('la dona interpola en varios react sin ocultar el host ni pasar por carga, y termina en la figura exacta', async () => {
|
||||||
const c = controller();
|
const c = controller();
|
||||||
|
|||||||
@@ -27,6 +27,25 @@ function mixColor(from: unknown, to: unknown, t: number): unknown {
|
|||||||
return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`;
|
return `rgba(${v.slice(0, 3).map(Math.round).join(',')},${+v[3].toFixed(3)})`;
|
||||||
}
|
}
|
||||||
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n));
|
const numbers = (v: unknown): v is number[] => Array.isArray(v) && v.every(n => typeof n === 'number' && Number.isFinite(n));
|
||||||
|
function mixDomain(from: unknown, to: unknown, t: number): { x: number[]; y: number[] } | undefined {
|
||||||
|
const read = (value: unknown) => {
|
||||||
|
if (!value || typeof value !== 'object') return undefined;
|
||||||
|
const x = (value as { x?: unknown }).x, y = (value as { y?: unknown }).y;
|
||||||
|
if (!numbers(x) || !numbers(y) || x.length !== 2 || y.length !== 2) return undefined;
|
||||||
|
return { x, y };
|
||||||
|
};
|
||||||
|
const start = read(from), end = read(to);
|
||||||
|
if (!start || !end) return undefined;
|
||||||
|
if (start.x.every((v, i) => v === end.x[i]) && start.y.every((v, i) => v === end.y[i])) return undefined;
|
||||||
|
const mix = (a: number[], b: number[]) => b.map((v, i) => a[i] + (v - a[i]) * t);
|
||||||
|
return { x: mix(start.x, end.x), y: mix(start.y, end.y) };
|
||||||
|
}
|
||||||
|
function mixPull(from: unknown, to: unknown, length: number, t: number): number[] | undefined {
|
||||||
|
const start = from === undefined ? Array<number>(length).fill(0) : from;
|
||||||
|
const end = to === undefined ? Array<number>(length).fill(0) : to;
|
||||||
|
if (!numbers(start) || !numbers(end) || start.length !== length || end.length !== length || start.every((v, i) => v === end[i])) return undefined;
|
||||||
|
return end.map((v, i) => start[i] + (v - start[i]) * t);
|
||||||
|
}
|
||||||
/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */
|
/** Pies cannot use layout.transition: both figures must have the same pies and value shapes. */
|
||||||
export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
|
export function piesInterpolable(from: PlotlyFigure, to: PlotlyFigure): boolean {
|
||||||
return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => {
|
return to.data.length > 0 && from.data.length === to.data.length && to.data.every((trace, i) => {
|
||||||
@@ -46,12 +65,16 @@ export function pieFrame(from: PlotlyFigure, to: PlotlyFigure, t: number): Plotl
|
|||||||
const marker = trace['marker'] as Record<string, unknown> | undefined;
|
const marker = trace['marker'] as Record<string, unknown> | undefined;
|
||||||
const oldColors = oldMarker?.['colors'], colors = marker?.['colors'];
|
const oldColors = oldMarker?.['colors'], colors = marker?.['colors'];
|
||||||
const sameValues = a.every((v, j) => v === b[j]);
|
const sameValues = a.every((v, j) => v === b[j]);
|
||||||
|
const clear = (list: unknown) => Array.isArray(list) && list.some(c => typeof c === 'string' && /,\s*0\)$/.test(c));
|
||||||
const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length
|
const mixColors = !!marker && Array.isArray(colors) && Array.isArray(oldColors) && oldColors.length === colors.length
|
||||||
&& colors.some((c, j) => c !== oldColors[j]);
|
&& !clear(colors) && !clear(oldColors) && colors.some((c, j) => c !== oldColors[j]);
|
||||||
if (sameValues && !mixColors && !moving) return trace;
|
const pull = mixPull(from.data[i]['pull'], trace['pull'], b.length, t);
|
||||||
|
const domain = mixDomain(from.data[i]['domain'], trace['domain'], t);
|
||||||
|
if (sameValues && !mixColors && !moving && !pull && !domain) return trace;
|
||||||
// Geometry is illustrative until the exact target render. Hide all clinical
|
// Geometry is illustrative until the exact target render. Hide all clinical
|
||||||
// readouts (including the centre) and never attach counts to moving slices.
|
// readouts (including the centre) and never attach counts to moving slices.
|
||||||
return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }),
|
return { ...trace, ...(sameValues ? {} : { values: b.map((v, j) => a[j] + (v - a[j]) * t) }),
|
||||||
|
...(pull ? { pull } : {}), ...(domain ? { domain } : {}),
|
||||||
...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '',
|
...(moving ? { text: b.map(() => ''), textinfo: 'none', texttemplate: '',
|
||||||
hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}),
|
hoverinfo: 'skip', hovertemplate: null, hovertext: [], customdata: [] } : {}),
|
||||||
...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };
|
...(mixColors ? { marker: { ...marker, colors: (colors as unknown[]).map((c, j) => mixColor((oldColors as unknown[])[j], c, t)) } } : {}) };
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
<title>Análisis de información | ISSSTELEON</title>
|
<title>Análisis de información | ISSSTELEON</title>
|
||||||
<base href="/" />
|
<base href="/" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<link rel="icon" type="image/x-icon" href="favicon.ico" />
|
<link rel="icon" type="image/x-icon" href="favicon.ico?v=3" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<app-root></app-root>
|
<app-root></app-root>
|
||||||
|
|||||||
@@ -9,6 +9,10 @@
|
|||||||
--color-surface: #ffffff;
|
--color-surface: #ffffff;
|
||||||
--color-border: #e3e7df;
|
--color-border: #e3e7df;
|
||||||
--color-step: #f0f3e8;
|
--color-step: #f0f3e8;
|
||||||
|
/* Action controls (home buttons, sign in, sign out): the theme's teal border
|
||||||
|
and the tint it takes under the pointer. */
|
||||||
|
--color-action: #5f9ea0;
|
||||||
|
--color-action-hover: #f1f6f6;
|
||||||
--font-body: 'Roboto', sans-serif;
|
--font-body: 'Roboto', sans-serif;
|
||||||
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
|
--font-heading: 'Rajdhani', 'Roboto Condensed', 'Arial Narrow', sans-serif;
|
||||||
--site-header-height: 72px;
|
--site-header-height: 72px;
|
||||||
@@ -137,6 +141,7 @@ body {
|
|||||||
.indicator-select-panel .option-go { flex: none; padding: .25rem .6rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius);
|
.indicator-select-panel .option-go { flex: none; padding: .25rem .6rem; border: 1px solid var(--issste-border); border-radius: var(--issste-radius);
|
||||||
color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; }
|
color: var(--issste-text); background: var(--issste-surface); font-weight: 600; text-decoration: none; }
|
||||||
.indicator-select-panel .option-go:hover { background: var(--issste-accent); }
|
.indicator-select-panel .option-go:hover { background: var(--issste-accent); }
|
||||||
|
.issste-help-tooltip { max-width: min(28rem, calc(100vw - 2rem)); white-space: pre-line; line-height: 1.45; }
|
||||||
.indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
.indicator-select-panel .option-go:focus-visible { outline: 2px solid var(--issste-text); outline-offset: 2px; }
|
||||||
|
|
||||||
// The TEA report: while it's being prepared, charts draw at a width that fits a page.
|
// The TEA report: while it's being prepared, charts draw at a width that fits a page.
|
||||||
|
|||||||
Reference in New Issue
Block a user